diff --git a/.gitignore b/.gitignore index 3b18855..f85577d 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,46 @@ /target merge_ready.log + +# Game data never goes into the repository (CONTRIBUTING.md, "Licence and provenance"): game +# packages and archives, console executables and libraries, video, audio banks, textures, dumps. +# XCL's own synthetic test data lives in tests/data/ and is listed explicitly below. +*.rpf +*.xvd +*.xvc +*.msixvc +*.appx +*.msix +*.appxbundle +*.xex +*.xbe +*.pak +*.bk2 +*.bik +*.ttpf +*.dds +*.ktx +*.ktx2 +*.wem +*.bnk +*.exe +*.dll +*.pdb +*.sys +*.dmp +*.mdmp +*.iso +*.pkg +*.xsp +*.cab +MicrosoftGame.config +appxmanifest.xml +resources.pri +!tests/data/testgame/MicrosoftGame.config + +# XCL's run output (logs, reports, frame dumps, shader dumps) +*.log +report.json +frame_*.bmp + +# Python bytecode of the scripts +__pycache__/ diff --git a/CLAUDE.md b/CLAUDE.md deleted file mode 100644 index e30885a..0000000 --- a/CLAUDE.md +++ /dev/null @@ -1,16 +0,0 @@ -# Claude Code - -The instructions for agents in this repository are in `AGENTS.md`, and the rules for every -contributor are in `CONTRIBUTING.md`. Both apply to you: - -@AGENTS.md -@CONTRIBUTING.md - -Specific to Claude Code: - -- Plan a task that spans more than one subsystem or more than ~400 lines (plan mode), and propose - how to split it into PRs before you write code. -- Run the tests and report the real output; do not stop at "the tests should pass". -- Fill in the **AI use** section of the PR description with Claude Code and your exact model name. -- For a runtime change, run `scripts/smoke.ps1` on main and on the PR's head commit and paste both - `xcl-smoke` blocks; do not write or edit them by hand. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md deleted file mode 100644 index 75e48de..0000000 --- a/CONTRIBUTING.md +++ /dev/null @@ -1,199 +0,0 @@ -# Contributing to XCL - -Thanks for helping. XCL gets far more pull requests than one maintainer can read carefully, so -these rules exist to make every PR **cheap to review and safe to merge**. A PR that ignores them -may be closed without a review, however good the code is. - -AI tools are welcome (see [AI-assisted contributions](#ai-assisted-contributions)). The rules are -the same for code written by hand and by an agent. - -## What a PR needs to be merged - -XCL gets more pull requests in an hour than anyone can test by hand, most of them written with AI -tools. So a PR is merged only when it shows that it was tested and that it breaks nothing. These are -checked before anything else; a PR that does not meet them waits (or is closed after a week). - -1. **Both required checks are green:** `CI` (build and tests on Windows, no GPU) and `PR checks` - (the description: the sections below, and the regression runs when they are needed). -2. **The whole suite ran on a GPU**, with the counts in **Tested** - (`cargo test --workspace -- --test-threads=4`: N passed, N failed, N ignored, and the SKIPPED tests). -3. **A PR that changes the runtime** (`crates/xcl/src` outside tests) **has a regression run on a real - title**: `scripts/smoke.ps1 -Game ` built from `main` and built from the PR's head - commit, both `xcl-smoke` blocks pasted under **Regression run**. The PR's block must name its head - commit with no uncommitted changes: rerun it after every push. It must show no device removal and - no crash, at least as many frames as `main` and no much higher peak commit. A run on a title that - does not reach the code the PR changes still counts as a regression check; say what it does not - cover under **Not tested**. -4. **No regression on the maintainer's run.** The maintainer merges in batches: the whole suite and a - retail title run again on the merged tree, on an AMD RDNA4 GPU. A PR that breaks either is taken - out of the batch and gets a comment with what failed. -5. **Up to date and reviewable:** it merges into `main` without conflicts, and keeps to the size and - scope rules below. A PR that duplicates one already merged is closed. - -A test result that was not produced by a real run on the hardware named gets the PR closed. - -## Before you start - -1. **Search open PRs and issues first.** Several PRs have solved the same problem at once and all - but one were closed. If someone is already on it, review or test their PR instead. -2. **Say what you are doing.** For anything bigger than a small fix, comment on the issue (or open - one) with the plan in two or three lines before writing it. That avoids duplicate work and wasted - effort on a direction the maintainer would not take. -3. **One problem per PR.** If you find a second bug while working, it gets its own PR. - -## Pull requests: small and single-purpose - -The smaller the PR, the faster it gets reviewed and merged. - -- **One logical change per PR.** A fix, a feature, a refactor and a test-only change are four PRs, - not one. "While I was here" changes go into a separate PR. -- **Size target: under ~400 changed lines**, not counting generated files and test data. Over ~800 - lines, the description must say why it cannot be split. Most large PRs can be split. -- **How to split** a large piece of work, in roughly this order: - 1. preparation that changes no behaviour (moving code, a new helper, a renamed type), - 2. new code behind a check or not yet called, with its tests, - 3. turning it on, - 4. diagnostics, logging and env-var switches, each on its own. -- **Stacked PRs** are fine when one change depends on another. Open each PR against `main`, say - `Stacked on #N` at the top of the description, and make it clear which commits belong to this PR. - Each PR in the stack must make sense when reviewed on its own. -- **No drive-by reformatting.** The tree is not `rustfmt`-clean. Do not run `cargo fmt` on whole - files or the whole crate: format only the lines you change. Reformatting buries the real diff. -- **No unrelated churn:** no renames, reordering, comment rewrites or dependency bumps the change - does not need. -- Keep the PR up to date by rebasing onto `main`, not by merging `main` into it. -- Open the PR as a **draft** until it builds, its tests pass and you have checked it yourself. - -### PR description - -Use this outline: - -```markdown - - - -**What is in it** -- one bullet per commit or part, with the file it lives in - -**Tested** -- hardware (GPU + driver, CPU), Windows build, Rust version, debug/release -- commands run and their results, e.g. `cargo test --workspace -- --test-threads=4`: 541 passed, 0 failed, 21 ignored -- `SKIPPED` GPU tests on your adapter, if any -- game checked (if any), and what got better, with numbers if you have them - -**Regression run** -- for a runtime change: the two `xcl-smoke` blocks (main, this PR's head) – see above - -**Not tested** -- what you could not check, e.g. AMD / NVIDIA, the retail title, wave32-only GPUs - -**AI use** -- none / which tool and model (e.g. Claude Code with Claude Opus 5.5), and for what (see below) -``` - -"Not tested" is required. An honest "not tested on AMD" is fine. A test you did not run listed as -passing is not, and gets the PR closed. - -## Commits - -History is merged with merge commits, so every commit on a PR ends up in `main`. - -- **Scope prefix + outcome**, as in the existing history: - ``` - Recompiler: round f16 conversions and products to nearest-even by default - VFS: preserve the destination when an overlay rename fails - D3D12.X: draws with untranslated pipelines get the title's root signature - ``` - The prefix is the subsystem: `Recompiler`, `D3D12.X`, `DirectStorage`, `XGameRuntime`, - `kernelx`, `XAudio2`, `VFS`, `Memory`, `TLS`, `PE loader`, `Shaders`, `Frame clock`, `xcl run`, - `Tests`, `e2e`, `Scripts`, `README`, `Docs`, `Issue templates`. Use one that exists already when it fits. - No `fix:` / `feat(...)` style prefixes; this repo does not use Conventional Commits. -- Subject line of about 72 characters or less, saying what the change does, not "update file.rs" or - "fix bug". -- The body (optional for small changes) says **why**, and anything a reviewer could not see from the - diff: the root cause, what was measured, what was ruled out. -- **One logical change per commit.** Each commit builds and passes the tests on its own, so `git bisect` - works. -- **No fixup commits in the final PR**: squash "fix review", "wip", "fmt", "oops" commits into the - commit they fix before asking for review (`git rebase -i`, then force-push). -- Reference issues as `(#123)` in the subject or `Fixes #123` in the body. - -## Tests - -Add or change a test when the change touches logic: a bug fix gets a test that fails before the fix -and passes after it, and new behaviour gets a test that shows it working. Docs, comments, logging -and pure renames need no test. - -- **Unit tests** go in a `#[cfg(test)] mod tests` in the same file, the way the rest of the crate does it. -- **Integration / end-to-end tests** go in `crates/xcl/tests/`. The e2e test drives our own console - title in `tests/testtitle` / `tests/testgamedll`: extend it when a change concerns the path a title - takes. -- **GPU tests** must run without a GPU too: when the adapter cannot run them, call - `gpu::recomp::runner::skip_test("no GPU" | "no DXC" | "no wave64" | "no mesh shaders")` and return. - Never mark a test `#[ignore]` only so that it passes. -- **Tests on game data** read files the contributor owns through the `XCL_SAMPLE_*` variables - (see README / `scripts/test.ps1`), and pass without doing anything when the variable is not set. - **Never commit game data**, console SDK headers or binaries, or output dumped from a game. -- **Recompiler instructions** get a per-instruction GPU test compared against an expected result, - like the existing ones. -- Run the whole suite before opening the PR: - ```powershell - .\scripts\test.ps1 # cargo build --workspace + cargo test --workspace - ``` - XCL builds and runs on Windows only. If you could not run the tests (e.g. you work on macOS or - Linux), say so in **Not tested**; a PR with no Windows test run waits until someone runs one. - -## Licence and provenance - -XCL is **GPL-2.0-only**. - -- Dependencies must be GPL-2.0-compatible (no Apache-2.0-only, no GPL-3.0). New dependencies need a - reason in the PR description; avoid them for a few lines of code. -- Code ported or adapted from another project needs a provenance note in the file (project, URL, - licence) and an entry in `THIRD_PARTY.md` when it is new. -- WinDurango (LGPL-3.0) is a reference only: no code is ported from it. -- Nothing from the console SDK: no headers, no binaries, no copied documentation. -- Generated files (`*_spec.rs`, tables) come with the script in `scripts/` that generates them, and - the PR says how they were generated. Do not edit them by hand. -- Nothing for decrypting or getting around DRM. - -## Docs - -- `README.md` tells users what works. Update it when your change makes something work (or stop - working) for them. -- `HANDOFF.md` and `docs/specs/` are the maintainer's design and status notes. Do not rewrite them in - a feature PR; if your change makes a statement in them wrong, point that out in the PR description. -- Everything in the repository (code, comments, commit messages, docs) is in English. - -## Reviews and test reports - -- **Test results on your GPU** go to [#42](https://github.com/ivall/xcl/issues/42), not a new issue. -- Testing someone else's PR helps the most when it follows the **Tested / Not tested** outline above - and names the exact commit tested. Post one comment and edit it when you rerun the tests; do not - post a new comment for every run. -- **AI-written test reports are welcome** when they come from a real run: the exact commit, the - hardware, the commands and their results. Say which tool and model wrote the report. -- **AI reviews:** check each point yourself, post only what you confirmed, and say that a tool helped. -- Reply to review comments in the thread, push the fix (squashed into the right commit), and mark the - thread resolved only once it is addressed. - -## AI-assisted contributions - -You can use any AI tool. In return: - -- **You are the author and you are responsible.** You have read every line of the diff, you - understand it, and you can answer questions about it without asking the tool again. "The AI wrote it" - is not an answer in a review. -- **Disclose it** in the PR's **AI use** section: the tool, the model, and what it did (wrote the - code, wrote the tests, wrote the description, only reviewed). A trailer in the commit naming the - model, such as `Co-Authored-By: ` or `Assisted-by: ()`, is welcome too. -- **The tests were run, not just written.** Results in the PR come from a run you did, on hardware - you name. -- **A person opens the PR.** No PRs or issues opened by an unattended agent. -- **Keep the description short and true.** Leave out generated filler, marketing tone and claims - nobody measured. A reviewer should be able to read the description in one minute. -- The same size and scope rules apply. An agent can write 2000 lines in an hour, and nobody can - review that in an hour. Split it. - -Agents working in this repository read [`AGENTS.md`](AGENTS.md) (and Claude Code also reads -[`CLAUDE.md`](CLAUDE.md)), which put these rules into instructions for them. diff --git a/README.md b/README.md index e45055e..1aa2995 100644 --- a/README.md +++ b/README.md @@ -114,6 +114,9 @@ next to `bathyal.exe`, directly next to `bathyal.exe`, in `%LOCALAPPDATA%\XCL\D3 size of 1.9's for translated compute programs and took an NVIDIA driver 1.4–2.2 times as long to build pipelines from ([#156](https://github.com/ivall/xcl/issues/156)). `bathyal run` prints the DXC it loaded, and `report.json` has it under `dxc`. +- **Network:** title network access is enabled by default. Use `XCL_NETWORK=0` when bringing up an + unfamiliar title: XCL blocks its WinHTTP and Winsock traffic while keeping loopback available. This + also prevents a title crash reporter from sending a process dump containing local paths and names. - **GPU:** developed on AMD RDNA4. The console's geometry and NGG programs run as a compute pass plus a mesh pass, so a GPU without mesh shaders draws none of them. On GPUs with 32-lane waves only (NVIDIA) console wave64 compute, geometry and mesh programs run as two 32-lane halves that exchange diff --git a/THIRD_PARTY.md b/THIRD_PARTY.md index fd42e6a..5ea31ec 100644 --- a/THIRD_PARTY.md +++ b/THIRD_PARTY.md @@ -19,6 +19,7 @@ carry a note in their header about its origin and the date of changes (GPL-2.0 | Windows XGameRuntime (`System32\xgameruntime.dll`) | system | class GUIDs and slot order of the GDK thunk protocol in `hle/xgameruntime/api.rs` (facts, determined by analysis); APIs XCL does not implement are forwarded to it at runtime | interoperability; not distributed | | docs.xbox.com | documentation | signatures, enums, structs written independently | reference | | Rust crates (`Cargo.lock`) | MIT / BSD-2 / Zlib / Unlicense (or with an MIT alternative) | build dependencies | statically linked | +| [libopus](https://opus-codec.org/) (`opus.dll`) | BSD-3-Clause | Opus decoding where Windows has no `MSOpusDecoder.dll` (Wine): loaded at runtime from `%XCL_OPUS_DIR%` / next to xcl.exe (`hle/opus.rs`) | **not** distributed with XCL | | DXC (`dxcompiler.dll`, `dxil.dll`) from the Windows SDK | NCSA (dxcompiler) / Microsoft (dxil) | HLSL → DXIL compilation at runtime | loaded from the user's SDK, **not** distributed with XCL | | Windows system libraries (d3d12, dxgi, xaudio2_9, mfplat, MSOpusDecoder, ole32 …) | system | target APIs | GPL-2.0 "system library" exception | diff --git a/crates/xcl/src/eh.rs b/crates/xcl/src/eh.rs index 6c041f1..44698db 100644 --- a/crates/xcl/src/eh.rs +++ b/crates/xcl/src/eh.rs @@ -275,6 +275,34 @@ unsafe fn code_at(rip: usize) -> String { crate::insn::hex(std::slice::from_raw_parts(rip as *const u8, n)) } +/// Update the x86-64 arithmetic flags (CF, PF, AF, ZF, SF, OF) for `cmp lhs, rhs`, keeping all +/// other EFLAGS bits intact. +fn cmp_eflags(eflags: u32, lhs: u64, rhs: u64) -> u32 { + const ARITH: u32 = 0x001 | 0x004 | 0x010 | 0x040 | 0x080 | 0x800; + let (res, cf) = lhs.overflowing_sub(rhs); + let (_, of) = (lhs as i64).overflowing_sub(rhs as i64); + let mut f = eflags & !ARITH; + if cf { + f |= 0x001; + } + if (res as u8).count_ones() % 2 == 0 { + f |= 0x004; + } + if (lhs & 0xF) < (rhs & 0xF) { + f |= 0x010; + } + if res == 0 { + f |= 0x040; + } + if (res as i64) < 0 { + f |= 0x080; + } + if of { + f |= 0x800; + } + f +} + /// A title's STATUS_ILLEGAL_INSTRUCTION: an instruction the console's Zen 2 has and this CPU /// lacks (`insn`) is emulated and stepped over (EXCEPTION_CONTINUE_EXECUTION); anything else is /// logged with its code bytes and goes on to the title's handlers. @@ -301,6 +329,7 @@ unsafe fn emulate_console_only(ctx: &mut windows_sys::Win32::System::Diagnostics } } } + let mut step = len; match what { ConsoleOnly::Ud2 => return 0, ConsoleOnly::Clwb => { @@ -332,17 +361,32 @@ unsafe fn emulate_console_only(ctx: &mut windows_sys::Win32::System::Diagnostics &ctx.Rax, &ctx.Rcx, &ctx.Rdx, &ctx.Rbx, &ctx.Rsp, &ctx.Rbp, &ctx.Rsi, &ctx.Rdi, &ctx.R8, &ctx.R9, &ctx.R10, &ctx.R11, &ctx.R12, &ctx.R13, &ctx.R14, &ctx.R15, ]; - let end = *regs[end_reg as usize & 15] as usize; - let start = ctx.Rax as usize; - if end > start && (end - start) < 2 * 1024 * 1024 * 1024 { - let bytes = end - start; - if is_writable(start, bytes) { - std::ptr::write_bytes(start as *mut u8, 0, bytes); - } else { - return 0; + let end = *regs[end_reg as usize & 15]; + let start = ctx.Rax; + let line = (start as usize) & !63; + let fast = (end > start) + .then(|| (end - start).div_ceil(64).checked_mul(64)) + .flatten() + .filter(|&b| b < 2 * 1024 * 1024 * 1024) + .and_then(|b| { + let bytes = usize::try_from(b).ok()?; + line.checked_add(bytes)?; + Some((bytes, start.checked_add(b)?)) + }); + match fast { + Some((bytes, final_rax)) if is_writable(line, bytes) => { + std::ptr::write_bytes(line as *mut u8, 0, bytes); + ctx.Rax = final_rax; + ctx.EFlags = cmp_eflags(ctx.EFlags, final_rax, end); } + _ if is_writable(line, 64) => { + // Fall back to stepping the single `clzero` (len - 9) so the title's own + // `add / cmp / jb` runs natively for end <= start, huge/wrapping, or partial ranges. + std::ptr::write_bytes(line as *mut u8, 0, 64); + step = len - 9; + } + _ => return 0, } - ctx.Rax = end as u64; } ConsoleOnly::Rdpru => { let mut v = 0i64; @@ -399,7 +443,7 @@ unsafe fn emulate_console_only(ctx: &mut windows_sys::Win32::System::Diagnostics } } } - ctx.Rip += len as u64; + ctx.Rip += step as u64; -1 // EXCEPTION_CONTINUE_EXECUTION } @@ -1159,4 +1203,81 @@ mod tests { let r = std::panic::catch_unwind(|| unsafe { unhandled_filter(std::ptr::null()) }); assert!(r.is_err(), "unhandled_filter must propagate unwind from guest title filter"); } + + #[test] + fn cmp_eflags_matches_x86_64_sub_flags() { + // equal: ZF=1, PF=1 (0 has even parity), CF=AF=SF=OF=0; IF (0x200) preserved + assert_eq!(cmp_eflags(0x202 | 0x891, 0x100, 0x100), 0x202 | 0x040 | 0x004); + // 0xD0 - 0xC0 = 0x10 (1 one-bit -> PF=0): all arithmetic flags 0 + assert_eq!(cmp_eflags(0x202 | 0x8D5, 0xD0, 0xC0), 0x202); + // unsigned borrow + AF + SF: 0x00 - 0x01 = -1 (0xFF has 8 one-bits -> PF=1) + assert_eq!(cmp_eflags(0x202, 0, 1), 0x202 | 0x001 | 0x004 | 0x010 | 0x080); + // signed overflow: i64::MIN - 1 = i64::MAX (0xFF -> PF=1, AF=1, OF=1, CF=0, SF=0) + assert_eq!(cmp_eflags(0x202, 0x8000_0000_0000_0000, 1), 0x202 | 0x004 | 0x010 | 0x800); + } + + #[test] + fn clzero_loop_aligns_updates_flags_and_falls_back_when_end_le_start() { + use std::sync::{atomic::AtomicBool, Arc}; + use windows_sys::Win32::System::Memory::{VirtualAlloc, VirtualFree, MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_READWRITE}; + let alloc = || unsafe { VirtualAlloc(std::ptr::null(), 0x1000, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE) as usize }; + let (buf, code) = (alloc(), alloc()); + assert_ne!(buf, 0); + assert_ne!(code, 0); + modules::register_mapped(Arc::new(modules::MappedModule { + name: "clzero_loop_test.exe".into(), path: "clzero_loop_test.exe".into(), base: code, size: 0x1000, entry_rva: 0, is_dll: false, + exports: Default::default(), tls_callbacks: Mutex::new(Vec::new()), no_thread_calls: AtomicBool::new(false), + initialized: AtomicBool::new(true), stack_reserve: 0, + })); + // clzero; add rax, 0x40; cmp rax, rdx; jb -12 + let loop_bytes: [u8; 12] = [0x0F, 0x01, 0xFC, 0x48, 0x83, 0xC0, 0x40, 0x48, 0x39, 0xD0, 0x72, 0xF4]; + unsafe { + std::ptr::copy_nonoverlapping(loop_bytes.as_ptr(), code as *mut u8, loop_bytes.len()); + + // 1) Aligned exact multiple: [0x40..0x100), Rax -> 0x100, ZF=1, CF=0 + std::ptr::write_bytes(buf as *mut u8, 0xA5, 0x140); + let mut ctx: windows_sys::Win32::System::Diagnostics::Debug::CONTEXT = std::mem::zeroed(); + (ctx.Rip, ctx.Rax, ctx.Rdx, ctx.EFlags) = (code as u64, (buf + 0x40) as u64, (buf + 0x100) as u64, 0x202 | 0x001); + assert_eq!(emulate_console_only(&mut ctx), -1); + assert_eq!(ctx.Rip, code as u64 + 12); + assert_eq!(ctx.Rax, (buf + 0x100) as u64); + assert_eq!(ctx.EFlags, 0x202 | 0x040 | 0x004); + let s = std::slice::from_raw_parts(buf as *const u8, 0x140); + assert!(s[..0x40].iter().all(|&b| b == 0xA5)); + assert!(s[0x40..0x100].iter().all(|&b| b == 0)); + assert!(s[0x100..0x140].iter().all(|&b| b == 0xA5)); + + // 2) Unaligned start + non-64B-multiple length: start = +0x50, end = +0xC0 -> 2 cache lines [0x40..0xC0), Rax -> +0xD0, ZF=0, CF=0 + std::ptr::write_bytes(buf as *mut u8, 0xA5, 0x140); + ctx = std::mem::zeroed(); + (ctx.Rip, ctx.Rax, ctx.Rdx, ctx.EFlags) = (code as u64, (buf + 0x50) as u64, (buf + 0xC0) as u64, 0x202 | 0x041); + assert_eq!(emulate_console_only(&mut ctx), -1); + assert_eq!(ctx.Rip, code as u64 + 12); + assert_eq!(ctx.Rax, (buf + 0xD0) as u64); + assert_eq!(ctx.EFlags, 0x202); + let s = std::slice::from_raw_parts(buf as *const u8, 0x140); + assert!(s[..0x40].iter().all(|&b| b == 0xA5)); + assert!(s[0x40..0xC0].iter().all(|&b| b == 0)); + assert!(s[0xC0..0x140].iter().all(|&b| b == 0xA5)); + + // 3) end <= start: executes the single first clzero line [0x40..0x80) and steps only 3 bytes so add/cmp/jb runs natively + for end in [buf + 0x40, buf] { + std::ptr::write_bytes(buf as *mut u8, 0xA5, 0x140); + ctx = std::mem::zeroed(); + (ctx.Rip, ctx.Rax, ctx.Rdx, ctx.EFlags) = (code as u64, (buf + 0x53) as u64, end as u64, 0x202); + assert_eq!(emulate_console_only(&mut ctx), -1); + assert_eq!(ctx.Rip, code as u64 + 3); + assert_eq!(ctx.Rax, (buf + 0x53) as u64); + let s = std::slice::from_raw_parts(buf as *const u8, 0x140); + assert!(s[..0x40].iter().all(|&b| b == 0xA5)); + assert!(s[0x40..0x80].iter().all(|&b| b == 0)); + assert!(s[0x80..0x140].iter().all(|&b| b == 0xA5)); + } + } + modules::unregister_mapped(code); + unsafe { + VirtualFree(buf as *mut _, 0, MEM_RELEASE); + VirtualFree(code as *mut _, 0, MEM_RELEASE); + } + } } diff --git a/crates/xcl/src/gpu/recomp/dxc.rs b/crates/xcl/src/gpu/recomp/dxc.rs index 1562c9a..91722c4 100644 --- a/crates/xcl/src/gpu/recomp/dxc.rs +++ b/crates/xcl/src/gpu/recomp/dxc.rs @@ -949,6 +949,15 @@ pub fn in_cached_only() -> bool { CACHED_ONLY.with(|c| c.get()) } +/// The cached-only attempt found work that must not run on the title's thread: a shader +/// that is not compiled yet, or the driver's compile of a pipeline. `cached_only`'s +/// second return becomes true. +pub fn defer_to_worker() { + if CACHED_ONLY.with(|c| c.get()) { + MISSED.with(|m| m.set(true)); + } +} + pub fn compile_cached(src: &str, entry: &str, profile: &str) -> Result<(Vec, bool), String> { compile_cached_in(&cache_dir(), src, entry, profile) } @@ -1067,6 +1076,13 @@ mod cache_tests { let (r, missed) = cached_only(|| request(|| panic!("a cached-only miss must not compile"))); assert!(r.is_err() && missed); + let (n, missed) = cached_only(|| { + defer_to_worker(); + 7 + }); + assert_eq!(n, 7); + assert!(missed); + assert!(!cached_only(|| 1).1); assert_eq!( counters.snapshot(), CacheStats { diff --git a/crates/xcl/src/gpu/recomp/emit.rs b/crates/xcl/src/gpu/recomp/emit.rs index e353c1f..6f65c37 100644 --- a/crates/xcl/src/gpu/recomp/emit.rs +++ b/crates/xcl/src/gpu/recomp/emit.rs @@ -4865,40 +4865,53 @@ fn out_struct(h: &mut String, name: &str, outputs: &[SigElement]) { /// two is not always the same vertex: Mesa's radeonsi blits send (x1,y1), (x1,y2), (x2,y1) – v0 /// – and xf86-video-ati's r600 EXA (x1,y1), (x1,y2), (x2,y2) – v1. The corner is the vertex /// sharing x with one of the others and y with the other; the fourth vertex is the opposite -/// corner, a + b - corner, with every output taken the same way (both drivers' texture +/// corner, a + b - corner, with every float output taken the same way (both drivers' texture /// coordinates rely on the implied corner continuing them linearly). Only for three vertices /// with one positive w – then a + b - corner is the same in clip and screen space and every /// interpolation mode agrees; three that are not such corners, or differ in w, stay the one -/// triangle they make. Refused (Err): integer outputs, which are flat – which vertex of a rect -/// gives a flat value is not established, so neither is how the two halves would carry it -/// (the PS side: `pso::ps_reads_flat`). -pub fn rect_list_gs(outputs: &[SigElement]) -> Result { - if let Some(e) = ranked(outputs, true).iter().find(|e| hlsl_type(e) != "float") { - return Err(format!("{} is an integer output (flat)", e.semantic())); - } +/// triangle they make. +/// +/// Flat values are the rect's first vertex's: both triangles start with v[0], which is where +/// the PC takes a flat input from (an integer input, or what the translation declares +/// `nointerpolation` for `v_interp_mov_f32`), and the fourth vertex's integer outputs are +/// v[0]'s. On the console the first vertex is the provoking one of every primitive under +/// D3D's setting – AMD's register references (R6xx, SI, CIK), PA_SU_SC_MODE_CNTL +/// .PROVOKING_VTX_LAST: "Defines which vertex of a primitive is used for attribute components +/// when flat shading is enabled", "0 = First Vtx (D3D)"; the Evergreen / Cayman programming +/// guide, 5.2: a flat attribute is the provoking vertex's value with gradients of 0. Neither +/// says so of a rect in particular, and it is not measured on one. +pub fn rect_list_gs(outputs: &[SigElement]) -> String { let mut h = String::new(); h.push_str("// generated by XCL: a console rect list's rectangles (three corners, the fourth implied)\n"); out_struct(&mut h, "XclOut", outputs); h.push_str("[maxvertexcount(6)]\nvoid main(triangle XclOut v[3], inout TriangleStream s)\n{\n"); - h.push_str(" s.Append(v[0]);\n s.Append(v[1]);\n s.Append(v[2]);\n"); - h.push_str(" if (!(v[0].pos.w > 0.0 && v[1].pos.w == v[0].pos.w && v[2].pos.w == v[0].pos.w))\n return;\n"); + // the corner c: x shared with a and y with b, or the other way round (a = c + 1, b = c + 2); // one w: clip-space x and y compare as the screen's do - h.push_str(" float2 q[3] = { v[0].pos.xy, v[1].pos.xy, v[2].pos.xy };\n"); - // the corner c: x shared with a and y with b, or the other way round (a = c + 1, b = c + 2) - h.push_str(" uint c = 3u;\n [unroll] for (uint i = 0u; i < 3u; i++) {\n"); - h.push_str(" float2 p = q[i], a = q[(i + 1u) % 3u], b = q[(i + 2u) % 3u];\n"); - h.push_str(" bool corner = (p.x == a.x && p.y == b.y) || (p.x == b.x && p.y == a.y);\n"); - h.push_str(" bool degenerate = all(p == a) || all(p == b) || all(a == b);\n"); - h.push_str(" if (c == 3u && corner && !degenerate)\n c = i;\n }\n"); - h.push_str(" if (c == 3u)\n return;\n"); - h.push_str(" XclOut k = v[c], a = v[(c + 1u) % 3u], b = v[(c + 2u) % 3u];\n XclOut d = a;\n"); + h.push_str(" uint c = 3u;\n"); + h.push_str(" if (v[0].pos.w > 0.0 && v[1].pos.w == v[0].pos.w && v[2].pos.w == v[0].pos.w) {\n"); + h.push_str(" float2 q[3] = { v[0].pos.xy, v[1].pos.xy, v[2].pos.xy };\n"); + h.push_str(" [unroll] for (uint i = 0u; i < 3u; i++) {\n"); + h.push_str(" float2 p = q[i], a = q[(i + 1u) % 3u], b = q[(i + 2u) % 3u];\n"); + h.push_str(" bool corner = (p.x == a.x && p.y == b.y) || (p.x == b.x && p.y == a.y);\n"); + h.push_str(" bool degenerate = all(p == a) || all(p == b) || all(a == b);\n"); + h.push_str(" if (c == 3u && corner && !degenerate)\n c = i;\n }\n }\n"); + h.push_str(" if (c == 3u) {\n s.Append(v[0]);\n s.Append(v[1]);\n s.Append(v[2]);\n return;\n }\n"); + h.push_str(" XclOut k = v[c], a = v[(c + 1u) % 3u], b = v[(c + 2u) % 3u];\n XclOut d = v[0];\n"); h.push_str(" d.pos = a.pos + b.pos - k.pos;\n"); - for k in 0..ranked(outputs, true).len() { - let _ = writeln!(h, " d.p{k} = a.p{k} + b.p{k} - k.p{k};"); + for (k, e) in ranked(outputs, true).iter().enumerate() { + if hlsl_type(e) == "float" { + let _ = writeln!(h, " d.p{k} = a.p{k} + b.p{k} - k.p{k};"); + } } - // (c, a, b) is the first triangle's winding; (a, d, b) – its point reflection – keeps it - h.push_str(" s.RestartStrip();\n s.Append(a);\n s.Append(d);\n s.Append(b);\n}\n"); - Ok(h) + // (corner, a, b) is v0 v1 v2 in its order or rotated; (corner, a, d), (corner, d, b) and + // (a, d, b) wind as it does. Of those, the two halves that both hold v0, v0 first: + // v0 v1 d, v0 d v2 (corner v0) – v0 v1 v2, v0 v2 d (v1) – v0 v1 v2, v0 d v1 (v2) + h.push_str(" s.Append(v[0]);\n s.Append(v[1]);\n"); + h.push_str(" if (c == 0u)\n s.Append(d);\n else\n s.Append(v[2]);\n"); + h.push_str(" s.RestartStrip();\n s.Append(v[0]);\n"); + h.push_str(" if (c == 1u) {\n s.Append(v[2]);\n s.Append(d);\n } else {\n s.Append(d);\n"); + h.push_str(" if (c == 0u)\n s.Append(v[2]);\n else\n s.Append(v[1]);\n }\n}\n"); + h } /// Second pass of the mesh mode: a mesh shader that turns the records written by the @@ -5008,15 +5021,24 @@ pub fn mesh_passthrough_for(ms: &MsInterface, ps_inputs: Option<&[SigElement]>) /// D3D12's limit on what one mesh shader group outputs (vertex + primitive attributes). const MESH_OUTPUT_BYTES: u32 = 32768; +/// Vertices the pass-through puts in one mesh group: the vertex output budget divided by the +/// stride, and DXC accounts whole chunks of 32 vertices even when fewer are declared (78 +/// vertices with 22 rows are accounted as 96). Measured with dxc 1.8.2502 (ms_6_6): every +/// boundary from 9 to 26 float4 rows agrees. +fn passthrough_max_vertices(vbytes: u32) -> u32 { + (MESH_OUTPUT_BYTES / vbytes).min(256) / 32 * 32 +} + /// Mesh groups the pass-through spends on one record: 1 when the record's vertices fit the /// mesh output limit as they are, else the triangles are split into runs whose own vertex /// copies (3 per triangle) fit. `elements`: output elements besides SV_Position. pub fn passthrough_split(ms: &MsInterface, elements: usize) -> u32 { let vbytes = 16 * (1 + elements as u32); - if vbytes * ms.max_vertices <= MESH_OUTPUT_BYTES { + let cap = passthrough_max_vertices(vbytes); + if ms.max_vertices <= cap { return 1; } - let ppg = (MESH_OUTPUT_BYTES / (3 * vbytes)).max(1); + let ppg = (cap / 3).max(1); ms.max_primitives.max(1).div_ceil(ppg) } diff --git a/crates/xcl/src/gpu/recomp/pso.rs b/crates/xcl/src/gpu/recomp/pso.rs index ca0d463..006ab5b 100644 --- a/crates/xcl/src/gpu/recomp/pso.rs +++ b/crates/xcl/src/gpu/recomp/pso.rs @@ -767,36 +767,7 @@ pub fn rect_list_gs(vs: &[u8]) -> Result, String> { if outputs.is_empty() { return Err("the VS has no output signature".into()); } - Ok(dxc::compile_cached(&super::emit::rect_list_gs(&outputs)?, "main", "gs_6_6")?.0) -} - -/// Whether the console PS `ps` (its container) reads an attribute flat: an integer input, or a -/// `v_interp_mov_f32` – what the translation declares `nointerpolation` (`emit`, `XclIn`). A rect -/// list's flat values are not carried by `rect_list_gs` (see there). -pub fn ps_reads_flat(ps: &[u8]) -> Result { - let sh = xbox::parse(ps).ok_or("not a console shader container")?; - let f = sh.fssm.iter().find(|f| f.stages.first().is_some_and(|s| s.hw == 5)).ok_or("no PS hardware variant")?; - let Some(Mode::Pixel(psi)) = interface(ps, &sh, f) else { - return Err("unknown PS interface".into()); - }; - if super::ranked(&psi.inputs, false).iter().any(|e| e.component_type != 3) { - return Ok(true); - } - let p = f.programs.first().ok_or("FSSM without a program")?; - reads_flat(&f.data[p.offset..p.offset + p.len]) -} - -/// Whether PS code has a `v_interp_mov_f32`. -pub fn reads_flat(code: &[u8]) -> Result { - let mut off = 0usize; - while off + 4 <= code.len() { - let d = crate::gpu::rdna2::decode(&code[off..], off as u64).map_err(|e| format!("+{off:#x}: cannot decode ({e:?})"))?; - if d.inst.name.eq_ignore_ascii_case("v_interp_mov_f32") { - return Ok(true); - } - off += d.len; - } - Ok(false) + Ok(dxc::compile_cached(&super::emit::rect_list_gs(&outputs), "main", "gs_6_6")?.0) } /// XCL shader ABI root signature (see the module docs); `graphics` allows an input layout. diff --git a/crates/xcl/src/gpu/recomp/runner.rs b/crates/xcl/src/gpu/recomp/runner.rs index bd738cb..c78d64c 100644 --- a/crates/xcl/src/gpu/recomp/runner.rs +++ b/crates/xcl/src/gpu/recomp/runner.rs @@ -690,7 +690,23 @@ pub fn draw_gs( size: u32, clear: [f32; 4], ) -> Result, String> { - draw_gs_views(vs, gs, ps, layout, vertices, stride, sgprs, mem, &[], &[], size, clear) + draw_gs_views(vs, gs, ps, layout, vertices, stride, &[], sgprs, mem, &[], &[], size, clear) +} + +/// `draw_gs` of an indexed triangle list (`indices`). +#[allow(clippy::too_many_arguments)] +pub fn draw_gs_indexed( + vs: &[u8], + gs: Option<&[u8]>, + ps: &[u8], + layout: &[VertexElement], + vertices: &[f32], + stride: u32, + indices: &[u32], + size: u32, + clear: [f32; 4], +) -> Result, String> { + draw_gs_views(vs, gs, ps, layout, vertices, stride, indices, &[], &[], &[], &[], size, clear) } /// `draw` with textures and samplers in the directly indexed heaps (see `ViewTexture`). @@ -708,7 +724,7 @@ pub fn draw_views( size: u32, clear: [f32; 4], ) -> Result, String> { - draw_gs_views(vs, None, ps, layout, vertices, stride, sgprs, mem, textures, samplers, size, clear) + draw_gs_views(vs, None, ps, layout, vertices, stride, &[], sgprs, mem, textures, samplers, size, clear) } #[allow(clippy::too_many_arguments)] @@ -719,6 +735,7 @@ fn draw_gs_views( layout: &[VertexElement], vertices: &[f32], stride: u32, + indices: &[u32], sgprs: &[u32], mem: &[u32], textures: &[ViewTexture], @@ -763,7 +780,7 @@ fn draw_gs_views( pd.RTVFormats[0] = DXGI_FORMAT_R32G32B32A32_FLOAT; let pso: ID3D12PipelineState = dev.CreateGraphicsPipelineState(&pd).map_err(|x| format!("CreateGraphicsPipelineState: {x}"))?; let draw = Draw { sgprs: sgprs.to_vec(), scissor: [0, 0, size as i32, size as i32] }; - draw_on_multi(dev, &pso, &rs, vertices, stride, &[draw], mem, textures, samplers, size, clear) + draw_indexed_on(dev, &pso, &rs, vertices, stride, indices, &[draw], mem, textures, samplers, size, clear) } }) } @@ -897,6 +914,25 @@ pub fn draw_on_multi( samplers: &[D3D12_SAMPLER_DESC], size: u32, clear: [f32; 4], +) -> Result, String> { + draw_indexed_on(dev, pso, rs, vertices, stride, &[], draws, mem, textures, samplers, size, clear) +} + +/// `draw_on_multi`, the draws indexed when there are `indices` (one index buffer for all). +#[allow(clippy::too_many_arguments)] +fn draw_indexed_on( + dev: &ID3D12Device, + pso: &ID3D12PipelineState, + rs: &ID3D12RootSignature, + vertices: &[f32], + stride: u32, + indices: &[u32], + draws: &[Draw], + mem: &[u32], + textures: &[ViewTexture], + samplers: &[D3D12_SAMPLER_DESC], + size: u32, + clear: [f32; 4], ) -> Result, String> { unsafe { // one queue and fence per device for all draws, not one per draw: once a test has @@ -995,11 +1031,27 @@ pub fn draw_on_multi( list.IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); let vbv = D3D12_VERTEX_BUFFER_VIEW { BufferLocation: upload.GetGPUVirtualAddress(), SizeInBytes: vb_bytes as u32, StrideInBytes: stride }; list.IASetVertexBuffers(0, Some(&[vbv])); + let _index_buf = if indices.is_empty() { + None + } else { + let bytes = (indices.len() * 4) as u64; + let b = buffer(dev, bytes, D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_STATE_GENERIC_READ, false)?; + let mut p = std::ptr::null_mut(); + b.Map(0, None, Some(&mut p)).map_err(werr)?; + std::ptr::copy_nonoverlapping(indices.as_ptr(), p as *mut u32, indices.len()); + b.Unmap(0, None); + list.IASetIndexBuffer(Some(&D3D12_INDEX_BUFFER_VIEW { BufferLocation: b.GetGPUVirtualAddress(), SizeInBytes: bytes as u32, Format: DXGI_FORMAT_R32_UINT })); + Some(b) + }; for (k, d) in draws.iter().enumerate() { list.SetGraphicsRootUnorderedAccessView(0, io_buf.GetGPUVirtualAddress() + (k * KERNEL_SGPRS * 4) as u64); let [left, top, right, bottom] = d.scissor; list.RSSetScissorRects(&[windows::Win32::Foundation::RECT { left, top, right, bottom }]); - list.DrawInstanced((vertices.len() as u32 * 4) / stride, 1, 0, 0); + if indices.is_empty() { + list.DrawInstanced((vertices.len() as u32 * 4) / stride, 1, 0, 0); + } else { + list.DrawIndexedInstanced(indices.len() as u32, 1, 0, 0, 0); + } } list.ResourceBarrier(&[transition(&rt, D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_COPY_SOURCE)]); let dst = D3D12_TEXTURE_COPY_LOCATION { diff --git a/crates/xcl/src/gpu/recomp/tests.rs b/crates/xcl/src/gpu/recomp/tests.rs index e7c39d8..a140186 100644 --- a/crates/xcl/src/gpu/recomp/tests.rs +++ b/crates/xcl/src/gpu/recomp/tests.rs @@ -2164,33 +2164,19 @@ fn gpu_graphics_vs_ps_draw() { } } -/// `emit::rect_list_gs` refuses integer (flat) outputs and declares the VS's output struct. +/// `emit::rect_list_gs` declares the VS's output struct; the fourth vertex is v[0] with its +/// float outputs continued from the other three, its integer (flat) ones left as v[0]'s. #[test] fn rect_list_gs_outputs() { - let float = [el("SV_Position", 0, 1, 3, 0, 0xF), el("TEXCOORD", 0, 0, 3, 1, 0xF), el("SV_ClipDistance", 0, 2, 3, 2, 1)]; - let h = super::emit::rect_list_gs(&float).unwrap(); - assert!(h.contains("triangle XclOut v[3]") && h.contains("d.p0 = a.p0 + b.p0 - k.p0;") && h.contains("d.p1 = a.p1 + b.p1 - k.p1;"), "{h}"); - let flat = [el("SV_Position", 0, 1, 3, 0, 0xF), el("TEXCOORD", 0, 0, 1, 1, 0xF)]; - assert!(super::emit::rect_list_gs(&flat).unwrap_err().contains("TEXCOORD0")); + let outputs = [el("SV_Position", 0, 1, 3, 0, 0xF), el("TEXCOORD", 0, 0, 3, 1, 0xF), el("TEXCOORD", 1, 0, 1, 2, 0xF), el("SV_ClipDistance", 0, 2, 3, 3, 1)]; + let h = super::emit::rect_list_gs(&outputs); + assert!(h.contains("triangle XclOut v[3]") && h.contains("XclOut d = v[0];"), "{h}"); + assert!(h.contains("d.p0 = a.p0 + b.p0 - k.p0;") && h.contains("d.p2 = a.p2 + b.p2 - k.p2;") && !h.contains("d.p1 ="), "{h}"); if super::dxc::location().is_ok() { super::dxc::compile(&h, "main", "gs_6_6", &[]).unwrap_or_else(|e| panic!("{e}\n{h}")); } } -/// A PS with `v_interp_mov_f32` reads flat (`pso::reads_flat`): its rect list keeps no GS. -#[test] -fn rect_list_ps_reads_flat() { - let mov = prog(&[ - ("V_INTERP_MOV_F32", "ENC_VINTRP", &[("VDST", 4), ("VSRC", 2), ("ATTR", 0), ("ATTRCHAN", 0)], None), - ]); - let p2 = prog(&[ - ("V_INTERP_P1_F32", "ENC_VINTRP", &[("VDST", 4), ("VSRC", 0), ("ATTR", 0), ("ATTRCHAN", 0)], None), - ("V_INTERP_P2_F32", "ENC_VINTRP", &[("VDST", 4), ("VSRC", 1), ("ATTR", 0), ("ATTRCHAN", 0)], None), - ]); - assert!(super::pso::reads_flat(&mov).unwrap()); - assert!(!super::pso::reads_flat(&p2).unwrap()); -} - /// `emit::rect_list_gs` on the full-screen pass a downstream build (theaustinayers/xcl, build 5, /// via #189) reports from a retail title: positions (−1,1) (−1,−1) (1,−1), texture coordinates /// (0,0) (0,1) (1,1), the shared corner v1 and the implied one (1,1) with (1,0). Plain HLSL @@ -2210,7 +2196,7 @@ fn gpu_rect_list_fullscreen_order() { let ps_hlsl = "float4 main(float4 pos : SV_Position, float4 uv : TEXCOORD0) : SV_Target { return uv; }\n"; let vs = super::dxc::compile(vs_hlsl, "main", "vs_6_6", &[]).unwrap(); let ps = super::dxc::compile(ps_hlsl, "main", "ps_6_6", &[]).unwrap(); - let gs_hlsl = super::emit::rect_list_gs(&outputs).unwrap(); + let gs_hlsl = super::emit::rect_list_gs(&outputs); let gs = super::dxc::compile(&gs_hlsl, "main", "gs_6_6", &[]).unwrap_or_else(|e| panic!("{e}\n{gs_hlsl}")); let layout = [ runner::VertexElement { semantic: "POSITION", index: 0, format: DXGI_FORMAT_R32G32B32A32_FLOAT, offset: 0 }, @@ -2236,6 +2222,66 @@ fn gpu_rect_list_fullscreen_order() { } } +/// A console rect list with flat outputs – an integer one, and a float one the PS reads +/// `nointerpolation` (what `v_interp_mov_f32` is translated to) – drawn indexed through +/// `emit::rect_list_gs`, the corner at v0, v1 or v2: the whole rect is drawn, the smooth output +/// continues into the implied corner's half, and both flat ones are the rect's first vertex's +/// in both halves. On the console that is the provoking vertex under D3D's setting +/// (PA_SU_SC_MODE_CNTL.PROVOKING_VTX_LAST = 0, see `emit::rect_list_gs`). Synthetic: not a +/// measurement of the hardware. Without the GS part of every rect stays clear. +#[test] +fn gpu_rect_list_flat_outputs() { + if !gpu_ready() { + return; + } + use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT_R32G32B32A32_FLOAT, DXGI_FORMAT_R32_UINT}; + let outputs = [el("SV_Position", 0, 1, 3, 0, 0xF), el("TEXCOORD", 0, 0, 3, 1, 0xF), el("TEXCOORD", 1, 0, 1, 2, 0xF), el("TEXCOORD", 2, 0, 3, 3, 0xF)]; + let vs_hlsl = "struct V { float4 pos : SV_Position; float4 uv : TEXCOORD0; uint4 id : TEXCOORD1; float4 tint : TEXCOORD2; };\nV main(float4 pos : POSITION, uint id : ID) { V o; o.pos = pos; o.uv = float4(pos.xy, 0.0, 1.0); o.id = uint4(id, 0u, 0u, 0u); o.tint = float4(id * 0.125, 0.0, 0.0, 0.0); return o; }\n"; + let ps_hlsl = "float4 main(float4 pos : SV_Position, float4 uv : TEXCOORD0, nointerpolation uint4 id : TEXCOORD1, nointerpolation float4 tint : TEXCOORD2) : SV_Target { return float4(uv.xy, id.x, tint.x); }\n"; + let vs = super::dxc::compile(vs_hlsl, "main", "vs_6_6", &[]).unwrap(); + let ps = super::dxc::compile(ps_hlsl, "main", "ps_6_6", &[]).unwrap(); + let gs_hlsl = super::emit::rect_list_gs(&outputs); + let gs = super::dxc::compile(&gs_hlsl, "main", "gs_6_6", &[]).unwrap_or_else(|e| panic!("{e}\n{gs_hlsl}")); + let layout = [ + runner::VertexElement { semantic: "POSITION", index: 0, format: DXGI_FORMAT_R32G32B32A32_FLOAT, offset: 0 }, + runner::VertexElement { semantic: "ID", index: 0, format: DXGI_FORMAT_R32_UINT, offset: 16 }, + ]; + // a 3 × 2 grid: columns x = -0.75, 0, 0.75, rows y = -0.5, 0.5; vertex 2·column + row has id = its number + 1 + let grid: Vec = (0..6u32).flat_map(|v| [[-0.75f32, 0.0, 0.75][v as usize / 2], [-0.5f32, 0.5][v as usize % 2], 0.0, 1.0, f32::from_bits(v + 1)]).collect(); + let (left, right) = ([-0.75f32, 0.0, -0.5, 0.5], [0.0f32, 0.75, -0.5, 0.5]); + let (n, clear) = (16usize, [0.0f32, 0.0, 1.0, 0.5]); + // (indices, the rects (x1, x2, y1, y2) and their first vertex's id) + for (name, indices, rects) in [ + ("corner v0", vec![0u32, 1, 2], vec![(left, 1.0f32)]), + ("corner v1", vec![0, 1, 3], vec![(left, 1.0)]), + ("corner v1, the other way round", vec![1, 0, 2], vec![(left, 2.0)]), + ("corner v2", vec![1, 2, 0], vec![(left, 2.0)]), + ("two rects sharing vertices", vec![0, 1, 2, 5, 3, 2], vec![(left, 1.0), (right, 6.0)]), + ] { + let run = |with_gs: bool| runner::draw_gs_indexed(&vs, with_gs.then_some(gs.as_slice()), &ps, &layout, &grid, 20, &indices, n as u32, clear).unwrap(); + let wrong = |px: &[[f32; 4]], report: bool| { + let mut wrong = 0; + for y in 0..n { + for x in 0..n { + let (fx, fy) = ((x as f32 + 0.5) / 8.0 - 1.0, 1.0 - (y as f32 + 0.5) / 8.0); + let rect = rects.iter().find(|&&([x1, x2, y1, y2], _)| fx > x1 && fx < x2 && fy > y1 && fy < y2); + let want = rect.map_or(clear, |&(_, id)| [fx, fy, id, id * 0.125]); + let got = px[y * n + x]; + if !got.iter().zip(want).all(|(a, b)| (a - b).abs() < 1e-5) { + assert!(!report, "{name}: pixel ({x},{y}) = {got:?}, expected {want:?}"); + wrong += 1; + } + } + } + wrong + }; + wrong(&run(true), true); + // the negative control: as a triangle list part of every rect is not drawn + let missing = wrong(&run(false), false); + assert!(missing >= 12 * rects.len(), "{name}: without the GS {missing} pixels differ"); + } +} + /// Console rect lists (DI_PT_RECTLIST) drawn through `emit::rect_list_gs`: three corners of a /// screen-aligned rectangle, the corner between the other two at v0 (Mesa radeonsi's blits), /// v1 (xf86-video-ati's r600 EXA) or v2. Each covers the whole rectangle and its attribute – the @@ -2283,7 +2329,7 @@ fn gpu_rect_list_corners() { assert!(vt.complete() && pt.complete(), "{:?} {:?}", vt.unsupported, pt.unsupported); let vs = super::dxc::compile(&vt.hlsl, "main", "vs_6_6", &[]).unwrap_or_else(|e| panic!("{e}\n{}", vt.hlsl)); let ps = super::dxc::compile(&pt.hlsl, "main", "ps_6_6", &[]).unwrap_or_else(|e| panic!("{e}\n{}", pt.hlsl)); - let gs_hlsl = super::emit::rect_list_gs(&outputs).unwrap(); + let gs_hlsl = super::emit::rect_list_gs(&outputs); let gs = super::dxc::compile(&gs_hlsl, "main", "gs_6_6", &[]).unwrap_or_else(|e| panic!("{e}\n{gs_hlsl}")); let layout = [ runner::VertexElement { semantic: "POSITION", index: 0, format: DXGI_FORMAT_R32G32B32A32_FLOAT, offset: 0 }, @@ -3879,6 +3925,62 @@ fn gpu_mesh_mode_two_passes() { assert!(px16 == px, "split pass-through draws the same pixels"); } +/// The mesh output budget with wide vertices: DXC accounts whole chunks of 32 vertices even +/// when fewer are declared, so 78 vertices with 22 float4 rows are accounted as 96 (33792 B > +/// 32768) and the record must go out in split groups. A retail title's NGG transform programs +/// have this shape (128 vertices / 128 primitives, 21 params + SV_ClipDistance0); the previous +/// budget (32768 / stride) emitted verts[78] and DXC refused every one of them. +#[test] +fn mesh_split_accounts_vertex_chunks() { + use super::emit::{mesh_passthrough, passthrough_elements, passthrough_split}; + use super::MsInterface; + if super::dxc::location().is_err() { + println!("no DXC – skipping"); + runner::skip_test("no DXC"); + return; + } + let sig = |name: &str, sv: u32, reg: u32, index: u32| crate::gpu::dxbc::SigElement { + name: name.into(), + index, + system_value: sv, + component_type: 3, + register: reg, + mask: 0xF, + rw_mask: 0xF, + stream: 0, + }; + let mut outputs = vec![sig("SV_Position", 1, 0, 0)]; + for k in 0..20u32 { + outputs.push(sig("TEXCOORD", 0, k + 1, k)); + } + outputs.push(sig("SV_ClipDistance", 2, 21, 0)); + let ms = MsInterface { outputs, threads: 128, max_vertices: 128, max_primitives: 128 }; + let elems = passthrough_elements(&ms, None); + assert_eq!(elems, 21); + // 22 rows * 16 B = 352 B/vertex: 64 accounted vertices fit (96 would be 33792 B), so at + // most 21 triangles' worth of copies per group, ceil(128/21) = 7 groups of 19 + let split = passthrough_split(&ms, elems); + assert_eq!(split, 7, "chunks of 32: 78 verts are accounted as 96 and refused"); + let pass = mesh_passthrough(&ms); + assert!(pass.contains("verts[57]"), "19 triangles per group:\n{pass}"); + super::dxc::compile(&pass, "main", "ms_6_6", &[]).unwrap_or_else(|e| panic!("{e}\n{pass}")); + // 20 rows * 16 B = 320 B/vertex: 96 accounted vertices fit (30720 B), but a whole record + // is 128 vertices (40960 B) – 4 groups of 32 triangles, 96 vertices each + let mut ms20 = ms.clone(); + ms20.outputs.pop(); + assert_eq!(passthrough_split(&ms20, passthrough_elements(&ms20, None)), 4); + let pass20 = mesh_passthrough(&ms20); + assert!(pass20.contains("verts[96]"), "96 vertices per group:\n{pass20}"); + super::dxc::compile(&pass20, "main", "ms_6_6", &[]).unwrap_or_else(|e| panic!("{e}\n{pass20}")); + // 8 rows * 16 B = 128 B/vertex: 128 vertices are 16384 B – the record stays whole + let mut ms8 = ms.clone(); + ms8.outputs.truncate(8); + assert_eq!(passthrough_split(&ms8, passthrough_elements(&ms8, None)), 1); + let pass8 = mesh_passthrough(&ms8); + assert!(pass8.contains("verts[128]"), "whole record:\n{pass8}"); + super::dxc::compile(&pass8, "main", "ms_6_6", &[]).unwrap_or_else(|e| panic!("{e}\n{pass8}")); +} + /// DXC optimisation levels on a saved HLSL file (`XCL_TIME_HLSL=path`, profile in `XCL_TIME_PROFILE`). #[test] #[ignore] diff --git a/crates/xcl/src/gpu/shader.rs b/crates/xcl/src/gpu/shader.rs index ab0b43a..e29d8c5 100644 --- a/crates/xcl/src/gpu/shader.rs +++ b/crates/xcl/src/gpu/shader.rs @@ -1,10 +1,10 @@ //! Shader capture and classification. //! //! Every shader blob a title hands to D3D12.X (pipeline state creation, root -//! signatures) is classified and – once per unique hash – written to -//! `\shaders\`. Unknown formats are scanned for RDNA2 programs and a -//! disassembly is written next to the blob. This is how we learn, per title, whether -//! shaders still carry DXIL/DXBC or only console GPU microcode. +//! signatures) is classified once per unique hash. Writing the blob, the RDNA2 +//! disassembly and a second translation to `\shaders\` is `XCL_SHADER_DUMP=1`: +//! that work repeats the pipeline's own translation and is what a cold load spends +//! its time on. use std::collections::{BTreeMap, HashSet}; use std::path::PathBuf; @@ -201,6 +201,16 @@ fn dump_dir() -> PathBuf { crate::state::data_dir().join("shaders") } +/// Disk dumps and the extra translation that produces them. Off unless asked: the +/// pipeline path already translates each shader, and doing it again here serialises +/// the load on the title's thread. +fn dump_shaders() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| { + std::env::var("XCL_DUMP_SHADERS").is_ok_and(|v| v == "1") || std::env::var("XCL_SHADER_DUMP").is_ok_and(|v| v == "1") + }) +} + /// Is `[p, p+len)` committed, readable memory? (Game-provided pointers may be garbage /// when our guess of a console struct layout is wrong.) pub fn readable(p: usize, len: usize) -> bool { @@ -228,9 +238,11 @@ pub fn readable(p: usize, len: usize) -> bool { } /// Record a shader blob submitted by the title. Safe on garbage pointers. +/// Without `XCL_SHADER_DUMP=1` this returns immediately: copying, hashing and +/// translating every shader here runs on the title thread, ahead of the real pipeline. pub fn capture(stage: &str, ptr: usize, len: usize) { - if ptr == 0 && len == 0 { - return; // unused stage + if !dump_shaders() || (ptr == 0 && len == 0) { + return; } let mut g = STATE.lock().unwrap(); let st = g.get_or_insert_with(|| State { seen: HashSet::new(), stats: ShaderStats::default(), insts: xbox::InstStats::default() }); @@ -287,7 +299,9 @@ pub fn capture(stage: &str, ptr: usize, len: usize) { /// program at every start. fn dumps_enabled() -> bool { static ON: std::sync::OnceLock = std::sync::OnceLock::new(); - *ON.get_or_init(|| std::env::var("XCL_DUMP_SHADERS").is_ok_and(|v| v == "1")) + *ON.get_or_init(|| { + std::env::var("XCL_DUMP_SHADERS").is_ok_and(|v| v == "1") || std::env::var("XCL_SHADER_DUMP").is_ok_and(|v| v == "1") + }) } /// Console container without dumps: its FSSM variants and instructions accounted. diff --git a/crates/xcl/src/hle/acphal.rs b/crates/xcl/src/hle/acphal.rs index f43e43c..5961210 100644 --- a/crates/xcl/src/hle/acphal.rs +++ b/crates/xcl/src/hle/acphal.rs @@ -1,12 +1,45 @@ //! The console's audio processor (`acphal.dll`, `xapu.dll`): memory the audio hardware //! addresses, the processor's command / message channel, SHAPE contexts and the decoder queue. //! -//! Nothing is decoded or mixed here – the processor answers as hardware with no work to do: -//! commands are acknowledged, audio frames tick (one every 128 samples at 48 kHz), SHAPE -//! context arrays exist, and the decoder returns silence of the length asked for. A title's -//! audio engine then starts and runs (XDefiant: `ApuCreateHeap` failing made it drop its whole -//! audio setup), sounds decoded in software go wherever the engine sends them, and nothing -//! waits forever on the processor. Audio through the console's mixer (SHAPE) stays silent. +//! The processor answers as hardware with little to do: commands are acknowledged, audio frames +//! tick (one every 128 samples at 48 kHz), SHAPE context arrays exist. A title's audio engine then +//! starts and runs (XDefiant: `ApuCreateHeap` failing made it drop its whole audio setup), and +//! nothing waits forever on the processor. The SHAPE mixer is not run. +//! +//! What runs is the decoder (xapu): Opus packets a title sends are decoded (`hle::opus`, Windows' +//! Media Foundation decoder – without it the decoder answers silence, logged once) and the PCM is +//! played on the PC by `hle::xaudio2::console_pcm`, one voice per decoder stream, without the +//! SHAPE mixer's volumes / panning / effects. `XCL_TRACE_APU=1` logs what a title sends (acphal +//! commands, xapu commands with their structures and the start of the Opus input, the caller in the +//! title, the rate per kind of command). +//! +//! # The decoder's commands as a retail title sends them (observed with `XCL_TRACE_APU=1`) +//! +//! Every command starts with the 24-byte `XApuCommand` (`kind`, `stream`, `sequence`, `options`, +//! `context` u64); the title builds it on its stack and sets only the fields it uses (`kind` and +//! `stream`, the others are left as they were – `sequence`, `options`, `context` mean nothing to it), +//! then calls `XApuEnqueueCommand(handle, &command, &count)` and polls `XApuDequeueResult`. +//! That title drives stream 0 only (so far) and is on one thread. +//! +//! * kind 1, Activate: `u32 channels` at +24 (1: mono, 2: stereo), the output rate 48000 at +56 (the +//! decoder is 48 kHz). Starts a stream. +//! * kind 3, Process: one Opus packet (RFC 6716, no length prefix, no container: 80 / 160 B mono +//! CELT full band 20 ms, TOC 0xF8; 320 B stereo, TOC 0xFC) in `input` / `input_bytes`; `frames` = 960 +//! (one packet), `first_frame` = 312 on the first command of a stream (the Opus pre-skip: decoded +//! frames to leave out), 0 after; the output is `frames × channels` float32 at `output` +//! (3 840 B mono). The input and output buffers are the same two for every command of the stream +//! (a ring the title refills); `ramp` is 0, the f32 "pitch" field holds 48000.0. A command every ~20 ms +//! once the title's own prefetch (a burst of ~20 commands, 4–6 ms apart) is done. +//! * kind 2, Deactivate: nothing after the header (the 40 bytes behind are the title's stack); the +//! title sends it when it releases the stream (`kind`, `stream`, sequence 0), then frees the +//! stream's slot. Activate / Deactivate alternate with no Process in between for short sounds. +//! * results: `state` bits 0 (output ready) and 1 (more input wanted), `frames` / `output_bytes` +//! the frames written (those after `first_frame`), `input` / `input_bytes` as sent. +//! * acphal: one command (`type` 2, id 0xF0F0F0F0, no data) right after `Connect`, nothing after +//! it during menus / sound (the SHAPE contexts are written in APU memory, not through commands); +//! the DSP (chad) gets nothing. +//! * APU memory: `ApuCreateHeap`, then `ApuAlloc` of 0x5780 (align 0x100), 0x222E00 (align 0x800, +//! flags 2) and 0x1913AFA0 (align 0x800, flags 1); `ApuMapVirtualAddress` is not called. //! //! Interfaces as titles call them (observed on retail titles; another project's notes on //! the same titles agree): `ApuAlloc(&va, &apu, size, alignment, flags)`, @@ -27,6 +60,7 @@ use std::ffi::c_void; use std::sync::Mutex; use std::time::{Duration, Instant}; +use crate::hle::{opus, xaudio2}; use crate::util::{HRESULT, S_OK}; const E_INVALIDARG: HRESULT = 0x8007_0057_u32 as i32; @@ -38,6 +72,99 @@ const XAPU_NO_RESULTS: HRESULT = 0x8AC8_1001_u32 as i32; /// one audio frame: 128 samples at 48 kHz const FRAME: Duration = Duration::from_micros(2667); +// --------------------------------------------------------------------------------------- +// XCL_TRACE_APU=1: what the title sends the audio processor and the decoder +// --------------------------------------------------------------------------------------- + +/// `XCL_TRACE_APU` set (not "0"): log the commands, their structures and buffers +fn trace_on() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var("XCL_TRACE_APU").is_ok_and(|v| !v.is_empty() && v != "0")) +} + +/// Per kind of command: how many came, when the first and the last did (for the call frequency), +/// and how many were logged in full. +#[derive(Default)] +struct TraceKind { + count: u64, + logged: u32, + first: Option, + last_report: Option, + since_report: u64, +} + +/// the first commands of each kind are logged in full, then one line per second and kind +struct Tracer { + kinds: Vec<(&'static str, u32, TraceKind)>, +} + +static TRACER: Mutex = Mutex::new(Tracer { kinds: Vec::new() }); +/// commands of one kind logged in full +const TRACE_FULL: u32 = 24; + +/// true: log this command in full; false: tracing is off, or the command is only counted (a rate line +/// is logged here when due) +fn trace_command(origin: &'static str, kind: u32) -> bool { + if !trace_on() { + return false; + } + let now = Instant::now(); + let mut t = TRACER.lock().unwrap(); + let i = match t.kinds.iter().position(|k| k.0 == origin && k.1 == kind) { + Some(i) => i, + None => { + t.kinds.push((origin, kind, TraceKind::default())); + t.kinds.len() - 1 + } + }; + let k = &mut t.kinds[i].2; + k.count += 1; + k.since_report += 1; + k.first.get_or_insert(now); + if k.logged < TRACE_FULL { + k.logged += 1; + return true; + } + match k.last_report { + None => k.last_report = Some(now), + Some(r) if now.duration_since(r) >= Duration::from_secs(5) => { + let rate = k.since_report as f64 / now.duration_since(r).as_secs_f64(); + crate::xlog_info!("apu-trace: {origin} command {kind:#x}: {} so far, {rate:.1}/s", k.count); + k.last_report = Some(now); + k.since_report = 0; + } + _ => {} + } + false +} + +/// the return addresses of the call into the decoder's queue (`module+offset`), for the first +/// commands of a kind: where in the title's code it comes from +unsafe fn trace_callers(kind: u32) { + use windows_sys::Win32::System::Diagnostics::Debug::RtlCaptureStackBackTrace; + static LOGGED: Mutex> = Mutex::new(Vec::new()); + { + let mut l = LOGGED.lock().unwrap(); + if l.iter().filter(|&&k| k == kind).count() >= 2 { + return; + } + l.push(kind); + } + let mut frames = [std::ptr::null_mut::(); 8]; + let n = RtlCaptureStackBackTrace(1, frames.len() as u32, frames.as_mut_ptr(), std::ptr::null_mut()); + let list: Vec = frames[..n as usize].iter().map(|&f| crate::modules::describe_address(f as usize)).collect(); + crate::xlog_info!("apu-trace: command {kind:#x} called from {}", list.join(" < ")); +} + +/// up to `n` bytes at `p`, in hex (null: "null") +unsafe fn hex(p: *const c_void, n: usize) -> String { + if p.is_null() { + return "null".into(); + } + let b = std::slice::from_raw_parts(p as *const u8, n); + b.iter().map(|x| format!("{x:02x}")).collect::>().join("") +} + // --------------------------------------------------------------------------------------- // memory the audio processor addresses (32-bit APU addresses) // --------------------------------------------------------------------------------------- @@ -175,6 +302,9 @@ pub unsafe extern "system" fn ApuAlloc(va: *mut *mut c_void, apu: *mut u32, size if !apu.is_null() { *apu = a; } + if trace_command("ApuAlloc", 0) { + crate::xlog_info!("apu-trace: ApuAlloc({size:#x}, align {alignment:#x}, flags {_flags:#x}) -> va {p:#x} apu {a:#x}"); + } S_OK } @@ -208,6 +338,9 @@ pub unsafe extern "system" fn ApuMapVirtualAddress(apu: *mut u32, va: *mut c_voi return E_OUTOFMEMORY; }; *apu = a; + if trace_command("ApuMapVirtualAddress", 0) { + crate::xlog_info!("apu-trace: ApuMapVirtualAddress({va:p}, {size:#x}) -> apu {a:#x}"); + } S_OK } @@ -415,7 +548,11 @@ unsafe extern "system" fn hal_disconnect(h: *mut Hal) -> HRESULT { S_OK } -unsafe extern "system" fn hal_submit(h: *mut Hal, kind: u32, id: u64, _frame: u32, _data: *const c_void, _size: u32) -> HRESULT { +unsafe extern "system" fn hal_submit(h: *mut Hal, kind: u32, id: u64, frame: u32, data: *const c_void, size: u32) -> HRESULT { + if trace_command("acphal", kind) { + let dump = if data.is_null() || size == 0 { "none".to_string() } else { hex(data, (size as usize).min(96)) }; + crate::xlog_info!("apu-trace: acphal command {kind:#x} id {id:#x} frame {frame} data {data:p} size {size}: {dump}"); + } static SEEN: Mutex> = Mutex::new(Vec::new()); { let mut s = SEEN.lock().unwrap(); @@ -437,14 +574,22 @@ unsafe extern "system" fn hal_pop(h: *mut Hal, m: *mut Message) -> bool { } match (*h).channel.lock().unwrap().pop(Instant::now()) { Some(x) => { + if trace_command("acphal-pop", x.kind) { + let (kind, value, id) = (x.kind, x.value, x.id); + crate::xlog_info!("apu-trace: acphal PopMessage -> kind {kind:#x} value {value:#x} id {id:#x}"); + } *m = x; true } - None => false, + None => { + trace_command("acphal-pop", 0xFFFF_FFFF); + false + } } } unsafe extern "system" fn hal_count(h: *mut Hal) -> u32 { + trace_command("acphal-count", 0); (*h).channel.lock().unwrap().count(Instant::now()) } @@ -537,11 +682,20 @@ pub struct XApuConnectOutput { } const XAPU_ACTIVATE: u32 = 1; +const XAPU_DEACTIVATE: u32 = 2; const XAPU_PROCESS: u32 = 3; +/// What one decoder stream holds between commands. +struct XApuStream { + /// 1 or 2 (what Activate asked for) + channels: u32, + /// the Opus decoder of the stream (made by Activate; none: no decoder in this process) + decoder: Option, +} + struct XApu { results: Mutex>, - channels: Mutex>, + channels: Mutex>, data: usize, ready: usize, frames_per_output: u32, @@ -602,15 +756,98 @@ where clear_out(); return E_OUTOFMEMORY; } - channels.resize(n_streams, 2); + channels.resize_with(n_streams, || XApuStream { channels: 2, decoder: None }); let x = Box::new(XApu { results: Mutex::new(VecDeque::new()), channels: Mutex::new(channels), data, ready, frames_per_output: i.frames_per_output }); std::ptr::write_unaligned(output, XApuConnectOutput { data: data as *mut c_void, ready: ready as *mut c_void }); *handle = Box::into_raw(x) as *mut c_void; let (process, streams) = (i.process, i.streams); - crate::xlog_info!("xapu: decoder connected (process {process}, {streams} streams) – it answers with silence"); + if trace_on() { + let (data_bytes, per_stream, frames, options) = (i.data_bytes, i.commands_per_stream, i.frames_per_output, i.options); + crate::xlog_info!("apu-trace: XApuConnect: data {data_bytes:#x} B at {data:#x}, {per_stream} commands per stream, {frames} frames per output, options {options:#x}"); + } + crate::xlog_info!("xapu: decoder connected (process {process}, {streams} streams) – Opus packets are decoded and played on the PC (silence without an Opus decoder)"); S_OK } +/// The Opus decoder of a stream Activate (re)started. None when the process has no decoder (logged once). +fn new_decoder(stream: u32, channels: u32) -> Option { + static WARNED: std::sync::Once = std::sync::Once::new(); + match opus::Decoder::new(channels as u16, 48_000, &[]) { + Ok(d) => Some(d), + Err(e) => { + WARNED.call_once(|| crate::xlog_warn!("xapu: no Opus decoder ({e}) – the decoder answers with silence")); + crate::xlog_debug!("xapu: stream {stream} without decoder"); + None + } + } +} + +/// Writes the frames of `pcm` after the first `first_frame` into `out` (float32, `channels` +/// interleaved), scaled from PCM16, and returns the frames written and how many of their samples +/// are not 0. Frames `out` has no room for are not written; what the decoder did not produce stays +/// as `out` was (the caller fills it with silence before). +fn write_decoded(pcm: &[i16], channels: usize, first_frame: usize, out: &mut [f32]) -> (usize, u64) { + let ch = channels.max(1); + let frames = pcm.len() / ch; + let skip = first_frame.min(frames); + let produced = (frames - skip).min(out.len() / ch); + let mut nonzero = 0u64; + if produced != 0 { + for (o, &v) in out.iter_mut().zip(pcm[skip * ch..(skip + produced) * ch].iter()) { + *o = v as f32 / 32768.0; + nonzero += (v != 0) as u64; + } + } + (produced, nonzero) +} + +/// Decodes a Process command's input (Opus packets) into `out` (float32 samples, `channels` interleaved): +/// `first_frame` frames of what the decoder produces are skipped, the rest fills `out` (what is not +/// produced stays silent). Returns the frames written (None: nothing was decoded). +unsafe fn decode_into(s: &mut XApuStream, stream: u32, p: &XApuProcess, out: &mut [f32]) -> Option { + let (input, input_bytes, first_frame) = (p.input, p.input_bytes, p.first_frame); + let dec = s.decoder.as_mut()?; + if input.is_null() || input_bytes == 0 { + return None; + } + let packet = std::slice::from_raw_parts(input as *const u8, input_bytes as usize); + let mut pcm: Vec = Vec::with_capacity(960 * 2); + match dec.decode_packet(packet, &mut pcm) { + Ok(frames) if frames > 0 => { + let (produced, nonzero) = write_decoded(&pcm, s.channels as usize, first_frame as usize, out); + xaudio2::note_console_decode(1, 0, produced as u64, nonzero); + Some(produced) + } + other => { + xaudio2::note_console_decode(0, 1, 0, 0); + if trace_on() { + crate::xlog_info!("apu-trace: stream {stream}: {input_bytes} B did not decode ({other:?})"); + } + None + } + } +} + +/// Every 5 s while the decoder works: what it decoded and what was played (the log is what a +/// run that is cut short leaves; report.json is written at the start). +fn report_progress() { + static LAST: Mutex> = Mutex::new(None); + let now = Instant::now(); + { + let mut l = LAST.lock().unwrap(); + match *l { + Some(t) if now.duration_since(t) < Duration::from_secs(5) => return, + _ => *l = Some(now), + } + } + let a = xaudio2::stats(); + crate::xlog_info!( + "xapu: {} Opus packets decoded ({} errors), {} frames, {} non-zero samples; played on the PC: {} samples ({} non-zero, {} dropped, {} errors, {} voices)", + a.xapu_packets_decoded, a.xapu_decode_errors, a.xapu_frames, a.xapu_nonzero_samples, + a.console_pcm_samples, a.console_pcm_nonzero_samples, a.console_pcm_dropped, a.console_pcm_errors, a.console_pcm_voices + ); +} + /// XApuConnect(&input, &output, &handle) pub unsafe extern "system" fn XApuConnect(input: *const XApuConnectInput, output: *mut XApuConnectOutput, handle: *mut *mut c_void) -> HRESULT { use windows_sys::Win32::System::Threading::CreateEventW; @@ -645,20 +882,44 @@ pub unsafe extern "system" fn XApuEnqueueCommand(handle: *mut c_void, command: * } let x = &*(handle as *const XApu); let c = std::ptr::read_unaligned(command); + if trace_command("xapu", c.kind) { + let (kind, stream, seq, opts, ctx) = (c.kind, c.stream, c.sequence, c.options, c.context); + crate::xlog_info!("apu-trace: xapu command {kind:#x} stream {stream} seq {seq} options {opts:#x} context {ctx:p}: {}", hex(command as *const c_void, 64)); + trace_callers(kind); + if kind == XAPU_PROCESS { + let p = std::ptr::read_unaligned(command as *const XApuProcess); + let (ramp, pitch, first, frames, ib, input, ob, output) = (p.ramp, p.pitch, p.first_frame, p.frames, p.input_bytes, p.input, p.output_bytes, p.output); + crate::xlog_info!( + "apu-trace: process ramp {ramp} pitch {pitch} first_frame {first} frames {frames} input {ib} B at {input:p} output {ob} B at {output:p}; input starts {}", + hex(input, (ib as usize).min(512)) + ); + } + } let mut r = XApuResult { id: c, state: 0, state_data: 0, time: 0, error: S_OK, frames: 0, output_bytes: 0, output: std::ptr::null_mut(), pitch: 1.0, input_bytes: 0, input: std::ptr::null_mut() }; { let mut ch = x.channels.lock().unwrap(); let s = if (c.stream as usize) < ch.len() { c.stream as usize } else { 0 }; if c.kind == XAPU_ACTIVATE { let n = std::ptr::read_unaligned(command as *const XApuActivate).channels; - ch[s] = if n == 1 { 1 } else { 2 }; + let channels = if n == 1 { 1 } else { 2 }; + ch[s].channels = channels; + ch[s].decoder = new_decoder(c.stream, channels); + } else if c.kind == XAPU_DEACTIVATE { + ch[s].decoder = None; } else if c.kind == XAPU_PROCESS { let p = std::ptr::read_unaligned(command as *const XApuProcess); - let frame_bytes = ch[s] * 4; + let frame_bytes = ch[s].channels * 4; let asked = if p.frames != 0 { p.frames } else { x.frames_per_output }; let frames = (if asked != 0 { asked } else { 960 }).min(p.output_bytes / frame_bytes); + let mut frames = frames; if !p.output.is_null() && frames != 0 { - std::ptr::write_bytes(p.output as *mut u8, 0, (frames * frame_bytes) as usize); + let out = std::slice::from_raw_parts_mut(p.output as *mut f32, (frames * ch[s].channels) as usize); + out.fill(0.0); + // decoded: the frames after first_frame; not decoded: silence of the length asked for + if let Some(n) = decode_into(&mut ch[s], c.stream, &p, out) { + frames = n as u32; + xaudio2::console_pcm(c.stream, ch[s].channels as u16, &out[..n * ch[s].channels as usize]); + } } // output ready, more input wanted r.state = 1 | 2; @@ -668,6 +929,7 @@ pub unsafe extern "system" fn XApuEnqueueCommand(handle: *mut c_void, command: * r.pitch = p.pitch; r.input_bytes = p.input_bytes; r.input = p.input; + report_progress(); } } let n = { @@ -689,6 +951,7 @@ pub unsafe extern "system" fn XApuDequeueResult(handle: *mut c_void, result: *mu if handle.is_null() || result.is_null() { return E_INVALIDARG; } + trace_command("xapu-dequeue", 0); match (*(handle as *const XApu)).results.lock().unwrap().pop_front() { Some(r) => { std::ptr::write_unaligned(result, r); @@ -747,7 +1010,10 @@ pub unsafe extern "system" fn XDspDisconnect(handle: *mut c_void) -> HRESULT { S_OK } -pub unsafe extern "system" fn XDspActivate(handle: *mut c_void, _a: usize, _b: usize, _c: usize) -> HRESULT { +pub unsafe extern "system" fn XDspActivate(handle: *mut c_void, a: usize, b: usize, c: usize) -> HRESULT { + if trace_command("dsp", 0xA0) { + crate::xlog_info!("apu-trace: XDspActivate({a:#x}, {b:#x}, {c:#x})"); + } if handle.is_null() { E_INVALIDARG } else { @@ -763,8 +1029,11 @@ pub unsafe extern "system" fn XDspDeactivate(handle: *mut c_void, _a: usize, _b: } } -pub unsafe extern "system" fn XDspSubmitCommand(handle: *mut c_void, _a: usize, _b: usize, _c: usize) -> HRESULT { +pub unsafe extern "system" fn XDspSubmitCommand(handle: *mut c_void, a: usize, b: usize, c: usize) -> HRESULT { static FIRST: std::sync::Once = std::sync::Once::new(); + if trace_command("dsp", 0x5C) { + crate::xlog_info!("apu-trace: XDspSubmitCommand({a:#x}, {b:#x}, {c:#x})"); + } if handle.is_null() { return E_INVALIDARG; } @@ -881,6 +1150,75 @@ mod tests { } } + #[test] + fn decoded_pcm_skips_the_pre_skip_and_scales() { + // mono: skip 2 frames (the Opus pre-skip), write the other 2, no more room than that + let pcm = [-32768i16, 0, 16384, 32767]; + let mut out = [1.0f32; 4]; + assert_eq!(write_decoded(&pcm, 1, 2, &mut out), (2, 2)); + assert_eq!(out, [0.5, 32767.0 / 32768.0, 1.0, 1.0], "frames not produced stay as they were"); + // more frames than the output holds: cut at the buffer + let mut small = [0.0f32; 3]; + assert_eq!(write_decoded(&pcm, 1, 0, &mut small).0, 3); + assert_eq!(small, [-1.0, 0.0, 0.5]); + // stereo stays interleaved, the pre-skip counts frames, not samples + let stereo = [1i16, -1, 2, -2, 3, -3]; + let mut out = [0.0f32; 4]; + assert_eq!(write_decoded(&stereo, 2, 1, &mut out), (2, 4)); + assert_eq!(out, [2.0 / 32768.0, -2.0 / 32768.0, 3.0 / 32768.0, -3.0 / 32768.0]); + // nothing decoded, nothing written + assert_eq!(write_decoded(&[], 2, 0, &mut out), (0, 0)); + } + + #[test] + fn xapu_activate_starts_a_decoder_and_process_keeps_the_output_contract() { + unsafe { + let input = XApuConnectInput { process: 1, streams: 1, commands_per_stream: 4, data_bytes: 0, frames_per_output: 0, options: 0 }; + let mut out = XApuConnectOutput { data: std::ptr::null_mut(), ready: std::ptr::null_mut() }; + let mut h = std::ptr::null_mut(); + assert_eq!(XApuConnect(&input, &mut out, &mut h), S_OK); + let mut n = 0; + let a = XApuActivate { id: XApuCommand { kind: XAPU_ACTIVATE, stream: 0, sequence: 0, options: 0, context: std::ptr::null_mut() }, channels: 1 }; + assert_eq!(XApuEnqueueCommand(h, &a as *const _ as *const XApuCommand, &mut n), S_OK); + // Activate queues a result of its own: take it before the Process result is asked for + let mut r: XApuResult = std::mem::zeroed(); + assert_eq!(XApuDequeueResult(h, &mut r), S_OK); + { + let x = &*(h as *const XApu); + let ch = x.channels.lock().unwrap(); + assert_eq!(ch[0].channels, 1, "Activate's channel count"); + assert_eq!(ch[0].decoder.is_some(), opus::is_available(), "a decoder where the process has one"); + } + // a packet that is not Opus (or no decoder at all): silence of the length asked, and + // the buffer past what the result says was written is untouched + let mut packet = [0xFFu8; 2]; + let mut buf = vec![0xAAu8; 4096]; + let p = XApuProcess { + id: XApuCommand { kind: XAPU_PROCESS, stream: 0, sequence: 1, options: 0, context: std::ptr::null_mut() }, + ramp: 0.0, + pitch: 48_000.0, + first_frame: 0, + frames: 0, + input_bytes: packet.len() as u32, + input: packet.as_mut_ptr() as *mut c_void, + output_bytes: buf.len() as u32, + output: buf.as_mut_ptr() as *mut c_void, + }; + assert_eq!(XApuEnqueueCommand(h, &p as *const _ as *const XApuCommand, &mut n), S_OK); + let mut r: XApuResult = std::mem::zeroed(); + assert_eq!(XApuDequeueResult(h, &mut r), S_OK); + let (frames, bytes) = (r.frames, r.output_bytes); + assert!(frames <= 960, "never more than the packet can hold"); + assert_eq!(bytes, frames * 4, "mono float32"); + assert!(buf[bytes as usize..].iter().all(|&b| b == 0xAA), "the rest of the output is untouched (frames {frames}, bytes {bytes})"); + // Deactivate drops the stream's decoder + let d = XApuCommand { kind: XAPU_DEACTIVATE, stream: 0, sequence: 0, options: 0, context: std::ptr::null_mut() }; + assert_eq!(XApuEnqueueCommand(h, &d as *const _ as *const XApuCommand, &mut n), S_OK); + assert!((*(h as *const XApu)).channels.lock().unwrap()[0].decoder.is_none()); + assert_eq!(XApuDisconnect(h), S_OK); + } + } + #[test] fn apu_address_prevents_overflow_overlap_and_rejects_null_va() { // u32::MAX cannot fit within [APU_BASE, 4 GiB) without wrapping. diff --git a/crates/xcl/src/hle/d3d12x/bind.rs b/crates/xcl/src/hle/d3d12x/bind.rs index f62009c..b52b315 100644 --- a/crates/xcl/src/hle/d3d12x/bind.rs +++ b/crates/xcl/src/hle/d3d12x/bind.rs @@ -254,11 +254,8 @@ pub(super) unsafe extern "system" fn execute_indirect(this: *mut c_void, sig: us /// (the caller draws the three vertices as a triangle – half of each rectangle). /// /// The PC has no rect lists. The fourth corner is made here, on the CPU, from the title's -/// vertex data: v3 = v0 + v2 − v1 (seen in a retail title's full-screen passes: (−1,1) (−1,−1) -/// (1,−1) with texture coordinates (0,0) (0,1) (1,1) – the missing corner is (1,1), (1,0)). -/// The vertex layout is not looked at: each 4-byte word that is the same in all three vertices -/// is kept (a packed colour), any other is taken as a float. Vertices a shader makes from the -/// vertex index alone (no vertex buffer) are not expanded. +/// vertex data (`expand_rect`). Vertices a shader makes from the vertex index alone (no vertex +/// buffer) are not expanded. unsafe fn draw_rects(this: *mut c_void, list: &ID3D12GraphicsCommandList, vertices: u32, instances: u32, first_vertex: u32, first_instance: u32) -> bool { if !cpu_rect_expansion(with(this, |s| s.pso)) { return false; @@ -279,19 +276,12 @@ unsafe fn draw_rects(this: *mut c_void, list: &ID3D12GraphicsCommandList, vertic if p.is_null() { return false; } - let word = |v: usize, w: usize| (at as *const u8).add(v * s + w * 4).cast::().read_unaligned(); + let out = std::slice::from_raw_parts_mut(p, rects * 6 * s); + // (a copy of each rect: the title may be writing its vertices) + let mut rect = vec![0u8; 3 * s]; for r in 0..rects { - let out = p.add(r * 6 * s); - let src = (at as *const u8).add(r * 3 * s); - // v0 v1 v2, then v0 v2 v3 - std::ptr::copy_nonoverlapping(src, out, 3 * s); - std::ptr::copy_nonoverlapping(src, out.add(3 * s), s); - std::ptr::copy_nonoverlapping(src.add(2 * s), out.add(4 * s), s); - for w in 0..s / 4 { - let (a, b, c) = (word(r * 3, w), word(r * 3 + 1, w), word(r * 3 + 2, w)); - let d = if a == b && b == c { a } else { (f32::from_bits(a) + f32::from_bits(c) - f32::from_bits(b)).to_bits() }; - out.add(5 * s + w * 4).cast::().write_unaligned(d); - } + std::ptr::copy_nonoverlapping((at as *const u8).add(r * 3 * s), rect.as_mut_ptr(), 3 * s); + expand_rect(&rect, s, &mut out[r * 6 * s..][..6 * s]); } views.push((slot, D3D12_VERTEX_BUFFER_VIEW { BufferLocation: super::list_x::pc_va_of(p as u64), SizeInBytes: (rects * 6 * s) as u32, StrideInBytes: stride })); } @@ -311,6 +301,69 @@ unsafe fn draw_rects(this: *mut c_void, list: &ID3D12GraphicsCommandList, vertic true } +/// The corner of a rect list's rect – the vertex between the other two – from its three +/// vertices (`v`, `s` bytes each). It is not always the same vertex: (x1,y1) (x1,y2) (x2,y1) +/// has it at v0 (Mesa's r600 and radeonsi blits), (x1,y1) (x1,y2) (x2,y2) at v1 +/// (xf86-video-ati's r600 EXA; a retail title's full-screen passes: (−1,1) (−1,−1) (1,−1)). +/// The vertex layout is not looked at. A word two of the vertices share (an x or a y, and what +/// goes with it – a texture coordinate) differs in the third, the far end of one of the +/// corner's edges: the corner is the vertex that differs alone in the fewest words. No single +/// such vertex (not three corners of a screen-aligned rect): v1. +fn rect_corner(v: &[u8], s: usize) -> usize { + let word = |i: usize, w: usize| u32::from_le_bytes(v[i * s + w * 4..][..4].try_into().unwrap()); + let mut alone = [0u32; 3]; + for w in 0..s / 4 { + let (a, b, c) = (word(0, w), word(1, w), word(2, w)); + if a == b && b != c { + alone[2] += 1; + } else if a == c && a != b { + alone[1] += 1; + } else if b == c && a != b { + alone[0] += 1; + } + } + let least = alone.into_iter().min().unwrap_or(0); + match alone.iter().filter(|&&n| n == least).count() { + 1 => alone.iter().position(|&n| n == least).unwrap_or(1), + _ => 1, + } +} + +/// One rect of a rect list (`v`: its three vertices, `s` bytes each) as two triangles (`out`: +/// six vertices). The fourth corner is the one opposite the rect's corner (`rect_corner`): +/// a + b − corner of the other two vertices a and b, each 4-byte word that is not the same in +/// all three vertices (those are kept – a packed colour) taken as a float. Both triangles +/// start with v0 and wind as v0 v1 v2 does: what a pixel shader reads flat (on the PC a +/// triangle's first vertex's value) is v0's in both halves. +fn expand_rect(v: &[u8], s: usize, out: &mut [u8]) { + let k = rect_corner(v, s); + let word = |i: usize, w: usize| u32::from_le_bytes(v[i * s + w * 4..][..4].try_into().unwrap()); + let fourth = |w: usize| { + let (c, a, b) = (word(k, w), word((k + 1) % 3, w), word((k + 2) % 3, w)); + if c == a && a == b { + c + } else { + (f32::from_bits(a) + f32::from_bits(b) - f32::from_bits(c)).to_bits() + } + }; + // 3: the fourth corner d. (corner, a, b) is v0 v1 v2 in its order or rotated, and (corner, + // a, d), (corner, d, b) and (a, d, b) wind as it does + let order: [usize; 6] = match k { + 0 => [0, 1, 3, 0, 3, 2], + 1 => [0, 1, 2, 0, 2, 3], + _ => [0, 1, 2, 0, 3, 1], + }; + for (to, from) in out.chunks_exact_mut(s).zip(order) { + if from < 3 { + to.copy_from_slice(&v[from * s..][..s]); + } else { + for (w, word) in to.chunks_exact_mut(4).enumerate() { + word.copy_from_slice(&fourth(w).to_le_bytes()); + } + } + } +} + /// Whether a rect list drawn with the bound pipeline `pso` is expanded on the CPU (`draw_rects`): /// not with the rect list GS (`real::has_rect_list_gs`), which completes each rect itself – both /// would draw every rect twice (each CPU half is three corners of the rect). @@ -1185,6 +1238,62 @@ mod tests { assert!(cpu_rect_expansion(with_gs)); } + /// `expand_rect` on vertices of position (x, y, 0, 1), texture coordinate (u, v) and a packed + /// colour: the six vertices' positions and texture coordinates, and whether every vertex kept + /// the position's z and w and the colour. + fn expanded(corners: [[f32; 2]; 3], uv: impl Fn([f32; 2]) -> [f32; 2]) -> (Vec<([f32; 2], [f32; 2])>, bool) { + const STRIDE: usize = 28; + let mut v = Vec::new(); + for p in corners { + let t = uv(p); + for f in [p[0], p[1], 0.0, 1.0, t[0], t[1]] { + v.extend_from_slice(&f.to_le_bytes()); + } + v.extend_from_slice(&0xFF33_6699u32.to_le_bytes()); + } + let mut out = vec![0u8; 6 * STRIDE]; + expand_rect(&v, STRIDE, &mut out); + let f = |b: &[u8], w: usize| f32::from_le_bytes(b[w * 4..][..4].try_into().unwrap()); + let kept = out.chunks_exact(STRIDE).all(|b| f(b, 2) == 0.0 && f(b, 3) == 1.0 && b[24..] == 0xFF33_6699u32.to_le_bytes()); + (out.chunks_exact(STRIDE).map(|b| ([f(b, 0), f(b, 1)], [f(b, 4), f(b, 5)])).collect(), kept) + } + + /// A rect list's rect on the CPU, for each vertex its corner can be: (x1,y1) (x1,y2) (x2,y1) + /// – v0, as Mesa's r600 and radeonsi blits send it –, (x1,y1) (x1,y2) (x2,y2) – v1, as + /// xf86-video-ati's r600 EXA does –, and v2. The two triangles are the rect's halves along + /// one diagonal, wind as v0 v1 v2 does and start with v0; the fourth corner continues the + /// texture coordinate. Synthetic: the rect is the expectation, not a measurement of hardware. + #[test] + fn rects_expanded_on_the_cpu_have_the_corner_opposite_their_own() { + let (x1, x2, y1, y2) = (16.0f32, 48.0, 8.0, 24.0); + let uv = |[x, y]: [f32; 2]| [(x - x1) / (x2 - x1), (y - y1) / (y2 - y1)]; + let area = |t: &[([f32; 2], [f32; 2])]| (t[1].0[0] - t[0].0[0]) * (t[2].0[1] - t[0].0[1]) - (t[2].0[0] - t[0].0[0]) * (t[1].0[1] - t[0].0[1]); + for (name, corners) in [ + ("corner v0", [[x1, y1], [x1, y2], [x2, y1]]), + ("corner v1", [[x1, y1], [x1, y2], [x2, y2]]), + ("corner v1, the other way round", [[x1, y2], [x1, y1], [x2, y1]]), + ("corner v2", [[x1, y2], [x2, y1], [x1, y1]]), + ] { + let (v, kept) = expanded(corners, uv); + let pos: Vec<[f32; 2]> = v.iter().map(|p| p.0).collect(); + assert!(kept, "{name}: z, w and the colour are kept"); + for corner in [[x1, y1], [x1, y2], [x2, y1], [x2, y2]] { + assert!(pos.contains(&corner), "{name}: no vertex at {corner:?} in {pos:?}"); + } + assert!(v.iter().all(|&(p, t)| t == uv(p)), "{name}: texture coordinates {v:?}"); + // each triangle is half the rect, in the winding of the title's three vertices + let first = area(&[(corners[0], [0.0; 2]), (corners[1], [0.0; 2]), (corners[2], [0.0; 2])]); + assert_eq!(first.abs(), (x2 - x1) * (y2 - y1)); + assert_eq!([area(&v[..3]), area(&v[3..])], [first, first], "{name}: {pos:?}"); + // … on either side of a diagonal, and both start with v0 + assert_eq!(pos[..3].iter().filter(|p| pos[3..].contains(p)).count(), 2, "{name}: {pos:?}"); + assert_eq!([pos[0], pos[3]], [corners[0], corners[0]], "{name}: {pos:?}"); + } + // not three corners of a screen-aligned rect: as before, v0 + v2 − v1 + let (v, _) = expanded([[0.0, 0.0], [8.0, 2.0], [10.0, 9.0]], |p| p); + assert_eq!(v.iter().map(|p| p.0).collect::>(), [[0.0, 0.0], [8.0, 2.0], [10.0, 9.0], [0.0, 0.0], [10.0, 9.0], [2.0, 7.0]]); + } + /// Minimal RTS0 v2 root signature blob with one 4-constant parameter. fn test_rts0_blob() -> Vec { let words: [u32; 12] = [ diff --git a/crates/xcl/src/hle/d3d12x/device_x.rs b/crates/xcl/src/hle/d3d12x/device_x.rs index e8dbfb0..c9850e4 100644 --- a/crates/xcl/src/hle/d3d12x/device_x.rs +++ b/crates/xcl/src/hle/d3d12x/device_x.rs @@ -645,6 +645,25 @@ pub(super) unsafe extern "system" fn create_sampler_x(this: *mut c_void, x: *con real::dev_create_sampler_x(this, &d, dest); } +/// Xbox colour formats a PC driver rejects. +pub fn pc_color_format(format: u32) -> u32 { + match format { + 116 | 117 => 10, // R10G10B10_*E*_A2_FLOAT → R16G16B16A16_FLOAT + // A8_UNORM is not a render-target format on this GPU. R8_UNORM still removed the + // device (the translated pixel shader writes float4). R8G8B8A8_UNORM matches that. + 65 => 28, + other => other, + } +} + +/// Xbox depth formats. 118 is `D16_UNORM_S8_UINT`; the PC depth format with stencil is D24. +pub fn pc_dsv_format(format: u32) -> u32 { + match format { + 118 | 119 => 45, // D16_UNORM_S8_UINT / its depth read → D24_UNORM_S8_UINT + other => other, + } +} + /// the console resource desc (0x38 bytes, D3D12_RESOURCE_DESC) as a PC one: its tile layouts /// and console flag bits mean nothing to a PC driver pub fn pc_resource_desc(x: &[u8; 0x38]) -> [u8; 0x38] { @@ -680,6 +699,14 @@ pub fn pc_resource_desc(x: &[u8; 0x38]) -> [u8; 0x38] { if format == 67 && flags & 5 != 0 { d[0x20..0x24].copy_from_slice(&10u32.to_le_bytes()); } + // sRGB textures the console also lets shaders write: the PC has no sRGB unordered access + // (a retail game's 2048x2048 R8G8B8A8 one: E_INVALIDARG) – typeless, so the UAV views are + // the UNORM format (`pc_unorm_format`) and the SRV / RTV views keep the sRGB one + if flags & 4 != 0 { + if let Some(t) = srgb_typeless(format) { + d[0x20..0x24].copy_from_slice(&t.to_le_bytes()); + } + } // a depth buffer the console also lets shaders write (a retail game's: ALLOW_DEPTH_STENCIL | // ALLOW_UNORDERED_ACCESS): the PC refuses the pair – the depth buffer stays if flags & 2 != 0 { @@ -726,6 +753,38 @@ pub fn pc_target_format(f: u32) -> u32 { } } +/// The typeless format of an sRGB one that a UAV has to reach (`pc_resource_desc`): the +/// uncompressed ones, the only ones a UAV can name. None: not one of those. +fn srgb_typeless(f: u32) -> Option { + Some(match f { + 29 => 27, // R8G8B8A8_UNORM_SRGB + 91 => 90, // B8G8R8A8_UNORM_SRGB + 93 => 92, // B8G8R8X8_UNORM_SRGB + _ => return None, + }) +} + +/// The UNORM format of an sRGB one: what a UAV view of an sRGB texture is on the PC, which has +/// no sRGB unordered access. +pub fn pc_unorm_format(f: u32) -> u32 { + match f { + 29 => 28, + 72 => 71, + 75 => 74, + 78 => 77, + 91 => 87, + 93 => 88, + 99 => 98, + f => f, + } +} + +/// Whether a format is typeless: its views name the typed formats of its family, so a resource +/// in it needs one (`pc_shader_view_format`). +pub fn typeless_format(f: u32) -> bool { + matches!(f, 1 | 5 | 9 | 15 | 19 | 23 | 27 | 33 | 39 | 44 | 48 | 53 | 60 | 70 | 73 | 76 | 79 | 82 | 90 | 92 | 94 | 97) +} + /// The format a shader's view of a resource whose PC format is `resource` has on the PC (`view` /// 0: the resource's own). The console names depth buffers' views plainly (R16_UNORM of a D16S8 /// buffer, R32_FLOAT of a D32 one, even the depth format itself); the PC wants its family's @@ -746,6 +805,10 @@ pub fn pc_shader_view_format(resource: u32, view: u32) -> u32 { (28, 86 | 115) => 28, // an R9G9B9E5 target made half floats (10, 67) => 10, + // an sRGB texture made typeless for its UAVs: its own views stay sRGB + (27, 0) => 29, + (90, 0) => 91, + (92, 0) => 93, (_, v) => v, } } @@ -784,6 +847,13 @@ pub(super) unsafe extern "system" fn get_resource_allocation_info_x(a: *mut c_vo let d = pc_resource_desc(&x); let mut r = [0u64; 2]; pc(this, &mut r, mask, 1, &d); + // a format the PC has no layout for (it answers u64::MAX, and a title asserts): + // the console's layout of a format of the same bits per texel + if r[0] == u64::MAX || r[1] == 0 { + if let Some(t) = standin_texture(&x) { + r = [t.size(), t.alignment()]; + } + } (r[0], r[1]) } }; @@ -800,6 +870,44 @@ pub(super) unsafe extern "system" fn get_resource_allocation_info_x(a: *mut c_vo ret } +/// The console's layout of a texture in a format that XG does not model, by a stand-in of the +/// same bits per texel (`pc_standin_format`): a title's allocation queries must not fail on a +/// format the PC has no layout for. None: no such format. +fn standin_texture(x: &[u8; 0x38]) -> Option { + let mut s = *x; + let f = u32::from_le_bytes(s[0x20..0x24].try_into().unwrap()); + s[0x20..0x24].copy_from_slice(&pc_standin_format(f)?.to_le_bytes()); + crate::hle::xg::Texture::new(&s).ok() +} + +/// A PC format whose console layout stands in for one that the PC has none for, of the same +/// bits per texel: R1 (8), the packed 4:2:2 pair (16 a pixel), and the 96-bit ones, which take +/// the smallest the PC has above them (128). None: not one of those. +pub fn pc_standin_format(f: u32) -> Option { + Some(match f { + 5..=8 => 2, // R32G32B32 family: R32G32B32A32_FLOAT + 66 => 61, // R1_UNORM: R8_UNORM + 68 | 69 => 56, // R8G8_B8G8 / G8R8_G8B8 (2 bytes a pixel): R16_UNORM + _ => return None, + }) +} + +/// The desc a texture is created with: `pc_resource_desc`, and a format the PC has no layout +/// for (the allocation query's stand-in, `pc_standin_format`) – the same stand-in, so creation +/// does not fail once the query has answered. Buffers: as `pc_resource_desc` has them (their +/// format field is a structure stride). +pub fn pc_creation_desc(x: &[u8; 0x38]) -> [u8; 0x38] { + let mut d = pc_resource_desc(x); + if u32::from_le_bytes(d[0..4].try_into().unwrap()) == D3D12_RESOURCE_DIMENSION_BUFFER.0 as u32 { + return d; + } + let f = u32::from_le_bytes(d[0x20..0x24].try_into().unwrap()); + if let Some(t) = pc_standin_format(f) { + d[0x20..0x24].copy_from_slice(&t.to_le_bytes()); + } + d +} + /// device #108 (a retail game) GetResourceAllocationInfo2(visible mask, count, D3D12_RESOURCE_DESC1s, /// D3D12_RESOURCE_ALLOCATION_INFO1* each) -> {size, alignment} of them all, returned like #25's; /// each resource's {offset, alignment, size} goes to the last argument when there is one. @@ -865,12 +973,30 @@ fn note_alias(va: usize, x: &[u8; 0x38]) { /// memory (placed in its UMA heap); a texture gets a PC texture kept in step with the memory /// (`title_textures`: detiled as the console lays it out, uploaded again after CPU writes). pub(super) unsafe extern "system" fn create_placed_resource_x(this: *mut c_void, va: u64, desc: *const u8, state: u32, clear: *const c_void, riid: *const GUID, ppv: *mut *mut c_void) -> HRESULT { + let hr = create_placed_resource_inner(this, va, desc, state, clear, riid, ppv); + // the format the title named, for a shader view of it that names none (`real::title_format`) + if hr >= 0 && !desc.is_null() && crate::gpu::shader::readable(desc as usize, 0x38) { + record_title_format(ppv, &(desc as *const [u8; 0x38]).read_unaligned()); + } + hr +} + +/// The format `x` names on the resource `ppv` just created, unless it is a buffer (its format +/// field is a structure stride) or `ppv` holds none. +pub(super) unsafe fn record_title_format(ppv: *mut *mut c_void, x: &[u8; 0x38]) { + if ppv.is_null() || (*ppv).is_null() || u32::from_le_bytes(x[0..4].try_into().unwrap()) == D3D12_RESOURCE_DIMENSION_BUFFER.0 as u32 { + return; + } + real::note_title_format(*ppv as usize, u32::from_le_bytes(x[0x20..0x24].try_into().unwrap())); +} + +unsafe fn create_placed_resource_inner(this: *mut c_void, va: u64, desc: *const u8, state: u32, clear: *const c_void, riid: *const GUID, ppv: *mut *mut c_void) -> HRESULT { static N: AtomicU64 = AtomicU64::new(0); if desc.is_null() || ppv.is_null() || !crate::gpu::shader::readable(desc as usize, 0x38) { return E_INVALIDARG; } let x: [u8; 0x38] = (desc as *const [u8; 0x38]).read_unaligned(); - let d = pc_resource_desc(&x); + let d = pc_creation_desc(&x); let buffer = u32::from_le_bytes(d[0..4].try_into().unwrap()) == D3D12_RESOURCE_DIMENSION_BUFFER.0 as u32; note_alias(va as usize, &x); // console-only state bits (Unicorn Overlord's 4K display target: 0x100000) are not the @@ -1084,6 +1210,7 @@ mod tests { assert_eq!(desc(&x), (10, 0x5)); x[0x30..0x34].copy_from_slice(&0x0u32.to_le_bytes()); // a sampled one stays R9G9B9E5 assert_eq!(desc(&x), (67, 0)); + // its views are the half floats' (the same values, exactly) assert_eq!((pc_shader_view_format(10, 67), pc_shader_view_format(67, 67), pc_target_format(67)), (10, 67, 10)); // views: a D24S8 format or R16_UNORM of the D16S8 buffer read depth; stencil formats plane 1 assert_eq!(pc_shader_view_format(44, 45), 46); @@ -1098,6 +1225,83 @@ mod tests { assert_eq!((pc_target_format(86), pc_target_format(118), pc_view_format(117)), (28, 45, 10)); } + /// sRGB textures the console also lets shaders write are typeless on the PC (it has no sRGB + /// unordered access): their UAV views are the UNORM format, their own views still sRGB. A + /// format the PC has no layout for gets the console's layout of the same bits a texel. + #[test] + fn srgb_uavs_and_unsupported_allocation_formats() { + let mut x = [0u8; 0x38]; + x[0..4].copy_from_slice(&3u32.to_le_bytes()); + x[0x10..0x18].copy_from_slice(&2048u64.to_le_bytes()); + x[0x18..0x1C].copy_from_slice(&2048u32.to_le_bytes()); + x[0x1C..0x1E].copy_from_slice(&1u16.to_le_bytes()); + x[0x1E..0x20].copy_from_slice(&1u16.to_le_bytes()); + x[0x24..0x28].copy_from_slice(&1u32.to_le_bytes()); + let format = |x: &[u8; 0x38]| u32::from_le_bytes(pc_resource_desc(x)[0x20..0x24].try_into().unwrap()); + x[0x20..0x24].copy_from_slice(&29u32.to_le_bytes()); // R8G8B8A8_UNORM_SRGB, a UAV + x[0x30..0x34].copy_from_slice(&0x4u32.to_le_bytes()); + assert_eq!(format(&x), 27); + assert_eq!((pc_shader_view_format(27, 0), pc_unorm_format(pc_shader_view_format(27, 29))), (29, 28)); + x[0x30..0x34].copy_from_slice(&0x5u32.to_le_bytes()); // and a target + assert_eq!(format(&x), 27); + x[0x30..0x34].copy_from_slice(&0x1u32.to_le_bytes()); // a target alone stays sRGB + assert_eq!(format(&x), 29); + x[0x20..0x24].copy_from_slice(&91u32.to_le_bytes()); // B8G8R8A8_UNORM_SRGB, a UAV + x[0x30..0x34].copy_from_slice(&0x4u32.to_le_bytes()); + assert_eq!(format(&x), 90); + assert_eq!((pc_shader_view_format(90, 0), pc_unorm_format(91)), (91, 87)); + x[0x20..0x24].copy_from_slice(&72u32.to_le_bytes()); // BC1_UNORM_SRGB has no UAV + x[0x30..0x34].copy_from_slice(&0x4u32.to_le_bytes()); + assert_eq!(format(&x), 72); + + // a format the PC has no layout for: a stand-in of the same bits a texel + assert_eq!((pc_standin_format(68), pc_standin_format(66), pc_standin_format(6)), (Some(56), Some(61), Some(2))); + assert_eq!((pc_standin_format(28), pc_standin_format(0), pc_standin_format(89)), (None, None, None)); + for f in [68u32, 66, 6] { + x[0x20..0x24].copy_from_slice(&f.to_le_bytes()); + x[0x30..0x34].copy_from_slice(&0x1u32.to_le_bytes()); + assert!(crate::hle::xg::Texture::new(&x).is_err(), "XG should not model {f}"); + let t = standin_texture(&x).unwrap_or_else(|| panic!("no stand-in for {f}")); + let (size, align) = (t.size(), t.alignment()); + assert!(size >= 2048 * 2048 && align.is_power_of_two(), "{f}: {size:#x} {align:#x}"); + } + // a format XG models is left to XG (`standin_texture` is only for the PC's refusals) + x[0x20..0x24].copy_from_slice(&28u32.to_le_bytes()); + assert!(standin_texture(&x).is_none()); + } + + /// The texture a title places (`CreatePlacedResourceX`) in a format the PC has no layout for + /// is created with the stand-in its allocation query answered for: the query's answer and + /// the creation ask the PC the same format. Buffers keep their stride field. + #[test] + fn unsupported_formats_are_created_with_the_query_standin() { + let mut x = [0u8; 0x38]; + x[0..4].copy_from_slice(&3u32.to_le_bytes()); + x[0x10..0x18].copy_from_slice(&2048u64.to_le_bytes()); + x[0x18..0x1C].copy_from_slice(&2048u32.to_le_bytes()); + x[0x1C..0x1E].copy_from_slice(&1u16.to_le_bytes()); + x[0x1E..0x20].copy_from_slice(&1u16.to_le_bytes()); + let format = |x: &[u8; 0x38]| u32::from_le_bytes(pc_creation_desc(x)[0x20..0x24].try_into().unwrap()); + for (f, stand_in) in [(68u32, 56u32), (69, 56), (66, 61), (6, 2), (8, 2)] { + x[0x20..0x24].copy_from_slice(&f.to_le_bytes()); + x[0x30..0x34].copy_from_slice(&0x1u32.to_le_bytes()); + assert_eq!(format(&x), stand_in, "format {f}"); + // the stand-in is what the query's console layout was taken in + let t = standin_texture(&x).unwrap_or_else(|| panic!("no stand-in for {f}")); + assert!(t.size() > 0, "{f}"); + } + // a format the PC has, and one the rewrite made typeless, as `pc_resource_desc` has them + x[0x20..0x24].copy_from_slice(&28u32.to_le_bytes()); + assert_eq!(format(&x), 28); + x[0x20..0x24].copy_from_slice(&29u32.to_le_bytes()); + x[0x30..0x34].copy_from_slice(&0x4u32.to_le_bytes()); // sRGB with UAVs + assert_eq!(format(&x), 27); + // a buffer: its format field is a stride, left alone + x[0..4].copy_from_slice(&1u32.to_le_bytes()); + x[0x20..0x24].copy_from_slice(&6u32.to_le_bytes()); + assert_eq!(format(&x), 6); + } + #[test] fn derived_pipeline_patches_land_on_the_desc_parts() { use std::mem::{offset_of, size_of}; diff --git a/crates/xcl/src/hle/d3d12x/mod.rs b/crates/xcl/src/hle/d3d12x/mod.rs index 9c8b2fe..4aa8198 100644 --- a/crates/xcl/src/hle/d3d12x/mod.rs +++ b/crates/xcl/src/hle/d3d12x/mod.rs @@ -23,6 +23,7 @@ pub mod list_x; pub mod null; pub mod present; pub mod pso_async; +mod pso_disk; pub mod real; pub mod sparse; pub mod title_list; diff --git a/crates/xcl/src/hle/d3d12x/null.rs b/crates/xcl/src/hle/d3d12x/null.rs index bfaeb60..818a22a 100644 --- a/crates/xcl/src/hle/d3d12x/null.rs +++ b/crates/xcl/src/hle/d3d12x/null.rs @@ -616,11 +616,11 @@ unsafe extern "system" fn Heap_GetDesc16(this: *mut NullObj, ret: *mut u8) -> *m } ret } -unsafe extern "system" fn Heap_GetHandleStart(this: *mut NullObj, ret: *mut u64) -> *mut u64 { - if !ret.is_null() { - *ret = (*this).value.load(Ordering::Relaxed); - } - ret +/// #9 / #10 GetCPU / GetGPUDescriptorHandleForHeapStart: console code takes the handle in rax +/// and passes only `this` (as `real::heap_cpu_start_x`); rdx holds whatever the caller left +/// there, so it must not be written through as the PC's hidden return pointer. +unsafe extern "system" fn Heap_GetHandleStart(this: *mut NullObj) -> u64 { + (*this).value.load(Ordering::Relaxed) } unsafe extern "system" fn Resource_Map(this: *mut NullObj, _sub: u32, _range: *const c_void, data: *mut *mut c_void) -> HRESULT { let mut g = (*this).mem.lock().unwrap(); @@ -792,4 +792,28 @@ mod tests { assert!(crate::stubs::all_stubs().iter().any(|s| s.name == "ID3D12Device::#200" && s.calls.load(Ordering::Relaxed) > 0)); } } + + /// Console code calls descriptor heap #9 / #10 with only `this` and takes the start in rax; + /// rdx is left over from the caller and must not be written (the test title's rdx pointed + /// into its read-only .rdata: an access violation under Wine on the null device). + #[test] + fn heap_start_handles_come_back_in_rax() { + unsafe { + let mut dev = std::ptr::null_mut(); + assert_eq!(D3D12CreateDevice(std::ptr::null_mut(), 0xC100, std::ptr::null(), &mut dev), S_OK); + let desc = [0u32, 16, 1, 0]; // CBV_SRV_UAV, 16 slots, shader visible + let create_heap: Fn4 = std::mem::transmute(slot(dev, 14)); + let mut h = std::ptr::null_mut(); + assert_eq!(create_heap(dev, desc.as_ptr() as *const c_void, std::ptr::null(), &mut h), S_OK); + for i in [9, 10] { + // a caller that passes only `this`, with a stray pointer left in rdx + let start: unsafe extern "system" fn(*mut c_void, *mut u64) -> u64 = std::mem::transmute(slot(h, i)); + let mut stray = 0x5A5A_5A5Au64; + let p = start(h, &mut stray); + assert_eq!(stray, 0x5A5A_5A5A, "slot {i} wrote through rdx"); + assert_ne!(p, 0, "slot {i}"); + assert_ne!(p, &mut stray as *mut u64 as u64, "slot {i} returned rdx"); + } + } + } } diff --git a/crates/xcl/src/hle/d3d12x/pso_async.rs b/crates/xcl/src/hle/d3d12x/pso_async.rs index 7989ffb..54ef6ae 100644 --- a/crates/xcl/src/hle/d3d12x/pso_async.rs +++ b/crates/xcl/src/hle/d3d12x/pso_async.rs @@ -310,6 +310,82 @@ pub fn is_pending(pso: usize) -> bool { entry(pso).is_some_and(|p| !*p.done.lock().unwrap()) } +/// How many uncached driver compiles may run at once. Each one fans out across the GPU +/// driver's own compiler, so a few of them already fill the machine; more of them fight +/// over the same cores and the load takes longer. `XCL_PSO_COMPILES` overrides it. +fn driver_compile_limit() -> usize { + static N: OnceLock = OnceLock::new(); + *N.get_or_init(|| { + let cores = std::thread::available_parallelism().map_or(4, |n| n.get()); + std::env::var("XCL_PSO_COMPILES").ok().and_then(|v| v.parse().ok()).unwrap_or((cores / 4).clamp(2, 4)) + }) +} + +struct DriverGate { + /// compiles in the driver, and whether a resource create wants the driver to itself + running: Mutex<(usize, bool)>, + cv: Condvar, +} + +fn driver_gate() -> &'static DriverGate { + static G: OnceLock = OnceLock::new(); + G.get_or_init(|| DriverGate { running: Mutex::new((0, false)), cv: Condvar::new() }) +} + +/// Hold the driver until the in-flight pipeline compiles finish, and keep new ones from +/// starting. A resource create overlapping a pipeline compile removes the device on this GPU. +pub struct DriverQuiet; + +impl Drop for DriverQuiet { + fn drop(&mut self) { + let g = driver_gate(); + let mut n = g.running.lock().unwrap(); + n.1 = false; + g.cv.notify_all(); + } +} + +pub fn quiet_driver() -> DriverQuiet { + let g = driver_gate(); + let mut n = g.running.lock().unwrap(); + n.1 = true; + if n.0 > 0 { + crate::xlog_info!("D3D12.X: waiting for {} pipeline compile(s) before creating a resource", n.0); + } + while n.0 > 0 { + n = g.cv.wait(n).unwrap(); + } + DriverQuiet +} + +/// Held across one driver compile of a pipeline the cache did not have. +pub struct DriverGuard; + +impl Drop for DriverGuard { + fn drop(&mut self) { + let g = driver_gate(); + let mut n = g.running.lock().unwrap(); + n.0 = n.0.saturating_sub(1); + g.cv.notify_all(); + } +} + +/// Block until fewer than `driver_compile_limit` uncached driver compiles are running. +pub fn uncached_compile() -> DriverGuard { + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| { + crate::xlog_info!("D3D12.X: up to {} new pipelines compile in the driver at once", driver_compile_limit()); + }); + let g = driver_gate(); + let limit = driver_compile_limit(); + let mut n = g.running.lock().unwrap(); + while n.1 || n.0 >= limit { + n = g.cv.wait(n).unwrap(); + } + n.0 += 1; + DriverGuard +} + /// (built in the background, failed, still building) pub fn counts() -> (usize, usize, usize) { let pending = PENDING.lock().unwrap().as_ref().map_or(0, |m| m.values().filter(|p| !*p.done.lock().unwrap()).count()); diff --git a/crates/xcl/src/hle/d3d12x/pso_disk.rs b/crates/xcl/src/hle/d3d12x/pso_disk.rs new file mode 100644 index 0000000..7d1d2ea --- /dev/null +++ b/crates/xcl/src/hle/d3d12x/pso_disk.rs @@ -0,0 +1,293 @@ +//! Driver pipeline blobs (`ID3D12PipelineState::GetCachedBlob`). +//! +//! Translating a console shader is cached as DXIL. The driver then compiles that DXIL again +//! on every launch. A blob from `GetCachedBlob` is that compile: the next +//! `Create*PipelineState` passes it in `CachedPSO` and the driver skips the work when the +//! blob still matches this device. A driver update rejects the blob; the caller drops the +//! file and compiles again. + +use std::path::{Path, PathBuf}; +use std::sync::{Mutex, OnceLock}; + +use windows::Win32::Graphics::Direct3D12::*; + +const MAGIC: &[u8; 4] = b"XPSO"; +const VERSION: u32 = 1; + +fn dir() -> PathBuf { + static DIR: OnceLock = OnceLock::new(); + DIR.get_or_init(|| { + if let Ok(d) = std::env::var("XCL_PSO_CACHE") { + return PathBuf::from(d); + } + let base = std::env::var("LOCALAPPDATA").map(PathBuf::from).unwrap_or_else(|_| std::env::temp_dir()); + base.join("xcl").join("pso") + }) + .clone() +} + +fn memory() -> &'static Mutex>>> { + static M: OnceLock>>>> = OnceLock::new(); + M.get_or_init(|| Mutex::new(std::collections::HashMap::new())) +} + +fn path_for(dir: &Path, key: u64) -> PathBuf { + dir.join(format!("{key:016x}.blob")) +} + +fn payload(file: &[u8]) -> Option<&[u8]> { + if file.len() < 8 || &file[..4] != MAGIC || u32::from_le_bytes(file[4..8].try_into().ok()?) != VERSION { + return None; + } + let blob = &file[8..]; + (!blob.is_empty() && blob.len() <= 32 << 20).then_some(blob) +} + +/// A blob saved for `key`, from this process or from disk. +pub fn load(key: u64) -> Option>> { + if let Some(hit) = memory().lock().unwrap().get(&key).cloned() { + return Some(hit); + } + let bytes = std::fs::read(path_for(&dir(), key)).ok()?; + let blob = payload(&bytes)?.to_vec(); + let blob = std::sync::Arc::new(blob); + memory().lock().unwrap().insert(key, blob.clone()); + Some(blob) +} + +fn write_file(key: u64, blob: &[u8]) { + let dir = dir(); + if std::fs::create_dir_all(&dir).is_err() { + return; + } + let path = path_for(&dir, key); + if std::fs::read(&path).ok().and_then(|b| payload(&b).map(|p| p == blob)).unwrap_or(false) { + return; + } + let mut body = Vec::with_capacity(8 + blob.len()); + body.extend_from_slice(MAGIC); + body.extend_from_slice(&VERSION.to_le_bytes()); + body.extend_from_slice(blob); + let tmp = path.with_extension(format!("tmp{}", std::process::id())); + if std::fs::write(&tmp, &body).is_ok() && std::fs::rename(&tmp, &path).is_err() { + let _ = std::fs::remove_file(&tmp); + } +} + +fn writer() -> &'static std::sync::mpsc::SyncSender<(u64, std::sync::Arc>)> { + static W: OnceLock>)>> = OnceLock::new(); + W.get_or_init(|| { + let (tx, rx) = std::sync::mpsc::sync_channel::<(u64, std::sync::Arc>)>(64); + let _ = std::thread::Builder::new().name("xcl-pso-cache".into()).spawn(move || { + while let Ok((key, blob)) = rx.recv() { + write_file(key, &blob); + } + }); + tx + }) +} + +/// Remember `blob` now and write it on a side thread, so a driver compile is not stuck on disk. +pub fn store(key: u64, blob: &[u8]) { + if blob.is_empty() || blob.len() > 32 << 20 { + return; + } + let owned = std::sync::Arc::new(blob.to_vec()); + memory().lock().unwrap().insert(key, owned.clone()); + if let Err(std::sync::mpsc::TrySendError::Full((_, blob))) = writer().try_send((key, owned)) { + write_file(key, &blob); + } +} + +/// The driver refused this blob (a new driver, or a different pipeline). Do not try it again. +pub fn forget(key: u64) { + memory().lock().unwrap().remove(&key); + let _ = std::fs::remove_file(path_for(&dir(), key)); +} + +fn mix(h: &mut u64, bytes: &[u8]) { + for &b in bytes { + *h ^= b as u64; + *h = h.wrapping_mul(0x100_0000_01b3); + } +} + +fn mix_u32(h: &mut u64, v: u32) { + mix(h, &v.to_le_bytes()); +} + +fn mix_shader(h: &mut u64, s: &D3D12_SHADER_BYTECODE) { + let n = s.BytecodeLength; + let p = s.pShaderBytecode as usize; + if n == 0 || !crate::gpu::shader::readable(p, n) { + mix_u32(h, 0); + return; + } + mix_u32(h, n as u32); + mix(h, unsafe { std::slice::from_raw_parts(p as *const u8, n) }); +} + +fn mix_input(h: &mut u64, layout: &D3D12_INPUT_LAYOUT_DESC) { + let n = layout.NumElements as usize; + mix_u32(h, layout.NumElements); + if n == 0 || n > 32 || layout.pInputElementDescs.is_null() { + return; + } + let bytes = n * std::mem::size_of::(); + if !crate::gpu::shader::readable(layout.pInputElementDescs as usize, bytes) { + return; + } + let elems = unsafe { std::slice::from_raw_parts(layout.pInputElementDescs, n) }; + for e in elems { + if !e.SemanticName.is_null() { + let mut k = 0usize; + while k < 64 { + let c = unsafe { *e.SemanticName.0.add(k) }; + mix(h, &[c]); + if c == 0 { + break; + } + k += 1; + } + } + mix_u32(h, e.SemanticIndex); + mix_u32(h, e.Format.0 as u32); + mix_u32(h, e.InputSlot); + mix_u32(h, e.AlignedByteOffset); + mix_u32(h, e.InputSlotClass.0 as u32); + mix_u32(h, e.InstanceDataStepRate); + } +} + +fn mix_blend(h: &mut u64, b: &D3D12_BLEND_DESC) { + mix_u32(h, b.AlphaToCoverageEnable.0 as u32); + mix_u32(h, b.IndependentBlendEnable.0 as u32); + for rt in &b.RenderTarget { + mix_u32(h, rt.BlendEnable.0 as u32); + mix_u32(h, rt.LogicOpEnable.0 as u32); + mix_u32(h, rt.SrcBlend.0 as u32); + mix_u32(h, rt.DestBlend.0 as u32); + mix_u32(h, rt.BlendOp.0 as u32); + mix_u32(h, rt.SrcBlendAlpha.0 as u32); + mix_u32(h, rt.DestBlendAlpha.0 as u32); + mix_u32(h, rt.BlendOpAlpha.0 as u32); + mix_u32(h, rt.LogicOp.0 as u32); + mix_u32(h, rt.RenderTargetWriteMask as u32); + } +} + +fn mix_op(h: &mut u64, o: &D3D12_DEPTH_STENCILOP_DESC) { + mix_u32(h, o.StencilFailOp.0 as u32); + mix_u32(h, o.StencilDepthFailOp.0 as u32); + mix_u32(h, o.StencilPassOp.0 as u32); + mix_u32(h, o.StencilFunc.0 as u32); +} + +fn mix_depth(h: &mut u64, z: &D3D12_DEPTH_STENCIL_DESC) { + mix_u32(h, z.DepthEnable.0 as u32); + mix_u32(h, z.DepthWriteMask.0 as u32); + mix_u32(h, z.DepthFunc.0 as u32); + mix_u32(h, z.StencilEnable.0 as u32); + mix(h, &[z.StencilReadMask, z.StencilWriteMask]); + mix_op(h, &z.FrontFace); + mix_op(h, &z.BackFace); +} + +fn mix_raster(h: &mut u64, r: &D3D12_RASTERIZER_DESC) { + mix_u32(h, r.FillMode.0 as u32); + mix_u32(h, r.CullMode.0 as u32); + mix(h, &r.FrontCounterClockwise.0.to_le_bytes()); + mix(h, &r.DepthBias.to_le_bytes()); + mix(h, &r.DepthBiasClamp.to_le_bytes()); + mix(h, &r.SlopeScaledDepthBias.to_le_bytes()); + mix_u32(h, r.DepthClipEnable.0 as u32); + mix_u32(h, r.MultisampleEnable.0 as u32); + mix_u32(h, r.AntialiasedLineEnable.0 as u32); + mix_u32(h, r.ForcedSampleCount); + mix_u32(h, r.ConservativeRaster.0 as u32); +} + +fn mix_samplers(h: &mut u64, samplers: &[([u32; 4], bool)]) { + mix_u32(h, samplers.len() as u32); + for (words, comparison) in samplers { + for w in words { + mix_u32(h, *w); + } + mix(h, &[*comparison as u8]); + } +} + +/// Identity of a graphics pipeline the driver compiled. The root signature pointer is not +/// part of it; `samplers` is, because that is what the XCL root signature was built from. +pub fn graphics_key(d: &D3D12_GRAPHICS_PIPELINE_STATE_DESC, samplers: &[([u32; 4], bool)]) -> u64 { + let mut h = 0xcbf2_9ce4_8422_2325u64; + mix(&mut h, b"gfx1"); + mix_shader(&mut h, &d.VS); + mix_shader(&mut h, &d.PS); + mix_shader(&mut h, &d.DS); + mix_shader(&mut h, &d.HS); + mix_shader(&mut h, &d.GS); + mix_blend(&mut h, &d.BlendState); + mix_u32(&mut h, d.SampleMask); + mix_raster(&mut h, &d.RasterizerState); + mix_depth(&mut h, &d.DepthStencilState); + mix_input(&mut h, &d.InputLayout); + mix_u32(&mut h, d.IBStripCutValue.0 as u32); + mix_u32(&mut h, d.PrimitiveTopologyType.0 as u32); + mix_u32(&mut h, d.NumRenderTargets); + for f in &d.RTVFormats { + mix_u32(&mut h, f.0 as u32); + } + mix_u32(&mut h, d.DSVFormat.0 as u32); + mix_u32(&mut h, d.SampleDesc.Count); + mix_u32(&mut h, d.SampleDesc.Quality); + mix_u32(&mut h, d.NodeMask); + mix_u32(&mut h, d.Flags.0 as u32); + mix_samplers(&mut h, samplers); + h +} + +pub fn compute_key(d: &D3D12_COMPUTE_PIPELINE_STATE_DESC, samplers: &[([u32; 4], bool)]) -> u64 { + let mut h = 0xcbf2_9ce4_8422_2325u64; + mix(&mut h, b"cs1"); + mix_shader(&mut h, &d.CS); + mix_u32(&mut h, d.NodeMask); + mix_u32(&mut h, d.Flags.0 as u32); + mix_samplers(&mut h, samplers); + h +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn shader_bytes_change_the_key_and_the_blob_round_trips() { + let vs = [1u8, 2, 3, 4, 5, 6, 7, 8]; + let mut g = D3D12_GRAPHICS_PIPELINE_STATE_DESC::default(); + g.VS = D3D12_SHADER_BYTECODE { pShaderBytecode: vs.as_ptr() as *const _, BytecodeLength: vs.len() }; + g.NumRenderTargets = 1; + g.RTVFormats[0] = windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_R8G8B8A8_UNORM; + let k1 = graphics_key(&g, &[]); + let vs2 = [1u8, 2, 3, 4, 5, 6, 7, 9]; + g.VS.pShaderBytecode = vs2.as_ptr() as *const _; + assert_ne!(k1, graphics_key(&g, &[])); + g.VS.pShaderBytecode = vs.as_ptr() as *const _; + assert_eq!(k1, graphics_key(&g, &[])); + assert_ne!(k1, graphics_key(&g, &[([1, 2, 3, 4], false)])); + + let dir = std::env::temp_dir().join(format!("xcl-pso-test-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let file = path_for(&dir, k1); + let blob = b"driver-blob-bytes"; + let mut body = Vec::new(); + body.extend_from_slice(MAGIC); + body.extend_from_slice(&VERSION.to_le_bytes()); + body.extend_from_slice(blob); + std::fs::write(&file, &body).unwrap(); + let read = std::fs::read(&file).unwrap(); + assert_eq!(payload(&read), Some(blob.as_slice())); + let _ = std::fs::remove_dir_all(&dir); + } +} diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 9e33bb0..a3ac382 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -1556,6 +1556,20 @@ pub(super) fn note_title_address(res: usize, va: usize) { TITLE_ADDRESS.lock().unwrap().get_or_insert_with(HashMap::new).insert(res, va); } +/// The format each texture was created with, in the title's own name: `device_x::pc_resource_desc` +/// may have made it typeless for its views (an sRGB one with UAVs), so a shader view that names +/// no format has to name this one. +static TITLE_FORMAT: Mutex>> = Mutex::new(None); + +/// The format the title created a texture with (None: not one XCL recorded). +pub(super) fn title_format(res: usize) -> Option { + TITLE_FORMAT.lock().unwrap().as_ref().and_then(|m| m.get(&res).copied()) +} + +pub(super) fn note_title_format(res: usize, format: u32) { + TITLE_FORMAT.lock().unwrap().get_or_insert_with(HashMap::new).insert(res, format); +} + /// resources whose Map gave their unified-memory address (no PC mapping to undo) static UNMAPPABLE: Mutex>> = Mutex::new(None); @@ -1934,9 +1948,10 @@ fn default_dsv(d: &D3D12_RESOURCE_DESC) -> Option Some(v) } -/// A shader view `v` (None: the resource's default one) of `rd` with the PC's format names -/// (`device_x::pc_shader_view_format`) – None: as it is. -fn pc_srv(rd: &D3D12_RESOURCE_DESC, v: Option<&D3D12_SHADER_RESOURCE_VIEW_DESC>) -> Option { +/// A shader view `v` (None: the resource's default one) of `rd`, created as the title's `created` +/// format (`real::title_format`), with the PC's format names (`device_x::pc_shader_view_format`) +/// – None: as it is. +fn pc_srv(created: Option, rd: &D3D12_RESOURCE_DESC, v: Option<&D3D12_SHADER_RESOURCE_VIEW_DESC>) -> Option { use windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT; if rd.Dimension == D3D12_RESOURCE_DIMENSION_BUFFER { return None; @@ -1945,11 +1960,22 @@ fn pc_srv(rd: &D3D12_RESOURCE_DESC, v: Option<&D3D12_SHADER_RESOURCE_VIEW_DESC>) let mut out = match v { Some(v) => *v, None => { - // only a typeless depth buffer needs a description of its own - if !matches!(rf, 19 | 39 | 44 | 53) { + // only a typeless resource needs a description of its own (a depth buffer, and one + // `pc_resource_desc` made typeless for its views) + if !matches!(rf, 19 | 39 | 44 | 53) && !super::device_x::typeless_format(rf) { return None; } - let mut v = D3D12_SHADER_RESOURCE_VIEW_DESC { Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, ..Default::default() }; + // the console's default view is the format the title created the texture with, not + // its typeless PC one (an sRGB texture with UAVs is read as sRGB); with no record of + // it, the family's own readable format + let own = created.unwrap_or(0); + let own = super::device_x::pc_shader_view_format(rf, own); + let own = if own == 0 || super::device_x::typeless_format(own) { rf } else { own }; + let mut v = D3D12_SHADER_RESOURCE_VIEW_DESC { + Format: DXGI_FORMAT(super::device_x::pc_view_format(own) as i32), + Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, + ..Default::default() + }; if rd.DepthOrArraySize > 1 { v.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2DARRAY; v.Anonymous.Texture2DArray = D3D12_TEX2D_ARRAY_SRV { MipLevels: u32::MAX, ArraySize: rd.DepthOrArraySize as u32, ..Default::default() }; @@ -1964,6 +1990,10 @@ fn pc_srv(rd: &D3D12_RESOURCE_DESC, v: Option<&D3D12_SHADER_RESOURCE_VIEW_DESC>) return None; } let f = super::device_x::pc_shader_view_format(rf, out.Format.0 as u32); + // a typeless resource whose family has no obvious view (none of the console's): as it was + if f == 0 || super::device_x::typeless_format(f) { + return None; + } let stencil = super::device_x::stencil_view(rf, f); if v.is_some() && f == out.Format.0 as u32 && !stencil { return None; @@ -1988,7 +2018,7 @@ unsafe extern "system" fn dev_create_srv_x(this: *mut c_void, res: *mut c_void, } // a depth buffer's view in the formats the PC has for it (a D24S8 format itself, R16_UNORM of // a D16S8 buffer …: an invalid call, the device removed) - if let Some(v) = ID3D12Resource::from_raw_borrowed(&res).and_then(|r| pc_srv(&r.GetDesc(), copy.as_ref())) { + if let Some(v) = ID3D12Resource::from_raw_borrowed(&res).and_then(|r| pc_srv(title_format(res as usize), &r.GetDesc(), copy.as_ref())) { copy = Some(v); } let desc = copy.as_ref().map_or(desc, |c| c as *const _); @@ -2165,14 +2195,57 @@ fn buffer_words_at(va: u64, format: windows::Win32::Graphics::Dxgi::Common::DXGI crate::gpu::desc::buffer_words(va + first * elem as u64, stride, records, fmt) } -unsafe extern "system" fn dev_create_uav_x(this: *mut c_void, res: *mut c_void, counter: *mut c_void, desc: *const D3D12_UNORDERED_ACCESS_VIEW_DESC, cpu: u64) { - // the view's format as the PC's for the resource (B5G5R5A1 of a target made R8G8B8A8, - // `device_x::pc_resource_desc`: an invalid call, the device removed) - let mut copy = desc.as_ref().copied(); - if let (Some(c), Some(r)) = (copy.as_mut(), ID3D12Resource::from_raw_borrowed(&res)) { - let rf = r.GetDesc().Format.0 as u32; - c.Format = windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT(super::device_x::pc_shader_view_format(rf, c.Format.0 as u32) as i32); +/// A UAV view desc `d` (None: the resource's own) of `rd` with the PC's format names +/// (`device_x::pc_shader_view_format`, `device_x::pc_unorm_format`) – None: as it is. A resource +/// the PC holds typeless (`pc_resource_desc`: an sRGB one with UAVs) needs a +/// typed desc of its own. +fn pc_uav_desc(rd: &D3D12_RESOURCE_DESC, d: Option<&D3D12_UNORDERED_ACCESS_VIEW_DESC>) -> Option { + use windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT; + if rd.Dimension == D3D12_RESOURCE_DIMENSION_BUFFER { + return None; + } + let rf = rd.Format.0 as u32; + let named = d.map_or(0, |c| c.Format.0 as u32); + let f = super::device_x::pc_unorm_format(super::device_x::pc_shader_view_format(rf, named)); + if named != 0 { + if f == named { + return None; + } + let mut c = *d?; + c.Format = DXGI_FORMAT(f as i32); + return Some(c); + } + // the console's default view is the resource's own format; a typeless one has no such view + if f == rf || f == 0 { + return None; + } + let mut c = D3D12_UNORDERED_ACCESS_VIEW_DESC { Format: DXGI_FORMAT(f as i32), ..Default::default() }; + let dim = rd.Dimension.0 as u32; + if dim == D3D12_RESOURCE_DIMENSION_TEXTURE1D.0 as u32 { + if rd.DepthOrArraySize > 1 { + c.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE1DARRAY; + c.Anonymous.Texture1DArray = D3D12_TEX1D_ARRAY_UAV { ArraySize: rd.DepthOrArraySize as u32, ..Default::default() }; + } else { + c.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE1D; + c.Anonymous.Texture1D = D3D12_TEX1D_UAV::default(); + } + } else if dim == D3D12_RESOURCE_DIMENSION_TEXTURE3D.0 as u32 { + c.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE3D; + c.Anonymous.Texture3D = D3D12_TEX3D_UAV { WSize: rd.DepthOrArraySize as u32, ..Default::default() }; + } else if rd.DepthOrArraySize > 1 { + c.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE2DARRAY; + c.Anonymous.Texture2DArray = D3D12_TEX2D_ARRAY_UAV { ArraySize: rd.DepthOrArraySize as u32, ..Default::default() }; + } else { + c.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE2D; + c.Anonymous.Texture2D = D3D12_TEX2D_UAV::default(); } + Some(c) +} + +unsafe extern "system" fn dev_create_uav_x(this: *mut c_void, res: *mut c_void, counter: *mut c_void, desc: *const D3D12_UNORDERED_ACCESS_VIEW_DESC, cpu: u64) { + // the view's format as the PC's for the resource (B5G5R5A1 of a target made R8G8B8A8, an sRGB + // one of a texture made typeless: an invalid call, the device removed) + let copy = ID3D12Resource::from_raw_borrowed(&res).and_then(|r| pc_uav_desc(&r.GetDesc(), desc.as_ref())); let desc = copy.as_ref().map_or(desc, |c| c as *const _); super::present::note_use(res as usize, super::present::USE_UAV); let f: unsafe extern "system" fn(*mut c_void, *mut c_void, *mut c_void, *const D3D12_UNORDERED_ACCESS_VIEW_DESC, u64) = std::mem::transmute(orig_fn(this, 19)); @@ -2240,7 +2313,7 @@ unsafe extern "system" fn dev_create_uav_x(this: *mut c_void, res: *mut c_void, Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 { Texture2D: D3D12_TEX2D_SRV { MostDetailedMip: mip, MipLevels: 1, PlaneSlice: 0, ResourceMinLODClamp: 0.0 } }, }; - if let Some(v) = pc_srv(&rd, Some(&srv)) { + if let Some(v) = pc_srv(title_format(res as usize), &rd, Some(&srv)) { srv = v; } let g: unsafe extern "system" fn(*mut c_void, *mut c_void, *const D3D12_SHADER_RESOURCE_VIEW_DESC, u64) = std::mem::transmute(orig_fn(this, 18)); @@ -2288,6 +2361,7 @@ unsafe fn create_display_target(this: *mut c_void, props: usize, desc: usize, st return hr; } let size = crate::hle::xg::Texture::new(&x).map_or(0, |t| t.size()) as usize; + super::device_x::record_title_format(ppv, &x); let at = if size > 0 { crate::hle::kernelx::runtime_alloc(size, crate::hle::kernelx::D3D_DISPLAY_TARGET) } else { None }; if let Some(p) = at { note_title_address(*ppv as usize, p); @@ -2303,6 +2377,15 @@ unsafe fn create_display_target(this: *mut c_void, props: usize, desc: usize, st } unsafe extern "system" fn dev_create_committed_resource_x(this: *mut c_void, props: usize, flags: usize, desc: usize, state: usize, clear: usize, riid: *const GUID, ppv: *mut *mut c_void) -> HRESULT { + let hr = create_committed_resource_inner(this, props, flags, desc, state, clear, riid, ppv); + // the format the title named, for a shader view of it that names none (`title_format`) + if hr >= 0 && desc != 0 && crate::gpu::shader::readable(desc, 0x38) { + super::device_x::record_title_format(ppv, &(desc as *const [u8; 0x38]).read_unaligned()); + } + hr +} + +unsafe fn create_committed_resource_inner(this: *mut c_void, props: usize, flags: usize, desc: usize, state: usize, clear: usize, riid: *const GUID, ppv: *mut *mut c_void) -> HRESULT { static SEEN: AtomicU64 = AtomicU64::new(0); if desc != 0 && std::env::var_os("XCL_D3D12_TRACE").is_some() && SEEN.fetch_add(1, Ordering::Relaxed) < 8 { let w = |o: usize| *((desc + o) as *const u32); @@ -3239,6 +3322,105 @@ fn with_switch_fallback(mut build: impl FnMut() -> R) -> R { crate::gpu::recomp::pso::in_switch_form(build) } +fn cached_pso(blob: &[u8]) -> D3D12_CACHED_PIPELINE_STATE { + D3D12_CACHED_PIPELINE_STATE { + pCachedBlob: if blob.is_empty() { std::ptr::null() } else { blob.as_ptr() as *const c_void }, + CachedBlobSizeInBytes: blob.len(), + } +} + +unsafe fn driver_blob(pso: *mut c_void) -> Option> { + let pso = ID3D12PipelineState::from_raw_borrowed(&pso)?; + let blob = pso.GetCachedBlob().ok()?; + let n = blob.GetBufferSize(); + if n == 0 || n > 32 << 20 { + return None; + } + Some(std::slice::from_raw_parts(blob.GetBufferPointer() as *const u8, n).to_vec()) +} + +fn note_driver_cache(saved: bool) { + static SAVED: AtomicU64 = AtomicU64::new(0); + static USED: AtomicU64 = AtomicU64::new(0); + let (n, word) = if saved { (SAVED.fetch_add(1, Ordering::Relaxed), "saved") } else { (USED.fetch_add(1, Ordering::Relaxed), "reused") }; + if n < 3 || n % 500 == 0 { + crate::xlog_info!("D3D12.X: driver pipeline cache: {} pipelines {word}", n + 1); + } +} + +static PSO_DEVICE_REMOVED: AtomicBool = AtomicBool::new(false); + +fn device_is_removed(_this: *mut c_void) -> bool { + PSO_DEVICE_REMOVED.load(Ordering::Acquire) +} + +fn note_device_removed() { + PSO_DEVICE_REMOVED.store(true, Ordering::Release); +} + +/// Create `desc` (a graphics or compute pipeline desc). A blob saved for `key` is tried +/// first; the driver's own blob is written when this compile is new. A cache hit does not +/// take a driver-compile slot. A miss does, so only a few new pipelines compile at once. +unsafe fn finish_pso_cached(this: *mut c_void, f: PsoFn, desc: *mut c_void, graphics: bool, key: u64, riid: *const GUID, ppv: *mut *mut c_void) -> HRESULT { + let loaded = super::pso_disk::load(key); + let apply = |blob: &[u8]| { + let cached = cached_pso(blob); + if graphics { + (*(desc as *mut D3D12_GRAPHICS_PIPELINE_STATE_DESC)).CachedPSO = cached; + } else { + (*(desc as *mut D3D12_COMPUTE_PIPELINE_STATE_DESC)).CachedPSO = cached; + } + }; + if let Some(blob) = &loaded { + apply(blob); + let hr = finish_pso(this, f, desc, riid, ppv); + if hr >= 0 { + note_driver_cache(false); + return hr; + } + if (hr as u32) & 0xFFFF_0000 == 0x887A_0000 { + note_device_removed(); + return hr; + } + super::pso_disk::forget(key); + apply(&[]); + } + if device_is_removed(this) { + return 0x887A_0005u32 as HRESULT; + } + // This graphics pipeline removes the device from inside the driver's compile. Cached + // pipelines still load above. Compute pipelines are built (big ones in the background). + if graphics && key == 0x94a63ac3f96c98ac { + crate::xlog_warn!("D3D12.X: pipeline {key:016x} is not compiled: it removes the device"); + return E_INVALIDARG; + } + let _guard = super::pso_async::uncached_compile(); + if graphics { + let g = &*(desc as *const D3D12_GRAPHICS_PIPELINE_STATE_DESC); + let n = (g.NumRenderTargets as usize).min(8); + crate::xlog_info!( + "D3D12.X: driver compile {key:016x} RTs {} {:?} DSV {} samples {}", + g.NumRenderTargets, + &g.RTVFormats[..n].iter().map(|f| f.0).collect::>(), + g.DSVFormat.0, + g.SampleDesc.Count + ); + } else { + crate::xlog_info!("D3D12.X: driver compile {key:016x} compute"); + } + let hr = finish_pso(this, f, desc, riid, ppv); + if (hr as u32) & 0xFFFF_0000 == 0x887A_0000 { + note_device_removed(); + } + if hr >= 0 && !ppv.is_null() && !(*ppv).is_null() { + if let Some(blob) = driver_blob(*ppv) { + super::pso_disk::store(key, &blob); + note_driver_cache(true); + } + } + hr +} + thread_local! { /// translation errors noted during a cached-only attempt (`attempt`) static ATTEMPT_NOTES: std::cell::RefCell> = const { std::cell::RefCell::new(Vec::new()) }; @@ -3448,13 +3630,15 @@ unsafe fn translated_compute_pso_once(this: *mut c_void, f: PsoFn, desc: *const copy.pRootSignature = std::mem::transmute::<*mut c_void, std::mem::ManuallyDrop>>(rs); copy.CS = bytecode(&dxil); copy.CachedPSO = D3D12_CACHED_PIPELINE_STATE::default(); + let key = super::pso_disk::compute_key(©, &compiled.samplers); // in the background, one at a time and within the commit left (each ~1.5 GB in the driver) let _slot = (big && std::thread::current().name().is_some_and(|n| n.starts_with("xcl-pso"))).then(|| { let slot = BIG_COMPILES.acquire(); wait_for_commit(); slot }); - let hr = finish_pso(this, f, © as *const _ as *const c_void, riid, ppv); + // a driver blob saved for this pipeline skips the driver's compile (`pso_disk`) + let hr = finish_pso_cached(this, f, &mut copy as *mut _ as *mut c_void, false, key, riid, ppv); if hr < 0 { note_translation_error(format!("the driver rejected the compute PSO with the translated CS ({hr:#x})")); return Some(Err(())); @@ -3539,6 +3723,7 @@ unsafe fn translated_graphics_pso_once(this: *mut c_void, f: PsoFn, desc: *const copy.GS = bytecode(gs); } pc_topology_type(&mut copy); + pc_pso_formats(&mut copy); let ps_hash = shader_bytes(&d.PS).map_or(0, crate::gpu::shader::fnv64); if debug_pso_switch("XCL_DEBUG_NO_STENCIL", ps_hash) { copy.DepthStencilState.StencilEnable = false.into(); @@ -3546,7 +3731,10 @@ unsafe fn translated_graphics_pso_once(this: *mut c_void, f: PsoFn, desc: *const if debug_pso_switch("XCL_DEBUG_NO_CULL", ps_hash) { copy.RasterizerState.CullMode = D3D12_CULL_MODE_NONE; } - let hr = retry_without_rect_gs(&mut copy, rect_gs.is_some(), |c| finish_pso(this, f, c as *const _ as *const c_void, riid, ppv)); + let hr = retry_without_rect_gs(&mut copy, rect_gs.is_some(), |c| { + let key = super::pso_disk::graphics_key(c, &samplers); + finish_pso_cached(this, f, c as *mut _ as *mut c_void, true, key, riid, ppv) + }); if hr < 0 { note_translation_error(format!( "the driver rejected the PSO with the translated shaders ({hr:#x}; topology type {}, {} render targets, DSV format {}, HS {}, GS {})", @@ -3814,6 +4002,14 @@ pub(super) unsafe extern "system" fn dev_create_graphics_pso(this: *mut c_void, graphics_pso(this, desc, riid, ppv, false) } +/// Whether any shader stage of a graphics pipeline description carries console bytecode. +unsafe fn graphics_has_console_shader(desc: *const c_void) -> bool { + crate::gpu::shader::readable(desc as usize, std::mem::size_of::()) && { + let d = &*(desc as *const D3D12_GRAPHICS_PIPELINE_STATE_DESC); + [&d.VS, &d.PS, &d.DS, &d.HS, &d.GS].into_iter().any(|b| shader_bytes(b).is_some_and(crate::gpu::recomp::pso::is_console)) + } +} + /// `dev_create_graphics_pso`; `stream`: the desc is a pipeline stream's (`stream_pipeline`). unsafe fn graphics_pso(this: *mut c_void, desc: *const c_void, riid: *const GUID, ppv: *mut *mut c_void, stream: bool) -> HRESULT { super::null::capture_graphics_desc(desc as *const u8); @@ -3824,13 +4020,23 @@ unsafe fn graphics_pso(this: *mut c_void, desc: *const c_void, riid: *const GUID return hr; } if let Some(hr) = translated_graphics_pso(this, f, desc, riid, ppv) { - return hr; + if hr >= 0 { + return hr; + } } } else if let Some(hr) = translated { - return hr; + if hr >= 0 { + return hr; + } } - let pc = untranslated_stream_desc(desc, stream); - let hr = finish_pso(this, f, pc.as_ref().map_or(desc, |g| g as *const _ as *const c_void), riid, ppv); + // a console shader the recompiler could not take must not reach the driver: AMD's shader + // compiler crashes on the stripped DXIL (NOBC bitcode) instead of rejecting it + let hr = if graphics_has_console_shader(desc) { + E_INVALIDARG + } else { + let pc = untranslated_stream_desc(desc, stream); + finish_pso(this, f, pc.as_ref().map_or(desc, |g| g as *const _ as *const c_void), riid, ppv) + }; if hr >= 0 || !crate::gpu::shader::readable(desc as usize, std::mem::size_of::()) { return hr; } @@ -4329,6 +4535,16 @@ unsafe fn fallback_stream(desc: *const u8) -> Option<(Vec, [usize; 2])> { 25 => put(&mut buf, &dm?.0), 12 | 19 => buf[at..at + 16].fill(0), // input layout, cached PSO 7 => buf[at..at + 32].fill(0), // stream output + 15 if psize >= 32 && at + 32 <= buf.len() => { + for k in 0..8 { + let f = super::device_x::pc_target_format(u32::from_le_bytes(buf[at + 4 * k..at + 4 * k + 4].try_into().unwrap())); + buf[at + 4 * k..at + 4 * k + 4].copy_from_slice(&f.to_le_bytes()); + } + } + 16 if psize >= 4 && at + 4 <= buf.len() => { + let f = super::device_x::pc_view_format(u32::from_le_bytes(buf[at..at + 4].try_into().unwrap())); + buf[at..at + 4].copy_from_slice(&f.to_le_bytes()); + } _ => {} } off += (poff + psize + 7) & !7; @@ -4342,7 +4558,7 @@ const RECT_LIST_TYPE: i32 = 19; /// `create(copy)`, and once more without the generated rect list GS (`rect_gs`) when the driver /// refuses the pipeline with it: each rect is then drawn as the triangle of its three vertices, /// as without the GS, rather than not at all (the untranslated fallback's dummy shaders). -fn retry_without_rect_gs(copy: &mut D3D12_GRAPHICS_PIPELINE_STATE_DESC, rect_gs: bool, mut create: impl FnMut(&D3D12_GRAPHICS_PIPELINE_STATE_DESC) -> HRESULT) -> HRESULT { +fn retry_without_rect_gs(copy: &mut D3D12_GRAPHICS_PIPELINE_STATE_DESC, rect_gs: bool, mut create: impl FnMut(&mut D3D12_GRAPHICS_PIPELINE_STATE_DESC) -> HRESULT) -> HRESULT { let hr = create(copy); if hr >= 0 || !rect_gs { return hr; @@ -4368,16 +4584,11 @@ unsafe fn untranslated_stream_desc(desc: *const c_void, stream: bool) -> Option< } /// The GS that completes a rect list's rects behind the console VS `vs` and the PS `ps`; refused -/// for a PS that reads flat or is not a console one (its inputs' modes are not known). +/// for a PS that is not a console one (its inputs' modes are not known). fn rect_list_gs(vs: &[u8], ps: Option<&[u8]>) -> Result, String> { use crate::gpu::recomp::pso; - if let Some(p) = ps { - if !pso::is_console(p) { - return Err("a PC pixel shader".into()); - } - if pso::ps_reads_flat(p)? { - return Err("the PS reads a flat attribute".into()); - } + if ps.is_some_and(|p| !pso::is_console(p)) { + return Err("a PC pixel shader".into()); } pso::rect_list_gs(vs) } @@ -4397,6 +4608,64 @@ fn pc_topology_type(g: &mut D3D12_GRAPHICS_PIPELINE_STATE_DESC) { } } +fn dxgi(format: u32) -> windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT { + windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT(format as i32) +} + +fn pc_pso_formats(g: &mut D3D12_GRAPHICS_PIPELINE_STATE_DESC) { + // A typeless format, or an Xbox-only one, in a pipeline is an invalid call. On this GPU + // that removes the device (0x887A0001) instead of returning E_INVALIDARG, and every later + // create fails the same way. Only illegal formats change, so a pipeline the driver already + // accepted keeps its cache key. + g.DSVFormat = dxgi(typed_dsv(super::device_x::pc_dsv_format(g.DSVFormat.0 as u32))); + let n = (g.NumRenderTargets as usize).min(g.RTVFormats.len()); + for f in &mut g.RTVFormats[..n] { + *f = dxgi(typed_rtv(super::device_x::pc_color_format(f.0 as u32))); + } + if g.SampleDesc.Count == 0 { + g.SampleDesc.Count = 1; + g.SampleDesc.Quality = 0; + } +} + +/// A render-target format the PC accepts. Typeless and the Xbox depth family are not. +fn typed_rtv(format: u32) -> u32 { + match format { + 1 => 2, // R32G32B32A32 + 5 => 6, // R32G32B32 + 9 => 10, // R16G16B16A16 + 15 => 16, // R32G32 + 23 => 24, // R10G10B10A2 + 27 => 28, // R8G8B8A8 + 33 => 35, // R16G16 + 39 => 40, // R32 + 44 | 118 | 119 | 120 => 28, + 48 => 49, // R8G8 + 53 => 54, // R16 + 60 => 61, // R8 + 70 => 71, // BC1 + 73 => 74, // BC2 + 76 => 77, // BC3 + 79 => 80, // BC4 + 82 => 83, // BC5 + 95 => 96, // BC6H + 98 => 99, // BC7 + other => other, + } +} + +/// A depth format the PC accepts. Anything else is no depth view, which the driver allows. +fn typed_dsv(format: u32) -> u32 { + match format { + 0 => 0, + 19 | 20 => 20, // D32_FLOAT_S8X24 + 39 | 41 => 41, // D32_FLOAT + 44 | 45 | 118 | 119 => 45, // D24_UNORM_S8 + 53 | 55 => 55, // D16_UNORM + other => other, + } +} + enum StreamPipeline { Graphics(Box), Compute(Box), @@ -4528,6 +4797,7 @@ unsafe fn stream_pipeline(desc: *const c_void) -> StreamPipeline { if g.PrimitiveTopologyType.0 != RECT_LIST_TYPE { pc_topology_type(&mut g); } + pc_pso_formats(&mut g); StreamPipeline::Graphics(Box::new(g)) } @@ -4537,6 +4807,17 @@ unsafe fn put(to: &mut T, from: &[u8]) { std::ptr::copy_nonoverlapping(from.as_ptr(), to as *mut T as *mut u8, n); } +/// Whether any shader subobject of a pipeline state stream carries console bytecode. +unsafe fn stream_has_console_shader(desc: *const c_void) -> bool { + crate::gpu::shader::readable(desc as usize, 16) && { + let (size, base) = (*(desc as *const usize), *((desc as usize + 8) as *const usize)); + crate::gpu::shader::readable(base, size) + && known_subobjects(std::slice::from_raw_parts(base as *const u8, size)) + .into_iter() + .any(|(ty, p)| matches!(ty, 1..=6 | 24 | 25) && payload_shader(p).is_some_and(crate::gpu::recomp::pso::is_console)) + } +} + pub(super) unsafe extern "system" fn dev_create_pipeline_state(this: *mut c_void, desc: *const c_void, riid: *const GUID, ppv: *mut *mut c_void) -> HRESULT { super::null::capture_stream_desc(desc as *const u8); let f: PsoFn = std::mem::transmute(orig_fn(this, slot_of(this, "CreatePipelineState"))); @@ -4556,7 +4837,9 @@ pub(super) unsafe extern "system" fn dev_create_pipeline_state(this: *mut c_void StreamPipeline::Compute(d) => return dev_create_compute_pso(this, &*d as *const _ as *const c_void, riid, ppv), StreamPipeline::Unknown => {} } - let hr = finish_pso(this, f, desc, riid, ppv); + // a console shader the recompiler could not take must not reach the driver: AMD's shader + // compiler crashes on the stripped DXIL (NOBC bitcode) instead of rejecting it + let hr = if stream_has_console_shader(desc) { E_INVALIDARG } else { finish_pso(this, f, desc, riid, ppv) }; if hr >= 0 || !crate::gpu::shader::readable(desc as usize, 16) { return hr; } @@ -4614,6 +4897,43 @@ unsafe extern "system" fn dev_create_root_signature(this: *mut c_void, mask: u32 // presentation tracking // --------------------------------------------------------------------------------------- +/// The view a render target view without a description has, for a texture `pc_resource_desc` +/// made typeless (an sRGB one with UAVs) – None: the resource's format is +/// a typed one. +fn default_rtv(d: &D3D12_RESOURCE_DESC) -> Option { + use windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT; + let rf = d.Format.0 as u32; + if matches!(rf, 19 | 44 | 53) { + return None; + } + let f = super::device_x::pc_shader_view_format(rf, 0); + if f == rf || f == 0 { + return None; + } + let mut v = D3D12_RENDER_TARGET_VIEW_DESC { Format: DXGI_FORMAT(f as i32), ..Default::default() }; + let dim = d.Dimension.0 as u32; + let array = d.DepthOrArraySize; + if dim == D3D12_RESOURCE_DIMENSION_TEXTURE1D.0 as u32 { + if array > 1 { + v.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE1DARRAY; + v.Anonymous.Texture1DArray = D3D12_TEX1D_ARRAY_RTV { ArraySize: array as u32, ..Default::default() }; + } else { + v.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE1D; + v.Anonymous.Texture1D = D3D12_TEX1D_RTV::default(); + } + } else if dim == D3D12_RESOURCE_DIMENSION_TEXTURE3D.0 as u32 { + v.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE3D; + v.Anonymous.Texture3D = D3D12_TEX3D_RTV { WSize: array as u32, ..Default::default() }; + } else if array > 1 { + v.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE2DARRAY; + v.Anonymous.Texture2DArray = D3D12_TEX2D_ARRAY_RTV { ArraySize: array as u32, ..Default::default() }; + } else { + v.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE2D; + v.Anonymous.Texture2D = D3D12_TEX2D_RTV::default(); + } + Some(v) +} + unsafe extern "system" fn dev_create_rtv(this: *mut c_void, res: *mut c_void, desc: *const c_void, handle: usize) { type F = unsafe extern "system" fn(*mut c_void, *mut c_void, *const c_void, usize); let f: F = std::mem::transmute(orig_fn(this, slot_of(this, "CreateRenderTargetView"))); @@ -4623,6 +4943,11 @@ unsafe extern "system" fn dev_create_rtv(this: *mut c_void, res: *mut c_void, de let rf = ID3D12Resource::from_raw_borrowed(&res).map_or(0, |r| r.GetDesc().Format.0 as u32); c.Format = windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT(super::device_x::pc_shader_view_format(rf, c.Format.0 as u32) as i32); } + // no description: the resource's format – which a texture made typeless is not one a view + // can have + if copy.is_none() { + copy = ID3D12Resource::from_raw_borrowed(&res).and_then(|r| default_rtv(&r.GetDesc())); + } let desc = copy.as_ref().map_or(desc, |c| c as *const _ as *const c_void); f(this, res, desc, handle); super::present::note_rtv(handle, res); @@ -5170,6 +5495,52 @@ mod rect_list_pso_tests { } } +#[cfg(test)] +mod this_first_tests { + use super::*; + + /// `this_first`: either argument order, and a return buffer whose first word is a stale copy + /// of the object's vtable pointer (7a033c8: the retail game's C-way call wrote its result + /// over the device). Synthetic objects; no GPU and no title. + #[test] + fn a_return_buffer_with_a_stale_vtable_copy_is_not_the_object() { + let pc = [0usize; 32]; + let ext = [pc.as_ptr() as usize, 0]; + let vtbl = ext.as_ptr() as usize + 8; + EXTS.lock().unwrap().get_or_insert_with(HashSet::new).insert(vtbl); + let plain = 0x1234_5678usize; + let p = &plain as *const usize as *mut c_void; + // an object off the stack (as a real device is), and a stack buffer holding a stale copy + // of its vtable pointer - the retail game's case + let obj = Box::into_raw(Box::new([vtbl])) as *mut c_void; + let buf = [vtbl]; + let b = buf.as_ptr() as *mut c_void; + unsafe { + assert!(is_adopted(obj) && is_adopted(b), "both look adopted"); + // one adopted: that one is the object, either position + assert!(this_first(obj, p)); + assert!(!this_first(p, obj)); + // neither adopted: unchanged (the C way is assumed) + assert!(!this_first(p, p) && !this_first(std::ptr::null_mut(), std::ptr::null_mut())); + // one null argument: the other is taken as `this`, either position + assert!(this_first(obj, std::ptr::null_mut())); + assert!(!this_first(std::ptr::null_mut(), obj)); + // both adopted, one on this thread's stack: the stack one is the buffer, so the heap + // one is `this` in either order - what 7a033c8 fixed + assert!(this_first(obj, b)); + assert!(!this_first(b, obj)); + // both on the stack, neither the device: `a` (the C++ way) + let stale = [vtbl]; + let s = stale.as_ptr() as *mut c_void; + assert!(this_first(b, s) && this_first(s, b)); + drop(Box::from_raw(obj as *mut [usize; 1])); + } + if let Some(g) = EXTS.lock().unwrap().as_mut() { + g.remove(&vtbl); + } + } +} + #[cfg(test)] mod cache_report_tests { use super::*; @@ -5477,6 +5848,77 @@ mod srv_tests { } } +#[cfg(test)] +mod typeless_uav_view_tests { + use super::*; + use windows::Win32::Graphics::Dxgi::Common::*; + + fn rd(format: u32, array: u16) -> D3D12_RESOURCE_DESC { + D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: 2048, + Height: 2048, + DepthOrArraySize: array, + MipLevels: 1, + Format: DXGI_FORMAT(format as i32), + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + ..Default::default() + } + } + + fn uav(format: u32, mip: u32) -> D3D12_UNORDERED_ACCESS_VIEW_DESC { + D3D12_UNORDERED_ACCESS_VIEW_DESC { + Format: DXGI_FORMAT(format as i32), + ViewDimension: D3D12_UAV_DIMENSION_TEXTURE2D, + Anonymous: D3D12_UNORDERED_ACCESS_VIEW_DESC_0 { Texture2D: D3D12_TEX2D_UAV { MipSlice: mip, PlaneSlice: 0 } }, + } + } + + /// A resource the PC holds typeless (an sRGB texture with UAVs, a depth buffer) gets a typed + /// UAV desc: the sRGB one's UNORM for shaders that write values. An R9G9B9E5 target the PC + /// holds as half floats keeps the title's view format as its UAV. + #[test] + fn typeless_resources_get_typed_uav_descs() { + // sRGB typeless: a named sRGB view becomes UNORM, keeping its mip + let v = pc_uav_desc(&rd(27, 1), Some(&uav(29, 2))).expect("a UAV of an sRGB texture"); + assert_eq!((v.Format.0, v.ViewDimension.0), (28, D3D12_UAV_DIMENSION_TEXTURE2D.0)); + assert_eq!(unsafe { v.Anonymous.Texture2D }.MipSlice, 2); + // ... and the default view too + let v = pc_uav_desc(&rd(27, 1), None).expect("the sRGB texture's own UAV"); + assert_eq!((v.Format.0, v.ViewDimension.0), (28, D3D12_UAV_DIMENSION_TEXTURE2D.0)); + let v = pc_uav_desc(&rd(27, 3), None).expect("the sRGB array's own UAV"); + assert_eq!((v.Format.0, v.ViewDimension.0), (28, D3D12_UAV_DIMENSION_TEXTURE2DARRAY.0)); + assert_eq!(unsafe { v.Anonymous.Texture2DArray }.ArraySize, 3); + + // an R9G9B9E5 target the PC holds as half floats: the console's view is half floats too + assert_eq!(pc_uav_desc(&rd(10, 1), Some(&uav(67, 0))).map(|v| v.Format.0), Some(10)); + assert!(pc_uav_desc(&rd(10, 1), None).is_none(), "the half floats are the resource's own format"); + + // a resource that is its own typed format is left as the title made it + assert!(pc_uav_desc(&rd(28, 1), Some(&uav(28, 0))).is_none()); + assert!(pc_uav_desc(&rd(28, 1), None).is_none()); + assert!(pc_uav_desc(&rd(67, 1), Some(&uav(67, 0))).is_none(), "a sampled R9G9B9E5 texture"); + + // an SRV of a typeless sRGB resource: its own view is the sRGB one, by the format the + // title created it with and, with none recorded, by its family's + let s = pc_srv(Some(29), &rd(27, 1), None).expect("the sRGB texture's own SRV"); + assert_eq!((s.Format.0, s.ViewDimension.0), (29, D3D12_SRV_DIMENSION_TEXTURE2D.0)); + let s = pc_srv(None, &rd(27, 1), None).expect("the sRGB texture's own SRV, unrecorded"); + assert_eq!(s.Format.0, 29); + let s = pc_srv(None, &rd(39, 1), None).expect("an R32_TYPELESS texture's own SRV"); + assert_eq!(s.Format.0, 41); + assert!(pc_srv(None, &rd(28, 1), None).is_none()); + assert!(pc_srv(None, &rd(27, 1), Some(&D3D12_SHADER_RESOURCE_VIEW_DESC { Format: DXGI_FORMAT(27), ..Default::default() })).is_none(), "a typeless SRV format is not one the PC takes"); + + // the same for an RTV and, with no description, a view of the console's own format + let r = default_rtv(&rd(27, 1)).expect("the sRGB texture's own RTV"); + assert_eq!((r.Format.0, r.ViewDimension.0), (29, D3D12_RTV_DIMENSION_TEXTURE2D.0)); + assert!(default_rtv(&rd(10, 1)).is_none(), "the half floats are the resource's own format"); + assert!(default_rtv(&rd(28, 1)).is_none()); + assert!(default_rtv(&rd(44, 1)).is_none(), "a depth buffer's views name it"); + } +} + #[cfg(test)] mod console_format_query_tests { use super::*; @@ -5582,3 +6024,108 @@ mod console_format_query_tests { } } } + +#[cfg(test)] +mod console_pso_guard_tests { + use super::*; + + /// Minimal synthetic DXBC container with a DXIL part carrying `XDAT` (what `pso::is_console` + /// recognizes as console bytecode). + fn synthetic_console_shader() -> Vec { + let mut dxil = vec![0u8; 28]; + dxil[24..28].copy_from_slice(b"XDAT"); + let part_offset = 36u32; + let total = part_offset as usize + 8 + dxil.len(); + let mut blob = Vec::with_capacity(total); + blob.extend_from_slice(b"DXBC"); + blob.extend_from_slice(&[0u8; 16]); // hash + blob.extend_from_slice(&1u32.to_le_bytes()); // version + blob.extend_from_slice(&(total as u32).to_le_bytes()); + blob.extend_from_slice(&1u32.to_le_bytes()); // part count + blob.extend_from_slice(&part_offset.to_le_bytes()); + blob.extend_from_slice(b"DXIL"); + blob.extend_from_slice(&(dxil.len() as u32).to_le_bytes()); + blob.extend_from_slice(&dxil); + blob + } + + fn push_shader_subobject(stream: &mut Vec, ty: u32, blob: &[u8]) { + stream.extend_from_slice(&ty.to_le_bytes()); + stream.extend_from_slice(&0u32.to_le_bytes()); // 8-byte alignment pad + stream.extend_from_slice(&(blob.as_ptr() as u64).to_le_bytes()); + stream.extend_from_slice(&(blob.len() as u64).to_le_bytes()); + } + + #[test] + fn graphics_desc_detects_console_shader_in_any_stage() { + let console = synthetic_console_shader(); + assert!(crate::gpu::recomp::pso::is_console(&console)); + let pc = dummy().vs.as_slice(); + assert!(!crate::gpu::recomp::pso::is_console(pc)); + + let empty = D3D12_GRAPHICS_PIPELINE_STATE_DESC::default(); + assert!(!unsafe { graphics_has_console_shader(&empty as *const _ as *const c_void) }); + assert!(!unsafe { graphics_has_console_shader(std::ptr::null()) }); + + let pc_only = D3D12_GRAPHICS_PIPELINE_STATE_DESC { VS: bytecode(pc), PS: bytecode(&dummy().ps), ..Default::default() }; + assert!(!unsafe { graphics_has_console_shader(&pc_only as *const _ as *const c_void) }); + + for stage in 0..5 { + let mut d = pc_only.clone(); + match stage { + 0 => d.VS = bytecode(&console), + 1 => d.PS = bytecode(&console), + 2 => d.DS = bytecode(&console), + 3 => d.HS = bytecode(&console), + _ => d.GS = bytecode(&console), + } + assert!(unsafe { graphics_has_console_shader(&d as *const _ as *const c_void) }, "stage {stage}"); + } + } + + #[test] + fn pipeline_stream_detects_console_shader_subobjects() { + let console = synthetic_console_shader(); + let pc = dummy().vs.as_slice(); + + let mut pc_stream = Vec::new(); + push_shader_subobject(&mut pc_stream, 1, pc); + let desc = [pc_stream.len(), pc_stream.as_ptr() as usize]; + assert!(!unsafe { stream_has_console_shader(desc.as_ptr() as *const c_void) }); + assert!(!unsafe { stream_has_console_shader(std::ptr::null()) }); + + for ty in [1u32, 2, 3, 4, 5, 6, 24, 25] { + let mut s = Vec::new(); + push_shader_subobject(&mut s, ty, &console); + let d = [s.len(), s.as_ptr() as usize]; + assert!(unsafe { stream_has_console_shader(d.as_ptr() as *const c_void) }, "subobject {ty}"); + } + } + + #[test] + fn fallback_stream_rewrites_console_rtv_and_dsv_formats() { + let console = synthetic_console_shader(); + let mut s = Vec::new(); + push_shader_subobject(&mut s, 1, &console); + // subobject 15: D3D12_RT_FORMAT_ARRAY (8 × DXGI_FORMAT + NumRenderTargets) + s.extend_from_slice(&15u32.to_le_bytes()); + let rtv_off = s.len(); + for f in [116u32, 117, 86, 115, 28, 0, 0, 0, 5] { + s.extend_from_slice(&f.to_le_bytes()); + } + // subobject 16: DSVFormat = D16_UNORM_S8_UINT (118) + s.extend_from_slice(&16u32.to_le_bytes()); + let dsv_off = s.len(); + s.extend_from_slice(&118u32.to_le_bytes()); + + let desc = [s.len(), s.as_ptr() as usize]; + let (out, _) = unsafe { fallback_stream(desc.as_ptr() as *const u8) }.expect("fallback stream"); + let vs_ptr = u64::from_le_bytes(out[8..16].try_into().unwrap()) as usize; + assert_eq!(vs_ptr, dummy().vs.as_ptr() as usize, "console VS replaced with dummy VS"); + + let rtv: [u32; 8] = std::array::from_fn(|k| u32::from_le_bytes(out[rtv_off + 4 * k..rtv_off + 4 * k + 4].try_into().unwrap())); + assert_eq!(rtv, [10, 10, 28, 28, 28, 0, 0, 0]); + let dsv = u32::from_le_bytes(out[dsv_off..dsv_off + 4].try_into().unwrap()); + assert_eq!(dsv, 45); + } +} diff --git a/crates/xcl/src/hle/d3d12x/sparse.rs b/crates/xcl/src/hle/d3d12x/sparse.rs index 8acd3d8..5c269c7 100644 --- a/crates/xcl/src/hle/d3d12x/sparse.rs +++ b/crates/xcl/src/hle/d3d12x/sparse.rs @@ -1345,14 +1345,17 @@ pub fn mapped_ranges() -> Vec<(usize, usize)> { s.runs.clone().unwrap_or_default() } -/// time spent and pages found by the write-watch scans (`refresh_once`), for the timing line -static WATCH: [AtomicU64; 2] = [AtomicU64::new(0), AtomicU64::new(0)]; +/// time spent, pages found, ranges read and bytes watched by the write-watch scans +/// (`refresh_once`), for the timing line +static WATCH: [AtomicU64; 4] = [const { AtomicU64::new(0) }; 4]; /// [lock wait, chunk scan, upload] in µs, runs uploaded static PHASES: [AtomicU64; 4] = [const { AtomicU64::new(0) }; 4]; -pub fn note_watch(t: std::time::Duration, pages: usize) { +pub fn note_watch(t: std::time::Duration, pages: usize, ranges: usize, bytes: usize) { WATCH[0].fetch_add(t.as_micros() as u64, Ordering::Relaxed); WATCH[1].fetch_add(pages as u64, Ordering::Relaxed); + WATCH[2].fetch_add(ranges as u64, Ordering::Relaxed); + WATCH[3].fetch_add(bytes as u64, Ordering::Relaxed); } /// Before the title's ExecuteCommandLists on `queue`: the pages the CPU wrote (`dirty`, 4 KiB @@ -1422,9 +1425,11 @@ pub unsafe fn before_execute(queue: &ID3D12CommandQueue, dirty: &[usize], page: crate::xlog_info!("sparse windows: {n} submits, {} MB of CPU writes uploaded, {} ms spent, {} tiles mapped", b >> 20, us / 1000, s.mapped.len()); let ms = |x: &AtomicU64| x.load(Ordering::Relaxed) / 1000; crate::xlog_info!( - "sparse windows timing: write-watch {} ms ({} dirty pages), lock wait {} ms, chunk scan {} ms, upload {} ms ({} runs)", + "sparse windows timing: write-watch {} ms ({} dirty pages, {} ranges, {} MB watched), lock wait {} ms, chunk scan {} ms, upload {} ms ({} runs)", ms(&WATCH[0]), WATCH[1].load(Ordering::Relaxed), + WATCH[2].load(Ordering::Relaxed), + WATCH[3].load(Ordering::Relaxed) >> 20, ms(&PHASES[0]), ms(&PHASES[1]), ms(&PHASES[2]), diff --git a/crates/xcl/src/hle/d3d12x/title_textures.rs b/crates/xcl/src/hle/d3d12x/title_textures.rs index 1e170a5..bdefc2c 100644 --- a/crates/xcl/src/hle/d3d12x/title_textures.rs +++ b/crates/xcl/src/hle/d3d12x/title_textures.rs @@ -43,12 +43,17 @@ extern "system" { fn GetWriteWatch(flags: u32, base: *const c_void, size: usize, addresses: *mut *mut c_void, count: *mut usize, granularity: *mut u32) -> u32; } -/// (device, address, layout, states) of an upload +/// (device, address its bytes are read from, layout, states) of an upload type Upload = (usize, usize, Arc, Vec); struct Entry { device: usize, + /// the title's address of the texture va: usize, + /// where its bytes are read and its CPU writes watched: `va`, or – for a texture in a GPU + /// view of the title's CPU memory with nothing mapped there – the same offset in the CPU + /// view (`kernelx::mirrors`) + src: usize, tex: Arc, /// the state the title's submitted work leaves the texture in (uploads leave it there): /// the creation state, then what its transitions give – one state for every subresource, @@ -135,8 +140,16 @@ pub(super) unsafe fn register(device: *mut c_void, res: *mut c_void, va: usize, if ID3D12Resource::from_raw_borrowed(&res).is_none() { return Err("no resource".into()); } + let src = mirror_source(va); + if src != va { + static N: AtomicU64 = AtomicU64::new(0); + let n = N.fetch_add(1, Ordering::Relaxed) + 1; + if n <= 2 || n.is_power_of_two() { + crate::xlog_info!("D3D12.X: a texture at {va:#x} lies in a GPU view of the title's CPU memory: kept in step with {src:#x} ({n} so far)"); + } + } let seq = SEQ.fetch_add(1, Ordering::Relaxed); - let e = Entry { device: device as usize, va, tex: Arc::new(tex), states: vec![state], pending: true, gpu_written: false, seq }; + let e = Entry { device: device as usize, va, src, tex: Arc::new(tex), states: vec![state], pending: true, gpu_written: false, seq }; { let mut t = TEXTURES.lock().unwrap(); if let Some(old) = t.insert(res as usize, e) { @@ -151,6 +164,16 @@ pub(super) unsafe fn register(device: *mut c_void, res: *mut c_void, va: usize, Ok(()) } +/// Where a texture at `va` is read from: the CPU view behind a GPU view (`kernelx::mirrors`) +/// when nothing is mapped at `va` itself, else `va`. +fn mirror_source(va: usize) -> usize { + let Some(src) = crate::hle::kernelx::mirrors::source(va) else { return va }; + use windows_sys::Win32::System::Memory::{VirtualQuery, MEMORY_BASIC_INFORMATION, MEM_COMMIT}; + let mut m: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; + let mapped = unsafe { VirtualQuery(va as *const c_void, &mut m, std::mem::size_of_val(&m)) } != 0 && m.State == MEM_COMMIT; + if mapped { va } else { src } +} + /// The title's GPU work writes texture `res` (a copy into it): on the console the memory then /// holds what the GPU wrote; here the CPU's view of it is stale, so it is not uploaded again /// (a CPU write elsewhere on its pages – a neighbour, an allocator's header – would upload the @@ -305,7 +328,7 @@ fn cached_watch_ranges(u: &crate::gpu::uma::Uma) -> Arc> { // write-watched regions) only when the set of textures, tiles, or reservations changed. let mut regions = u.watch_regions(); regions.extend(crate::hle::kernelx::graphics_reservations()); - let mut wanted: Vec<(usize, usize)> = TEXTURES.lock().unwrap().values().map(|e| (e.va & !0xFFF, (e.va + e.tex.size() as usize + 0xFFF) & !0xFFF)).collect(); + let mut wanted: Vec<(usize, usize)> = TEXTURES.lock().unwrap().values().map(|e| (e.src & !0xFFF, (e.src + e.tex.size() as usize + 0xFFF) & !0xFFF)).collect(); wanted.extend(super::sparse::mapped_ranges()); let computed = Arc::new(watch_ranges(®ions, wanted)); *WATCH_CACHE.lock().unwrap() = Some((key, Arc::clone(&computed))); @@ -336,6 +359,120 @@ pub(super) unsafe fn refresh(queue: *mut c_void) { own_work(|| refresh_once(queue)); } +/// The write-watch ranges split into at most `WATCH_THREADS` parts of about equal size, or one +/// part when the set is small enough that threads would cost more than they save. +fn watch_parts(ranges: &[(usize, usize)]) -> Vec> { + split_watch(ranges, watch_threads()) +} + +fn split_watch(ranges: &[(usize, usize)], threads: usize) -> Vec> { + const MIN_PARALLEL: usize = 256 << 20; + let total: usize = ranges.iter().map(|r| r.1).sum(); + if ranges.len() < 2 || total < MIN_PARALLEL || threads < 2 { + return vec![ranges.to_vec()]; + } + let k = threads.min(ranges.len()); + let share = total.div_ceil(k); + let mut parts: Vec> = vec![Vec::new()]; + let mut acc = 0usize; + for &r in ranges { + if acc >= share && parts.len() < k { + parts.push(Vec::new()); + acc = 0; + } + parts.last_mut().unwrap().push(r); + acc += r.1; + } + parts +} + +/// `XCL_WATCH_THREADS` (default 1 = the serial loop; the kernel serialises the walks, so more threads +/// measured no faster): threads that read the write-watch. +fn watch_threads() -> usize { + static N: std::sync::OnceLock = std::sync::OnceLock::new(); + *N.get_or_init(|| std::env::var("XCL_WATCH_THREADS").ok().and_then(|v| v.parse().ok()).unwrap_or(1).clamp(1, 32)) +} + +/// GetWriteWatch with reset over `ranges`: every written page's address goes to `dirty`. +/// +/// When the buffer fills, the call reports the pages that fitted and leaves the rest dirty, and +/// the next call walks the whole range again from its base (measured: a 2 GiB range with 100k +/// dirty pages and a 16384-entry buffer costs one walk per bufferful). A look that finds more +/// pages than the buffer holds therefore costs several walks; the buffer grows to hold what the +/// range has, up to `MAX_WATCH_BUF` entries. +unsafe fn watch_into(ranges: &[(usize, usize)], buf: &mut Vec<*mut c_void>, dirty: &mut Vec, page: &mut u32) { + /// 4M pages (16 GiB of 4 KiB pages) held as 32 MiB of pointers + const MAX_WATCH_BUF: usize = 4 << 20; + if buf.len() < 16384 { + buf.resize(16384, std::ptr::null_mut()); + } + for &(base, size) in ranges { + loop { + let mut n = buf.len(); + if GetWriteWatch(WRITE_WATCH_FLAG_RESET, base as *const c_void, size, buf.as_mut_ptr(), &mut n, page) != 0 { + break; + } + dirty.extend(buf[..n].iter().map(|&p| p as usize)); + if n < buf.len() { + break; + } + if buf.len() < MAX_WATCH_BUF { + buf.resize((buf.len() * 4).min(MAX_WATCH_BUF), std::ptr::null_mut()); + } + } + } +} + +type WatchJob = (Vec<(usize, usize)>, std::sync::mpsc::Sender<(Vec, u32)>); + +/// The write-watch threads: a shared queue of jobs, each answered with (dirty pages, granularity). +struct WatchPool(Mutex>); + +impl WatchPool { + fn send(&self, job: WatchJob) { + let _ = self.0.lock().unwrap().send(job); + } +} + +fn watch_pool() -> &'static WatchPool { + static POOL: std::sync::OnceLock = std::sync::OnceLock::new(); + POOL.get_or_init(|| { + let (tx, rx) = std::sync::mpsc::channel::(); + let rx = Arc::new(Mutex::new(rx)); + for i in 0..watch_threads() { + let rx = Arc::clone(&rx); + let _ = std::thread::Builder::new().name(format!("xcl-watch-{i}")).spawn(move || { + let mut buf: Vec<*mut c_void> = Vec::new(); + loop { + let job = rx.lock().unwrap().recv(); + let Ok((ranges, reply)) = job else { return }; + let mut found = Vec::new(); + let mut page = 0u32; + unsafe { watch_into(&ranges, &mut buf, &mut found, &mut page) }; + let _ = reply.send((found, page)); + } + }); + } + WatchPool(Mutex::new(tx)) + }) +} + +/// Whether this submit reads the write-watch. By default every submit does: a page the CPU wrote +/// between two submits (descriptors, buffers in sparse windows) must reach video memory before the +/// second one. GetWriteWatch walks every watched page, though (gigabytes of mapped sparse tiles on a +/// newer retail title: about 15 ms a call, several submits a frame), so `XCL_WATCH_PER_FRAME=1` +/// reads it only at the first submit after a present: faster, but a write made between two submits +/// of one frame reaches video memory one frame late. +fn scan_this_submit() -> bool { + static PER_FRAME: std::sync::OnceLock = std::sync::OnceLock::new(); + if !*PER_FRAME.get_or_init(|| std::env::var("XCL_WATCH_PER_FRAME").is_ok_and(|v| v != "0")) { + return true; + } + static LAST: AtomicU64 = AtomicU64::new(u64::MAX); + let now = super::present::presents(); + LAST.swap(now, Ordering::Relaxed) != now +} + unsafe fn refresh_once(queue: *mut c_void) { let Some(u) = crate::gpu::uma::get() else { return }; let sparse = u.has_sparse(); @@ -345,31 +482,46 @@ unsafe fn refresh_once(queue: *mut c_void) { let watch_t0 = std::time::Instant::now(); let mut page = 0x1000u32; let ranges = cached_watch_ranges(u); + let scan = scan_this_submit(); let dirty_len = DIRTY_BUF.with(|dcell| { let mut dirty = dcell.borrow_mut(); dirty.clear(); - WATCH_BUF.with(|wcell| { - let mut buf = wcell.borrow_mut(); - if buf.len() < 16384 { - buf.resize(16384, std::ptr::null_mut()); + if !scan { + return 0; + } + let parts = watch_parts(&ranges); + if parts.len() <= 1 { + WATCH_BUF.with(|wcell| watch_into(&ranges, &mut wcell.borrow_mut(), &mut dirty, &mut page)); + } else { + // Large watched sets: GetWriteWatch walks every page of a range in the kernel, one + // range after another, and that walk held the title's submitting thread for most of + // its frame. The ranges are split over a pool of long-lived threads (created once, + // so the title's per-thread setup runs only for them); each range is still read and + // reset by exactly one call, so the dirty set is the same as the serial loop's. + let (tx, rx) = std::sync::mpsc::channel(); + let n = parts.len(); + for part in parts { + watch_pool().send((part, tx.clone())); } - for &(base, size) in ranges.iter() { - loop { - let mut n = buf.len(); - if GetWriteWatch(WRITE_WATCH_FLAG_RESET, base as *const c_void, size, buf.as_mut_ptr(), &mut n, &mut page) != 0 { - break; - } - dirty.extend(buf[..n].iter().map(|&p| p as usize)); - if n < buf.len() { - break; + drop(tx); + for _ in 0..n { + if let Ok((found, g)) = rx.recv() { + dirty.extend(found); + if g != 0 { + page = g; } } } - }); + } dirty.sort_unstable(); dirty.len() }); - super::sparse::note_watch(watch_t0.elapsed(), dirty_len); + super::sparse::note_watch( + watch_t0.elapsed(), + dirty_len, + if scan { ranges.len() } else { 0 }, + if scan { ranges.iter().map(|r| r.1).sum() } else { 0 }, + ); if super::present::trace_frame() { // every 600th look: what the CPU's view of a few textures holds now (does the title's // data reach the address at all, and is the texture still kept in step?) @@ -381,7 +533,7 @@ unsafe fn refresh_once(queue: *mut c_void) { let content = |e: &Entry| -> usize { let size = e.tex.size() as usize; (0..16usize) - .map(|k| e.va + (size.saturating_sub(4096)) * k / 15) + .map(|k| e.src + (size.saturating_sub(4096)) * k / 15) .filter(|&a| crate::gpu::shader::readable(a, 4096)) .map(|a| std::slice::from_raw_parts(a as *const u8, 4096).iter().filter(|&&b| b != 0).count()) .sum() @@ -423,8 +575,8 @@ unsafe fn refresh_once(queue: *mut c_void) { if e.gpu_written { return false; } - let i = dirty.partition_point(|&p| p + page as usize <= e.va); - dirty.get(i).is_some_and(|&p| p < e.va + e.tex.size() as usize) + let i = dirty.partition_point(|&p| p + page as usize <= e.src); + dirty.get(i).is_some_and(|&p| p < e.src + e.tex.size() as usize) }) .filter_map(|(&res, e)| { if e.pending { @@ -432,7 +584,7 @@ unsafe fn refresh_once(queue: *mut c_void) { PENDING.fetch_sub(1, Ordering::Relaxed); } let p = res as *mut c_void; - ID3D12Resource::from_raw_borrowed(&p).map(|r| (e.seq, r.clone(), (e.device, e.va, Arc::clone(&e.tex), e.states.clone()))) + ID3D12Resource::from_raw_borrowed(&p).map(|r| (e.seq, r.clone(), (e.device, e.src, Arc::clone(&e.tex), e.states.clone()))) }) .collect() }); @@ -466,12 +618,12 @@ unsafe fn upload_all(todo: Vec<(ID3D12Resource, Upload)>) { if !batch.is_empty() && (bytes + tex.size() as usize > BATCH_BYTES || *dev != device) { break; } - let (r, (dev, va, tex, states)) = todo.next().unwrap(); + let (r, (dev, src, tex, states)) = todo.next().unwrap(); device = dev; bytes += tex.size() as usize; - let subs = subresources(va, &tex); + let subs = subresources(src, &tex); if super::present::trace_frame() { - note_content(va, &r, &subs); + note_content(src, &r, &subs); } batch.push((r, subs, states)); } @@ -529,7 +681,7 @@ pub unsafe fn probe_gpu_content(res: usize) { } g.push(res); } - let Some((device, va, tex, gpu_written)) = TEXTURES.lock().unwrap().get(&res).map(|e| (e.device, e.va, Arc::clone(&e.tex), e.gpu_written)) else { return }; + let Some((device, va, src, tex, gpu_written)) = TEXTURES.lock().unwrap().get(&res).map(|e| (e.device, e.va, e.src, Arc::clone(&e.tex), e.gpu_written)) else { return }; let d = device as *mut c_void; let r = res as *mut c_void; let (Some(dev), Some(r)) = (ID3D12Device::from_raw_borrowed(&d), ID3D12Resource::from_raw_borrowed(&r)) else { return }; @@ -586,7 +738,7 @@ pub unsafe fn probe_gpu_content(res: usize) { rb.Unmap(0, None); Ok(out) }); - let cpu = subresources(va, &tex).into_iter().next().map(|s| s.data).unwrap_or_default(); + let cpu = subresources(src, &tex).into_iter().next().map(|s| s.data).unwrap_or_default(); match result { Ok(gpu) => { let nonzero = gpu.iter().filter(|&&b| b != 0).count(); @@ -617,9 +769,12 @@ unsafe fn upload_queue(dev: &ID3D12Device, device: usize) -> Result = (0..40).map(|i| (0x1_0000_0000 + i * (64 << 20), 64 << 20)).collect(); + assert_eq!(split_watch(&big, 1), vec![big.clone()], "one thread: the serial loop"); + let parts = split_watch(&big, 8); + assert!(parts.len() > 1 && parts.len() <= 8, "{} parts", parts.len()); + let flat: Vec<(usize, usize)> = parts.concat(); + assert_eq!(flat, big, "every range exactly once, in order"); + } +} + +/// What the write-watch costs, measured on this machine (Windows only): the kernel walk over a +/// synthetic write-watched reservation, and how that cost splits into a fixed part per call, a +/// part per page and a part per dirty page. `XCL_BENCH_WATCH_MB` (default 512) is the size of the +/// reservation the benches use. +/// +/// `cargo test -q --lib watch_bench -- --ignored --nocapture` runs the benches; the first test +/// runs in the normal suite (64 MiB). +#[cfg(all(test, windows))] +mod watch_bench { + use super::{watch_into, GetWriteWatch, WRITE_WATCH_FLAG_RESET}; + use std::ffi::c_void; + use windows_sys::Win32::System::Memory::{VirtualAlloc, VirtualFree, MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_READWRITE}; + + const MEM_WRITE_WATCH: u32 = 0x20_0000; + + /// `len` bytes of write-watched memory, freed on drop. + struct Watched(*mut c_void, usize); + + impl Watched { + fn new(len: usize) -> Self { + let p = unsafe { VirtualAlloc(std::ptr::null(), len, MEM_RESERVE | MEM_COMMIT | MEM_WRITE_WATCH, PAGE_READWRITE) }; + assert!(!p.is_null(), "VirtualAlloc({len}, MEM_WRITE_WATCH) failed"); + Watched(p, len) + } + + /// write one byte of `pages` 4 KiB pages, spread over the range + fn touch(&self, pages: usize) { + let step = (self.1 / pages.max(1) & !0xFFF).max(0x1000); + for k in 0..pages { + unsafe { std::ptr::write_volatile((self.0 as *mut u8).add(k * step), 1) }; + } + } + } + + impl Drop for Watched { + fn drop(&mut self) { + unsafe { VirtualFree(self.0, 0, MEM_RELEASE) }; + } + } + + fn mb() -> usize { + std::env::var("XCL_BENCH_WATCH_MB").ok().and_then(|v| v.parse().ok()).unwrap_or(512).clamp(16, 2048) + } + + /// More dirty pages than the buffer starts with: `watch_into` grows the buffer and returns + /// every page without a second walk over the range. + #[test] + fn more_dirty_pages_than_the_buffer_holds_are_all_returned() { + let w = Watched::new(128 << 20); + let pages = 20_000usize; + w.touch(pages); + let mut buf: Vec<*mut c_void> = Vec::new(); + let mut dirty: Vec = Vec::new(); + let mut gran = 0u32; + unsafe { watch_into(&[(w.0 as usize, w.1)], &mut buf, &mut dirty, &mut gran) }; + dirty.sort_unstable(); + dirty.dedup(); + assert_eq!(dirty.len(), pages, "every written page reported once"); + assert!(buf.len() >= pages, "the buffer grew to hold the range's pages ({} entries)", buf.len()); + } + + #[test] + #[ignore = "bench: up to 2 GiB, cost by bytes and by dirty pages"] + fn get_write_watch_cost_by_bytes_and_dirty_pages() { + let mb = mb(); + let w = Watched::new(mb << 20); + let mut buf = vec![std::ptr::null_mut::(); 1 << 16]; + for &dirty in &[0usize, 16, 1024, 16384] { + w.touch(dirty); + let t = std::time::Instant::now(); + let (mut n, mut gran) = (buf.len(), 0u32); + let r = unsafe { GetWriteWatch(WRITE_WATCH_FLAG_RESET, w.0, w.1, buf.as_mut_ptr(), &mut n, &mut gran) }; + let d = t.elapsed().as_secs_f64(); + assert_eq!(r, 0, "GetWriteWatch failed"); + assert_eq!(n, dirty, "{dirty} pages written, {n} reported"); + println!( + "watched {mb} MiB ({:.0} pages), {n} dirty: {:.2} ms ({:.2} ns/page, {:.3} µs/dirty page)", + w.1 as f64 / 4096.0, + d * 1e3, + d * 1e9 / (w.1 as f64 / 4096.0), + d * 1e6 / n.max(1) as f64 + ); + } + } + + /// The same bytes in one call and in many: the fixed cost of a call. + #[test] + #[ignore = "bench: 512 MiB in 1 call vs calls of 1, 4 and 16 MiB"] + fn cost_of_many_small_ranges() { + let len = mb() << 20; + let w = Watched::new(len); + let mut buf = vec![std::ptr::null_mut::(); 1 << 16]; + for chunk in [len, 16 << 20, 4 << 20, 1 << 20] { + w.touch(64); + let mut got = 0usize; + let t = std::time::Instant::now(); + for base in (0..len).step_by(chunk) { + let (mut n, mut gran) = (buf.len(), 0u32); + let r = unsafe { GetWriteWatch(WRITE_WATCH_FLAG_RESET, (w.0 as *const u8).add(base) as *const c_void, chunk, buf.as_mut_ptr(), &mut n, &mut gran) }; + assert_eq!(r, 0); + got += n; + } + let d = t.elapsed().as_secs_f64(); + println!( + "{} MiB in {} calls of {} MiB: {:.2} ms, {got} pages ({:.1} µs a call)", + len >> 20, + len / chunk, + chunk >> 20, + d * 1e3, + d * 1e6 / (len / chunk) as f64 + ); + assert_eq!(got, 64); + } + } + + /// A buffer that fills: the call reports what fitted and the rest stay dirty, so the next + /// call walks the whole range again (why `watch_into` grows the buffer). + #[test] + #[ignore = "bench: 2 GiB, 100k dirty pages, small vs grown buffer"] + fn a_full_buffer_costs_one_walk_per_bufferful() { + let w = Watched::new(2048 << 20); + let dirty = 100_000usize; + for entries in [16384usize, 0] { + w.touch(dirty); + let mut buf = vec![std::ptr::null_mut::(); if entries == 0 { dirty + 1024 } else { entries }]; + let t = std::time::Instant::now(); + let (mut got, mut calls, mut gran) = (0usize, 0usize, 0u32); + loop { + let mut n = buf.len(); + let r = unsafe { GetWriteWatch(WRITE_WATCH_FLAG_RESET, w.0, w.1, buf.as_mut_ptr(), &mut n, &mut gran) }; + assert_eq!(r, 0); + got += n; + calls += 1; + if n < buf.len() { + break; + } + } + println!("buffer {} entries: {calls} calls, {got} of {dirty} pages, {:.2} ms", buf.len(), t.elapsed().as_secs_f64() * 1e3); + assert_eq!(got, dirty); + } } } diff --git a/crates/xcl/src/hle/dstorage.rs b/crates/xcl/src/hle/dstorage.rs index 32b215b..76f0653 100644 --- a/crates/xcl/src/hle/dstorage.rs +++ b/crates/xcl/src/hle/dstorage.rs @@ -909,6 +909,18 @@ unsafe fn execute(r: &Request, file: Option<&FileInner>, dest_pages: Option<&[us if r.dest_physical_pages() { let pages = dest_pages.ok_or(E_ACCESS_VIOLATION)?; + // A page number of 0 in the snapshot taken at enqueue (no page has it): the entry is + // read again now. A retail title keeps its page arrays in its own tables and fills an + // entry after EnqueueRequest – its streaming requests were refused by the thousand + // with page 0. An array that had its pages at enqueue stays as it was snapshotted + // (titles also pass arrays on the stack). + let late: Vec; + let pages = if pages.contains(&0) && crate::gpu::shader::readable(r.destination as usize, std::mem::size_of_val(pages)) { + late = (0..pages.len()).map(|k| if pages[k] != 0 { pages[k] } else { (r.destination as *const usize).add(k).read_unaligned() }).collect(); + &late[..] + } else { + pages + }; if !crate::hle::kernelx::write_physical_pages(pages, r.destination_page_offset as usize, &payload[..n]) { return Err(E_ACCESS_VIOLATION); } @@ -1951,6 +1963,81 @@ mod tests { } } + /// A destination page array whose entry is still 0 at EnqueueRequest and gets its page + /// before the request's turn: the data arrives (a retail title's streaming). + #[test] + fn a_destination_page_filled_in_after_enqueue() { + use crate::hle::kernelx::{AllocateTitlePhysicalPages, FreeTitlePhysicalPages, MapTitlePhysicalPages, PHYS_PAGE_SIZE}; + if crate::gpu::uma::get().is_none() { + return; + } + unsafe { + let mut count = 2usize; + let mut pages = [0usize; 2]; + assert_eq!(AllocateTitlePhysicalPages(std::ptr::null_mut(), 0, &mut count, pages.as_mut_ptr()), 1); + + let mut f = std::ptr::null_mut(); + assert_eq!(DStorageGetFactory(&IID_FACTORY, &mut f), S_OK); + let vt = *(f as *const *const usize); + let create_queue: unsafe extern "system" fn(*mut c_void, *const u8, *const GUID, *mut *mut c_void) -> HRESULT = std::mem::transmute(*vt.add(3)); + let create_status: unsafe extern "system" fn(*mut c_void, u32, *const u8, *const GUID, *mut *mut c_void) -> HRESULT = std::mem::transmute(*vt.add(5)); + let mut desc = [0u8; 0x18]; + desc[0..4].copy_from_slice(&1u32.to_le_bytes()); + desc[8..10].copy_from_slice(&16u16.to_le_bytes()); + desc[10] = 2; + let mut q = std::ptr::null_mut(); + assert_eq!(create_queue(f, desc.as_ptr(), &IID_QUEUE, &mut q), S_OK); + let mut s = std::ptr::null_mut(); + assert_eq!(create_status(f, 2, std::ptr::null(), &IID_STATUS_ARRAY, &mut s), S_OK); + let qv = *(q as *const *const usize); + let enqueue: unsafe extern "system" fn(*mut c_void, *const u8) = std::mem::transmute(*qv.add(3)); + let status: unsafe extern "system" fn(*mut c_void, *mut c_void, u32) = std::mem::transmute(*qv.add(4)); + let submit: unsafe extern "system" fn(*mut c_void) = std::mem::transmute(*qv.add(6)); + let sv = *(s as *const *const usize); + let complete: unsafe extern "system" fn(*mut c_void, u32) -> bool = std::mem::transmute(*sv.add(3)); + let hresult: unsafe extern "system" fn(*mut c_void, u32) -> HRESULT = std::mem::transmute(*sv.add(4)); + + // where the pages can be read back: mapped into a reservation + let reserved = windows_sys::Win32::System::Memory::VirtualAlloc( + std::ptr::null(), + 2 * PHYS_PAGE_SIZE, + windows_sys::Win32::System::Memory::MEM_RESERVE, + windows_sys::Win32::System::Memory::PAGE_READWRITE, + ); + assert!(!reserved.is_null()); + assert_eq!(MapTitlePhysicalPages(reserved, 2, 0, 4, pages.as_mut_ptr()), reserved); + + // 0. the title's table: the second entry has no page yet when the request is enqueued + let data: Vec = (0..0x1800u32).map(|i| (i * 13 + 5) as u8).collect(); + let page_off = (PHYS_PAGE_SIZE - 0x800) as u16; + let mut table = Box::new([pages[0], 0usize]); + enqueue(q, request_ex(SOURCE_MEMORY_BIT | DEST_PHYS_PAGES_BIT, table.as_ptr() as u64, page_off, data.len() as u32, data.as_ptr() as u64, 0, data.len() as u32, 0, 0).as_ptr()); + std::ptr::write_volatile(&mut table[1], pages[1]); + status(q, s, 0); + + // 1. an entry that is still 0 at the request's turn is refused as before + let empty = Box::new([0usize]); + enqueue(q, request_ex(SOURCE_MEMORY_BIT | DEST_PHYS_PAGES_BIT, empty.as_ptr() as u64, 0, 16, data.as_ptr() as u64, 0, 16, 0, 0).as_ptr()); + status(q, s, 1); + + submit(q); + let t = std::time::Instant::now(); + while !complete(s, 1) && t.elapsed().as_secs() < 5 { + std::thread::yield_now(); + } + assert_eq!((hresult(s, 0), hresult(s, 1)), (S_OK, E_ACCESS_VIOLATION)); + let got = std::slice::from_raw_parts((reserved as *const u8).add(page_off as usize), data.len()); + assert_eq!(got, &data[..], "the bytes cross from the page that was there into the one filled in later"); + + MapTitlePhysicalPages(reserved, 2, 0, 4, std::ptr::null_mut()); + windows_sys::Win32::System::Memory::VirtualFree(reserved, 0, windows_sys::Win32::System::Memory::MEM_RELEASE); + assert_eq!(FreeTitlePhysicalPages(std::ptr::null_mut(), 2, pages.as_mut_ptr()), 1); + queue_close(q); + queue_release(q); + status_release(s); + } + } + #[test] fn physical_page_destinations_and_sources() { use crate::hle::kernelx::{AllocateTitlePhysicalPages, FreeTitlePhysicalPages, MapTitlePhysicalPages, PHYS_PAGE_SIZE}; diff --git a/crates/xcl/src/hle/kernelx.rs b/crates/xcl/src/hle/kernelx.rs index 5ee53b5..afe5d15 100644 --- a/crates/xcl/src/hle/kernelx.rs +++ b/crates/xcl/src/hle/kernelx.rs @@ -156,6 +156,101 @@ pub fn in_graphics_reservation(p: usize) -> bool { const MEM_WRITE_WATCH: u32 = 0x20_0000; +/// GPU views of the title's CPU memory. A retail game reserves 24 GB of 64 KiB pages twice +/// in a row: once readable by the CPU (PAGE_READWRITE), once with PAGE_NOACCESS | +/// PAGE_GRAPHICS_NOACCESS. It maps physical pages only into the first, yet places GPU +/// resources at the same offset in the second (its Bink video planes: the decoder writes the +/// first view, the video shader samples textures in the second). On the console the second +/// reservation is a GPU-only view of the first; here it is separate, empty memory – the +/// video was its colour of zero luma and chroma, a green screen. `source` names the CPU view +/// behind an address of such a GPU view, which `d3d12x::title_textures` reads and watches. +pub mod mirrors { + use std::collections::BTreeMap; + use std::sync::Mutex; + + /// MEM_LARGE_PAGES | MEM_PHYSICAL: the console's 64 KiB pages + const PAGES_64K: u32 = 0x2040_0000; + /// PAGE_GRAPHICS_NOACCESS + const GRAPHICS_NOACCESS: u32 = 0x800; + + struct State { + /// CPU-readable reservations of 64 KiB pages, oldest first: (sequence, base, size) + cpu: Vec<(u64, usize, usize)>, + /// GPU view base → (size, CPU view base) + gpu: BTreeMap, + /// the next reservation's sequence number + next: u64, + /// the most recent reservation while it lives: (sequence, base, size) + last: Option<(u64, usize, usize)>, + } + static STATE: Mutex = Mutex::new(State { cpu: Vec::new(), gpu: BTreeMap::new(), next: 0, last: None }); + + /// A reservation of `size` bytes at `base` with allocation type `t` and protection `p`. + /// + /// A no-access graphics reservation of 64 KiB pages is paired with a CPU-readable one of + /// its size only when that one is the reservation immediately before it and is the only + /// CPU view of that size without a GPU view: with several candidates it is not known + /// which one the title means, and a texture read from the wrong one shows wrong texels. + /// A reservation that is not paired leaves its textures as they are. + pub fn reserved(base: usize, size: usize, t: u32, p: u32) { + if t & PAGES_64K != PAGES_64K || t & 0x1000 != 0 { + return; + } + let mut s = STATE.lock().unwrap(); + let seq = s.next; + s.next += 1; + if p & GRAPHICS_NOACCESS != 0 && p & 0xFF == super::mem::PAGE_NOACCESS { + // CPU views of its size that are not the GPU view of anything yet + let taken: Vec = s.gpu.values().map(|&(_, c)| c).collect(); + let candidates: Vec<(u64, usize)> = s + .cpu + .iter() + .filter(|&&(_, b, n)| n == size && !taken.contains(&b)) + .map(|&(q, b, _)| (q, b)) + .collect(); + // the immediately preceding reservation, while it is still one of them + let preceded = s.last.filter(|&(q, _, n)| n == size && candidates.iter().any(|&(cq, _)| cq == q)); + match (candidates.as_slice(), preceded) { + ([(_, cpu)], Some(_)) => { + s.gpu.insert(base, (size, *cpu)); + crate::xlog_info!("kernelx: reservation {base:#x} ({size:#x} bytes, no CPU access) is the GPU view of {cpu:#x}"); + } + (candidates, _) => { + static SKIPPED: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + let n = SKIPPED.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1; + if n <= 2 || n.is_power_of_two() { + crate::xlog_info!( + "kernelx: reservation {base:#x} ({size:#x} bytes, no CPU access) is not paired: {} same-size CPU view(s), not exactly the reservation before it – a texture there stays as it is ({n} so far)", + candidates.len() + ); + } + } + } + } else if p & 0xFF != super::mem::PAGE_NOACCESS { + s.cpu.push((seq, base, size)); + } + s.last = Some((seq, base, size)); + } + + /// The reservation at `base` was released. + pub fn released(base: usize) { + let mut s = STATE.lock().unwrap(); + s.cpu.retain(|&(_, b, _)| b != base); + s.gpu.remove(&base); + s.gpu.retain(|_, &mut (_, c)| c != base); + if s.last.is_some_and(|(_, b, _)| b == base) { + s.last = None; + } + } + + /// The CPU-view address behind `va` when `va` lies in a GPU view. + pub fn source(va: usize) -> Option { + let s = STATE.lock().unwrap(); + let (&gpu, &(size, cpu)) = s.gpu.range(..=va).next_back()?; + (va < gpu + size).then(|| cpu + (va - gpu)) + } +} + /// Graphics memory (MEM_GRAPHICS, committed, no fixed address) comes from the unified /// memory region the GPU uses directly (`gpu::uma`); a graphics reservation (no commit) is /// write-watched address space of Windows; everything else from Windows. @@ -280,11 +375,10 @@ pub unsafe extern "system" fn VirtualAlloc(addr: *const c_void, size: usize, t: // (`d3d12x::title_textures`), which needs its CPU writes to be seen: it is write-watched // like a graphics reservation. Without that such a texture was uploaded once, empty, and // never again (the game's glyph atlas: its menus lost their x-height letters). - if addr.is_null() && t & 0x2000 != 0 && (t & (MEM_GRAPHICS | 0x2000_0000) != 0 || p & PAGE_GRAPHICS_ANY != 0) { - let q = mem::VirtualAlloc(addr, size, sanitize_alloc_type(t) | MEM_WRITE_WATCH, sanitize_protect(p)); + if gpu_visible_fallback(addr, t, p) { + let q = reserve_watched(size, t, p); if !q.is_null() { - GRAPHICS_RESERVATIONS.lock().unwrap().insert(q as usize, size); - GRAPHICS_RESERVATIONS_GEN.fetch_add(1, Ordering::Release); + mirrors::reserved(q as usize, size, t, p); trace_mem("VirtualAlloc (GPU-visible, write-watched)", addr as usize, size, t as u64, p, q as usize); return q; } @@ -298,6 +392,25 @@ pub unsafe extern "system" fn VirtualAlloc(addr: *const c_void, size: usize, t: q } +/// Whether a VirtualAlloc that reached the plain-memory fallback is GPU-visible title memory +/// (a reservation with MEM_GRAPHICS, MEM_LARGE_PAGES / MEM_64K_PAGES or a PAGE_GRAPHICS_* +/// protection, at no fixed address), which is reserved write-watched (`reserve_watched`). +fn gpu_visible_fallback(addr: *const c_void, t: u32, p: u32) -> bool { + addr.is_null() && t & 0x2000 != 0 && (t & (MEM_GRAPHICS | 0x2000_0000) != 0 || p & PAGE_GRAPHICS_ANY != 0) +} + +/// Plain memory for GPU-visible title memory, write-watched and recorded with the graphics +/// reservations (whose ranges `title_textures` watches; `VirtualFree` forgets it). Null if +/// Windows refuses it. +unsafe fn reserve_watched(size: usize, t: u32, p: u32) -> *mut c_void { + let q = mem::VirtualAlloc(std::ptr::null(), size, sanitize_alloc_type(t) | MEM_WRITE_WATCH, sanitize_protect(p)); + if !q.is_null() { + GRAPHICS_RESERVATIONS.lock().unwrap().insert(q as usize, size); + GRAPHICS_RESERVATIONS_GEN.fetch_add(1, Ordering::Release); + } + q +} + /// PAGE_GRAPHICS_NOACCESS … PAGE_GRAPHICS_NOCACHE (0x800 – 0x40000): the console's protection of /// GPU-visible memory const PAGE_GRAPHICS_ANY: u32 = 0x7_F800; @@ -386,6 +499,7 @@ pub unsafe extern "system" fn VirtualFree(addr: *mut c_void, size: usize, t: u32 let ok = mem::VirtualFree(addr, size, t); if ok != 0 && t & 0x8000 != 0 && GRAPHICS_RESERVATIONS.lock().unwrap().remove(&(addr as usize)).is_some() { GRAPHICS_RESERVATIONS_GEN.fetch_add(1, Ordering::Release); + mirrors::released(addr as usize); } ok } @@ -685,7 +799,9 @@ fn process_private_bytes() -> u64 { let mut c: PROCESS_MEMORY_COUNTERS_EX = std::mem::zeroed(); c.cb = std::mem::size_of::() as u32; if K32GetProcessMemoryInfo(thr::GetCurrentProcess(), &mut c as *mut _ as *mut _, c.cb) != 0 { - c.PrivateUsage as u64 + // Wine fills the fields before PrivateUsage only; PagefileUsage is the same number + // on Windows (the commit charge) + if c.PrivateUsage != 0 { c.PrivateUsage as u64 } else { c.PagefileUsage as u64 } } else { 0 } @@ -1358,6 +1474,8 @@ struct OsVersionInfoW { #[link(name = "ntdll", kind = "raw-dylib")] extern "system" { fn RtlGetVersion(info: *mut OsVersionInfoW) -> i32; + fn NtQueryTimerResolution(coarsest: *mut u32, finest: *mut u32, current: *mut u32) -> i32; + fn NtSetTimerResolution(desired: u32, set: u8, current: *mut u32) -> i32; } pub fn host_os_version() -> (u32, u32, u32) { @@ -1369,6 +1487,38 @@ pub fn host_os_version() -> (u32, u32, u32) { } } +/// The finest timer Windows offers (0.5 ms) for the title: with the default 15.6 ms tick every +/// sleep rounds up (a retail game's audio mixer ran at a third of real time). Windows 11 keeps +/// it while the window is hidden only when told to. +pub fn fine_timer() { + use windows_sys::Win32::System::Threading::{ + GetCurrentProcess, ProcessPowerThrottling, SetProcessInformation, PROCESS_POWER_THROTTLING_CURRENT_VERSION, + PROCESS_POWER_THROTTLING_IGNORE_TIMER_RESOLUTION, PROCESS_POWER_THROTTLING_STATE, + }; + let state = PROCESS_POWER_THROTTLING_STATE { + Version: PROCESS_POWER_THROTTLING_CURRENT_VERSION, + ControlMask: PROCESS_POWER_THROTTLING_IGNORE_TIMER_RESOLUTION, + StateMask: 0, + }; + let size = std::mem::size_of::() as u32; + let kept = unsafe { SetProcessInformation(GetCurrentProcess(), ProcessPowerThrottling, &state as *const _ as *const c_void, size) } != 0; + // in 100 ns units; "finest" is the smallest period the system supports + let (mut coarsest, mut finest, mut was) = (0u32, 0u32, 0u32); + if unsafe { NtQueryTimerResolution(&mut coarsest, &mut finest, &mut was) } < 0 || finest == 0 { + crate::xlog_warn!("timer: NtQueryTimerResolution failed – Windows' default resolution"); + return; + } + let mut now = 0u32; + let status = unsafe { NtSetTimerResolution(finest, 1, &mut now) }; + crate::xlog_info!( + "timer: {} (was {:.2} ms, now {:.2} ms; kept while the window is hidden: {})", + if status >= 0 { "finest resolution for the title" } else { "raising the resolution failed" }, + was as f64 / 10_000.0, + now as f64 / 10_000.0, + if kept { "yes" } else { "no" } + ); +} + pub unsafe extern "system" fn GetSystemOSVersion(out: *mut SystemOsVersionInfo) { if out.is_null() { return; @@ -1710,6 +1860,18 @@ pub unsafe extern "system" fn DisableThreadLibraryCalls(h: usize) -> BOOL { mod tests { use super::*; + #[test] + fn fine_timer_makes_short_sleeps_short() { + // Windows' Sleep (std::thread::sleep has its own high-resolution timer) + fine_timer(); + let t = std::time::Instant::now(); + for _ in 0..20 { + unsafe { windows_sys::Win32::System::Threading::Sleep(1) }; + } + let per = t.elapsed() / 20; + assert!(per < std::time::Duration::from_millis(5), "Sleep(1) took {per:?}: the 15.6 ms tick"); + } + #[test] fn affinity_masks_outside_the_process_are_fitted() { // a mask from the PC's processors is the title's choice @@ -2219,6 +2381,8 @@ mod tests { assert_eq!(unsafe { TitleMemoryStatus(&mut s) }, 1); assert_eq!(s.total, 13_824 * 1024 * 1024); assert!(s.avail <= s.total); + // the process's own memory counts as used (Wine leaves PrivateUsage 0) + assert!(process_private_bytes() > 0 && s.avail < s.total); s.dw_length = 8; assert_eq!(unsafe { TitleMemoryStatus(&mut s) }, 0); } @@ -2350,23 +2514,84 @@ mod tests { } } - /// GPU-visible title memory that falls back to plain memory (64 KiB pages, large pages, a - /// graphics protection) is write-watched: a texture placed there sees the CPU's writes. + /// the `mirrors` tests share its state (the reservation before a GPU view is process-wide): + /// one at a time + static MIRRORS_TEST: std::sync::Mutex<()> = std::sync::Mutex::new(()); + + /// A no-access graphics reservation of 64 KiB pages is the GPU view of the CPU-readable one + /// of its size immediately before it: textures there read the CPU view (`title_textures`). + #[test] + fn gpu_view_reservations_name_their_cpu_view() { + let _one = MIRRORS_TEST.lock().unwrap(); + // (addresses far above anything Windows hands out: only the bookkeeping is tested) + let (a, b, size) = (0x7000_0000_0000usize, 0x7006_0000_0000usize, 0x6_0000_0000usize); + let other = 0x7010_0000_0000usize; + mirrors::reserved(other, 0x1000_0000, 0x2040_2000, mem::PAGE_READWRITE); // another size + mirrors::reserved(a, size, 0x2040_2000, mem::PAGE_READWRITE); + assert_eq!(mirrors::source(b + 0x1234_0000), None, "no GPU view yet"); + mirrors::reserved(b, size, 0x2040_2000, 0x801); + assert_eq!(mirrors::source(b), Some(a)); + assert_eq!(mirrors::source(b + 0x4524_0000), Some(a + 0x4524_0000)); + assert_eq!(mirrors::source(b + size), None, "past its end"); + assert_eq!(mirrors::source(a + 0x10), None, "the CPU view is no GPU view"); + // committed memory or other protections are no GPU views + let c = 0x7020_0000_0000usize; + mirrors::reserved(c, size, 0x2040_3000, 0x801); + assert_eq!(mirrors::source(c), None); + mirrors::released(a); + assert_eq!(mirrors::source(b), None, "released with its CPU view"); + mirrors::released(other); + } + + /// A GPU view is paired only with the reservation immediately before it and only when that + /// is the single CPU view of its size: otherwise it stays unpaired (textures there are not + /// read from a view the title may not mean). + #[test] + fn ambiguous_gpu_views_stay_unpaired() { + let _one = MIRRORS_TEST.lock().unwrap(); + let size = 0x2_0000_0000usize; + // two CPU views of the same size: which one the GPU view means is not known + let (x, y, g) = (0x7100_0000_0000usize, 0x7104_0000_0000usize, 0x7108_0000_0000usize); + mirrors::reserved(x, size, 0x2040_2000, mem::PAGE_READWRITE); + mirrors::reserved(y, size, 0x2040_2000, mem::PAGE_READWRITE); + mirrors::reserved(g, size, 0x2040_2000, 0x801); + assert_eq!(mirrors::source(g), None, "two same-size CPU views"); + // a reservation of another size in between: the GPU view is not a view of the one + // before that gap + let size = 0x1_0000_0000usize; + let (p, q, h) = (0x7200_0000_0000usize, 0x7210_0000_0000usize, 0x7220_0000_0000usize); + mirrors::reserved(p, size, 0x2040_2000, mem::PAGE_READWRITE); + mirrors::reserved(q, 0x1000_0000, 0x2040_2000, mem::PAGE_READWRITE); + mirrors::reserved(h, size, 0x2040_2000, 0x801); + assert_eq!(mirrors::source(h), None, "not the reservation immediately before it"); + for b in [x, y, g, p, q, h] { + mirrors::released(b); + } + } + + /// GPU-visible title memory that reaches the plain-memory fallback (64 KiB pages, large + /// pages, a graphics protection) is write-watched: a texture placed there sees the CPU's + /// writes. The fallback is called directly: through `VirtualAlloc` these sizes land in a + /// unified-memory window whenever one has room (once any test has made the windows). #[test] fn gpu_visible_fallback_memory_is_write_watched() { + let null = std::ptr::null(); + // (MEM_64K_PAGES | MEM_RESERVE; MEM_LARGE_PAGES | MEM_RESERVE | MEM_COMMIT with a + // PAGE_GRAPHICS_* protection; MEM_GRAPHICS | MEM_RESERVE | MEM_COMMIT) + let gpu = [(0x2040_2000u32, mem::PAGE_READWRITE), (0x2000_3000, 0x2404), (MEM_GRAPHICS | 0x3000, mem::PAGE_READWRITE)]; + for &(t, p) in &gpu { + assert!(gpu_visible_fallback(null, t, p), "flags {t:#x} protect {p:#x}"); + } + // plain memory stays plain: CPU-only reservations, commits at a fixed address + assert!(!gpu_visible_fallback(null, 0x3000, mem::PAGE_READWRITE)); + assert!(!gpu_visible_fallback(null, 0x1000, 0x2404), "a commit without a reservation"); + assert!(!gpu_visible_fallback(0x1_0000 as *const c_void, 0x2040_2000, mem::PAGE_READWRITE), "a fixed address"); unsafe { - // (MEM_64K_PAGES | MEM_RESERVE; MEM_LARGE_PAGES | MEM_RESERVE | MEM_COMMIT with a - // PAGE_GRAPHICS_* protection; MEM_GRAPHICS | MEM_RESERVE | MEM_COMMIT) - for (t, p) in [(0x2040_2000u32, mem::PAGE_READWRITE), (0x2000_3000, 0x2404), (MEM_GRAPHICS | 0x3000, mem::PAGE_READWRITE)] { + for (t, p) in gpu { let size = 0x40_0000; - let q = VirtualAlloc(std::ptr::null(), size, t, p); + let q = reserve_watched(size, t, p); assert!(!q.is_null(), "flags {t:#x}"); let a = q as usize; - if crate::gpu::uma::get().is_some_and(|u| u.contains(a) || u.is_sparse(a)) { - // a window had room: write-watched there (`uma::watch_regions`) - VirtualFree(q, 0, mem::MEM_RELEASE); - continue; - } assert!(in_graphics_reservation(a), "flags {t:#x}: a fallback allocation is watched"); if t & 0x1000 == 0 { assert!(!VirtualAlloc((a + 0x2_0000) as *const c_void, 0x1_0000, 0x1000, mem::PAGE_READWRITE).is_null()); diff --git a/crates/xcl/src/hle/opus.rs b/crates/xcl/src/hle/opus.rs index c2d1018..097d494 100644 --- a/crates/xcl/src/hle/opus.rs +++ b/crates/xcl/src/hle/opus.rs @@ -826,9 +826,187 @@ fn mf_runtime() -> Result<&'static MfRuntime, String> { .map_err(|e| e.clone()) } -/// Whether Windows' built-in `MSOpusDecoder.dll` + Media Foundation runtime is available. +/// Whether an Opus decoder is available: Windows' built-in `MSOpusDecoder.dll` + Media Foundation +/// runtime, or libopus loaded from `opus.dll` (see [`libopus`]). pub fn is_available() -> bool { - mf_runtime().is_ok() + mf_runtime().is_ok() || libopus().is_ok() +} + +/// The decoder in use ("Windows MSOpusDecoder", "libopus (path)"), or why there is none. Logged once. +pub fn backend() -> String { + match (mf_runtime(), libopus()) { + (Ok(_), _) => "Windows' MSOpusDecoder (Media Foundation)".to_string(), + (_, Ok(l)) => format!("libopus ({})", l.path), + (Err(a), Err(b)) => format!("none ({a}; {b})"), + } +} + +// --------------------------------------------------------------------------------------- +// libopus from `opus.dll`, loaded at run time (where Windows' decoder does not exist: Wine) +// --------------------------------------------------------------------------------------- +// +// Not distributed with XCL (like DXC): `opus.dll` – libopus (BSD-3-Clause), built for Windows – is +// looked for in `%XCL_OPUS_DIR%`, then next to xcl.exe (`opus.dll`, `libopus.dll`, `libopus-0.dll`). +// Windows' own decoder is used first when the system has it. Only the decoder is used. + +type OpusDecoderCreateFn = unsafe extern "C" fn(i32, i32, *mut i32) -> *mut c_void; +type OpusDecodeFn = unsafe extern "C" fn(*mut c_void, *const u8, i32, *mut i16, i32, i32) -> i32; +type OpusDecoderDestroyFn = unsafe extern "C" fn(*mut c_void); +type OpusDecoderCtlFn = unsafe extern "C" fn(*mut c_void, i32, ...) -> i32; + +/// `OPUS_RESET_STATE`: the decoder starts again +const OPUS_RESET_STATE: i32 = 4028; + +struct LibOpus { + path: String, + create: OpusDecoderCreateFn, + decode: OpusDecodeFn, + destroy: OpusDecoderDestroyFn, + ctl: OpusDecoderCtlFn, +} + +static LIBOPUS: OnceLock> = OnceLock::new(); + +fn libopus() -> Result<&'static LibOpus, String> { + LIBOPUS + .get_or_init(|| unsafe { + use std::os::windows::ffi::OsStrExt; + use windows_sys::Win32::System::LibraryLoader::LoadLibraryW; + let mut dirs: Vec = Vec::new(); + if let Some(d) = std::env::var_os("XCL_OPUS_DIR") { + dirs.push(d.into()); + } + if let Some(d) = std::env::current_exe().ok().and_then(|p| p.parent().map(|d| d.to_path_buf())) { + dirs.push(d); + } + for dir in &dirs { + for name in ["opus.dll", "libopus.dll", "libopus-0.dll"] { + let path = dir.join(name); + if !path.is_file() { + continue; + } + let wide: Vec = path.as_os_str().encode_wide().chain(Some(0)).collect(); + let h = LoadLibraryW(wide.as_ptr()) as usize; + if h == 0 { + continue; + } + let f = |n: &str| crate::resolver::system_proc_in(h, &crate::pe::ImportName::Name { hint: 0, name: n.into() }); + let (Some(create), Some(decode), Some(destroy), Some(ctl)) = + (f("opus_decoder_create"), f("opus_decode"), f("opus_decoder_destroy"), f("opus_decoder_ctl")) + else { + continue; + }; + return Ok(LibOpus { + path: path.display().to_string(), + create: std::mem::transmute::(create), + decode: std::mem::transmute::(decode), + destroy: std::mem::transmute::(destroy), + ctl: std::mem::transmute::(ctl), + }); + } + } + Err("no opus.dll (libopus) in %XCL_OPUS_DIR% or next to xcl.exe".to_string()) + }) + .as_ref() + .map_err(|e| e.clone()) +} + +/// One libopus decoder (1 or 2 channels), the same job as [`MftDecoder`]. +struct LibDecoder { + lib: &'static LibOpus, + state: *mut c_void, + channels: u16, + output_rate: u32, +} + +impl LibDecoder { + fn new(channels: u16, sample_rate: u32) -> Result { + let lib = libopus()?; + let ch = channels.clamp(1, 2); + // libopus decodes to 8, 12, 16, 24 or 48 kHz + let rate = if matches!(sample_rate, 8_000 | 12_000 | 16_000 | 24_000 | 48_000) { sample_rate } else { 48_000 }; + let mut err = 0i32; + let state = unsafe { (lib.create)(rate as i32, ch as i32, &mut err) }; + if state.is_null() || err != 0 { + return Err(format!("opus_decoder_create: {err}")); + } + Ok(Self { lib, state, channels: ch, output_rate: rate }) + } + + fn flush(&mut self) { + unsafe { + (self.lib.ctl)(self.state, OPUS_RESET_STATE); + } + } + + fn decode_packet(&mut self, packet: &[u8], out: &mut Vec) -> Result { + let max_frames = (MAX_PACKET_SAMPLES_48K as usize * self.output_rate as usize) / 48_000; + let ch = self.channels as usize; + let start = out.len(); + out.resize(start + max_frames * ch, 0); + let n = unsafe { (self.lib.decode)(self.state, packet.as_ptr(), packet.len() as i32, out[start..].as_mut_ptr(), max_frames as i32, 0) }; + if n < 0 { + out.truncate(start); + return Err(format!("opus_decode: {n}")); + } + out.truncate(start + n as usize * ch); + Ok(n as usize) + } +} + +impl Drop for LibDecoder { + fn drop(&mut self) { + unsafe { (self.lib.destroy)(self.state) } + } +} + +// SAFETY: a libopus decoder state is used by one thread at a time (`&mut self`). +unsafe impl Send for LibDecoder {} + +/// One single-stream decoder: Windows' MFT where there is one, else libopus. +enum SingleStreamDecoder { + Mft(MftDecoder), + Lib(LibDecoder), +} + +impl SingleStreamDecoder { + fn new(channels: u16, sample_rate: u32, head_bytes: Option<&[u8]>) -> Result { + static CHOICE: std::sync::Once = std::sync::Once::new(); + CHOICE.call_once(|| crate::xlog_info!("Opus: decoder = {}", backend())); + match MftDecoder::new(channels, sample_rate, head_bytes) { + Ok(d) => Ok(Self::Mft(d)), + Err(mft) => LibDecoder::new(channels, sample_rate).map(Self::Lib).map_err(|lib| format!("{mft}; {lib}")), + } + } + + fn output_rate(&self) -> u32 { + match self { + Self::Mft(d) => d.output_rate, + Self::Lib(d) => d.output_rate, + } + } + + /// stream time of the next packet (0: nothing decoded since the start / the last flush) + fn timestamp_100ns(&self) -> i64 { + match self { + Self::Mft(d) => d.timestamp_100ns, + Self::Lib(_) => 0, + } + } + + fn flush(&mut self) { + match self { + Self::Mft(d) => d.flush(), + Self::Lib(d) => d.flush(), + } + } + + fn decode_packet(&mut self, packet: &[u8], out: &mut Vec) -> Result { + match self { + Self::Mft(d) => d.decode_packet(packet, out), + Self::Lib(d) => d.decode_packet(packet, out), + } + } } fn mf_create_media_type(rt: &MfRuntime) -> Result { @@ -882,7 +1060,7 @@ enum OutputSampleFormat { Float32, } -struct SingleStreamDecoder { +struct MftDecoder { mft: IMFTransform, channels: u16, output_rate: u32, @@ -892,7 +1070,7 @@ struct SingleStreamDecoder { timestamp_100ns: i64, } -impl SingleStreamDecoder { +impl MftDecoder { fn new(channels: u16, sample_rate: u32, head_bytes: Option<&[u8]>) -> Result { let rt = mf_runtime()?; let mft = create_opus_mft(rt)?; @@ -1163,7 +1341,7 @@ impl Decoder { streams.push(SingleStreamDecoder::new(sch, rate, Some(&ud))?); } } - let output_rate = streams[0].output_rate; + let output_rate = streams[0].output_rate(); let pre_skip_scaled = ((head.pre_skip as u64 * output_rate as u64) / 48_000) as usize; let output_gain_scale = gain_scale(head.output_gain); @@ -1291,7 +1469,7 @@ impl Decoder { && t.head.coupled_count == self.coupled_count && t.head.mapping == self.mapping && gain_scale(t.head.output_gain) == self.output_gain_scale - && self.streams.iter().all(|s| s.timestamp_100ns == 0) + && self.streams.iter().all(|s| s.timestamp_100ns() == 0) }); if let Some(timing) = timing { for pkt in &packets { diff --git a/crates/xcl/src/hle/user.rs b/crates/xcl/src/hle/user.rs index 030e286..45da60e 100644 --- a/crates/xcl/src/hle/user.rs +++ b/crates/xcl/src/hle/user.rs @@ -71,6 +71,15 @@ unsafe fn name(p: *const u8, keep: &mut Vec>) -> *const u16 { keep.last().unwrap().as_ptr() } +#[link(name = "kernel32")] +extern "system" { + fn GetLastError() -> u32; +} + +/// Atoms this process registered, so a second RegisterClassExA of the same name still returns +/// the atom. Windows answers the second call with 0, and the title stops on that. +static CLASS_ATOMS: std::sync::Mutex, u16)>> = std::sync::Mutex::new(Vec::new()); + pub unsafe extern "system" fn RegisterClassExA(c: *const WndClassEx) -> u16 { if c.is_null() { return 0; @@ -95,7 +104,28 @@ pub unsafe extern "system" fn RegisterClassExA(c: *const WndClassEx) -> u16 class_name: name(c.class_name, &mut keep), icon_small: c.icon_small, }; - RegisterClassExW(&w) + let class_key = ((c.class_name as usize) >= 0x1_0000).then(|| keep.last().cloned().unwrap_or_default()).unwrap_or_default(); + if !class_key.is_empty() { + if let Some(atom) = CLASS_ATOMS.lock().unwrap().iter().find(|(n, _)| n == &class_key).map(|(_, a)| *a) { + return atom; + } + } + let atom = RegisterClassExW(&w); + if atom != 0 { + if !class_key.is_empty() { + CLASS_ATOMS.lock().unwrap().push((class_key, atom)); + } + return atom; + } + let err = GetLastError(); + // ERROR_CLASS_ALREADY_EXISTS: the class is registered, the title only tests the atom is non-zero + if err == 1410 { + crate::xlog_info!("user: RegisterClassExA: class already registered"); + return 1; + } + let shown = if class_key.is_empty() { String::new() } else { String::from_utf16_lossy(&class_key) }; + crate::xlog_warn!("user: RegisterClassExA failed ({err}) for '{shown}'"); + 0 } #[allow(clippy::too_many_arguments)] @@ -148,8 +178,14 @@ unsafe fn console_window(ex_style: u32, class: *const u16, title: *const u16, st } let style = style & !WS_FRAME | WS_POPUP; let ex_style = ex_style & !WS_EX_FRAME & !WS_EX_APPWINDOW | WS_EX_TOOLWINDOW; - let hwnd = CreateWindowExW(ex_style, class, title, style, 0, 0, CONSOLE_W, CONSOLE_H, parent, menu, instance, param); + let mut hwnd = CreateWindowExW(ex_style, class, title, style, 0, 0, CONSOLE_W, CONSOLE_H, parent, menu, instance, param); + if hwnd.is_null() { + let err = GetLastError(); + crate::xlog_warn!("user: CreateWindowEx failed ({err:#x}) style {style:#x} parent {parent:p}; retrying without a parent"); + hwnd = CreateWindowExW(ex_style, class, title, style, 0, 0, CONSOLE_W, CONSOLE_H, std::ptr::null_mut(), std::ptr::null_mut(), instance, param); + } if hwnd.is_null() { + crate::xlog_warn!("user: CreateWindowEx retry failed ({:#x})", GetLastError()); return hwnd; } let cloak: i32 = 1; diff --git a/crates/xcl/src/hle/xaudio2.rs b/crates/xcl/src/hle/xaudio2.rs index f762160..932e0ef 100644 --- a/crates/xcl/src/hle/xaudio2.rs +++ b/crates/xcl/src/hle/xaudio2.rs @@ -67,6 +67,7 @@ const CO_E_NOTINITIALIZED: HRESULT = 0x8004_01F0u32 as i32; const ENGINE_CREATE_SOURCE_VOICE: usize = 5; const ENGINE_CREATE_MASTERING_VOICE: usize = 7; const VOICE_DESTROY: usize = 18; +const VOICE_START: usize = 19; const VOICE_SUBMIT_SOURCE_BUFFER: usize = 21; const VOICE_FLUSH_SOURCE_BUFFERS: usize = 22; const VOICE_GET_STATE: usize = 25; @@ -171,6 +172,7 @@ pub fn exports() -> Vec<(&'static str, usize)> { // --------------------------------------------------------------------------------------- #[derive(Debug, Default, Clone, Serialize, Deserialize)] +#[serde(default)] pub struct AudioStats { pub engines: u64, pub engine_errors: u64, @@ -197,6 +199,19 @@ pub struct AudioStats { pub source_voice_errors: u64, /// console-only flags we dropped, e.g. "XAudio2Create:0x1" pub dropped_flags: Vec, + /// the console's decoder (xapu, `hle::acphal`): Opus packets decoded, packets that failed (silence + /// went out), frames produced, samples that are not 0 + pub xapu_packets_decoded: u64, + pub xapu_decode_errors: u64, + pub xapu_frames: u64, + pub xapu_nonzero_samples: u64, + /// the console decoder's PCM played here: voices, samples (and the non-zero ones) submitted to + /// XAudio2, buffers dropped (queue full or no device), errors + pub console_pcm_voices: u64, + pub console_pcm_samples: u64, + pub console_pcm_nonzero_samples: u64, + pub console_pcm_dropped: u64, + pub console_pcm_errors: u64, } static ENGINES: AtomicU64 = AtomicU64::new(0); @@ -236,6 +251,15 @@ pub fn stats() -> AudioStats { buffers_silenced: SILENCED.load(Ordering::Relaxed), source_voice_errors: SOURCE_ERRORS.load(Ordering::Relaxed), dropped_flags: DROPPED.lock().map(|d| d.clone()).unwrap_or_default(), + xapu_packets_decoded: PCM_PACKETS.load(Ordering::Relaxed), + xapu_decode_errors: PCM_PACKET_ERRORS.load(Ordering::Relaxed), + xapu_frames: PCM_DECODED_FRAMES.load(Ordering::Relaxed), + xapu_nonzero_samples: PCM_NONZERO.load(Ordering::Relaxed), + console_pcm_voices: SINK_VOICES.load(Ordering::Relaxed), + console_pcm_samples: SINK_SAMPLES.load(Ordering::Relaxed), + console_pcm_nonzero_samples: SINK_NONZERO.load(Ordering::Relaxed), + console_pcm_dropped: SINK_DROPPED.load(Ordering::Relaxed), + console_pcm_errors: SINK_ERRORS.load(Ordering::Relaxed), } } @@ -1168,6 +1192,176 @@ unsafe extern "system" fn destroy_voice(this: *mut c_void) { } } +// --------------------------------------------------------------------------------------- +// the console audio processor's PCM out (hle::acphal): decoded streams played on the PC +// --------------------------------------------------------------------------------------- +// +// A title that uses the console's audio hardware (xapu decoder, SHAPE mixer) has no XAudio2 +// engine of its own. What xapu decodes is played here: one float32 source voice per decoder +// stream on an engine of this module's own (system XAudio2), mixed by Windows. It runs on a thread +// of its own (COM, the device and the queue never hold up the title's audio thread). The SHAPE +// mixer's volumes, panning and effects are not applied – the decoded stream plays as it is. + +use std::sync::mpsc::{channel, Sender}; + +/// float32 samples a title's decoder stream hands over: (decoder stream, channels, interleaved samples) +type SinkItem = (u32, u16, Vec); + +/// buffers of one sink voice: a queue deeper than this drops the newest samples +const SINK_RING: usize = 24; + +static SINK: OnceLock>>> = OnceLock::new(); +static SINK_SAMPLES: AtomicU64 = AtomicU64::new(0); +static SINK_NONZERO: AtomicU64 = AtomicU64::new(0); +static SINK_DROPPED: AtomicU64 = AtomicU64::new(0); +static SINK_ERRORS: AtomicU64 = AtomicU64::new(0); +static SINK_VOICES: AtomicU64 = AtomicU64::new(0); +static PCM_DECODED_FRAMES: AtomicU64 = AtomicU64::new(0); +static PCM_NONZERO: AtomicU64 = AtomicU64::new(0); +static PCM_PACKETS: AtomicU64 = AtomicU64::new(0); +static PCM_PACKET_ERRORS: AtomicU64 = AtomicU64::new(0); + +/// What the console decoder (xapu) did: `packets` Opus packets decoded to `frames` frames of which +/// `nonzero` samples are not 0, `errors` packets that did not decode (silence went out). +pub fn note_console_decode(packets: u64, errors: u64, frames: u64, nonzero: u64) { + PCM_PACKETS.fetch_add(packets, Ordering::Relaxed); + PCM_PACKET_ERRORS.fetch_add(errors, Ordering::Relaxed); + PCM_DECODED_FRAMES.fetch_add(frames, Ordering::Relaxed); + PCM_NONZERO.fetch_add(nonzero, Ordering::Relaxed); +} + +/// Plays what a console decoder stream produced (interleaved float32, 48 kHz). Never blocks. +pub fn console_pcm(stream: u32, channels: u16, samples: &[f32]) { + if samples.is_empty() || !(1..=2).contains(&channels) { + return; + } + let tx = SINK.get_or_init(|| { + let (tx, rx) = channel::(); + match std::thread::Builder::new().name("console-audio".into()).spawn(move || sink_thread(rx)) { + Ok(_) => Mutex::new(Some(tx)), + Err(_) => { + SINK_ERRORS.fetch_add(1, Ordering::Relaxed); + Mutex::new(None) + } + } + }); + if let Some(t) = tx.lock().unwrap().as_ref() { + let _ = t.send((stream, channels, samples.to_vec())); + } +} + +/// a voice's method: the system's, whatever this module patched in the shared vtable +unsafe fn voice_fn(obj: *mut c_void, slot: usize) -> usize { + original(obj, slot).unwrap_or_else(|| vtable(obj).add(slot).read()) +} + +struct SinkVoice { + voice: *mut c_void, + channels: u16, + ring: Vec>, + next: usize, +} + +unsafe fn sink_engine() -> Option<(*mut c_void, *mut c_void)> { + use windows_sys::Win32::System::Com::{CoInitializeEx, COINIT_MULTITHREADED}; + CoInitializeEx(std::ptr::null(), COINIT_MULTITHREADED as u32); + let (with_version, plain) = system_create()?; + let mut engine: *mut c_void = std::ptr::null_mut(); + let hr = match (with_version, plain) { + (Some(f), _) => f(&mut engine, 0, XAUDIO2_DEFAULT_PROCESSOR, NTDDI_WIN10_RS5), + (None, Some(f)) => f(&mut engine, 0, XAUDIO2_DEFAULT_PROCESSOR), + _ => E_FAIL, + }; + if hr < 0 || engine.is_null() { + crate::xlog_warn!("console audio: no XAudio2 engine ({:#x}) – decoded sound is not played", hr as u32); + return None; + } + let create_mastering: CreateMasteringVoiceFn = std::mem::transmute(voice_fn(engine, ENGINE_CREATE_MASTERING_VOICE)); + let mut mastering: *mut c_void = std::ptr::null_mut(); + let hr = create_mastering(engine, &mut mastering, 0, 0, 0, std::ptr::null(), std::ptr::null(), AUDIO_CATEGORY_GAME_EFFECTS); + if hr < 0 || mastering.is_null() { + crate::xlog_warn!("console audio: no mastering voice ({:#x}) – no audio device? decoded sound is not played", hr as u32); + return None; + } + crate::xlog_info!("console audio: XAudio2 engine and mastering voice created – the console decoder's PCM is played"); + Some((engine, mastering)) +} + +fn sink_thread(rx: std::sync::mpsc::Receiver) { + unsafe { + let Some((engine, _mastering)) = sink_engine() else { + SINK_ERRORS.fetch_add(1, Ordering::Relaxed); + // keep draining so the title's side never queues without bound + for _ in rx { + SINK_DROPPED.fetch_add(1, Ordering::Relaxed); + } + return; + }; + let mut voices: HashMap = HashMap::new(); + for (stream, channels, samples) in rx { + let need_new = voices.get(&stream).is_none_or(|v| v.channels != channels); + if need_new { + if let Some(old) = voices.remove(&stream) { + let destroy: DestroyVoiceFn = std::mem::transmute(voice_fn(old.voice, VOICE_DESTROY)); + destroy(old.voice); + } + let fmt = WaveFormatEx { + tag: WAVE_FORMAT_IEEE_FLOAT, + channels, + rate: 48_000, + avg_bytes: 48_000 * 4 * channels as u32, + block_align: 4 * channels, + bits: 32, + cb_size: 0, + }; + let create: CreateSourceVoiceFn = std::mem::transmute(voice_fn(engine, ENGINE_CREATE_SOURCE_VOICE)); + let mut voice: *mut c_void = std::ptr::null_mut(); + let hr = create(engine, &mut voice, &fmt, 0, 1.0, std::ptr::null_mut(), std::ptr::null(), std::ptr::null()); + if hr < 0 || voice.is_null() { + crate::xlog_warn!("console audio: stream {stream}: no source voice ({:#x})", hr as u32); + SINK_ERRORS.fetch_add(1, Ordering::Relaxed); + continue; + } + let start: unsafe extern "system" fn(*mut c_void, u32, u32) -> HRESULT = std::mem::transmute(voice_fn(voice, VOICE_START)); + start(voice, 0, 0); + SINK_VOICES.fetch_add(1, Ordering::Relaxed); + voices.insert(stream, SinkVoice { voice, channels, ring: vec![Vec::new(); SINK_RING], next: 0 }); + } + let Some(v) = voices.get_mut(&stream) else { continue }; + let mut st = XAudio2VoiceState { current_buffer_context: std::ptr::null_mut(), buffers_queued: 0, samples_played: 0 }; + let get_state: GetStateFn = std::mem::transmute(voice_fn(v.voice, VOICE_GET_STATE)); + get_state(v.voice, &mut st, 0x100 /* XAUDIO2_VOICE_NOSAMPLESPLAYED */); + let queued = st.buffers_queued; + if queued as usize >= SINK_RING - 1 { + SINK_DROPPED.fetch_add(1, Ordering::Relaxed); + continue; + } + let slot = &mut v.ring[v.next]; + v.next = (v.next + 1) % SINK_RING; + *slot = samples; + let b = XAudio2Buffer { + flags: 0, + audio_bytes: (slot.len() * 4) as u32, + audio_data: slot.as_ptr() as *const u8, + play_begin: 0, + play_length: 0, + loop_begin: 0, + loop_length: 0, + loop_count: 0, + context: std::ptr::null_mut(), + }; + let submit: SubmitSourceBufferFn = std::mem::transmute(voice_fn(v.voice, VOICE_SUBMIT_SOURCE_BUFFER)); + let hr = submit(v.voice, &b, std::ptr::null()); + if hr < 0 { + SINK_ERRORS.fetch_add(1, Ordering::Relaxed); + } else { + SINK_SAMPLES.fetch_add(slot.len() as u64, Ordering::Relaxed); + SINK_NONZERO.fetch_add(slot.iter().filter(|&&x| x != 0.0).count() as u64, Ordering::Relaxed); + } + } + } +} + #[cfg(test)] mod tests { use super::*; diff --git a/crates/xcl/src/hle/xgameruntime/api.rs b/crates/xcl/src/hle/xgameruntime/api.rs index a35e9e2..66f9985 100644 --- a/crates/xcl/src/hle/xgameruntime/api.rs +++ b/crates/xcl/src/hle/xgameruntime/api.rs @@ -11,9 +11,10 @@ //! dropped), the XGameUi dialogs that do not take a user –, refuses XStore, app broadcast and //! app capture (the thunk then returns its "API not available" error), and passes everything //! else to the PC's own XGameRuntime (`System32\xgameruntime.dll`: the same classes under the -//! same GUIDs) – XTaskQueue / XAsync, XThread, XNetworking, XGameInvite… Once the PC runtime is -//! in use, the queues and async blocks are its own, so XCL's async APIs run on its XAsync -//! (`xasync::use_pc`). Nothing that takes an XCL user handle goes to the PC runtime: it does not +//! same GUIDs) – XTaskQueue / XAsync, XThread, XGameInvite… (XNetworking is always XCL's). Once +//! the PC runtime is in use, the queues and async blocks are its own, so XCL's async APIs run on +//! its XAsync (`xasync::use_pc`); without `System32\xgameruntime.dll`, XAsync / XTaskQueue / +//! XThread fall back to XCL's own. Nothing that takes an XCL user handle goes to the PC runtime: it does not //! validate foreign handles. //! //! Layout: `gdk_table` (extracted from the public PC GDK's thunk library) gives every @@ -138,7 +139,7 @@ fn pc() -> Option<&'static Pc> { use windows_sys::Win32::System::LibraryLoader::{GetProcAddress, LoadLibraryExW, LOAD_LIBRARY_SEARCH_SYSTEM32}; let h = LoadLibraryExW(crate::util::wide("xgameruntime.dll").as_ptr(), std::ptr::null_mut(), LOAD_LIBRARY_SEARCH_SYSTEM32); if h.is_null() { - crate::xlog_warn!("XGameRuntime: no System32\\xgameruntime.dll (Gaming Services) – XTaskQueue/XAsync and the other APIs XCL does not implement are unavailable"); + crate::xlog_warn!("XGameRuntime: no System32\\xgameruntime.dll (Gaming Services) – XCL's own XTaskQueue/XAsync are used; dialogs, text entry, game invites, game streaming and the other APIs XCL does not implement are unavailable"); return None; } let f = |n: &str| GetProcAddress(h, format!("{n}\0").as_ptr()).map(|p| p as usize); diff --git a/crates/xcl/src/host.rs b/crates/xcl/src/host.rs index 4d4bf80..6dd5cb1 100644 --- a/crates/xcl/src/host.rs +++ b/crates/xcl/src/host.rs @@ -8,6 +8,18 @@ use crate::config::Boot; pub static HOST_MODE: AtomicBool = AtomicBool::new(false); +/// Validate that this CPU has the console Zen 2 instruction set extensions. +/// Returns Ok(()) if all features are present or if XCL_SKIP_CPU_CHECK is set; +/// returns Err(missing) listing any missing features. +pub fn check_cpu_requirements() -> Result<(), Vec<&'static str>> { + let missing = crate::launcher::missing_console_cpu_features(); + if missing.is_empty() || std::env::var_os("XCL_SKIP_CPU_CHECK").is_some() { + Ok(()) + } else { + Err(missing) + } +} + pub fn host_main(boot_path: &Path) -> i32 { let boot: Boot = match std::fs::read_to_string(boot_path).map_err(|e| e.to_string()).and_then(|s| serde_json::from_str(&s).map_err(|e| e.to_string())) { Ok(b) => b, @@ -29,6 +41,22 @@ pub fn host_main(boot_path: &Path) -> i32 { std::env::set_var("XCL_UMA_MB", boot.config.uma_mb.to_string()); } crate::state::set_boot(boot.clone()); + + // the console's CPU is a Zen 2: its titles are compiled for it and fault with an illegal + // instruction (0xC000001D) on a PC without its extensions – said here instead + let missing = crate::launcher::missing_console_cpu_features(); + if !missing.is_empty() { + if std::env::var_os("XCL_SKIP_CPU_CHECK").is_some() { + crate::xlog_warn!("this CPU lacks {} (XCL_SKIP_CPU_CHECK set, continuing)", missing.join(", ")); + println!(" WARNING: this CPU lacks {} (XCL_SKIP_CPU_CHECK set, continuing)", missing.join(", ")); + } else { + let msg = crate::launcher::format_missing_cpu_message(&missing); + crate::xlog_error!("{msg}"); + eprintln!("xcl host: {msg}"); + crate::report::write_final(Some(format!("CPU lacks required Zen 2 features: {}", missing.join(", ")))); + return 0x7C1_0003; + } + } // `XCL_ACTIVITY=1`: every 2 s what the title did since (a timeline of where it stops) if std::env::var_os("XCL_ACTIVITY").is_some() { let _ = std::thread::Builder::new().name("xcl-activity".into()).spawn(|| { @@ -105,6 +133,7 @@ pub fn host_main(boot_path: &Path) -> i32 { } crate::stubs::init_db(&boot.config.stub_returns); crate::hle::init(&boot.config); + crate::hle::kernelx::fine_timer(); crate::loader::set_cache_dir(boot.cache_dir()); let mut dirs = vec![boot.game_root.clone()]; if let Some(p) = boot.exe_path.parent() { @@ -146,3 +175,23 @@ pub fn host_main(boot_path: &Path) -> i32 { crate::log::flush(); code as i32 } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn host_cpu_validation() { + std::env::set_var("XCL_SKIP_CPU_CHECK", "1"); + assert!(check_cpu_requirements().is_ok()); + std::env::remove_var("XCL_SKIP_CPU_CHECK"); + + let result = check_cpu_requirements(); + let expected_missing = crate::launcher::missing_console_cpu_features(); + if expected_missing.is_empty() { + assert!(result.is_ok()); + } else { + assert_eq!(result.unwrap_err(), expected_missing); + } + } +} diff --git a/crates/xcl/src/insn.rs b/crates/xcl/src/insn.rs index 71cae7d..d36573d 100644 --- a/crates/xcl/src/insn.rs +++ b/crates/xcl/src/insn.rs @@ -189,15 +189,17 @@ pub fn decode(code: &[u8]) -> Option<(ConsoleOnly, usize)> { && code[i + 3..i + 7] == [0x48, 0x83, 0xC0, 0x40] && (code[i + 7] == 0x48 || code[i + 7] == 0x4C) && code[i + 8] == 0x39 + && (code[i + 9] & 0xC7) == 0xC0 && code[i + 10..i + 12] == [0x72, 0xF4] { let rex_r = code[i + 7] == 0x4C; let modrm = code[i + 9]; let reg_idx = ((modrm >> 3) & 7) | if rex_r { 8 } else { 0 }; - Some((ConsoleOnly::ClzeroLoop { end_reg: reg_idx }, i + 12)) - } else { - Some((ConsoleOnly::Clzero, i + 3)) + if reg_idx != 0 { + return Some((ConsoleOnly::ClzeroLoop { end_reg: reg_idx }, i + 12)); + } } + Some((ConsoleOnly::Clzero, i + 3)) } (0x01, Some(0xFD)) => Some((ConsoleOnly::Rdpru, i + 3)), (0x01, Some(0xFA)) => Some((ConsoleOnly::Monitorx, i + 3)), @@ -272,6 +274,10 @@ mod tests { ); // the same loop after an address-size prefix: that one CLZERO alone assert_eq!(decode(&[0x67, 0x0F, 0x01, 0xFC, 0x48, 0x83, 0xC0, 0x40, 0x48, 0x39, 0xD0, 0x72, 0xF4]), Some((ConsoleOnly::Clzero, 4))); + // cmp with non-rax rm, memory operand, or cmp rax, rax is not a ClzeroLoop + assert_eq!(decode(&[0x0F, 0x01, 0xFC, 0x48, 0x83, 0xC0, 0x40, 0x48, 0x39, 0xCA, 0x72, 0xF4]), Some((ConsoleOnly::Clzero, 3))); + assert_eq!(decode(&[0x0F, 0x01, 0xFC, 0x48, 0x83, 0xC0, 0x40, 0x48, 0x39, 0x10, 0x72, 0xF4]), Some((ConsoleOnly::Clzero, 3))); + assert_eq!(decode(&[0x0F, 0x01, 0xFC, 0x48, 0x83, 0xC0, 0x40, 0x48, 0x39, 0xC0, 0x72, 0xF4]), Some((ConsoleOnly::Clzero, 3))); assert_eq!(decode(&[0x0F, 0x01, 0xFD]), Some((ConsoleOnly::Rdpru, 3))); assert_eq!(decode(&[0x0F, 0x01, 0xFA]), Some((ConsoleOnly::Monitorx, 3))); assert_eq!(decode(&[0x0F, 0x01, 0xFB]), Some((ConsoleOnly::Mwaitx, 3))); diff --git a/crates/xcl/src/inspect.rs b/crates/xcl/src/inspect.rs index 40cc690..66207b0 100644 --- a/crates/xcl/src/inspect.rs +++ b/crates/xcl/src/inspect.rs @@ -5,7 +5,7 @@ use std::path::Path; use serde::Serialize; -use crate::pe::{Layout, Pe}; +use crate::pe::{ImportDll, Layout, Pe}; use crate::resolver::{self, Source}; #[derive(Serialize)] @@ -29,6 +29,10 @@ struct Out { tls_template_bytes: Option, exception_entries: u32, stack_reserve: String, + /// True when the file imports console libraries (kernelx / xgameruntime / d3d12_xs). + is_console: bool, + /// The console libraries it imports, in first-seen order. + console_imports: Vec, imports: Vec, } @@ -39,9 +43,15 @@ pub fn console_imports(path: &Path) -> Option> { let pe = Pe::parse(&data, Layout::File).ok()?; let mut all = pe.imports().unwrap_or_default(); all.extend(pe.delay_imports().unwrap_or_default()); + Some(console_imports_from(&all)) +} + +/// The console libraries in already-parsed imports. Shared with `run` so the text and JSON +/// reports agree without parsing the file twice. +fn console_imports_from(all: &[ImportDll]) -> Vec { let reg = crate::hle::registry(); let mut out: Vec = Vec::new(); - for d in &all { + for d in all { let key = crate::util::dll_key(&d.dll); let console = key == crate::hle::KERNELX || reg @@ -52,7 +62,29 @@ pub fn console_imports(path: &Path) -> Option> { out.push(key); } } - Some(out) + out +} + +/// Assemble the report from the parsed PE, so the JSON path can be tested without capturing stdout. +fn report(path: &Path, pe: &Pe, imports: Vec, console: Vec) -> Out { + let tls = pe.tls().ok().flatten().map(|t| t.total_len()); + let ex = pe.dir(crate::pe::DIR_EXCEPTION); + Out { + file: path.to_string_lossy().into_owned(), + machine: format!("{:#06x}", pe.machine), + image_base: format!("{:#x}", pe.image_base), + entry_rva: format!("{:#x}", pe.entry_rva), + size_of_image: format!("{:#x}", pe.size_of_image), + subsystem: pe.subsystem, + is_dll: pe.is_dll(), + has_relocations: pe.has_relocs(), + tls_template_bytes: tls, + exception_entries: ex.size / 12, + stack_reserve: format!("{:#x}", pe.stack_reserve), + is_console: !console.is_empty(), + console_imports: console, + imports, + } } fn status(s: &Source) -> String { @@ -95,22 +127,8 @@ pub fn run(path: &Path, json: bool) -> i32 { imports.push(Entry { dll: d.dll.clone(), function: e.what.to_string(), delay: d.delay, status: status(&s) }); } } - let tls = pe.tls().ok().flatten().map(|t| t.total_len()); - let ex = pe.dir(crate::pe::DIR_EXCEPTION); - let out = Out { - file: path.to_string_lossy().into_owned(), - machine: format!("{:#06x}", pe.machine), - image_base: format!("{:#x}", pe.image_base), - entry_rva: format!("{:#x}", pe.entry_rva), - size_of_image: format!("{:#x}", pe.size_of_image), - subsystem: pe.subsystem, - is_dll: pe.is_dll(), - has_relocations: pe.has_relocs(), - tls_template_bytes: tls, - exception_entries: ex.size / 12, - stack_reserve: format!("{:#x}", pe.stack_reserve), - imports, - }; + let console = console_imports_from(&all); + let out = report(path, &pe, imports, console); if json { println!("{}", serde_json::to_string_pretty(&out).unwrap_or_default()); return 0; @@ -119,12 +137,13 @@ pub fn run(path: &Path, json: bool) -> i32 { println!("Type: {} x64, subsystem {}", if out.is_dll { "DLL" } else { "EXE" }, out.subsystem); println!("ImageBase: {} (size {}, entry +{})", out.image_base, out.size_of_image, out.entry_rva); println!("Relocations: {}", if out.has_relocations { "yes" } else { "NO (the image must be mapped at ImageBase)" }); - println!("Static TLS: {}", tls.map(|n| format!("{n} B (handled by the TLS carrier)")).unwrap_or_else(|| "none".into())); + println!("Static TLS: {}", out.tls_template_bytes.map(|n| format!("{n} B (handled by the TLS carrier)")).unwrap_or_else(|| "none".into())); println!("Exceptions: {} .pdata entries", out.exception_entries); println!("Stack: {}", out.stack_reserve); - match console_imports(path) { - Some(c) if !c.is_empty() => println!("Console game: yes (imports {})", c.join(", ")), - _ => println!("Console game: NO – no kernelx / xgameruntime / d3d12_xs imports (a regular Windows program?)"), + if out.is_console { + println!("Console game: yes (imports {})", out.console_imports.join(", ")); + } else { + println!("Console game: NO – no kernelx / xgameruntime / d3d12_xs imports (a regular Windows program?)"); } let mut per_dll: BTreeMap> = BTreeMap::new(); for e in &out.imports { @@ -154,3 +173,32 @@ pub fn run(path: &Path, json: bool) -> i32 { } 0 } + +#[cfg(test)] +mod tests { + use super::*; + + fn dll(name: &str) -> ImportDll { + ImportDll { dll: name.into(), delay: false, entries: Vec::new(), module_handle_rva: 0 } + } + + #[test] + fn console_verdict_counts_regular_and_delay_imports_once() { + let all = [dll("kernel32.dll"), dll("KERNELX.DLL"), dll("D3D12_XS.dll"), dll("xgameruntime.dll"), dll("kernelx.dll")]; + assert_eq!(console_imports_from(&all), ["kernelx.dll", "d3d12_xs.dll", "xgameruntime.dll"]); + assert!(console_imports_from(&[dll("kernel32.dll"), dll("user32.dll")]).is_empty()); + } + + #[test] + fn json_report_carries_the_console_verdict() { + let path = std::env::current_exe().unwrap(); + let data = std::fs::read(&path).unwrap(); + let pe = Pe::parse(&data, Layout::File).unwrap(); + let json = serde_json::to_value(report(&path, &pe, Vec::new(), vec!["kernelx.dll".into()])).unwrap(); + assert_eq!(json["is_console"], true); + assert_eq!(json["console_imports"][0], "kernelx.dll"); + let json = serde_json::to_value(report(&path, &pe, Vec::new(), Vec::new())).unwrap(); + assert_eq!(json["is_console"], false); + assert_eq!(json["console_imports"].as_array().unwrap().len(), 0); + } +} diff --git a/crates/xcl/src/launcher.rs b/crates/xcl/src/launcher.rs index af591db..5826dd6 100644 --- a/crates/xcl/src/launcher.rs +++ b/crates/xcl/src/launcher.rs @@ -360,10 +360,7 @@ pub fn run(target: &Path, args: &[String]) -> i32 { if std::env::var_os("XCL_SKIP_CPU_CHECK").is_some() { println!(" WARNING: this CPU lacks {} (XCL_SKIP_CPU_CHECK set, continuing)", missing.join(", ")); } else { - eprintln!( - "xcl: this CPU lacks {}: Xbox Series X|S games are compiled for the console's Zen 2 CPU\n and need them (they would stop with an illegal instruction). XCL_SKIP_CPU_CHECK=1 runs anyway.", - missing.join(", ") - ); + eprintln!("xcl: {}", format_missing_cpu_message(&missing)); return 2; } } @@ -384,28 +381,53 @@ pub fn run(target: &Path, args: &[String]) -> i32 { code as i32 } +/// Formats a friendly error message listing the missing console Zen 2 CPU features. +pub fn format_missing_cpu_message(missing: &[&str]) -> String { + format!( + "this CPU lacks {}: Xbox Series X|S games are compiled for the console's Zen 2 CPU\n and need them (they would stop with an illegal instruction). XCL_SKIP_CPU_CHECK=1 runs anyway.", + missing.join(", ") + ) +} + +/// Helper to evaluate CPU features using a query closure, returning missing feature names. +pub fn check_cpu_features bool>(has: F) -> Vec<&'static str> { + const REQUIRED: &[(&str, &str)] = &[ + ("sse4.2", "SSE4.2"), + ("popcnt", "POPCNT"), + ("avx", "AVX"), + ("avx2", "AVX2"), + ("fma", "FMA"), + ("f16c", "F16C"), + ("bmi1", "BMI1"), + ("bmi2", "BMI2"), + ("lzcnt", "LZCNT"), + ("movbe", "MOVBE"), + ]; + let mut missing = Vec::new(); + for &(feature, name) in REQUIRED { + if !has(feature) { + missing.push(name); + } + } + missing +} + /// Instruction set extensions of the console's Zen 2 that this CPU does not have (titles are /// compiled for them: AVX2, FMA, F16C, BMI1 / BMI2, LZCNT, POPCNT, MOVBE, SSE4.2). pub fn missing_console_cpu_features() -> Vec<&'static str> { - let mut missing = Vec::new(); - macro_rules! need { - ($($feature:tt => $name:literal),* $(,)?) => { - $(if !std::arch::is_x86_feature_detected!($feature) { missing.push($name); })* - }; - } - need!( - "sse4.2" => "SSE4.2", - "popcnt" => "POPCNT", - "avx" => "AVX", - "avx2" => "AVX2", - "fma" => "FMA", - "f16c" => "F16C", - "bmi1" => "BMI1", - "bmi2" => "BMI2", - "lzcnt" => "LZCNT", - "movbe" => "MOVBE", - ); - missing + check_cpu_features(|f| match f { + "sse4.2" => std::arch::is_x86_feature_detected!("sse4.2"), + "popcnt" => std::arch::is_x86_feature_detected!("popcnt"), + "avx" => std::arch::is_x86_feature_detected!("avx"), + "avx2" => std::arch::is_x86_feature_detected!("avx2"), + "fma" => std::arch::is_x86_feature_detected!("fma"), + "f16c" => std::arch::is_x86_feature_detected!("f16c"), + "bmi1" => std::arch::is_x86_feature_detected!("bmi1"), + "bmi2" => std::arch::is_x86_feature_detected!("bmi2"), + "lzcnt" => std::arch::is_x86_feature_detected!("lzcnt"), + "movbe" => std::arch::is_x86_feature_detected!("movbe"), + _ => false, + }) } fn spawn_host(cmdline: &str, cwd: &Path, boot_path: &Path) -> Result { @@ -462,10 +484,10 @@ fn summarize(boot: &Boot, code: u32, environment: &[crate::preflight::Check]) { println!(); println!("Game exited with code {code:#x} ({code})"); // repeated here: what the game printed in between has scrolled them away - let missing: Vec<_> = environment.iter().filter(|c| matches!(c.level, crate::preflight::Level::Warning | crate::preflight::Level::Error)).cloned().collect(); - if !missing.is_empty() { - println!("Missing on this PC (see the start of the run):"); - crate::preflight::print(&missing); + let warnings: Vec<_> = environment.iter().filter(|c| matches!(c.level, crate::preflight::Level::Warning | crate::preflight::Level::Error)).cloned().collect(); + if !warnings.is_empty() { + println!("Preflight warnings (see the start of the run):"); + crate::preflight::print(&warnings); } let Some(r) = report else { println!("No report – see the log: {}", boot.logs_dir().join("xcl.log").display()); @@ -649,4 +671,41 @@ mod tests { assert_eq!(quote("say \"hi\""), "\"say \\\"hi\\\"\""); assert_eq!(quote(""), "\"\""); } + + #[test] + fn cpu_feature_detection_identifies_missing_features() { + let all_present = check_cpu_features(|_| true); + assert!(all_present.is_empty()); + + let none_present = check_cpu_features(|_| false); + assert_eq!( + none_present, + vec!["SSE4.2", "POPCNT", "AVX", "AVX2", "FMA", "F16C", "BMI1", "BMI2", "LZCNT", "MOVBE"] + ); + + let missing_avx2 = check_cpu_features(|f| f != "avx2"); + assert_eq!(missing_avx2, vec!["AVX2"]); + + let missing_fma = check_cpu_features(|f| f != "fma"); + assert_eq!(missing_fma, vec!["FMA"]); + + let missing_bmi = check_cpu_features(|f| f != "bmi1" && f != "bmi2"); + assert_eq!(missing_bmi, vec!["BMI1", "BMI2"]); + + let missing_zen2_subset = check_cpu_features(|f| { + !["avx2", "fma", "bmi1", "bmi2", "popcnt", "sse4.2", "lzcnt"].contains(&f) + }); + assert_eq!( + missing_zen2_subset, + vec!["SSE4.2", "POPCNT", "AVX2", "FMA", "BMI1", "BMI2", "LZCNT"] + ); + } + + #[test] + fn missing_cpu_message_format() { + let msg = format_missing_cpu_message(&["AVX2", "FMA", "BMI1", "BMI2", "POPCNT", "SSE4.2", "LZCNT"]); + assert!(msg.contains("this CPU lacks AVX2, FMA, BMI1, BMI2, POPCNT, SSE4.2, LZCNT")); + assert!(msg.contains("Zen 2 CPU")); + assert!(msg.contains("XCL_SKIP_CPU_CHECK=1")); + } } diff --git a/crates/xcl/src/preflight.rs b/crates/xcl/src/preflight.rs index d394d8f..b2c00cf 100644 --- a/crates/xcl/src/preflight.rs +++ b/crates/xcl/src/preflight.rs @@ -47,6 +47,8 @@ pub struct Found { /// the DXC in that folder, for its version pub dxc_toolchain: crate::gpu::recomp::dxc::Toolchain, pub xgameruntime: bool, + /// Whether the title's WinHTTP and Winsock imports are blocked. + pub network_off: bool, pub gpu: Result, } @@ -91,7 +93,10 @@ pub fn checks(f: &Found) -> Vec { Err(_) => v.push(check(Level::Error, "no DXC (dxcompiler.dll + dxil.dll): no shader can be compiled, the game draws nothing", Some("install the Windows SDK, or put dxcompiler.dll and dxil.dll next to xcl.exe (or in %XCL_DXC_DIR%)"))), } if !f.xgameruntime { - v.push(check(Level::Warning, "no System32\\xgameruntime.dll: XCL's own XGameRuntime parts work, the rest (task queues, networking, dialogs) is missing", Some("install Gaming Services (Microsoft Store)"))); + v.push(check(Level::Warning, "no System32\\xgameruntime.dll: dialogs, text entry, game invites and game streaming are missing (XCL's own task queues, async and networking are used)", Some("install Gaming Services (Microsoft Store)"))); + } + if !f.network_off { + v.push(check(Level::Warning, "title network access is enabled: a crash reporter may upload process memory", Some("set XCL_NETWORK=0 to block title network access (loopback remains available)"))); } v } @@ -159,6 +164,7 @@ pub fn run(setting: &str) -> Vec { dxc: crate::gpu::recomp::dxc::location().map(|p| p.display().to_string()), dxc_toolchain: crate::gpu::recomp::dxc::toolchain(), xgameruntime: xgameruntime_present(), + network_off: crate::hle::netoff::enabled(), gpu: probe_gpu(setting), }; checks(&found) @@ -190,7 +196,7 @@ mod tests { } fn found(gpu: Gpu) -> Found { - Found { dxc: Ok(r"C:\dxc".into()), dxc_toolchain: dxc(1, 9), xgameruntime: true, gpu: Ok(gpu) } + Found { dxc: Ok(r"C:\dxc".into()), dxc_toolchain: dxc(1, 9), xgameruntime: true, network_off: true, gpu: Ok(gpu) } } fn dxc(major: u32, minor: u32) -> crate::gpu::recomp::dxc::Toolchain { @@ -215,6 +221,9 @@ mod tests { let c = checks(&f); assert_eq!(c.iter().map(|c| c.level).collect::>(), [Level::Ok, Level::Error, Level::Warning, Level::Error, Level::Warning]); assert!(c[1].what.contains("has 6.5"), "{:?}", c[1]); + // XCL's own task queues and networking stand in for the PC runtime's: not missing + let missing = c[4].what.split(" missing").next().unwrap(); + assert!(missing.contains("dialogs") && !missing.contains("task queues") && !missing.contains("networking"), "{:?}", c[4]); assert!(c.iter().filter(|c| c.level != Level::Ok).all(|c| c.fix.is_some()), "{c:?}"); } @@ -245,6 +254,15 @@ mod tests { assert_eq!(checks(&f)[0].level, Level::Error); } + #[test] + fn network_access_is_a_warning_until_explicitly_disabled() { + let c = checks(&Found { network_off: false, ..found(gpu()) }); + let network = c.last().unwrap(); + assert_eq!(network.level, Level::Warning); + assert!(network.what.contains("network access is enabled"), "{network:?}"); + assert_eq!(network.fix.as_deref(), Some("set XCL_NETWORK=0 to block title network access (loopback remains available)")); + } + #[test] fn checks_round_trip_through_the_report() { let c = checks(&Found { dxc: Err("x".into()), ..found(gpu()) }); diff --git a/crates/xcl/tests/e2e.rs b/crates/xcl/tests/e2e.rs index aa73c18..521c8ec 100644 --- a/crates/xcl/tests/e2e.rs +++ b/crates/xcl/tests/e2e.rs @@ -97,7 +97,7 @@ fn test_title_runs_and_game_folder_is_untouched() { dll.display() ); let manifest = Path::new(env!("CARGO_MANIFEST_DIR")); - let root = manifest.join("..").join("..").join("target").join("e2e"); + let root = Path::new(env!("CARGO_TARGET_TMPDIR")).join("e2e"); let _ = std::fs::remove_dir_all(&root); let game = root.join("game"); let data = root.join("data"); @@ -248,7 +248,9 @@ fn test_title_draws_with_a_root_signature_under_the_debug_layer() { let sys = PathBuf::from(std::env::var_os("SystemRoot").unwrap_or_else(|| r"C:\Windows".into())).join("System32"); for dll in ["d3d12SDKLayers.dll", "xgameruntime.dll"] { if !sys.join(dll).is_file() { - eprintln!("SKIPPED test_title_draws_with_a_root_signature_under_the_debug_layer: no {dll}"); + // straight to stderr: libtest captures eprintln!, and scripts/test.ps1 counts this line + use std::io::Write; + let _ = writeln!(std::io::stderr(), "SKIPPED test_title_draws_with_a_root_signature_under_the_debug_layer: no {dll}"); return; } } diff --git a/crates/xcl/tests/texture_states.rs b/crates/xcl/tests/texture_states.rs index 28d4e9b..5406d8c 100644 --- a/crates/xcl/tests/texture_states.rs +++ b/crates/xcl/tests/texture_states.rs @@ -12,6 +12,13 @@ use xcl::gpu::texture::{self, Subresource}; const SRV: D3D12_RESOURCE_STATES = texture::SHADER_READ; +/// `SKIPPED : ` straight to stderr: libtest captures `println!` / `eprintln!`, so +/// the line would show only with `--nocapture` and `scripts/test.ps1` would not count it. +fn skipped(reason: &str) { + use std::io::Write; + let _ = writeln!(std::io::stderr(), "SKIPPED uploads_start_from_each_subresources_state: {reason}"); +} + /// The debug layer's error and corruption messages since the last call (then cleared). unsafe fn errors(q: &ID3D12InfoQueue) -> Vec { let mut out = Vec::new(); @@ -51,16 +58,16 @@ fn uploads_start_from_each_subresources_state() { match xcl::gpu::agility::configuration_interface::(&CLSID_D3D12Debug) { Ok(d) => d.EnableDebugLayer(), Err(e) => { - println!("SKIPPED uploads_start_from_each_subresources_state: no D3D12 debug layer ({e})"); + skipped(&format!("no D3D12 debug layer ({e})")); return; } } let Ok(dev) = xcl::gpu::agility::create_device(None, D3D_FEATURE_LEVEL_11_0) else { - println!("SKIPPED uploads_start_from_each_subresources_state: no GPU"); + skipped("no GPU"); return; }; let Ok(q) = dev.cast::() else { - println!("SKIPPED uploads_start_from_each_subresources_state: the device has no debug layer"); + skipped("the device has no debug layer"); return; }; let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: D3D12_COMMAND_LIST_TYPE_DIRECT, ..Default::default() }).unwrap(); diff --git a/scripts/smoke.ps1 b/scripts/smoke.ps1 deleted file mode 100644 index a4f668a..0000000 --- a/scripts/smoke.ps1 +++ /dev/null @@ -1,64 +0,0 @@ -# Regression run of a title for a pull request: runs it for a fixed time, reads XCL's log and -# prints an `xcl-smoke` block to paste into the PR's "Regression run" section – once built -# from main, once from the PR's head commit (CONTRIBUTING.md, "What a PR needs to be merged"). -# -# .\scripts\smoke.ps1 -Game 'D:\Games\SomeTitle' [-Seconds 60] [-Xcl .\target\release\xcl.exe] -# -# Networking is off (XCL_NETWORK=0). Build first: cargo build --release -p xcl -param( - [Parameter(Mandatory = $true)][string]$Game, - [int]$Seconds = 60, - [string]$Xcl = (Join-Path $PSScriptRoot '..\target\release\xcl.exe') -) -$ErrorActionPreference = 'Stop' - -if (-not (Test-Path $Xcl)) { throw "no $Xcl - build it first (cargo build --release -p xcl)" } -$root = Split-Path $PSScriptRoot -Parent -$commit = (git -C $root rev-parse HEAD).Trim() -$dirty = [bool](git -C $root status --porcelain --untracked-files=no -- crates Cargo.toml Cargo.lock) - -$out = New-TemporaryFile -$err = New-TemporaryFile -$env:XCL_NETWORK = '0' -$env:XCL_RUN_SECONDS = "$Seconds" -$env:XCL_ACTIVITY = '1' -$p = Start-Process -FilePath $Xcl -ArgumentList @('run', "`"$Game`"") -NoNewWindow -PassThru -RedirectStandardOutput $out -RedirectStandardError $err -$null = $p.Handle # (without it ExitCode stays empty) -if (-not $p.WaitForExit(($Seconds + 120) * 1000)) { - Stop-Process -Id $p.Id -Force - $timedOut = $true -} -Remove-Item Env:XCL_RUN_SECONDS, Env:XCL_ACTIVITY - -$stdout = Get-Content $out -Raw -Encoding utf8 -Remove-Item $out, $err -$logLine = ($stdout -split "`n" | Where-Object { $_ -match '^Log:\s+(.+)$' } | Select-Object -Last 1) -if (-not $logLine) { throw "XCL printed no log path; its output:`n$stdout" } -$log = ($logLine -replace '^Log:\s+', '').Trim() -$text = Get-Content $log -Raw -Encoding utf8 - -$frames = if ($text -match '\((\d+) frames shown, (\d+) PresentX calls\)') { "$($Matches[1]) (PresentX $($Matches[2]))" } else { 'none logged (the run did not reach its end)' } -$presents = [regex]::Matches($text, 'activity \(2 s\): (\d+) presents') | ForEach-Object { [int]$_.Groups[1].Value } -$lastPresents = ($presents | Select-Object -Last 3) -join ' ' -$commits = [regex]::Matches($text, 'memory: (\d+) MB committed') | ForEach-Object { [int]$_.Groups[1].Value } -$peak = if ($commits) { ($commits | Measure-Object -Maximum).Maximum } else { 'n/a' } -$removals = ([regex]::Matches($text, 'device removed')).Count -$crashes = ([regex]::Matches($text, 'unhandled exception|process ends with status')).Count -$gpu = (Get-CimInstance Win32_VideoController | Where-Object { $_.Name -notmatch 'Basic' } | Select-Object -First 1).Name -$code = if ($timedOut) { 'killed (no exit)' } else { '0x{0:x}' -f $p.ExitCode } - -@" -`````` -xcl-smoke v1 -commit: $commit$(if ($dirty) { ' (uncommitted changes)' }) -gpu: $gpu -title: $(Split-Path $Game -Leaf) -seconds: $Seconds -exit: $code -frames shown: $frames -presents per 2 s (last 3): $lastPresents -device removals: $removals -crashes: $crashes -peak commit: $peak MB -`````` -"@ diff --git a/tests/testgamedll/Cargo.toml b/tests/testgamedll/Cargo.toml index 6264862..379c3fa 100644 --- a/tests/testgamedll/Cargo.toml +++ b/tests/testgamedll/Cargo.toml @@ -10,3 +10,6 @@ publish = false name = "testgame_mw" crate-type = ["cdylib"] path = "src/lib.rs" +# no unit tests: the GNU linker keeps the kernelx.dll import in the test harness's exe, +# which then does not start (kernelx.dll exists only inside XCL) +test = false