Compare commits

..
Author SHA1 Message Date
千川白浪 b7df96f018 Merge pull request #8 from liuyaxuan123457-ctrl/fix/iosurface-transfer-recording
Queue Runtime Alpha / alpha (push) Waiting to run
Prevent IOSurface cache fills from waiting on their own uncommitted copies
2026-12-05 14:07:43 +08:00
NwflowerandClaude Opus 5.5 011fe14323 Pin metal2vulkan at the host batch queue
reims-go/metal2vulkan#3 landed on development as 8fd7fb5, which adds
Device::new_host_batch_queue(); the IOSurface transfer FIFO now builds
against the accepted revision instead of a local override.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-04 22:49:28 -07:00
Nwflower c6e8df0463 Merge intel-vm-suspend into fix/iosurface-transfer-recording 2026-12-04 22:46:50 -07:00
千川白浪 f7f0af3500 Merge pull request #19 from Nwflower/port-input-release
🆕 Port the configurable input release to the Windows runtime branch
2026-12-05 13:44:43 +08:00
Xiaochi You 6527829878 Merge pull request #20 from reims-go/feat/win32-aio-rawdisk-perf
feat(win32): native AIO, raw device in-place, disk cache policy, and bumped fast QEMU
2026-12-05 12:30:18 +08:00
YXC0915 91c0ce917a style(reims-ctl): run rustfmt on qemu and runtime 2026-12-05 12:17:08 +08:00
YXC0915 5a2083b951 feat(win32): enable native AIO, raw disk in-place, disk cache policy, and fast QEMU runtime 2026-12-05 12:01:05 +08:00
acd68ab830 🆕 Port the configurable input release to the Windows runtime branch
Port reims-go/reims-vgpu#7 (5f5995e9f) from master to the window's current
keyboard grab. An additional shortcut releases input as the built-in chord
does, and the mouse leaving the window can release the keyboard grab until it
comes back. The runtime declares window-release-shortcut.

Co-authored-by: hanyewei <139319228@qq.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-04 08:50:29 -07:00
Xiaochi You 82da699225 Merge pull request #6 from yxc0915/steelbrain/windows-usb-redir
🆕 Enable Windows USB redirection in the portable runtime
2026-12-04 21:49:52 +08:00
YXC0915 1adc8a59ce 🐛 Reconcile and harden Windows iPad enumeration
Keep the current Windows build, which already enables usb-redir. Preserve
successful initial enumeration when the device changes address before QMP
observes the attachment. Encode SuperSpeed EP0 size in bytes and publish
interrupt workers only after they have started.
2026-12-04 21:49:29 +08:00
Xiaochi You 6a1f03f862 Merge pull request #13 from yxc0915/steelbrain/pin-metal2vulkan-fixed-offset
Pin metal2vulkan fixed-offset draw batching
2026-12-04 18:25:24 +08:00
YXC0915 db0c7395f1 🐎 Pin metal2vulkan fixed-offset draw batching
Use the measured revision on the organization development branch and refresh the three workspace lockfile sources.
2026-12-04 18:17:47 +08:00
Xiaochi You 5f690a8165 Merge pull request #12 from yxc0915/steelbrain/merge-vulkan-mdi-pr3
Resolve #3 and merge opt-in Vulkan multi-draw indirect
2026-12-04 17:37:48 +08:00
YXC0915 410d4a3f59 🐎 Merge opt-in Vulkan multi-draw indirect
Resolve the draw-encoder conflict with the adaptation in steelbrain/reims-vgpu#206. Preserve encoded and refused outcomes and keep indirect batching disabled unless requested.
2026-12-04 17:21:04 +08:00
Xiaochi You 66a66b8c26 Merge pull request #11 from yxc0915/steelbrain/sync-upstream-0dc2233
Merge upstream Reims vGPU into the Windows runtime maintenance branch
2026-12-04 17:01:24 +08:00
YXC0915 79fdedd8f0 🐛 Preserve FileVault input during OpenCore renewal
Keep the existing tablet and keyboard EFI files and their UEFI input settings when the guest drivers are rebuilt. Verify the new image before replacing the old one.
2026-12-04 16:45:48 +08:00
YXC0915 f71a03f37c 🐛 Keep the scanout copy fallback scoped to fixed mode
Preserve upstream import refusal behavior for ordinary Windows and Unix scanouts. Describe the loopback endpoint without rustdoc HTML.
2026-12-04 16:26:34 +08:00
YXC0915 01df95a4a4 🐛 Use runtime clocks in the suspend paths
Keep snapshot timing and waits on the runtime monotonic clock, avoid overflow in the restored address range, and retain the pool test inspector.
2026-12-04 16:16:32 +08:00
YXC0915 f8f29ada50 🆕 Merge upstream into the Windows runtime maintenance branch
Integrate the upstream runtime and verified dependency pins. Preserve the Windows window handoff and GPU suspend state alongside the upstream device and rendering changes.
2026-12-04 16:14:04 +08:00
Xiaochi You e8a21294e6 Merge pull request #10 from yxc0915/codex/backport-processor-display
Backport the macOS processor display fix
2026-12-04 16:01:26 +08:00
YXC0915 2373afdd01 🐛 Backport the macOS processor display fix
Use the host CPU family when Apple provides a label for the x86 guest topology. Preserve explicit OpenCore settings and apply the change to a verified copy before boot.
2026-12-04 15:48:55 +08:00
千川白浪 e68e3ce939 Merge pull request #4 from reiasu2/fix/export-unattached-cb-deadlock
🐛 Fix snapshot save deadlock when >64 unattached surface caches are dirty
2026-12-04 13:51:42 +08:00
Xiaochi You 9324949b55 Merge pull request #9 from yxc0915/steelbrain/backport-hidpi-cursor
🐛 Backport HiDPI cursor crossing on x86 macOS
2026-12-03 23:48:54 +08:00
YXC0915 48dd6d2fad 🐛 Backport HiDPI cursor crossing on x86 macOS
Backport porcelainhorse's 4c6acb5e from steelbrain/reims-vgpu#180.

Rebuild both guest prebuilt sets with Xcode 27.2 from the maintenance tree to preserve its bundled guest changes.
2026-12-03 23:47:57 +08:00
liuyaxuan123457-ctrl 7c00df2c0b Use a host batch queue for IOSurface cache transfers 2026-12-03 17:23:51 +08:00
YXC0915 1bac132e21 🐛 Keep the Windows QMP socket path usable
Pass the absolute AF_UNIX socket path to the relay without resolving its Windows reparse point. Exercise the actual CLI path in the WHPX smoke.
2026-12-03 09:51:25 +08:00
YXC0915 d3ceaeaa0b 🆕 Add the Windows iPad Air M3 USB enumeration helper
Keep the filtered iPad session tied to the selected USB port and the
guest's QEMU process. Use manual reconnect for driver activation and
release, with a recovery record for interrupted sessions.

Adapt the Windows device transaction and exporter from
steelbrain/reims-vgpu#201 for the Air M3 enumeration test.
2026-12-03 09:50:03 +08:00
棠渚听潮 64c0e9a32a 🐎 Batch Vulkan vertex draws with opt-in multi-draw indirect 2026-12-03 09:47:18 +08:00
YXC0915 914debd758 🆕 Enable Windows USB redirection in the portable runtime
Port the Windows usbredir build dependency and staged QEMU check from steelbrain/reims-vgpu#200 so the runtime can support device-scoped USB forwarding.
2026-12-03 08:52:03 +08:00
YXC0915 2df30ffea9 🆕 Pin the organization runtime dependencies [skip ci]
Resolve metal2vulkan and reims-util from the maintained Reims-Go repositories. The new Vulkan pin establishes a suspend baseline for these build inputs.
2026-12-03 02:53:58 +08:00
Xiaochi You 6b7e7d7cad Merge pull request #1 from YinLiaoCo/feat/window-file-drop
feat(window): forward SDL3 file and text drops with normalized coords to host bridge
2026-12-03 02:08:14 +08:00
YXC0915 1a6d1626ca 📝 Record the Places texture-pool suspend baseline
The Places allocation patch changes the graphics memory layout. Give this Alpha build its own suspend compatibility family until recovery of older snapshots has been verified.
2026-12-03 01:02:03 +08:00
Xiaochi You 1ac525f616 Merge PR #2: Batch Vulkan draws and limit copied buffer sync
🐎 Batch Vulkan vertex draws and limit copied buffer sync to blit ranges
2026-12-03 00:01:49 +08:00
棠渚听潮 0427583422 🐛 Commit each unattached surface cache writeback before acquiring the next command buffer 2026-12-02 23:58:44 +08:00
棠渚听潮 0824c15d61 🐎 Limit copied buffer sync to blit ranges 2026-12-02 19:33:13 +08:00
棠渚听潮 7e7b50364b 🐎 Encode Vulkan vertex draws in batches 2026-12-02 19:33:13 +08:00
YXC0915 9835066ce3 🐛 Update maintenance branch references [ci skip]
Keep automation and documentation aligned with the renamed branch.
The source pins and build steps stay the same.
2026-12-02 19:27:54 +08:00
YXC0915 8ae206e06a Use the organization QEMU fork for runtime builds 2026-12-02 18:59:09 +08:00
Shroap bfea2dc988 feat(window): forward SDL3 text and URL drops to host bridge 2026-12-02 04:00:53 +08:00
Shroap 3fdde46abd feat(window): forward SDL3 file drops with normalized coords to host bridge 2026-12-02 03:56:21 +08:00
YXC0915 cf00aac721 🐛 Supersede unfinished Alpha builds on push
Cancel an older dispatcher and request the newest runtime build.
2026-12-02 02:05:39 +08:00
YXC0915 e76060b02c 🆕 Queue an Alpha for runtime branch pushes
Dispatch the default packaging workflow with the pushed runtime SHA.
Publish the verified build through the existing Alpha release path.
2026-12-02 01:58:33 +08:00
YXC0915 9d9be66a68 🐛 Pin the Win32 user NAT socket fix
Use the QEMU maintenance merge that removes Winsock fd_set truncation in Windows user networking.
2026-12-02 01:15:32 +08:00
YXC0915 c95335699c 🆕 Ask Reims-Go to confirm Windows VM close requests
Forward managed Windows closes to the desktop client. Keep the SDL question available when the desktop instance cannot take the request.
2026-12-01 12:04:24 +08:00
YXC0915 edd66dcc12 🐛 Pin the Win32 direct-write retry fix 2026-12-01 11:57:57 +08:00
YXC0915 ff284bc497 chore: bump vendor/qemu for fast Win32 mapped-ram suspend I/O
Updates vendor/qemu to yxc0915/qemu-reims-vgpu@4c4757156a with ascending zero-page partitioning, Win32 64 KiB NTFS sparse write coalescing, and Win32 direct-io support.
2026-12-01 11:40:59 +08:00
YXC0915 e0cb092b03 ffi: export the suspend functions in the generated C header 2026-12-01 09:47:41 +08:00
YXC0915 9e0d1bc1a0 build: pin suspend-capable QEMU and record runtime features 2026-12-01 09:41:13 +08:00
YXC0915 bcd18d6485 Apply reims-vgpu-snapshot-replay
Reims-Go-Patch: reims-vgpu-snapshot-replay.patch
2026-12-01 09:40:17 +08:00
YXC0915 6aa417aef6 Apply reims-ctl-qcow2-l2-cache
Reims-Go-Patch: reims-ctl-qcow2-l2-cache.patch
2026-12-01 09:40:16 +08:00
YXC0915 b1e8f45e9e Apply reims-ctl-virtio-discard-iothread
Reims-Go-Patch: reims-ctl-virtio-discard-iothread.patch
2026-12-01 09:40:16 +08:00
YXC0915 53b6af7574 Apply reims-ctl-win32-random-bytes
Reims-Go-Patch: reims-ctl-win32-random-bytes.patch
2026-12-01 09:40:16 +08:00
YXC0915 c8213cb933 Apply reims-vgpu-display-fixed-mode
Reims-Go-Patch: reims-vgpu-display-fixed-mode.patch
2026-12-01 09:40:15 +08:00
YXC0915 d1637583ba Apply reims-vgpu-win32-unicode-input
Reims-Go-Patch: reims-vgpu-win32-unicode-input.patch
2026-12-01 09:40:15 +08:00
239 changed files with 11203 additions and 13509 deletions

No files matched your search

+2 -2
View File
@@ -86,7 +86,7 @@ test-group = "@global"
# The tests that make an rt device: the Vulkan crate's but core's, reims-vgpu's named on_vulkan or
# on_rt_, and the C API's. Each of them failed, and no other test did, in a run on Linux with no
# Vulkan driver (2026-12-03, potluck job m3-max-85816).
# Vulkan driver (homelab-um870, 2026-12-03, potluck job m3-max-85816).
[[profile.nvidia.overrides]]
platform = 'cfg(target_os = "linux")'
filter = '''
@@ -99,7 +99,7 @@ test-group = "vulkan-devices"
# GitHub CI's profile (.github/workflows/ci.yml, docs/development.md "CI"), whose runners have no
# GPU: every test but those that make an rt device. They are the tests the nvidia profile's
# `vulkan-devices` group holds (above), and reims-vgpu's tests named `on_rt_`, which make one too.
# Measured on Linux with no Vulkan driver (2026-12-03, at 5cb932953e): 218 of the
# Measured on Linux with no Vulkan driver (homelab-um870, 2026-12-03, at 5cb932953e): 218 of the
# 3,439 tests that are not ignored failed, each of them one of these. CI runs these with the
# profile's filter turned over (`--profile ci --ignore-default-filter -E 'not default()'`) on
# Mesa's lavapipe, in a job of its own.
+2 -10
View File
@@ -262,9 +262,7 @@ jobs:
# The C compiler the C API's harness tests run and the git the build stamp's test runs, which
# the image's pin names neither of: installed into the image the build made, from the pin's
# own archive date, through the build's pacman.conf, package cache and databases, and kept
# under the same tag, which the run below uses. The archive's server can reset a download
# (run 47448102351: HTTP/2 PROTOCOL_ERROR), so pacman tries three times, keeping in the
# package cache what each try fetched.
# under the same tag, which the run below uses.
- name: Add cc and git to the image
env:
IMAGE: ${{ steps.image.outputs.dir }}
@@ -280,13 +278,7 @@ jobs:
-v "$cache/pacman.conf:/etc/pacman.conf:ro" "$image" bash -euc '
owner=$1
shift
try=1
until pacman -S --noconfirm --needed "$@"; do
[ "$try" -lt 3 ] || exit 1
echo "pacman -S failed on try $try of 3; trying again in 15 s"
try=$((try + 1))
sleep 15
done
pacman -S --noconfirm --needed "$@"
yes | pacman -Sc >/dev/null
chown -R "$owner" /var/cache/pacman/pkg /var/lib/pacman/sync
' bash "$(id -u):$(id -g)" "${extras[@]}"
@@ -0,0 +1,25 @@
name: Queue Runtime Alpha
on:
push:
branches: [intel-vm-suspend]
permissions:
actions: write
concurrency:
group: queue-runtime-alpha
cancel-in-progress: true
jobs:
alpha:
if: github.repository == 'reims-go/reims-vgpu'
runs-on: ubuntu-latest
timeout-minutes: 5
steps:
- name: Queue Alpha for the pushed commit
env:
GH_TOKEN: ${{ github.token }}
run: |
gh workflow run runtime-preview.yml --repo "$GITHUB_REPOSITORY" --ref master \
-f upstream_commit="$GITHUB_SHA" -f publish=true -f supersede=true
+2 -2
View File
@@ -1,4 +1,4 @@
[submodule "vendor/qemu"]
path = vendor/qemu
url = https://github.com/steelbrain/qemu-reims-vgpu
branch = steelbrain/reims-vgpu-rebase-2
url = https://github.com/reims-go/qemu-reims-vgpu.git
branch = intel-vm-suspend
Generated
+3
View File
@@ -213,6 +213,7 @@ checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
[[package]]
name = "metal2vulkan"
version = "0.2.0"
source = "git+https://github.com/reims-go/metal2vulkan?rev=8fd7fb5d9cf2df9164b121995b63187f95a3a191#8fd7fb5d9cf2df9164b121995b63187f95a3a191"
dependencies = [
"ash",
"metal2vulkan-air",
@@ -223,6 +224,7 @@ dependencies = [
[[package]]
name = "metal2vulkan-air"
version = "0.2.0"
source = "git+https://github.com/reims-go/metal2vulkan?rev=8fd7fb5d9cf2df9164b121995b63187f95a3a191#8fd7fb5d9cf2df9164b121995b63187f95a3a191"
dependencies = [
"sha2 0.11.1",
]
@@ -230,6 +232,7 @@ dependencies = [
[[package]]
name = "metal2vulkan-runtime"
version = "0.2.0"
source = "git+https://github.com/reims-go/metal2vulkan?rev=8fd7fb5d9cf2df9164b121995b63187f95a3a191#8fd7fb5d9cf2df9164b121995b63187f95a3a191"
dependencies = [
"ash",
"libc",
+2 -2
View File
@@ -33,11 +33,11 @@ reims-vgpu-graphics = { path = "crates/reims-vgpu-graphics" }
reims-vgpu-video = { path = "crates/reims-vgpu-video" }
# metal2vulkan's Metal types, for the Metal enums and descriptor values the runtime's calls take,
# from metal2vulkan's public repository at the commit both name.
metal2vulkan = { git = "https://github.com/steelbrain/metal2vulkan", rev = "08848fd8a579d6de1ccdb584f105a61ba2b2f57d" }
metal2vulkan = { git = "https://github.com/reims-go/metal2vulkan", rev = "8fd7fb5d9cf2df9164b121995b63187f95a3a191" }
# The Vulkan platform's runtime (architecture D1), metal2vulkan-runtime: a Metal-shaped API on
# Vulkan, one path for every device, under reims-vgpu-vulkan's `rt_platform` and `seam` and
# reims-vgpu's `pool::rt_blocks`.
metal2vulkan-runtime = { git = "https://github.com/steelbrain/metal2vulkan", rev = "08848fd8a579d6de1ccdb584f105a61ba2b2f57d" }
metal2vulkan-runtime = { git = "https://github.com/reims-go/metal2vulkan", rev = "8fd7fb5d9cf2df9164b121995b63187f95a3a191" }
# The hashes of the Vulkan platform's metallib sources (reims-vgpu-vulkan/build.rs).
sha2 = "0.10.9"
# A display window's swapchain on Linux (reims-vgpu-vulkan/src/swapchain.rs), at the runtime's
+41 -75
View File
@@ -226,11 +226,10 @@ what to do, and so do reims-ctl show and the VM's pane in reims-ctl.
An x86-64 VM's macOS sees this host's processor: sysctl machdep.cpu.brand_string reads its name \
as the host gives it, and About This Mac shows the Intel family Apple has a name for: Core i3, \
i5, i7 or i9 by the host's own (a Core Ultra 7 or a Ryzen 7 shows as Core i7), and Xeon for a \
Xeon, Threadripper or EPYC. The start writes it into the VM's OpenCore image where the image \
holds another, as after the VM moves to another host; a processor of no such family keeps \
OpenCore's own pick. About This Mac counts the VM's CPUs rounded up to a power of two, so 5 CPUs \
show as 8 cores, and says Unknown where Apple has no name for that many in the family: Core i5 \
and i7 are named at 2 to 8 CPUs, Core i9 at 5 to 8, Core i3 at 2 to 4, and a Xeon at 1 to 16.";
Xeon, Threadripper or EPYC. A cold start can set the display type where OpenCore uses automatic \
SMBIOS, and Apple has a label for the host family and the VM's CPU count. About This Mac counts \
the VM's CPUs rounded up to a power of two, so 5 CPUs show as 8 cores. Core i5 and i7 are named \
at 2 to 8 CPUs, Core i9 at 5 to 8, Core i3 at 2 to 4, and a Xeon at 1 to 16.";
const VIEW_HELP: &str = "\
For a VM started headless (reims-ctl start NAME --headless) or on a host with no screen, to \
@@ -721,6 +720,9 @@ pub struct CreateArgs {
/// directory are on one file system that makes them, else a full copy) or in-place
#[arg(long, default_value = "copy")]
pub disk_mode: String,
/// Host I/O cache policy for the system disk: default, writeback, none or unsafe
#[arg(long)]
pub disk_cache: Option<String>,
/// Download this macOS from Apple to install: a name (tahoe), a number (26) or latest; with
/// --offline, also a release (26.6.2) or a build (25G83)
#[arg(long, value_name = "VERSION", conflicts_with = "installer")]
@@ -768,13 +770,6 @@ pub struct CreateArgs {
/// Borderless windows that fill their screens, one for each display
#[arg(long, num_args = 0..=1, default_missing_value = "true")]
pub borderless: Option<bool>,
/// The one refresh rate, in Hz, such as 60 or 59.94, that each of reims-vgpu's displays
/// offers the guest every size at, titled or borderless (default: auto, the rate of the
/// screen a titled window opens on, and the rates of the screen a borderless window fills);
/// a rate above the screen's is lowered to the screen's, which the VM's logs/qemu.log says;
/// on a headless start (start --headless), 60 Hz
#[arg(long, value_name = "HZ|auto")]
pub refresh_rate: Option<String>,
/// The GPU: auto, a number or name from `reims-ctl gpus`, or a Vulkan ICD JSON file
#[arg(long)]
pub gpu: Option<String>,
@@ -821,6 +816,9 @@ pub struct SetArgs {
/// OpenCore may start it
#[arg(long)]
pub disk_controller: Option<String>,
/// Host I/O cache policy for the system disk: default, writeback, none or unsafe
#[arg(long)]
pub disk_cache: Option<String>,
/// The size each of reims-vgpu's windows opens at, WIDTHxHEIGHT in the desktop's points:
/// one size for every display, or one for each display, comma-separated
/// (2560x1440,1920x1080); on a headless start (start --headless), each display's mode
@@ -829,13 +827,6 @@ pub struct SetArgs {
/// Borderless windows that fill their screens, one for each display
#[arg(long, num_args = 0..=1, default_missing_value = "true")]
pub borderless: Option<bool>,
/// The one refresh rate, in Hz, such as 60 or 59.94, that each of reims-vgpu's displays
/// offers the guest every size at, titled or borderless, or auto, the rate of the screen a
/// titled window opens on, and the rates of the screen a borderless window fills; a rate
/// above the screen's is lowered to the screen's, which the VM's logs/qemu.log says; on a
/// headless start (start --headless), 60 Hz
#[arg(long, value_name = "HZ|auto")]
pub refresh_rate: Option<String>,
/// auto, a number or name from `reims-ctl gpus`, or a Vulkan ICD JSON file
#[arg(long)]
pub gpu: Option<String>,
@@ -1218,7 +1209,11 @@ fn create_cmd(a: CreateArgs, host: Host) -> Result<()> {
size_mib: parse_size_mib(sz)?,
}),
(None, Some(p)) => Some(DiskSource::Existing {
path: paths::absolute(&p.to_string_lossy()),
path: if vm::is_windows_raw_device(p) {
p.to_path_buf()
} else {
paths::absolute(&p.to_string_lossy())
},
mode: ImportMode::parse(&a.disk_mode)?,
}),
(None, None) => Some(DiskSource::New {
@@ -1240,6 +1235,11 @@ fn create_cmd(a: CreateArgs, host: Host) -> Result<()> {
}
});
s.mac = a.mac.clone();
s.disk_cache = a
.disk_cache
.as_deref()
.map(vm::DiskCache::parse)
.transpose()?;
s.graphics = a.graphics.as_deref().map(vm::Graphics::parse).transpose()?;
if let Some(n) = a.displays {
s.display.count = n;
@@ -1248,9 +1248,6 @@ fn create_cmd(a: CreateArgs, host: Host) -> Result<()> {
s.display.resolution = r.clone();
}
s.display.borderless = a.borderless.unwrap_or(false);
if let Some(r) = &a.refresh_rate {
s.display.refresh_rate = vm::parse_refresh_rate(r)?;
}
s.display.check()?;
if let Some(g) = &a.gpu {
s.gpu = resolve_gpu(g)?;
@@ -1464,14 +1461,19 @@ pub fn describe(vm: &Vm, host: Host, full: Option<&runtime::DiskFull>) -> Vec<(S
Err(_) => paths::tilde(&disk),
};
match &c.q35 {
Some(q) => add(
"disk",
format!(
"{disk_name} ({}, {})",
c.disk_format.as_str(),
q.disk_controller.describe()
),
),
Some(q) => {
add(
"disk",
format!(
"{disk_name} ({}, {})",
c.disk_format.as_str(),
q.disk_controller.describe()
),
);
if !q.disk_cache.is_default() {
add("disk cache", q.disk_cache.id().into());
}
}
None => add("disk", format!("{disk_name} ({})", c.disk_format.as_str())),
}
if let Some(a) = &c.vmapple {
@@ -1500,7 +1502,7 @@ pub fn describe(vm: &Vm, host: Host, full: Option<&runtime::DiskFull>) -> Vec<(S
g => add("graphics", g.describe().into()),
}
// reims-vgpu's displays follow their windows: of the settings, only their count, the
// windows' first sizes, borderless and the refresh rate reach them.
// windows' first sizes and borderless reach them.
if graphics == vm::Graphics::ReimsVgpu {
let n = c.display.count;
let at = window_sizes_named(&c.display);
@@ -1519,12 +1521,6 @@ pub fn describe(vm: &Vm, host: Host, full: Option<&runtime::DiskFull>) -> Vec<(S
format!("{n}, in {n} windows opening at {at}, whose sizes the guest follows"),
),
}
if let Some(hz) = c.display.refresh_rate {
add(
"refresh rate",
format!("{hz} Hz, or its screen's where that is lower"),
);
}
}
if graphics.library() && c.profile.gpu_choice(host) {
add(
@@ -1732,6 +1728,13 @@ fn set(a: SetArgs, host: Host) -> Result<()> {
None => bail!("{}: --disk-controller is for x86-64 VMs", c.name),
}
}
if let Some(dc) = &a.disk_cache {
let dc = vm::DiskCache::parse(dc)?;
match &mut c.q35 {
Some(q) => q.disk_cache = dc,
None => bail!("{}: --disk-cache is for x86-64 VMs", c.name),
}
}
// A count given is checked against the graphics; one kept from reims-vgpu waits unused on
// VMware SVGA, as the resolution does.
if let Some(n) = a.displays {
@@ -1744,9 +1747,6 @@ fn set(a: SetArgs, host: Host) -> Result<()> {
if let Some(b) = a.borderless {
c.display.borderless = b;
}
if let Some(r) = &a.refresh_rate {
c.display.refresh_rate = vm::parse_refresh_rate(r)?;
}
if let Some(g) = &a.gpu {
c.gpu = resolve_gpu(g)?;
}
@@ -2872,40 +2872,6 @@ mod tests {
assert_eq!(count(), 1);
}
/// `set --refresh-rate` takes a number of hertz, which the VM's settings keep and its summary
/// names, and auto clears it, saving none; 0, a negative rate and what is no number are
/// refused with a plain message, saving nothing.
#[test]
fn set_takes_a_refresh_rate_and_auto_clears_it() {
let env = Env::new("set-refresh-rate");
let dir = env.root.join("vms/t");
register("t", &dir, &config(""));
let rate = || Vm::load(&dir).unwrap().config.display.refresh_rate;
let host = Host::current();
let set_rate = |r: &str| {
let given = format!("--refresh-rate={r}");
set(set_args(&["reims-ctl", "set", "t", &given]), host)
};
assert_eq!(rate(), None);
set_rate("60").unwrap();
assert_eq!(rate(), Some(60.0));
let said = describe(&Vm::load(&dir).unwrap(), host, None);
let line = (
"refresh rate".to_string(),
"60 Hz, or its screen's where that is lower".to_string(),
);
assert!(said.contains(&line), "{said:?}");
for bad in ["0", "-60", "fast", "NaN", "2000"] {
let e = format!("{:#}", set_rate(bad).unwrap_err());
assert!(e.contains("a refresh rate is "), "{bad}: {e}");
assert_eq!(rate(), Some(60.0), "{bad}");
}
set_rate("auto").unwrap();
assert_eq!(rate(), None);
let file = std::fs::read_to_string(dir.join(vm::CONFIG_FILE)).unwrap();
assert!(!file.contains("refresh"), "{file}");
}
/// A VM's summary and its printed command say how many windows it opens: one, as before
/// the setting, or one for each display.
#[test]
+1 -1
View File
@@ -154,7 +154,7 @@ pub(super) fn clone(src: &Path, dst: &Path) -> io::Result<()> {
/// The parts of `f`, `len` bytes long, that a full copy reads: all of it. NTFS's allocated ranges
/// (FSCTL_QUERY_ALLOCATED_RANGES) left out data just written: a test's sparse source, asked
/// just after it was written, came back without the range written first, so its copy was zeros
/// there (job m3-max-32291 on Windows 11, 2026-11-15; job 32290 of the same code got the range).
/// there (job m3-max-32291 on the mini, 2026-11-15; job 32290 of the same code got the range).
/// [`super::full`] leaves the blocks of zeros it reads holes, so a copy is as sparse either way.
pub(super) fn data_ranges(_f: &File, len: u64) -> Vec<(u64, u64)> {
if len == 0 { Vec::new() } else { vec![(0, len)] }
+32 -5
View File
@@ -92,6 +92,7 @@ pub struct Spec {
pub ssh_port: Option<u16>,
pub mac: Option<String>,
// q35
pub disk_cache: Option<DiskCache>,
/// macOS to download from Apple, for the installer.
pub macos: Option<Download>,
pub opencore: Option<PathBuf>,
@@ -119,6 +120,7 @@ impl Spec {
network: true,
ssh_port: None,
mac: None,
disk_cache: None,
macos: None,
opencore: None,
installer: None,
@@ -224,13 +226,28 @@ pub fn create_with(
check_free(&dir)?;
// What was given is checked before the slow steps: a download, a disk's copy.
let mut foreign = None;
if let Some(DiskSource::Existing { path, .. }) = &spec.disk {
if !path.is_file() {
bail!("the disk {} does not exist", path.display());
let is_raw_dev = matches!(
&spec.disk,
Some(DiskSource::Existing { path, .. }) if crate::vm::is_windows_raw_device(path)
);
if let Some(DiskSource::Existing { path, mode }) = &spec.disk {
if crate::vm::is_windows_raw_device(path) {
if *mode != ImportMode::InPlace {
bail!(
"raw Windows disk/partition {} can only be used in-place (--disk-mode in-place)",
path.display()
);
}
} else {
if !path.is_file() {
bail!("the disk {} does not exist", path.display());
}
foreign = foreign_disk(path, profile)?;
}
foreign = foreign_disk(path, profile)?;
}
check_disk_fits(&spec, &dir, foreign.as_ref())?;
if !is_raw_dev {
check_disk_fits(&spec, &dir, foreign.as_ref())?;
}
if let (Some(f), Some(DiskSource::Existing { path, .. })) = (&foreign, &spec.disk) {
check_room(f, path, &dir)?;
}
@@ -1409,6 +1426,7 @@ fn make_q35(
cpu_model: default_cpu_model(),
cpu_flags: default_cpu_flags(),
disk_controller: DiskController::Ahci,
disk_cache: spec.disk_cache.unwrap_or_default(),
disk_port: 3,
});
Ok(Vm {
@@ -1424,6 +1442,15 @@ fn import_disk(
stem: &str,
progress: &mut dyn FnMut(&str),
) -> Result<(PathBuf, ImageFormat)> {
if crate::vm::is_windows_raw_device(src) {
if mode != ImportMode::InPlace {
bail!(
"raw Windows disk/partition {} can only be used in-place (--disk-mode in-place)",
src.display()
);
}
return Ok((src.to_path_buf(), ImageFormat::Raw));
}
if !src.is_file() {
bail!("the disk {} does not exist", src.display());
}
+416 -67
View File
@@ -18,8 +18,9 @@ use crate::vm::{Graphics, ImageFormat, Vm};
use crate::{paths, prebuilt, reims_util, runtime};
use anyhow::{Context, Result, bail, ensure};
use std::collections::BTreeMap;
use std::fs::File;
use std::fs::{self, File, OpenOptions};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Mutex, PoisonError};
use std::time::{Duration, SystemTime};
@@ -244,65 +245,119 @@ pub enum ProcessorTypeChange {
Written { from: u64, to: u16 },
}
/// Gives a stopped x86-64 VM's OpenCore image PlatformInfo > Generic > ProcessorType `value`
/// where it has another (processor.rs), so the guest's About This Mac names the processor as
/// `value` does from its next boot; refused while the VM, or another VM on the same image, runs.
/// The value goes into a copy of the image beside it, `<image>.part`, which is read back and then
/// renamed over the image, so a write stopped at any point leaves the image as it was, byte for
/// byte, or the whole new one at the VM's path, and either boots. Only config.plist's own
/// clusters change, its length kept ([`with_processor_type`]): the image's other files, its
/// volume's tables and the qcow2's are the same.
/// Sets the display type for an automatic SMBIOS configuration on a stopped x86-64 VM.
pub fn match_processor_type(vm: &Vm, value: u16) -> Result<ProcessorTypeChange> {
let Some(q) = vm.config.q35.as_ref() else {
return Ok(ProcessorTypeChange::Kept);
};
let name = vm.name();
let image = vm.path(&q.opencore);
if value == 0 || !fs::symlink_metadata(&image)?.is_file() {
return Ok(ProcessorTypeChange::Kept);
}
let format = q.opencore_format;
let Some(from) = Config::read(&image, format)?.processor_type() else {
let stamp = Stamp::of(&image).context("read OpenCore image metadata")?;
let Some(config) = read_file(&image, format, CONFIG_PLIST)? else {
return Ok(ProcessorTypeChange::Kept);
};
if from == u64::from(value) {
if !processor_type_is_automatic(&Config::parse(&config)?) {
return Ok(ProcessorTypeChange::Kept);
}
if runtime::running(vm) {
bail!("{name} is running: stop it first");
}
if let Some(other) = runtime::running_on_image(vm)? {
bail!("{other} is running on {name}'s OpenCore image: stop it first");
}
let config = read_file(&image, format, CONFIG_PLIST)?
.context("its EFI system partition has no EFI/OC/config.plist")?;
let edited = with_processor_type(&config, value)?;
let mut part = image.clone().into_os_string();
part.push(".part");
let part = PathBuf::from(part);
ensure_processor_image_unused(vm)?;
static NEXT: AtomicU64 = AtomicU64::new(0);
let part = image.with_extension(format!(
"cpu-{}-{}-{}.part",
std::process::id(),
SystemTime::now()
.duration_since(SystemTime::UNIX_EPOCH)?
.as_nanos(),
NEXT.fetch_add(1, Ordering::Relaxed),
));
let file = OpenOptions::new()
.write(true)
.create_new(true)
.open(&part)?;
let written = (|| -> Result<()> {
std::fs::copy(&image, &part).with_context(|| format!("copy {}", image.display()))?;
let mut source = File::open(&image)?;
file.set_permissions(source.metadata()?.permissions())?;
std::io::copy(&mut source, &mut &file)?;
drop(file);
drop(source);
let disk = Disk::open_rw(&part, format)?;
Fat32::open(&disk, esp_start(&disk)?)?.overwrite(CONFIG_PLIST, &edited)?;
disk.sync()?;
let fat = Fat32::open(&disk, esp_start(&disk)?)?;
ensure!(
Config::read(&part, format)?.processor_type() == Some(u64::from(value)),
"the copy does not read back with ProcessorType {value}"
fat.holds(CONFIG_PLIST, &config)? == Some(true),
"OpenCore config changed while copying"
);
fat.overwrite(CONFIG_PLIST, &edited)?;
disk.sync()?;
drop(disk);
ensure!(
read_file(&part, format, CONFIG_PLIST)?.as_deref() == Some(&edited),
"the OpenCore config did not read back"
);
#[cfg(test)]
tests::STOP_BEFORE_RENAME.with(|s| {
if s.get() {
bail!("stopped before the rename");
}
Ok(())
ensure!(!s.get(), "stopped before the rename");
Ok::<_, anyhow::Error>(())
})?;
std::fs::rename(&part, &image).with_context(|| format!("replace {}", image.display()))
ensure_processor_image_unused(vm)?;
ensure!(
Stamp::of(&image) == Some(stamp),
"OpenCore image changed while copying"
);
fs::rename(&part, &image).with_context(|| format!("replace {}", image.display()))
})();
if let Err(e) = written {
let _ = std::fs::remove_file(&part);
return Err(e);
if let Err(error) = written {
let _ = fs::remove_file(&part);
return Err(error);
}
KEPT.lock()
.unwrap_or_else(PoisonError::into_inner)
.remove(&image);
Ok(ProcessorTypeChange::Written { from, to: value })
Ok(ProcessorTypeChange::Written { from: 0, to: value })
}
fn ensure_processor_image_unused(vm: &Vm) -> Result<()> {
let name = vm.name();
ensure!(!runtime::running(vm), "{name} is running: stop it first");
if let Some(other) = runtime::running_on_image(vm)? {
bail!("{other} is running on {name}'s OpenCore image: stop it first");
}
Ok(())
}
fn processor_type_is_automatic(config: &Config) -> bool {
let vault = config
.0
.get("Misc")
.and_then(plist::Value::as_dictionary)
.and_then(|misc| misc.get("Security"))
.and_then(plist::Value::as_dictionary)
.and_then(|security| security.get("Vault"))
.and_then(plist::Value::as_string);
let Some(platform) = config
.0
.get("PlatformInfo")
.and_then(plist::Value::as_dictionary)
else {
return false;
};
vault == Some("Optional")
&& platform.get("Automatic").and_then(plist::Value::as_boolean) == Some(true)
&& platform
.get("UpdateSMBIOS")
.and_then(plist::Value::as_boolean)
== Some(true)
&& platform
.get("UpdateSMBIOSMode")
.and_then(plist::Value::as_string)
== Some("Create")
&& config.processor_type() == Some(0)
}
/// Whether a VM's OpenCore image shows its boot picker; `None` for an image reims-ctl cannot
@@ -598,6 +653,102 @@ pub fn made_for_other_graphics(vm: &Vm) -> bool {
}
}
/// The existing OpenCore drivers that provide keyboard and pointer input before macOS starts.
const PREBOOT_INPUT_DRIVERS: [&str; 2] = ["ReimsTablet.efi", "OpenUsbKbDxe.efi"];
#[derive(PartialEq)]
struct PrebootInput {
config: plist::Value,
files: BTreeMap<String, Vec<u8>>,
}
impl PrebootInput {
/// Reads the selected driver entries, their binaries, and the existing UEFI input settings.
fn read(config: &Config, image: &Path, format: ImageFormat) -> Result<Option<Self>> {
let Some(uefi) = config.0.get("UEFI").and_then(plist::Value::as_dictionary) else {
return Ok(None);
};
let mut drivers = Vec::new();
let mut files = BTreeMap::<String, Vec<u8>>::new();
for driver in uefi
.get("Drivers")
.and_then(plist::Value::as_array)
.into_iter()
.flatten()
{
let Some(path) = driver
.as_dictionary()
.and_then(|entry| entry.get("Path"))
.and_then(plist::Value::as_string)
else {
continue;
};
if !PREBOOT_INPUT_DRIVERS
.iter()
.any(|name| path.eq_ignore_ascii_case(name))
{
continue;
}
ensure!(
!files.keys().any(|seen| seen.eq_ignore_ascii_case(path)),
"OpenCore lists the preboot input driver {path} more than once"
);
let efi_path = format!("EFI/OC/Drivers/{path}");
let bytes = read_file(image, format, &efi_path)?
.filter(|bytes| !bytes.is_empty())
.with_context(|| {
format!("OpenCore's preboot input driver {efi_path} is missing or empty")
})?;
files.insert(path.to_owned(), bytes);
drivers.push(driver.clone());
}
if drivers.is_empty() {
return Ok(None);
}
let input = uefi
.get("Input")
.filter(|input| input.as_dictionary().is_some())
.context("OpenCore's preboot drivers require the existing UEFI > Input dictionary")?;
let mut bundle = plist::Dictionary::new();
bundle.insert("Input".into(), input.clone());
bundle.insert("Drivers".into(), plist::Value::Array(drivers));
Ok(Some(Self {
config: plist::Value::Dictionary(bundle),
files,
}))
}
fn stage(&self) -> Result<PrebootInputDir> {
static NEXT: AtomicU64 = AtomicU64::new(0);
let dir = std::env::temp_dir().join(format!(
"reims-ctl-opencore-input-{}-{}-{}",
std::process::id(),
SystemTime::now()
.duration_since(SystemTime::UNIX_EPOCH)?
.as_nanos(),
NEXT.fetch_add(1, Ordering::Relaxed),
));
crate::os::create_private_dir(&dir).context("create temporary preboot input directory")?;
let dir = PrebootInputDir(dir);
self.config
.to_writer_xml(File::create(dir.0.join("input.plist"))?)
.context("write preboot input configuration")?;
for (name, bytes) in &self.files {
fs::write(dir.0.join(name), bytes)
.with_context(|| format!("stage OpenCore's preboot input driver {name}"))?;
}
Ok(dir)
}
}
struct PrebootInputDir(PathBuf);
impl Drop for PrebootInputDir {
fn drop(&mut self) {
let _ = fs::remove_dir_all(&self.0);
}
}
/// Replaces a stopped VM's OpenCore image with one the installed reims-util makes, presenting
/// the same Mac, with its boot picker shown where `show_picker` says, or as the old image shows
/// it when `None`; refused while the VM, or another VM on the same image, runs. The new image is
@@ -606,7 +757,8 @@ pub fn made_for_other_graphics(vm: &Vm) -> bool {
/// one, so a renewal stopped at any point leaves the old image or the whole new one at the VM's
/// path, and either boots.
/// It holds the kexts for the VM's graphics ([`reims_util::kext_args`]): on reims-vgpu's own
/// device, the guest's that this reims-ctl carries. The VM keeps its OVMF: its variables hold
/// device, the guest's that this reims-ctl carries. Existing preboot keyboard and tablet drivers
/// and their input options are carried over. The VM keeps its OVMF: its variables hold
/// its boot entries. The image is set in the VM's settings as they are once it is made, which
/// `vm` becomes: others may be saved meanwhile. Returns what happened, and, where the old image
/// loaded reims-vgpu's kexts on other graphics, what they left in the guest
@@ -633,14 +785,33 @@ pub fn renew(
let read = || format!("read the Mac {} presents", paths::tilde(&old));
let config = Config::read(&old, q.opencore_format).with_context(read)?;
let id = config.identity().with_context(read)?;
let preboot = PrebootInput::read(&config, &old, q.opencore_format)
.context("read the old OpenCore image's preboot input")?;
let staged = preboot.as_ref().map(PrebootInput::stage).transpose()?;
let picker = show_picker.unwrap_or_else(|| config.shows_picker());
let image = vm.dir.join("opencore.qcow2");
let new = vm.dir.join("opencore.new.qcow2");
let dropped = holds_unused_guest_kexts(vm);
let kexts = reims_util::kext_args(vm.config.graphics())?;
let made = reims_util::opencore_as(&new, &id, picker, &kexts, progress).and_then(|()| {
let made = reims_util::opencore_as(
&new,
&id,
picker,
&kexts,
staged.as_ref().map(|dir| dir.0.as_path()),
progress,
)
.and_then(|()| {
let config = Config::read(&new, ImageFormat::Qcow2)
.context("read the new OpenCore image before replacing the old one")?;
if let Some(expected) = &preboot {
let actual = PrebootInput::read(&config, &new, ImageFormat::Qcow2)
.context("verify the new OpenCore image's preboot input")?;
ensure!(
actual.as_ref() == Some(expected),
"reims-util did not preserve the old OpenCore image's preboot input"
);
}
ensure!(
!config
.configured_kexts()
@@ -902,7 +1073,7 @@ impl Qcow2 {
}
/// Where guest cluster `index` is in the file; None where it reads as zeros.
fn cluster(&self, index: u64) -> Result<Option<u64>> {
fn cluster(&self, index: u64, write: bool) -> Result<Option<u64>> {
let per_table = 1u64 << (self.cluster_bits - 3);
let l1 = self
.l1
@@ -917,8 +1088,15 @@ impl Qcow2 {
.read_exact_at(&mut e, (l1 & QCOW2_OFFSET) + index % per_table * 8)?;
let e = u64::from_be_bytes(e);
ensure!(e & 1 << 62 == 0, "a qcow2 image with compressed clusters");
// Bit 0: a zero cluster.
Ok((e & 1 == 0 && e & QCOW2_OFFSET != 0).then_some(e & QCOW2_OFFSET))
// Bit 0 denotes a zero cluster. Bit 63 on both entries denotes exclusive ownership.
if e & 1 != 0 || e & QCOW2_OFFSET == 0 {
return Ok(None);
}
ensure!(
!write || l1 & e & (1 << 63) != 0,
"OpenCore QCOW2 cluster is shared"
);
Ok(Some(e & QCOW2_OFFSET))
}
/// Writes `buf` at `offset` of what the guest sees into the clusters the image has there;
@@ -930,9 +1108,11 @@ impl Qcow2 {
let at = offset + done as u64;
let within = at & (cluster - 1);
let n = ((cluster - within) as usize).min(buf.len() - done);
let c = self.cluster(at >> self.cluster_bits)?.with_context(|| {
format!("a write at {at:#x}, where the qcow2 image has no cluster")
})?;
let c = self
.cluster(at >> self.cluster_bits, true)?
.with_context(|| {
format!("a write at {at:#x}, where the qcow2 image has no cluster")
})?;
self.file.write_all_at(&buf[done..done + n], c + within)?;
done += n;
}
@@ -947,7 +1127,7 @@ impl Qcow2 {
let within = at & (cluster - 1);
let n = ((cluster - within) as usize).min(buf.len() - done);
let part = &mut buf[done..done + n];
match self.cluster(at >> self.cluster_bits)? {
match self.cluster(at >> self.cluster_bits, false)? {
Some(c) => self.file.read_exact_at(part, c + within)?,
None => part.fill(0),
}
@@ -1056,9 +1236,14 @@ impl<'a> Fat32<'a> {
c = u32::from_le_bytes(next) & 0x0fff_ffff;
}
ensure!(given == bytes.len() as u64, "{path} is cut short");
let mut before = vec![0; self.cluster_size as usize];
for (at, from, n) in spans {
self.disk
.write(at, &bytes[from as usize..(from + n) as usize])?;
let after = &bytes[from as usize..(from + n) as usize];
let before = &mut before[..after.len()];
self.disk.read(at, before)?;
if before != after {
self.disk.write(at, after)?;
}
}
Ok(())
}
@@ -1543,6 +1728,76 @@ pub(crate) mod tests {
assert!(!dir.join("opencore.img").exists());
}
#[test]
fn renew_keeps_preboot_input_and_refuses_a_lost_driver() {
let env = crate::testenv::Env::new("renew-preboot-input");
let dir = env.root.join("vm");
fs::create_dir(&dir).unwrap();
let plist = plist("").replace(
"</dict></plist>",
r#"<key>UEFI</key><dict>
<key>Drivers</key><array>
<dict><key>Path</key><string>reimstablet.efi</string>
<key>Enabled</key><true/><key>Arguments</key><string>tablet</string></dict>
<dict><key>Path</key><string>OpenUsbKbDxe.efi</string>
<key>Enabled</key><true/><key>LoadEarly</key><true/></dict>
<dict><key>Path</key><string>Extra.efi</string><key>Enabled</key><true/></dict>
</array>
<key>Input</key><dict><key>KeySupport</key><false/></dict>
</dict></dict></plist>"#,
);
let tablet = ("EFI/OC/Drivers/ReimsTablet.efi", &b"fake tablet"[..]);
let keyboard = ("EFI/OC/Drivers/OpenUsbKbDxe.efi", &b"fake keyboard"[..]);
let old = image_of_config(&plist, b"", &[tablet, keyboard]);
let mut vm = on_reims_vgpu(&dir, &old, ImageFormat::Raw);
let made = env.root.join("made.img");
let args = env.root.join("args");
let input = env.root.join("staged.plist");
let script = format!(
"#!/bin/sh\nprintf '%s\\n' \"$@\" > '{args}'\n\
while [ \"$1\" != -o ]; do shift; done\n\
out=$2\nshift 2\n\
while [ \"$1\" != --preboot-input ]; do shift; done\n\
cp \"$2/input.plist\" '{input}'\n\
test \"$(cat \"$2/reimstablet.efi\")\" = 'fake tablet' || exit 1\n\
test \"$(cat \"$2/OpenUsbKbDxe.efi\")\" = 'fake keyboard' || exit 1\n\
test ! -e \"$2/Extra.efi\" || exit 1\n\
cp '{made}' \"$out\"\n\
echo '{{\"event\":\"done\",\"result\":{{}}}}'\n",
args = args.display(),
input = input.display(),
made = made.display(),
);
let util = crate::testenv::program(&env.root.join("reims-util"), &script);
env.set("REIMS_CTL_UTIL", &util);
let old_path = dir.join("opencore.img");
fs::write(&old_path, image_of_config(&plist, b"", &[keyboard])).unwrap();
let err = renew(&mut vm, None, &mut |_| {}).unwrap_err();
assert!(format!("{err:#}").contains("reimstablet.efi is missing"));
assert!(!args.exists());
fs::write(&old_path, &old).unwrap();
fs::write(&made, qcow2(&image_of_config(&plist, b"", &[tablet]))).unwrap();
let err = renew(&mut vm, None, &mut |_| {}).unwrap_err();
assert!(format!("{err:#}").contains("OpenUsbKbDxe.efi is missing"));
assert_eq!(fs::read(&old_path).unwrap(), old);
assert!(!dir.join("opencore.new.qcow2").exists());
fs::write(&made, qcow2(&old)).unwrap();
renew(&mut vm, None, &mut |_| {}).unwrap();
let captured = fs::read_to_string(args).unwrap();
let staging = captured.lines().last().unwrap();
assert!(!Path::new(staging).exists());
let bundle = plist::Value::from_file(input).unwrap();
let bundle = bundle.as_dictionary().unwrap();
assert_eq!(
bundle["Input"].as_dictionary().unwrap()["KeySupport"].as_boolean(),
Some(false)
);
assert_eq!(bundle["Drivers"].as_array().unwrap().len(), 2);
assert!(!old_path.exists());
}
/// The old image goes only where its path, resolved, names a file in the VM's directory
/// other than the new image: an OpenCore path edited to `../other/oc.img` leaves that file
/// be, and one spelling the new image's place another way, `sub/../opencore.qcow2`, leaves
@@ -2341,11 +2596,30 @@ pub(crate) mod tests {
fn with_processor_type_key(plist: &str, value: u64) -> String {
let at = " <key>ROM</key>";
assert!(plist.contains(at));
plist.replacen(
at,
&format!("\t\t\t<key>ProcessorType</key>\n\t\t\t<integer>{value}</integer>\n{at}"),
1,
)
plist
.replacen(
" <key>PlatformInfo</key>",
concat!(
" <key>Misc</key><dict><key>Security</key><dict>",
"<key>Vault</key><string>Optional</string></dict></dict>\n",
" <key>PlatformInfo</key>",
),
1,
)
.replacen(
"<key>Automatic</key><true/>",
concat!(
"<key>Automatic</key><true/>\n",
"<key>UpdateSMBIOS</key><true/>\n",
"<key>UpdateSMBIOSMode</key><string>Create</string>",
),
1,
)
.replacen(
at,
&format!("\t\t\t<key>ProcessorType</key>\n\t\t\t<integer>{value}</integer>\n{at}"),
1,
)
}
/// A new ProcessorType keeps config.plist's length, whatever its digits, and changes
@@ -2386,7 +2660,7 @@ pub(crate) mod tests {
/// The value goes into the image, raw or qcow2, through a copy renamed over it: the image
/// keeps its length, every other file it holds and its identity, and no copy stays beside
/// it. The same value again writes nothing; 0 gives the name back to OpenCore's own pick.
/// it. An explicit type remains in the image across later starts.
#[test]
fn the_image_takes_the_processor_type() {
let env = crate::testenv::Env::new("processor-type");
@@ -2435,15 +2709,9 @@ pub(crate) mod tests {
assert_eq!(std::fs::read(&path).unwrap(), after);
assert_eq!(
match_processor_type(&v, 0).unwrap(),
ProcessorTypeChange::Written {
from: 0x0709,
to: 0
}
);
assert_eq!(
Config::read(&path, format).unwrap().processor_type(),
Some(0)
ProcessorTypeChange::Kept
);
assert_eq!(std::fs::read(&path).unwrap(), after);
}
// An image without the key is left as it is.
let dir = env.root.join("nokey");
@@ -2490,7 +2758,10 @@ pub(crate) mod tests {
);
let c = Config::read(&dir.join("opencore.qcow2"), ImageFormat::Qcow2).unwrap();
assert_eq!(c.processor_type(), Some(0x0709));
assert!(!part.exists());
assert_eq!(
std::fs::read(&part).unwrap(),
b"left by a write killed before"
);
}
/// The write is refused before any copy while another VM runs on the same image, which its
@@ -2542,8 +2813,7 @@ pub(crate) mod tests {
}
/// A start writes the host's processor type after it makes an image of an older set again,
/// whose reims-util writes OpenCore's own pick, 0: the new image boots with the host's. A host
/// whose CPU states no family gives the name back to OpenCore.
/// whose reims-util writes OpenCore's own pick, 0: the new image boots with the host's.
#[test]
fn a_start_names_the_hosts_processor_after_a_new_image() {
let env = crate::testenv::Env::new("start-processor-type");
@@ -2586,7 +2856,86 @@ pub(crate) mod tests {
crate::runtime::prepare(&mut v, &mut |s| said.push(s.to_string()))
});
assert!(warned.is_empty(), "{warned:?}");
assert_eq!(read(), Some(0));
assert!(said.last().unwrap().contains("to OpenCore"), "{said:?}");
assert_eq!(read(), Some(0x0709));
assert!(said.is_empty(), "{said:?}");
}
#[test]
fn processor_type_preserves_explicit_or_unsupported_configs() {
let env = crate::testenv::Env::new("processor-type-custom");
let baseline = with_processor_type_key(&plist(""), 0);
for (label, config) in [
("explicit", with_processor_type_key(&plist(""), 0x0709)),
(
"manual",
baseline.replace(
"<key>Automatic</key><true/>",
"<key>Automatic</key><false/>",
),
),
(
"no-smbios-update",
baseline.replace(
"<key>UpdateSMBIOS</key><true/>",
"<key>UpdateSMBIOS</key><false/>",
),
),
(
"other-mode",
baseline.replace("<string>Create</string>", "<string>Custom</string>"),
),
(
"secure",
baseline.replace("<string>Optional</string>", "<string>Secure</string>"),
),
(
"basic",
baseline.replace("<string>Optional</string>", "<string>Basic</string>"),
),
] {
let dir = env.root.join(label);
std::fs::create_dir_all(&dir).unwrap();
let source = image(config.as_bytes());
let vm = on_reims_vgpu(&dir, &source, ImageFormat::Raw);
let path = vm.path(&vm.config.q35.as_ref().unwrap().opencore);
assert_eq!(
match_processor_type(&vm, 0x0609).unwrap(),
ProcessorTypeChange::Kept,
"{label}"
);
assert_eq!(std::fs::read(&path).unwrap(), source, "{label}");
}
}
#[test]
fn processor_type_preserves_qcow2_with_shared_or_snapshotted_clusters() {
let env = crate::testenv::Env::new("processor-type-shared-clusters");
let config = with_processor_type_key(&plist(""), 0);
let generated = qcow2(&image(config.as_bytes()));
let mut shared = generated.clone();
let l1 = be64(&shared, 40) as usize;
let l1_size = be32(&shared, 36) as usize * 8;
for entry in shared[l1..l1 + l1_size].as_chunks_mut::<8>().0 {
entry[0] &= 0x7f;
}
let mut snapshot = generated;
snapshot[60..64].copy_from_slice(&1u32.to_be_bytes());
for (label, source) in [("shared", shared), ("snapshots", snapshot)] {
let dir = env.root.join(label);
std::fs::create_dir_all(&dir).unwrap();
let vm = on_reims_vgpu(&dir, &source, ImageFormat::Qcow2);
let path = vm.path(&vm.config.q35.as_ref().unwrap().opencore);
let error = match_processor_type(&vm, 0x0609).unwrap_err().to_string();
assert!(error.contains(label), "{error}");
assert_eq!(std::fs::read(&path).unwrap(), source, "{label}");
assert!(std::fs::read_dir(&dir).unwrap().all(|file| {
file.unwrap()
.path()
.extension()
.is_none_or(|ext| ext != "part")
}));
}
}
}
+4
View File
@@ -43,6 +43,10 @@ pub fn home() -> PathBuf {
/// after a `\`; elsewhere as it is.
pub fn native(p: PathBuf) -> PathBuf {
if cfg!(windows) {
if crate::vm::is_windows_raw_device(&p) {
let s = p.to_string_lossy().replace('/', "\\");
return PathBuf::from(s.trim_end_matches('\\'));
}
p.components().collect()
} else {
p
+19 -14
View File
@@ -19,10 +19,9 @@
//! picks one itself where that is 0, as reims-util's images have it: from QEMU's CPU, model 0x5E,
//! with no family in its brand string, it picks 0x0905, Core i3, which shows as "Quad-Core Intel
//! Core i3" with 4 vCPUs and "Unknown" with 8 (measured on macOS 26.7.2). reims-ctl writes the
//! value for the host's CPU instead, at each start ([`crate::opencore::match_processor_type`]):
//! the family its brand string states ([`Family::of`]), Intel's own words or AMD's rank of the
//! same steps, and 0, OpenCore's own pick, for a CPU that states none. The CPU the guest runs
//! on, its model and its features, is the same whatever the value: only the name changes.
//! value for the host's CPU on cold starts when the image uses automatic detection
//! ([`crate::opencore::match_processor_type`]). Where Apple has no name for the family and core
//! count, the image keeps its setting. The processor type controls the displayed name.
/// A family of the host's CPU that Apple has names for.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
@@ -88,16 +87,17 @@ impl Family {
/// Apple's processor type for the family, in a guest of `cpus` vCPUs: a value Intel's Macs
/// had, whose family Apple's table names at the core count macOS reads, `cpus` rounded up to
/// a power of two, where any of the family's types is named there. A Xeon is "Intel Xeon",
/// 0x0501, up to 4 vCPUs, and "Intel Xeon W", 0x0F01, from 5: macOS counts 5 to 8 vCPUs as 8
/// cores, which "Intel Xeon" has no name for and "Intel Xeon W" has.
/// 0x0501, up to 4 vCPUs, and "Intel Xeon W", 0x0F01, from 5 to 16: macOS counts 5 to 8 vCPUs as 8
/// cores, which "Intel Xeon" has no name for and "Intel Xeon W" has. Returns 0 where Apple has no name.
pub fn processor_type(self, cpus: u32) -> u16 {
match self {
Family::CoreI3 => 0x0909,
Family::CoreI5 => 0x0609,
Family::CoreI7 => 0x0709,
Family::CoreI9 => 0x1009,
Family::Xeon if cpus <= 4 => 0x0501,
Family::Xeon => 0x0F01,
match (self, cpus) {
(Family::CoreI3, 2..=4) => 0x0909,
(Family::CoreI5, 2..=8) => 0x0609,
(Family::CoreI7, 2..=8) => 0x0709,
(Family::CoreI9, 5..=8) => 0x1009,
(Family::Xeon, 1..=4) => 0x0501,
(Family::Xeon, 5..=16) => 0x0F01,
_ => 0,
}
}
}
@@ -179,7 +179,7 @@ mod tests {
}
/// The value for each family, which Apple's table names: Core i3 to i9 by their family's
/// type whatever the count, a Xeon as "Intel Xeon" up to 4 vCPUs and "Intel Xeon W" from 5;
/// type at a supported count, a Xeon as "Intel Xeon" up to 4 vCPUs and "Intel Xeon W" from 5;
/// 0 where the host states no family, or gives no brand string.
#[test]
fn each_family_has_its_processor_type() {
@@ -205,6 +205,11 @@ mod tests {
assert_eq!(processor_type(xeon, 6), 0x0F01);
assert_eq!(processor_type(xeon, 8), 0x0F01);
assert_eq!(processor_type(Some("Intel(R) Pentium(R) Gold 7505"), 4), 0);
assert_eq!(
processor_type(Some("Intel(R) Core(TM) i5-12400"), 8),
0x0609
);
assert_eq!(processor_type(Some("Intel(R) Core(TM) i9-13900H"), 4), 0);
assert_eq!(processor_type(None, 8), 0);
for t in [0x0909, 0x0609, 0x0709, 0x1009, 0x0501, 0x0F01] {
assert!(family_name(t).is_some(), "{t:#06x}");
+183 -27
View File
@@ -81,9 +81,7 @@
//! device's `resolution`: one size for every window, or one for each, comma-separated, each
//! comma doubled on QEMU's line; 1920x1080 by default) and follows its window's size at the
//! rate of the host screen the window is on; borderless reaches every window as
//! `REIMS_VGPU_WINDOW_BORDERLESS`, and the VM's refresh rate, where it has one, as
//! `REIMS_VGPU_WINDOW_REFRESH_RATE`, its hertz, which every display then offers each size at
//! alone, at most its screen's rate ([`crate::vm::Display::refresh_rate`]).
//! `REIMS_VGPU_WINDOW_BORDERLESS`.
//! - QEMU's `vmware-svga` (`graphics = "vmware-svga"`). The library then draws nothing, so the
//! window's and the GPU's variables are left out, and QEMU's own window, GTK's (`-display
//! gtk`), shows the display. Where QEMU's environment names no Wayland compositor or X server,
@@ -171,6 +169,8 @@ pub struct Ctx {
/// The host CPU's brand string ([`crate::host::cpu_brand`]), which an x86-64 guest's CPU
/// gives as its own (`model-id`); None where the host gives none.
pub cpu_brand: Option<String>,
/// Whether this Windows QEMU has the repaired native block AIO backend.
pub win32_native_aio: bool,
/// Whether QEMU's own window can open ([`crate::host::has_screen`]).
pub screen: bool,
/// Whether the start is headless (`reims-ctl start --headless`): it opens no window, and
@@ -253,9 +253,6 @@ pub fn invocation(vm: &Vm, ctx: &Ctx) -> Result<Invocation> {
if library && c.display.borderless {
env.push(("REIMS_VGPU_WINDOW_BORDERLESS".into(), "1".into()));
}
if let Some(hz) = c.display.refresh_rate.filter(|_| library) {
env.push(("REIMS_VGPU_WINDOW_REFRESH_RATE".into(), hz.to_string()));
}
if library && c.profile.gpu_choice(ctx.host) {
let dri_prime = c.gpu.dri_prime()?;
if let Some((vendor, device)) = c.gpu.selected()? {
@@ -456,31 +453,72 @@ fn q35(vm: &Vm, ctx: &Ctx, a: &mut Vec<String>) -> Result<()> {
),
]);
push(&["-device", "ide-hd,bus=sata.2,drive=opencore,bootindex=1"]);
let mut disk = format!(
"id=disk,if=none,format={},file={}",
c.disk_format.as_str(),
optp(&vm.disk())
);
let disk_path = vm.disk();
let is_raw_dev = crate::vm::is_windows_raw_device(&disk_path);
let mut disk = if is_raw_dev {
format!(
"id=disk,if=none,format=raw,file.driver=host_device,file.filename={}",
optp(&disk_path)
)
} else {
format!(
"id=disk,if=none,format={},file={}",
c.disk_format.as_str(),
optp(&disk_path)
)
};
// The qcow2 image's L2 cache, its table of where each cluster is, up to 32 MiB, which maps
// 256 GiB of a disk of 64 KiB clusters (qemu-img's default, which a new disk has). QEMU's own
// limit is 32 MiB on Linux and 8 MiB elsewhere, which maps 64 GiB, half a new 128 GiB disk:
// on Windows a guest access whose table has left the cache reads it from the image again.
// QEMU takes the smaller of this and what the image's size needs (block/qcow2.c,
// `read_cache_sizes`), so a smaller disk keeps a smaller cache.
if c.disk_format == crate::vm::ImageFormat::Qcow2 {
if !is_raw_dev && c.disk_format == crate::vm::ImageFormat::Qcow2 {
disk.push_str(",l2-cache-size=32M");
}
// An install's flushes, which the module's doc measures, are dropped while the installer is
// attached.
if q.installer.is_some() {
disk.push_str(",cache.no-flush=on");
if ctx.win32_native_aio
&& matches!(
q.disk_controller,
DiskController::Nvme | DiskController::Virtio
)
{
if is_raw_dev {
disk.push_str(",file.aio=native");
} else {
disk.push_str(",aio=native");
}
}
match q.disk_cache {
crate::vm::DiskCache::Default => {
// An install's flushes, which the module's doc measures, are dropped while the
// installer is attached.
if q.installer.is_some() {
disk.push_str(",cache.no-flush=on");
}
}
crate::vm::DiskCache::Writeback => {
disk.push_str(",cache.direct=off");
if q.installer.is_some() {
disk.push_str(",cache.no-flush=on");
}
}
crate::vm::DiskCache::None => {
disk.push_str(",cache.direct=on");
if q.installer.is_some() {
disk.push_str(",cache.no-flush=on");
}
}
crate::vm::DiskCache::Unsafe => {
disk.push_str(",cache.direct=off,cache.no-flush=on");
}
}
let discard_opt = if is_raw_dev { "" } else { ",discard=unmap" };
match q.disk_controller {
// `discard=unmap` passes the guest's TRIMs to the image, which frees their space. QEMU's
// NVMe controller needs a serial, and without an address takes slot 3, virtio-net's.
DiskController::Nvme => push(&[
"-drive",
&format!("{disk},discard=unmap"),
&format!("{disk}{discard_opt}"),
"-device",
"nvme,drive=disk,serial=reims-ctl,addr=0xa",
]),
@@ -497,7 +535,7 @@ fn q35(vm: &Vm, ctx: &Ctx, a: &mut Vec<String>) -> Result<()> {
"-object",
"iothread,id=io0",
"-drive",
&format!("{disk},discard=unmap"),
&format!("{disk}{discard_opt}"),
"-device",
"virtio-blk-pci,drive=disk,iothread=io0,addr=0x6",
]),
@@ -958,6 +996,7 @@ pub(crate) mod tests {
cpu_model: default_cpu_model(),
cpu_flags: default_cpu_flags(),
disk_controller: DiskController::Ahci,
disk_cache: crate::vm::DiskCache::Default,
disk_port: 3,
}),
vmapple: None,
@@ -985,6 +1024,7 @@ pub(crate) mod tests {
smbios_error_correction: Some(3),
smbios_memory_slots: None,
cpu_brand: None,
win32_native_aio: false,
screen: true,
headless: false,
graphics_rom: "/d/firmware/ReimsGraphics-0123456789abcdef.rom".into(),
@@ -2236,6 +2276,131 @@ pub(crate) mod tests {
));
}
#[test]
fn only_patched_windows_qemu_gets_native_aio_on_the_system_disk() {
let mut vm = q35_vm();
for controller in [
DiskController::Nvme,
DiskController::Virtio,
DiskController::Ahci,
] {
vm.config.q35.as_mut().unwrap().disk_controller = controller;
for supported in [false, true] {
let c = Ctx {
win32_native_aio: supported,
..ctx(Host {
os: Os::Windows,
..linux()
})
};
let args = invocation(&vm, &c).unwrap().args;
let disk = args.iter().find(|arg| arg.starts_with("id=disk,")).unwrap();
assert_eq!(
disk.split(',').any(|opt| opt == "aio=native"),
supported
&& matches!(controller, DiskController::Nvme | DiskController::Virtio),
);
assert!(args.iter().filter(|arg| arg.contains("aio=native")).count() <= 1);
assert!(!disk.contains("cache.no-flush"));
}
}
}
#[test]
fn disk_cache_modes_emit_expected_qemu_drive_options() {
use crate::vm::{DiskCache, ImageFormat};
for fmt in [ImageFormat::Qcow2, ImageFormat::Raw] {
let mut vm = q35_vm();
vm.config.disk_format = fmt;
vm.config.disk = if fmt == ImageFormat::Raw {
"disk.img".into()
} else {
"disk.qcow2".into()
};
vm.config.q35.as_mut().unwrap().disk_controller = DiskController::Nvme;
let c = Ctx {
win32_native_aio: true,
..ctx(Host {
os: Os::Windows,
..linux()
})
};
vm.config.q35.as_mut().unwrap().disk_cache = DiskCache::Default;
let d = invocation(&vm, &c)
.unwrap()
.args
.into_iter()
.find(|a| a.starts_with("id=disk,"))
.unwrap();
assert!(!d.contains("cache.direct"), "{d}");
assert!(!d.contains("cache.no-flush"), "{d}");
vm.config.q35.as_mut().unwrap().disk_cache = DiskCache::Writeback;
let d = invocation(&vm, &c)
.unwrap()
.args
.into_iter()
.find(|a| a.starts_with("id=disk,"))
.unwrap();
assert!(d.contains(",cache.direct=off"), "{d}");
assert!(!d.contains("cache.no-flush"), "{d}");
vm.config.q35.as_mut().unwrap().disk_cache = DiskCache::None;
let d = invocation(&vm, &c)
.unwrap()
.args
.into_iter()
.find(|a| a.starts_with("id=disk,"))
.unwrap();
assert!(d.contains(",cache.direct=on"), "{d}");
assert!(!d.contains("cache.no-flush"), "{d}");
vm.config.q35.as_mut().unwrap().disk_cache = DiskCache::Unsafe;
let d = invocation(&vm, &c)
.unwrap()
.args
.into_iter()
.find(|a| a.starts_with("id=disk,"))
.unwrap();
assert!(d.contains(",cache.direct=off,cache.no-flush=on"), "{d}");
}
}
#[test]
fn windows_raw_partition_uses_host_device_with_native_aio() {
use crate::vm::{DiskCache, ImageFormat};
let win_ctx = Ctx {
win32_native_aio: true,
..ctx(Host {
os: Os::Windows,
..linux()
})
};
for raw_path in [
r"\\?\Volume{11111111-2222-3333-4444-555555555555}",
r"\\.\PhysicalDrive2",
] {
let mut vm = q35_vm();
vm.config.disk = raw_path.into();
vm.config.disk_format = ImageFormat::Raw;
let q = vm.config.q35.as_mut().unwrap();
q.disk_controller = DiskController::Nvme;
q.disk_cache = DiskCache::Unsafe;
let args = invocation(&vm, &win_ctx).unwrap().args;
let d = args.iter().find(|a| a.starts_with("id=disk,")).unwrap();
assert!(
d.contains("format=raw,file.driver=host_device,file.filename="),
"{d}"
);
assert!(d.contains(raw_path), "{d}");
assert!(d.contains(",file.aio=native"), "{d}");
assert!(d.contains(",cache.direct=off,cache.no-flush=on"), "{d}");
assert!(!d.contains("discard=unmap"), "{d}");
assert!(!d.contains("l2-cache-size"), "{d}");
}
}
#[test]
fn installer_disk_goes_on_its_own_port_through_an_overlay() {
let mut vm = q35_vm();
@@ -2300,15 +2465,6 @@ pub(crate) mod tests {
let env: BTreeMap<_, _> = inv.env.iter().cloned().collect();
assert_eq!(env["REIMS_VGPU_LOG"], "trace");
assert_eq!(env["REIMS_VGPU_WINDOW_BORDERLESS"], "1");
// No refresh rate set: none given, and the display offers its screen's.
assert!(!env.contains_key("REIMS_VGPU_WINDOW_REFRESH_RATE"));
for (hz, given) in [(60.0, "60"), (59.94, "59.94"), (120.0, "120")] {
let mut rated = q35_vm();
rated.config.display.refresh_rate = Some(hz);
let inv = invocation(&rated, &ctx(linux())).unwrap();
let env: BTreeMap<_, _> = inv.env.iter().cloned().collect();
assert_eq!(env["REIMS_VGPU_WINDOW_REFRESH_RATE"], given);
}
// The GPU first, by its IDs, the loader limited to no driver.
assert_eq!(env["MESA_VK_DEVICE_SELECT"], "10de:2204");
assert_eq!(env["VK_LOADER_DEVICE_SELECT"], "0x10de:0x2204");
+16 -7
View File
@@ -1,4 +1,4 @@
//! reims-util (<https://github.com/steelbrain/reims-util>) makes what a new x86-64 VM boots from:
//! reims-util (<https://github.com/reims-go/reims-util>) makes what a new x86-64 VM boots from:
//! an OpenCore image, with OVMF's code and variables beside it, and a macOS installer, downloaded
//! from Apple and checked against Apple's chunklists. It also makes an existing VM a new OpenCore
//! image presenting the same Mac (opencore.rs). For a VM on reims-vgpu's own device, an image
@@ -43,9 +43,9 @@ use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::time::{Duration, Instant};
pub const REPO: &str = "https://github.com/steelbrain/reims-util";
pub const REPO: &str = "https://github.com/reims-go/reims-util";
/// The commit [`install`] installs.
pub const REV: &str = "7867384c0ab703b4c6aae36cbbb1a35fcffc8321";
pub const REV: &str = "c363a029b1a9bce696184b3247e6465aa11321bc";
/// The reims-util binary: `REIMS_CTL_UTIL`, else the one beside reims-ctl, where both are
/// installed, else the first on PATH.
@@ -342,7 +342,7 @@ pub fn opencore(
args.extend(["--model", m]);
}
args.extend(kexts.iter().map(String::as_str));
make_opencore(image, &args, progress)
make_opencore(image, &args, None, progress)
}
/// Makes an OpenCore image at `image` presenting the Mac `id`, for a VM that has its OVMF: no
@@ -353,6 +353,7 @@ pub fn opencore_as(
id: &Identity,
show_picker: bool,
kexts: &[String],
preboot_input: Option<&Path>,
progress: &mut dyn FnMut(&str),
) -> Result<()> {
let mut args = identity_args(id);
@@ -361,7 +362,7 @@ pub fn opencore_as(
args.push("--show-picker");
}
args.extend(kexts.iter().map(String::as_str));
make_opencore(image, &args, progress)
make_opencore(image, &args, preboot_input, progress)
}
/// Makes an OpenCore image at `image` presenting the Mac `id`, with `OVMF_CODE.fd` and
@@ -375,7 +376,7 @@ pub fn opencore_presenting(
) -> Result<()> {
let mut args = identity_args(id);
args.extend(kexts.iter().map(String::as_str));
make_opencore(image, &args, progress)
make_opencore(image, &args, None, progress)
}
/// The arguments that make reims-util's image present the Mac `id`.
@@ -386,9 +387,17 @@ fn identity_args(id: &Identity) -> Vec<&str> {
]
}
fn make_opencore(image: &Path, args: &[&str], progress: &mut dyn FnMut(&str)) -> Result<()> {
fn make_opencore(
image: &Path,
args: &[&str],
preboot_input: Option<&Path>,
progress: &mut dyn FnMut(&str),
) -> Result<()> {
let mut all: Vec<&OsStr> = vec!["opencore".as_ref(), "-o".as_ref(), image.as_os_str()];
all.extend(args.iter().map(OsStr::new));
if let Some(dir) = preboot_input {
all.extend([OsStr::new("--preboot-input"), dir.as_os_str()]);
}
let r = run(&all, progress)?;
if let Ok(o) = serde_json::from_value::<OpencoreResult>(r) {
progress(&format!(
+35 -205
View File
@@ -378,9 +378,15 @@ fn preflight_on(vm: &Vm, host: Host, kernel: &dyn Fn() -> Option<(u32, u32)>) ->
}
Ok(())
};
need(&vm.disk(), "the disk")?;
crate::create::check_disk_format(&vm.disk(), c.profile, crate::create::MAKE_A_VM_OF_THE_COPY)?;
crate::create::check_image_fits(&vm.disk(), c.disk_format)?;
if !crate::vm::is_windows_raw_device(&vm.disk()) {
need(&vm.disk(), "the disk")?;
crate::create::check_disk_format(
&vm.disk(),
c.profile,
crate::create::MAKE_A_VM_OF_THE_COPY,
)?;
crate::create::check_image_fits(&vm.disk(), c.disk_format)?;
}
match c.profile {
Profile::Q35X86_64 => {
let q = c.q35.as_ref().unwrap();
@@ -973,6 +979,7 @@ pub fn context(vm: &Vm, host: Host) -> Result<Ctx> {
let smbios_memory_type = smbios_memory_type(vm, &qemu);
let smbios_error_correction = smbios_error_correction(vm, &qemu);
let smbios_memory_slots = smbios_memory_slots(vm, &qemu);
let win32_native_aio = win32_native_aio(vm, host, &qemu);
Ok(Ctx {
host,
qemu,
@@ -985,6 +992,7 @@ pub fn context(vm: &Vm, host: Host) -> Result<Ctx> {
smbios_error_correction,
smbios_memory_slots,
cpu_brand: crate::host::cpu_brand(),
win32_native_aio,
screen,
headless: false,
graphics_rom: graphics_rom(vm)?,
@@ -1044,6 +1052,14 @@ fn smbios_memory_slots(vm: &Vm, qemu: &Path) -> Option<crate::reims_util::Memory
crate::reims_util::model_memory_slots(&config.identity().ok()?.model)
}
/// A version number alone does not distinguish the fixed Windows block backend.
fn win32_native_aio(vm: &Vm, host: Host, qemu: &Path) -> bool {
host.os == Os::Windows
&& vm.config.profile == Profile::Q35X86_64
&& crate::install::qemu_version(qemu)
.is_some_and(|version| version.ends_with(" [reims-win32-native-aio]"))
}
/// The option ROM of reims-vgpu's own device, written into the data directory for an x86-64 VM
/// on it ([`crate::prebuilt::graphics_rom`]); an empty path, which no command names, for another
/// VM. An arm64 VM's device has no option ROM: Ambrosia drives it with its module.
@@ -1094,6 +1110,7 @@ pub fn invocation_for_print(vm: &Vm, host: Host) -> Result<Invocation> {
let smbios_memory_type = smbios_memory_type(vm, &qemu);
let smbios_error_correction = smbios_error_correction(vm, &qemu);
let smbios_memory_slots = smbios_memory_slots(vm, &qemu);
let win32_native_aio = win32_native_aio(vm, host, &qemu);
Ctx {
host,
qemu,
@@ -1106,6 +1123,7 @@ pub fn invocation_for_print(vm: &Vm, host: Host) -> Result<Invocation> {
smbios_error_correction,
smbios_memory_slots,
cpu_brand: crate::host::cpu_brand(),
win32_native_aio,
screen: crate::host::has_screen(&vm.config.extra_env),
headless: false,
graphics_rom: graphics_rom(vm).unwrap_or_else(|_| crate::prebuilt::graphics_rom_path()),
@@ -1280,22 +1298,23 @@ pub fn prepare(vm: &mut Vm, progress: &mut dyn FnMut(&str)) -> Vec<String> {
)),
}
}
// The processor About This Mac names, from this host's CPU (processor.rs): after any new
// image, which reims-util makes with OpenCore's own pick.
if vm.config.profile == Profile::Q35X86_64 {
// Keep the OpenCore image intact while resuming an incoming QEMU VM.
if vm.config.profile == Profile::Q35X86_64
&& !vm
.config
.extra_args
.iter()
.any(|arg| arg == "-incoming" || arg.starts_with("-incoming="))
{
let brand = crate::host::cpu_brand();
let value = crate::processor::processor_type(brand.as_deref(), vm.config.cpus);
match crate::opencore::match_processor_type(vm, value) {
Ok(crate::opencore::ProcessorTypeChange::Written { .. }) => {
progress(&match crate::processor::family_name(value) {
Some(family) => format!(
"its OpenCore image now names the processor {family}, this host's \
family, in About This Mac"
),
None => "its OpenCore image now leaves the processor's name in About This \
Mac to OpenCore, as this host's CPU states no family Apple names"
.to_string(),
})
if let Some(family) = crate::processor::family_name(value) {
progress(&format!(
"its OpenCore image now names the processor {family}, this host's family, in About This Mac"
));
}
}
Ok(crate::opencore::ProcessorTypeChange::Kept) => {}
Err(e) => w.push(format!(
@@ -1487,15 +1506,6 @@ const WINDOW_SHOWN: &str = "reims-vgpu: window shown: ";
/// before its reason.
const NO_WINDOW: &str = "reims-vgpu: no window: ";
/// How the library's no-window line ends where it knows the GPU the desktop is drawn on, before
/// that GPU's DRM node, `<major>:<minor>` (docs/api.md, "The window's lines").
const DESKTOP: &str = "; the desktop is drawn on DRM node ";
/// How the library's line says a display's window has not opened yet, after the display and
/// before its readings: it opens once a screen is on, or the GPU may not show a window on this
/// desktop (docs/api.md, "The window's lines").
const NOT_OPENED: &str = "'s window has not opened yet: ";
/// What [`start`] started.
#[derive(Debug)]
pub struct Started {
@@ -2044,19 +2054,7 @@ fn start_window(vm: &Vm, ctx: &Ctx, progress: &mut dyn FnMut(&str)) -> StartWind
loop {
let said = window_said(&tail(&vm.qemu_log(), usize::MAX), vm.config.display.count);
if let Some(window) = said {
return match window {
StartWindow::None(Some(why))
if why.contains(DESKTOP) || why.contains(NOT_OPENED) =>
{
StartWindow::None(Some(desktop_named(
&why,
&vm.config.name,
&crate::gpu::list(),
drm_node_gpu,
)))
}
window => window,
};
return window;
}
if Instant::now() >= until || pid(vm).is_none() {
return StartWindow::NotShown;
@@ -2069,98 +2067,6 @@ fn start_window(vm: &Vm, ctx: &Ctx, progress: &mut dyn FnMut(&str)) -> StartWind
}
}
/// A GPU as the kernel lists its DRM node: its PCI address, `0000:00:02.0`, and its PCI vendor and
/// device IDs.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct NodeGpu {
pub pci: String,
pub vendor_id: u32,
pub device_id: u32,
}
/// The GPU of DRM node `major:minor`, as `/sys/dev/char` lists it (Linux): `None` where it lists
/// none, or the node is no PCI device's.
fn drm_node_gpu(node: (u32, u32)) -> Option<NodeGpu> {
let device = Path::new("/sys/dev/char")
.join(format!("{}:{}", node.0, node.1))
.join("device");
let id = |file: &str| {
let text = std::fs::read_to_string(device.join(file)).ok()?;
u32::from_str_radix(text.trim().trim_start_matches("0x"), 16).ok()
};
Some(NodeGpu {
pci: std::fs::canonicalize(&device)
.ok()?
.file_name()?
.to_string_lossy()
.into_owned(),
vendor_id: id("vendor")?,
device_id: id("device")?,
})
}
/// `why`, the library's reason no window shows, for the user of VM `name`, where it ends naming
/// the GPU the desktop is drawn on by its DRM node ([`DESKTOP`]), or says a display's window has
/// not opened yet ([`NOT_OPENED`]): that GPU's number among `gpus`, as `reims-ctl gpus` numbers
/// them, found by `node_gpu` (its PCI address, else its IDs where one GPU of `gpus` has them), and
/// how to give it to the VM, since it can show a window on that desktop; where none of `gpus` is
/// that GPU, or none is named, how to list them and give the VM one. A window not opened yet
/// opens once a screen is on, which the start does not ask, so it is told both: that, and the GPU
/// to pick where a screen is on and the window does not open. Any other reason stays as it is.
pub fn desktop_named(
why: &str,
name: &str,
gpus: &[crate::gpu::GpuInfo],
node_gpu: impl Fn((u32, u32)) -> Option<NodeGpu>,
) -> String {
let (reason, node) = match why.split_once(DESKTOP) {
Some((reason, node)) => (reason, Some(node)),
None => (why, None),
};
let not_opened = reason.split_once(NOT_OPENED).map(|(display, _)| display);
if node.is_none() && not_opened.is_none() {
return why.to_string();
}
let node = node.and_then(|n| {
let (major, minor) = n.trim().split_once(':')?;
Some((major.parse().ok()?, minor.parse().ok()?))
});
let found = node.and_then(&node_gpu).and_then(|g| {
let by_pci = gpus
.iter()
.position(|o| o.pci.as_deref() == Some(g.pci.as_str()));
let mut by_ids = gpus
.iter()
.enumerate()
.filter(|(_, o)| (o.vendor_id, o.device_id) == (g.vendor_id, g.device_id));
by_pci.or_else(|| match (by_ids.next(), by_ids.next()) {
(Some((i, _)), None) => Some(i),
_ => None,
})
});
let list = format!(
"`reims-ctl gpus` lists the GPUs, and `reims-ctl set {name} --gpu NUMBER` gives the VM \
the one your screen is plugged into"
);
let pick = match (found, node) {
(Some(i), _) => format!(
"your desktop is drawn by GPU {n}, {gpu}, which can show the window: `reims-ctl set \
{name} --gpu {n}` gives the VM that GPU",
n = i + 1,
gpu = gpus[i].name,
),
(None, Some(_)) => format!("your desktop is drawn by another GPU: {list}"),
(None, None) => list,
};
match not_opened {
Some(display) => format!(
"{display}{NOT_OPENED}it opens once a screen is on. If a screen is on and it does not, \
{pick}"
),
None => format!("{reason}. Y{}", pick.strip_prefix('y').unwrap_or(&pick)),
}
}
/// What the library's lines in `log`, QEMU's log, say since the start's `----` of the windows of a
/// VM of `displays` displays (docs/api.md, "The window's lines"): open once any window presented
/// its first frame; none, with the reason, where no window opens at all, or once every display's
@@ -2294,82 +2200,6 @@ impl Drop for TestQemu {
mod tests {
use super::*;
/// Where the library's reason no window shows names the GPU the desktop is drawn on by its DRM
/// node, the start names that GPU by its number in `reims-ctl gpus` and says how to give it to
/// the VM: found by its PCI address, else by IDs one GPU alone has; where none of the GPUs is
/// it, it says how to list them and give the VM one. A reason without the node stays as the
/// library said it. A host whose desktop is drawn on its integrated GPU, the VM's discrete GPU
/// presenting to no window of the desktop's.
#[test]
fn a_no_window_reason_names_the_gpu_the_desktop_is_drawn_on() {
let gpu = |name: &str, ids: (u32, u32), pci: &str| -> crate::gpu::GpuInfo {
serde_json::from_value(json!({
"name": name, "vendor_id": ids.0, "device_id": ids.1, "kind": "integrated",
"driver_file": "/icd/icd.json", "pci": pci,
}))
.unwrap()
};
let gpus = [
gpu("NVIDIA GeForce RTX 2080", (0x10de, 0x1e87), "0000:67:00.0"),
gpu("AMD Radeon 780M Graphics", (0x1002, 0x1900), "0000:c5:00.0"),
];
let reason = "this GPU cannot show a window on this desktop: it presents to neither \
its Wayland compositor nor its X server";
let why = format!("{reason}; the desktop is drawn on DRM node 226:0");
let igpu = |node: (u32, u32)| {
(node == (226, 0)).then(|| NodeGpu {
pci: "0000:c5:00.0".into(),
vendor_id: 0x1002,
device_id: 0x1900,
})
};
let named = format!(
"{reason}. Your desktop is drawn by GPU 2, AMD Radeon 780M Graphics, which can show \
the window: `reims-ctl set mac --gpu 2` gives the VM that GPU"
);
assert_eq!(desktop_named(&why, "mac", &gpus, igpu), named);
let elsewhere = |node| {
igpu(node).map(|g| NodeGpu {
pci: "0000:c6:00.0".into(),
..g
})
};
assert_eq!(
desktop_named(&why, "mac", &gpus, elsewhere),
named,
"by its IDs, where its address is not listed"
);
let unlisted = format!(
"{reason}. Your desktop is drawn by another GPU: `reims-ctl gpus` lists the GPUs, and \
`reims-ctl set mac --gpu NUMBER` gives the VM the one your screen is plugged into"
);
assert_eq!(desktop_named(&why, "mac", &gpus[..1], igpu), unlisted);
assert_eq!(desktop_named(&why, "mac", &gpus, |_| None), unlisted);
assert_eq!(desktop_named(reason, "mac", &gpus, igpu), reason);
// A window not opened yet: both readings, a screen off or a GPU to pick.
let library = "display 0's window has not opened yet: it opens once a screen is on; if a \
screen is on and it does not, this GPU may not show a window on this \
desktop";
assert_eq!(
desktop_named(&format!("{library}{DESKTOP}226:0"), "mac", &gpus, igpu),
"display 0's window has not opened yet: it opens once a screen is on. If a screen is \
on and it does not, your desktop is drawn by GPU 2, AMD Radeon 780M Graphics, which \
can show the window: `reims-ctl set mac --gpu 2` gives the VM that GPU"
);
assert_eq!(
desktop_named(library, "mac", &gpus, igpu),
"display 0's window has not opened yet: it opens once a screen is on. If a screen is \
on and it does not, `reims-ctl gpus` lists the GPUs, and `reims-ctl set mac --gpu \
NUMBER` gives the VM the one your screen is plugged into"
);
let head = "reims-ctl 0.1.0 started t at now\nqemu-system-x86_64 -display none\n----\n";
assert_eq!(
window_said(&format!("{head}reims-vgpu: no window: {why}\n"), 1),
Some(StartWindow::None(Some(why.clone()))),
"the library's line, its node and all"
);
}
/// The window shows once the library's line says a window presented its first frame, since
/// the start's `----`; none shows where no window opens at all, with the library's reason, or
/// once every display's window stays empty; until then nothing is said yet. A line of an
+7 -67
View File
@@ -2353,8 +2353,6 @@ impl App {
fields.extend([
Field::text("resolution", "Resolution", "1920x1080", RESOLUTION_HELP)
.show_if("graphics", LIBRARY),
Field::text("refresh_rate", "Refresh rate", "auto", REFRESH_RATE_HELP)
.show_if("graphics", LIBRARY),
Field::toggle(
"logs",
"Logs",
@@ -2400,8 +2398,7 @@ impl App {
self.overlay = Some(Overlay::Form(FormKind::Edit(c.name.clone()), form));
return;
}
// The displays', the resolution's, borderless's, the refresh rate's and the GPU's fields
// are reims-vgpu's.
// The displays', the resolution's, borderless's and the GPU's fields are reims-vgpu's.
fields.push(graphics_field(c.graphics()));
fields.extend([
displays_field(c.display.count).show_if("graphics", LIBRARY),
@@ -2419,13 +2416,6 @@ impl App {
"Windows without borders that fill their screens, one for each display.",
)
.show_if("graphics", LIBRARY),
Field::text(
"refresh_rate",
"Refresh rate",
&refresh_rate_named(c.display.refresh_rate),
REFRESH_RATE_HELP,
)
.show_if("graphics", LIBRARY),
]);
if c.profile.gpu_choice(self.host) {
fields.push(self.gpu_field(&c.gpu).show_if("graphics", LIBRARY));
@@ -2736,9 +2726,6 @@ impl App {
if f.is_shown("resolution") {
s.display.resolution = f.text("resolution");
}
if f.is_shown("refresh_rate") {
s.display.refresh_rate = crate::vm::parse_refresh_rate(&f.text("refresh_rate"))?;
}
s.display.check()?;
// The arm64 form has neither: its VM takes the defaults.
if f.is_shown("logs") {
@@ -3244,17 +3231,6 @@ const RESOLUTION_HELP: &str = "The size each window opens at, WIDTHxHEIGHT in th
is at least 3840 pixels wide. On a headless start (reims-ctl start NAME --headless) it is \
each display's mode.";
const REFRESH_RATE_HELP: &str = "The one refresh rate, in Hz, such as 60 or 59.94, that each \
display offers the guest every size at, titled or borderless; auto, the rate of the screen a \
titled window opens on, and the rates of the screen a borderless window fills. A rate above \
the screen's is lowered to the screen's, which the VM's logs/qemu.log says. On a headless \
start (reims-ctl start NAME --headless) it is 60 Hz.";
/// A VM's refresh rate as its edit form shows it: its hertz, or auto where it has none.
fn refresh_rate_named(rate: Option<f64>) -> String {
rate.map_or_else(|| "auto".into(), |hz| hz.to_string())
}
/// The choice of a VM's displays on reims-vgpu, at `current`.
fn displays_field(current: u32) -> Field {
let options = (1..=crate::vm::DISPLAYS_MAX)
@@ -3383,7 +3359,7 @@ fn apply_edit(vm: &mut Vm, f: &Form, gpus: Option<&[GpuInfo]>) -> Result<()> {
q.disk_controller = DiskController::parse(&f.choice("disk_controller"))?;
}
// Hidden on VMware SVGA, which has one display, the displays, the resolution, the windows'
// first size, borderless and the refresh rate stay as they were.
// first size, and borderless stay as they were.
if f.is_shown("displays") {
c.display.count = f.choice("displays").parse().context("displays: a number")?;
}
@@ -3394,9 +3370,6 @@ fn apply_edit(vm: &mut Vm, f: &Form, gpus: Option<&[GpuInfo]>) -> Result<()> {
if f.is_shown("borderless") {
c.display.borderless = f.toggle("borderless");
}
if f.is_shown("refresh_rate") {
c.display.refresh_rate = crate::vm::parse_refresh_rate(&f.text("refresh_rate"))?;
}
if f.is_shown("gpu") {
let id = f.choice("gpu");
if id != gpu_id(&c.gpu) {
@@ -3604,15 +3577,15 @@ of its own. A VM runs reims-vgpu's own GPU device unless its settings choose ano
says so): free space on that disk first; its guest carries on from where it
stopped
K kill it: power it off at once
e edit its settings: CPUs, memory, displays, resolution, borderless, refresh
rate, GPU, audio, network, logs, extra QEMU arguments (they apply at its next
start), its disk controller (SATA, NVMe or virtio), its installer image, its
boot selection (OpenCore's picker, which makes it a new OpenCore image) and
e edit its settings: CPUs, memory, displays, resolution, borderless, GPU,
audio, network, logs, extra QEMU arguments (they apply at its next start), its
disk controller (SATA, NVMe or virtio), its installer image, its boot selection
(OpenCore's picker, which makes it a new OpenCore image) and
graphics: reims-vgpu, its own GPU device, on one to four displays, each in a
window whose size the guest follows, with the macOS drivers reims-ctl puts in
its OpenCore image (made again on a change); or QEMU's VMware SVGA, one display
with no GPU acceleration, in QEMU's own window. Displays, resolution,
borderless, refresh rate and GPU are reims-vgpu's
borderless and GPU are reims-vgpu's
p give it this host's USB devices: Space gives the selected one to
the guest or takes it back, at once while the VM runs; a device you gave it
joins the guest when it is plugged in. More in reims-ctl usb --help
@@ -5104,36 +5077,6 @@ mod tests {
assert_eq!(form(&app).choice("disk_controller"), "ahci");
}
/// A VM's edit form shows its refresh rate, auto where it has none, and saves what is typed
/// there: a number of hertz, or auto for none; 0 is refused with the rate's own message.
#[test]
fn the_edit_form_takes_a_refresh_rate() {
let mut row = vm_row("t");
let c = &mut row.vm.as_mut().unwrap().config;
c.graphics = None;
c.display.refresh_rate = Some(59.94);
let mut app = test_app(vec![row]);
app.open_edit();
assert_eq!(form(&app).text("refresh_rate"), "59.94");
let mut vm = app.rows[0].vm.as_ref().unwrap().clone();
apply_edit(&mut vm, form(&app), None).unwrap();
assert_eq!(vm.config.display.refresh_rate, Some(59.94));
let mut typed = |rate: &str| {
let Some(Overlay::Form(_, f)) = &mut app.overlay else {
unreachable!()
};
let field = (f.fields.iter_mut()).find(|f| f.key == "refresh_rate");
if let Some(form::Value::Text { text, .. }) = field.map(|f| &mut f.value) {
*text = rate.into();
}
apply_edit(&mut vm, form(&app), None).map(|()| vm.config.display.refresh_rate)
};
assert_eq!(typed("120").unwrap(), Some(120.0));
assert_eq!(typed("auto").unwrap(), None);
let e = typed("0").unwrap_err().to_string();
assert!(e.contains("a refresh rate is 1 to 1000 Hz, not 0"), "{e}");
}
/// A VM's edit form shows the resolution and borderless on reims-vgpu, and hides them on
/// VMware SVGA, whose settings keep them as they were.
#[test]
@@ -5146,12 +5089,9 @@ mod tests {
app.open_edit();
assert_eq!(form(&app).choice("graphics"), "reims-vgpu");
assert!(form(&app).is_shown("borderless") && form(&app).is_shown("resolution"));
assert!(form(&app).is_shown("refresh_rate"));
assert_eq!(form(&app).text("refresh_rate"), "auto");
let mut vm = app.rows[0].vm.as_ref().unwrap().clone();
apply_edit(&mut vm, form(&app), None).unwrap();
assert_eq!(vm.config.graphics, Some(Graphics::ReimsVgpu));
assert_eq!(vm.config.display.refresh_rate, None, "auto keeps none");
for _ in 0..form(&app).fields.len() {
if form(&app).focused_key() == "graphics" {
break;
+82 -97
View File
@@ -244,17 +244,83 @@ impl DiskController {
}
}
/// Host cache policy for an x86-64 VM's system disk.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum DiskCache {
/// QEMU's default (`writeback` with flushes forwarded to the host, except
/// during installation when `cache.no-flush=on` is added automatically).
#[default]
Default,
/// Host page cache enabled (`cache.direct=off`), guest flushes forwarded.
Writeback,
/// Bypass host page cache (`cache.direct=on`), guest flushes forwarded.
None,
/// Host page cache enabled and guest flushes ignored (`cache.direct=off,cache.no-flush=on`).
Unsafe,
}
impl DiskCache {
pub const ALL: [DiskCache; 4] = [
DiskCache::Default,
DiskCache::Writeback,
DiskCache::None,
DiskCache::Unsafe,
];
pub fn id(self) -> &'static str {
match self {
DiskCache::Default => "default",
DiskCache::Writeback => "writeback",
DiskCache::None => "none",
DiskCache::Unsafe => "unsafe",
}
}
pub fn parse(s: &str) -> Result<DiskCache> {
let low = s.trim().to_ascii_lowercase();
DiskCache::ALL
.into_iter()
.find(|c| c.id() == low)
.with_context(|| format!("disk cache is default, writeback, none or unsafe, not {s:?}"))
}
pub fn is_default(&self) -> bool {
*self == DiskCache::Default
}
}
/// Reports whether `path` is a Windows raw physical disk or volume/partition
/// device path (`\\.\PhysicalDriveN`, `\\.\HarddiskVolumeN`,
/// `\\.\HarddiskNPartitionM`, `\\.\Volume{...}`, or `\\?\Volume{...}`),
/// excluding extended-length regular file paths like `\\?\D:\...`.
pub fn is_windows_raw_device(path: &Path) -> bool {
let norm = path.to_string_lossy().replace('/', "\\");
let rest = if let Some(r) = norm.strip_prefix(r"\\.\") {
r
} else if let Some(r) = norm.strip_prefix(r"\\?\") {
let low = r.to_ascii_lowercase();
return low.starts_with("volume{");
} else {
return false;
};
let low = rest.to_ascii_lowercase();
low.starts_with("physicaldrive")
|| low.starts_with("harddiskvolume")
|| low.starts_with("harddisk")
|| low.starts_with("volume{")
}
/// reims-vgpu's displays, one by default and up to [`DISPLAYS_MAX`], each in a window of its own:
/// each window opens at its display's size of the resolution ([`Display::window_sizes`]) and keeps
/// the size the person gives it, which its display follows, at the refresh rate of the host
/// screen it is on, or at the VM's own refresh rate ([`Display::refresh_rate`]). The guest starts
/// a HiDPI desktop by itself on a display whose window is at least 3840 pixels wide, and offers one
/// in its Displays settings from 2880 (the kext's HiDPI modes, whose pixels halve exactly: the
/// guest is offered the window's pixels, the width rounded down to a multiple of 16 and the height
/// to even). The count an older reims-ctl saved for apple-gfx's displays comes back as
/// reims-vgpu's ([`saved_display_count`]); its HiDPI and refresh rate are read past, and left out
/// of the next save, as is the `capture` an older reims-ctl saved, a setting the windows no longer
/// have.
/// screen it is on. The guest starts a HiDPI desktop by itself on a display whose window is at
/// least 3840 pixels wide, and offers one in its Displays settings from 2880 (the kext's HiDPI
/// modes, whose pixels halve exactly: the guest is offered the window's pixels, the width rounded
/// down to a multiple of 16 and the height to even). The count an older reims-ctl saved for
/// apple-gfx's displays comes back as reims-vgpu's ([`saved_display_count`]); its HiDPI and
/// refresh rate are read past, and left out of the next save, as is the `capture` an older
/// reims-ctl saved, a setting the windows no longer have.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct Display {
@@ -270,22 +336,8 @@ pub struct Display {
pub resolution: String,
/// Borderless windows that fill their screens: every display's.
pub borderless: bool,
/// The one refresh rate, in hertz, 1 to [`REFRESH_RATE_MAX_HZ`], that every display offers
/// the guest each of its sizes at, titled or borderless, and no other; at most the rate of
/// the host screen its window is on, which a higher one is lowered to (the library's
/// `REIMS_VGPU_WINDOW_REFRESH_RATE`). None, the default, which is not saved: a titled
/// window's display offers the rate of the screen it opened on, and a borderless one's the
/// rates of the screen it fills. Its key is `refresh_rate`, a key of its own: the `refresh`
/// an older reims-ctl saved for apple-gfx is retired ([`RETIRED`]), read past and left out
/// of the next save, and never sets it.
#[serde(skip_serializing_if = "Option::is_none")]
pub refresh_rate: Option<f64>,
}
/// The highest refresh rate a VM's displays take, in hertz ([`Display::refresh_rate`]), the
/// library's own top for `REIMS_VGPU_WINDOW_REFRESH_RATE`.
pub const REFRESH_RATE_MAX_HZ: f64 = 1000.0;
/// The most displays reims-vgpu's device takes (the device's `RGFX_DISPLAYS_MAX`, QEMU's
/// `displays` property's top).
pub const DISPLAYS_MAX: u32 = 4;
@@ -309,7 +361,6 @@ impl Default for Display {
count: 1,
resolution: "1920x1080".into(),
borderless: false,
refresh_rate: None,
}
}
}
@@ -379,36 +430,10 @@ impl Display {
if !(1..=DISPLAYS_MAX).contains(&self.count) {
bail!("a VM has 1 to {DISPLAYS_MAX} displays, not {}", self.count);
}
if let Some(hz) = self.refresh_rate {
check_refresh_rate(hz)?;
}
self.window_sizes().map(|_| ())
}
}
/// A refresh rate as `--refresh-rate` and the interface take it: a number of hertz, 1 to
/// [`REFRESH_RATE_MAX_HZ`], such as 60 or 59.94; or `auto`, none ([`Display::refresh_rate`]).
pub fn parse_refresh_rate(s: &str) -> Result<Option<f64>> {
let s = s.trim();
if s.eq_ignore_ascii_case("auto") {
return Ok(None);
}
let hz: f64 = s.parse().ok().with_context(|| {
format!("a refresh rate is a number of hertz, such as 60 or 59.94, or auto, not {s:?}")
})?;
check_refresh_rate(hz)?;
Ok(Some(hz))
}
/// An error for a refresh rate a VM does not take: 0, a negative one, one above
/// [`REFRESH_RATE_MAX_HZ`], or no number at all (NaN or an infinity).
fn check_refresh_rate(hz: f64) -> Result<()> {
if !(1.0..=REFRESH_RATE_MAX_HZ).contains(&hz) {
bail!("a refresh rate is 1 to {REFRESH_RATE_MAX_HZ} Hz, not {hz}");
}
Ok(())
}
pub fn parse_resolution(s: &str) -> Result<(u32, u32)> {
let (w, h) = s
.split_once(['x', 'X'])
@@ -600,6 +625,9 @@ pub struct Q35 {
/// installer may boot instead.
#[serde(default, skip_serializing_if = "DiskController::is_ahci")]
pub disk_controller: DiskController,
/// Host I/O cache mode for the system disk.
#[serde(default, skip_serializing_if = "DiskCache::is_default")]
pub disk_cache: DiskCache,
/// The system disk's AHCI port, on [`DiskController::Ahci`]: 3, after OpenCore's 2.
#[serde(default = "default_disk_port")]
pub disk_port: u32,
@@ -1033,6 +1061,10 @@ impl Vm {
}
pub fn disk(&self) -> PathBuf {
if is_windows_raw_device(&self.config.disk) {
let s = self.config.disk.to_string_lossy().replace('/', "\\");
return PathBuf::from(s.trim_end_matches('\\'));
}
self.path(&self.config.disk)
}
@@ -1453,6 +1485,7 @@ pub(crate) mod tests {
cpu_model: default_cpu_model(),
cpu_flags: default_cpu_flags(),
disk_controller: DiskController::Nvme,
disk_cache: DiskCache::Default,
disk_port: 3,
}),
vmapple: None,
@@ -1677,7 +1710,6 @@ pub(crate) mod tests {
let mut want = c.clone();
want.display.count = count;
assert_eq!(loaded, want, "{saved}");
assert_eq!(loaded.display.refresh_rate, None, "refresh sets no rate");
assert!(loaded.check().is_ok(), "{saved}");
let saved_again = toml::to_string_pretty(&loaded).unwrap();
if count == 1 {
@@ -1691,53 +1723,6 @@ pub(crate) mod tests {
}
}
/// A VM's refresh rate is a number of hertz, 1 to 1000, or auto, none; 0, a negative rate, one
/// above 1000 and what is no number are refused with a plain message, at set and at save.
/// It is saved as `refresh_rate`, and comes back as it was, a whole number written by hand
/// too; none is not saved. apple-gfx's retired `refresh` never sets it
/// ([`apple_gfx_s_settings_are_read_past`]).
#[test]
fn a_refresh_rate_is_a_number_of_hertz() {
assert_eq!(parse_refresh_rate("60").unwrap(), Some(60.0));
assert_eq!(parse_refresh_rate(" 59.94 ").unwrap(), Some(59.94));
assert_eq!(parse_refresh_rate("1").unwrap(), Some(1.0));
assert_eq!(parse_refresh_rate("1000").unwrap(), Some(1000.0));
assert_eq!(parse_refresh_rate("auto").unwrap(), None);
assert_eq!(parse_refresh_rate("Auto").unwrap(), None);
for (bad, says) in [
("0", "a refresh rate is 1 to 1000 Hz, not 0"),
("-60", "not -60"),
("0.5", "not 0.5"),
("1000.5", "not 1000.5"),
("NaN", "not NaN"),
("inf", "not inf"),
(
"60Hz",
"a number of hertz, such as 60 or 59.94, or auto, not \"60Hz\"",
),
("", "a number of hertz"),
("fast", "a number of hertz"),
] {
let e = parse_refresh_rate(bad).unwrap_err().to_string();
assert!(e.contains(says), "{bad:?}: {e}");
}
let mut c = x86_64_config();
let text = toml::to_string_pretty(&c).unwrap();
assert!(!text.contains("refresh"), "none is not saved: {text}");
c.display.refresh_rate = Some(120.0);
assert!(c.check().is_ok());
let saved = toml::to_string_pretty(&c).unwrap();
assert!(saved.contains("refresh_rate = 120.0\n"), "{saved}");
assert_eq!(toml::from_str::<VmConfig>(&saved).unwrap(), c);
let whole = saved.replace("refresh_rate = 120.0\n", "refresh_rate = 120\n");
assert_eq!(toml::from_str::<VmConfig>(&whole).unwrap(), c);
for bad in [0.0, -60.0, 1001.0, f64::NAN] {
c.display.refresh_rate = Some(bad);
let e = c.check().unwrap_err().to_string();
assert!(e.contains("a refresh rate is 1 to 1000 Hz"), "{bad}: {e}");
}
}
/// A save keeps what a newer reims-ctl wrote into a VM's settings, as an interface open since
/// before an update, or an older build a switch of channel installed, saves them. A key of the
/// newer build's own, one in a table this build has, and a table of its own stay as written,
+39
View File
@@ -1019,6 +1019,45 @@ RvgStatus rvg_graphics_device_read_display_at(RvgGraphicsDevice *device,
RvgDisplayCoord rvg_graphics_device_cursor_position_at(const RvgGraphicsDevice *device,
uint32_t display);
// Quiesces the graphics device prior to VM RAM & state snapshotting: pauses VBLANK/rings,
// drains pending compiles/workers, flushes dirty device-cached IOSurfaces back to Guest RAM,
// and waits for GPU idle.
//
// # Safety
// `device` is a live graphics device handle.
RvgStatus rvg_graphics_device_quiesce(RvgGraphicsDevice *device);
// Resumes VBLANK and ring threads after a snapshot finishes or fails.
//
// # Safety
// `device` is a live graphics device handle.
RvgStatus rvg_graphics_device_unquiesce(RvgGraphicsDevice *device);
// Serializes the full graphics device state into a heap-allocated buffer owned by the caller
// and released with [`rvg_graphics_snapshot_free`].
//
// # Safety
// `device` is a live graphics device handle; `out_data` and `out_len` are valid non-null pointers.
RvgStatus rvg_graphics_device_snapshot_save(RvgGraphicsDevice *device,
uint8_t **out_data,
size_t *out_len);
// Frees a snapshot buffer returned by [`rvg_graphics_device_snapshot_save`].
//
// # Safety
// `data` and `len` must come from a single [`rvg_graphics_device_snapshot_save`] call and not
// be freed more than once.
void rvg_graphics_snapshot_free(uint8_t *data, size_t len);
// Restores the full graphics device state from a snapshot buffer produced by
// [`rvg_graphics_device_snapshot_save`].
//
// # Safety
// `device` is a live graphics device handle; `data` points to `len` readable bytes.
RvgStatus rvg_graphics_device_snapshot_load(RvgGraphicsDevice *device,
const uint8_t *data,
size_t len);
#ifdef __cplusplus
} // extern "C"
#endif // __cplusplus
+116
View File
@@ -1258,5 +1258,121 @@ pub unsafe extern "C" fn rvg_graphics_device_cursor_position_at(
})
}
/// Quiesces the graphics device prior to VM RAM & state snapshotting: pauses VBLANK/rings,
/// drains pending compiles/workers, flushes dirty device-cached IOSurfaces back to Guest RAM,
/// and waits for GPU idle.
///
/// # Safety
/// `device` is a live graphics device handle.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn rvg_graphics_device_quiesce(device: *mut RvgGraphicsDevice) -> RvgStatus {
ffi::export(|| {
// SAFETY: the caller's contract.
let d = unsafe { live(device, "rvg_graphics_device_quiesce") };
match d.device.quiesce() {
Ok(()) => RVG_OK,
Err(e) => status(e),
}
})
}
/// Resumes VBLANK and ring threads after a snapshot finishes or fails.
///
/// # Safety
/// `device` is a live graphics device handle.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn rvg_graphics_device_unquiesce(
device: *mut RvgGraphicsDevice,
) -> RvgStatus {
ffi::export(|| {
// SAFETY: the caller's contract.
let d = unsafe { live(device, "rvg_graphics_device_unquiesce") };
d.device.unquiesce();
RVG_OK
})
}
/// Serializes the full graphics device state into a heap-allocated buffer owned by the caller
/// and released with [`rvg_graphics_snapshot_free`].
///
/// # Safety
/// `device` is a live graphics device handle; `out_data` and `out_len` are valid non-null pointers.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn rvg_graphics_device_snapshot_save(
device: *mut RvgGraphicsDevice,
out_data: *mut *mut u8,
out_len: *mut usize,
) -> RvgStatus {
ffi::export(|| {
if out_data.is_null() || out_len.is_null() {
return RVG_ERR_INVALID_ARGUMENT;
}
// SAFETY: the caller's contract.
let d = unsafe { live(device, "rvg_graphics_device_snapshot_save") };
match d.device.snapshot_save() {
Ok(bytes) => {
let mut boxed = bytes.into_boxed_slice();
let len = boxed.len();
let ptr = boxed.as_mut_ptr();
std::mem::forget(boxed);
// SAFETY: non-null checked above.
unsafe {
*out_data = ptr;
*out_len = len;
}
RVG_OK
}
Err(e) => status(e),
}
})
}
/// Frees a snapshot buffer returned by [`rvg_graphics_device_snapshot_save`].
///
/// # Safety
/// `data` and `len` must come from a single [`rvg_graphics_device_snapshot_save`] call and not
/// be freed more than once.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn rvg_graphics_snapshot_free(data: *mut u8, len: usize) {
ffi::export(|| {
if !data.is_null() {
// SAFETY: matches Box::<[u8]>::into_raw layout above.
unsafe {
let _ = Box::from_raw(std::ptr::slice_from_raw_parts_mut(data, len));
}
}
})
}
/// Restores the full graphics device state from a snapshot buffer produced by
/// [`rvg_graphics_device_snapshot_save`].
///
/// # Safety
/// `device` is a live graphics device handle; `data` points to `len` readable bytes.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn rvg_graphics_device_snapshot_load(
device: *mut RvgGraphicsDevice,
data: *const u8,
len: usize,
) -> RvgStatus {
ffi::export(|| {
if data.is_null() && len > 0 {
return RVG_ERR_INVALID_ARGUMENT;
}
// SAFETY: the caller's contract.
let d = unsafe { live(device, "rvg_graphics_device_snapshot_load") };
let slice = if len == 0 {
&[]
} else {
// SAFETY: caller's contract.
unsafe { std::slice::from_raw_parts(data, len) }
};
match d.device.snapshot_load(slice) {
Ok(()) => RVG_OK,
Err(e) => status(e),
}
})
}
#[cfg(test)]
mod tests;
+1 -1
View File
@@ -42,7 +42,7 @@ pub use status::RvgStatus;
/// The library's allocator on the targets that ship, x86-64 Linux and arm64 macOS: jemalloc, for
/// every Rust allocation in the library, metal2vulkan's runtime's among them. A command queue's
/// threads allocate memory that the runtime's threads free, and glibc's allocator refills its
/// arena for each such block on the allocating thread (measured on an Iris Xe with jemalloc
/// arena for each such block on the allocating thread (measured on ms01's Iris Xe with jemalloc
/// preloaded into all of QEMU: a drag at 36 frames/s under glibc, 42 under jemalloc). Its
/// symbols are prefixed (`_rjem_`), so the host's C code and the drivers keep the system's
/// `malloc`, and no block crosses between the two: the host is handed no block.
+5
View File
@@ -241,6 +241,11 @@ static void check_graphics(void) {
CHECK(wait_for(&graphics_moved, 2));
at = rvg_graphics_device_cursor_position(d);
CHECK(at.x == 0 && at.y == 0);
CHECK_STATUS(rvg_graphics_device_quiesce(d), RVG_OK);
CHECK_STATUS(rvg_graphics_device_snapshot_save(d, NULL, NULL), RVG_ERR_INVALID_ARGUMENT);
CHECK_STATUS(rvg_graphics_device_snapshot_load(d, NULL, 1), RVG_ERR_INVALID_ARGUMENT);
rvg_graphics_snapshot_free(NULL, 0);
CHECK_STATUS(rvg_graphics_device_unquiesce(d), RVG_OK);
rvg_graphics_device_release(d);
#if defined(_WIN32)
CloseHandle(bell);
+1 -1
View File
@@ -242,7 +242,7 @@ fn c_harness_calls_every_function() {
// A function with a form of each OS's (Windows's under `#if defined(_WIN32)`, the others'
// under `#if !defined(_WIN32)`) is declared once per form, one after the other.
declared.dedup();
assert_eq!(declared.len(), 19, "{declared:?}");
assert_eq!(declared.len(), 24, "{declared:?}");
let missing: Vec<&str> = declared
.iter()
.copied()
-1
View File
@@ -328,7 +328,6 @@ include = [
"RgfxScrollDevices",
"RgfxSetCursor",
"RgfxSetDisplayPower",
"RgfxSetDisplayRate",
"RgfxSetScanout",
"RgfxSetVblank",
"RgfxSharedEventCreate",
@@ -1031,18 +1031,6 @@
// limit (VideoToolbox's `DataRateLimits`), not the rate control's peak alone.
#define RGFX_VIDEO_ENCODE_HARD_LIMIT (1 << 0)
// [`RgfxVideoEncodeSettings::flags`]: the guest sends frames in the order it codes them, each
// at its own `frame_index`, its place in display order, which may come before the place of a
// frame sent ahead of it: one frame ahead at most, as a B picture's encoder sends its reference
// before it. The host codes each frame as it comes, at its place: a reference where the place
// is past every place since the last keyframe, and a picture no other predicts from where it
// is not; and its SPS says that one frame may come out of display order. Without it, each
// frame's place is past the last one's. Taken from a host whose
// [`RgfxVideoEncodeCaps::flags`](crate::wire::RgfxVideoEncodeCaps) has
// [`RGFX_VIDEO_ENCODE_CAP_REORDERED`](crate::wire::RGFX_VIDEO_ENCODE_CAP_REORDERED) for the
// codec.
#define RGFX_VIDEO_ENCODE_REORDERED (1 << 1)
// [`RgfxVideoEncodeSettings::entropy`]: H.264's CAVLC.
#define RGFX_VIDEO_ENTROPY_CAVLC 1
@@ -1859,12 +1847,11 @@
#define RGFX_REG_GUEST_BUNDLE 84
// `FEATURES_EXT`, RO: feature bits 64 to 95 the host offers. The guest uses each with no take,
// but those [`RGFX_REG_DRIVER_FEATURES_EXT`] takes ([`RGFX_FEATURE_EXT_SURFACE_HOLD`],
// [`RGFX_FEATURE_EXT_DISPLAY_RATE`]): a guest that sees one of the others may send the messages
// it names, and the host carries out nothing else for a guest that does, so a guest that never
// reads it gets the wire it had before. It reads [`RGFX_FEATURE_EXT_SHARED_TEXTURE_NAMES`],
// [`RGFX_FEATURE_EXT_SURFACE_HOLD`] and [`RGFX_FEATURE_EXT_DISPLAY_RATE`] where the host offers
// them; 0 from a host older than it, as at any offset a host does not know. A write
// but those [`RGFX_REG_DRIVER_FEATURES_EXT`] takes ([`RGFX_FEATURE_EXT_SURFACE_HOLD`]): a guest
// that sees one of the others may send the messages it names, and the host carries out nothing
// else for a guest that does, so a guest that never reads it gets the wire it had before. It
// reads [`RGFX_FEATURE_EXT_SHARED_TEXTURE_NAMES`] and [`RGFX_FEATURE_EXT_SURFACE_HOLD`] where the
// host offers them; 0 from a host older than it, as at any offset a host does not know. A write
// is ignored. Bit 1 is offered by no host: hosts built before the hold word left the block's
// header offered `SURFACE_HOLD` there, with the word in the header, and kexts built before it
// take it; a write of it takes nothing, so such a kext and this host, or this kext and such a
@@ -1872,8 +1859,7 @@
#define RGFX_REG_FEATURES_EXT 88
// `DRIVER_FEATURES_EXT`, RW: the feature bits 64 to 95 the guest's driver took of those
// `FEATURES_EXT` offers that are taken ([`RGFX_FEATURE_EXT_SURFACE_HOLD`],
// [`RGFX_FEATURE_EXT_DISPLAY_RATE`]). A write takes the
// `FEATURES_EXT` offers that are taken ([`RGFX_FEATURE_EXT_SURFACE_HOLD`]). A write takes the
// bits written that `FEATURES_EXT` offers and that are taken, and a read answers the bits taken.
// As at `DRIVER_FEATURES_LO`, a write while `STATUS` reads [`RGFX_STATUS_DRIVER_READY`] is
// ignored, and a reset clears it. A guest that never writes it (the option ROM, a kext built
@@ -1936,24 +1922,6 @@
// waits ([`RGFX_FEATURE_EXT_SURFACE_HOLD`]), which the host counts.
#define RGFX_SURFACE_HOLD_WAITED (1 << 1)
// `FEATURES_EXT` bit 3, feature bit 67, `DISPLAY_RATE`, taken in
// [`RGFX_REG_DRIVER_FEATURES_EXT`]. Where the guest took it:
// - **Other rates.** A display whose host screen lists other refresh rates at its size (a
// borderless window's screen) offers its sizes again at those below the screen's own, after
// its modes at the screen's rate, each more than 0.5 Hz from the screen's rate and from the
// others (`display::offered_modes`), and tells the guest with `DISPLAY_CHANGED` when they
// change, as for a change of its size.
// - **The rate set.** Ring 0 carries [`RGFX_CMD_SET_DISPLAY_RATE`], the rate of the mode the
// guest set, which it sends after each `SET_SCANOUT` of a mode. The host paces the display's
// refreshes at that rate, its `VBLANK`s and the presents it answers at them among them, while
// the display offers a mode at that rate, and at its first mode's rate otherwise, at once
// when the display stops offering it.
//
// A guest that does not take it is offered each size at the first mode's rate alone, and its
// display runs at that rate, as before. Every host offers it; the x86-64 and arm64e kexts take
// it.
#define RGFX_FEATURE_EXT_DISPLAY_RATE (1 << 3)
// A [`RGFX_REG_GUEST_BUNDLE`] value's bundle field: the kext's own version's bundle is on disk,
// and the accelerator registered for it.
#define RGFX_GUEST_BUNDLE_OURS 1
@@ -2214,10 +2182,6 @@
// [`RGFX_FEATURE_POINTER_MOTION`]: not answered.
#define RGFX_CMD_HIDDEN_PLACES 12
// Command `SET_DISPLAY_RATE` ([`RgfxSetDisplayRate`]), where the guest took
// [`RGFX_FEATURE_EXT_DISPLAY_RATE`]: answered by [`RGFX_EVT_COMPLETE`].
#define RGFX_CMD_SET_DISPLAY_RATE 13
// Event `COMPLETE` ([`RgfxComplete`]): a command's answer, with its `seqno`.
#define RGFX_EVT_COMPLETE 256
@@ -3692,10 +3656,6 @@
// no B pictures.
#define RGFX_VIDEO_ENCODE_CAP_IN_PLACE (1 << 0)
// [`RgfxVideoEncodeCaps::flags`]: the host takes frames in the order the guest codes them
// ([`RGFX_VIDEO_ENCODE_REORDERED`](crate::ops::video::RGFX_VIDEO_ENCODE_REORDERED)).
#define RGFX_VIDEO_ENCODE_CAP_REORDERED (1 << 1)
// A pipeline reflection reply's status: the pipeline was created.
#define RGFX_PIPELINE_OK 0
@@ -8388,20 +8348,6 @@ typedef struct {
uint32_t on;
} RgfxSetDisplayPower;
// `SET_DISPLAY_RATE`: the mode the guest set on display `display` runs at `refresh_mhz`
// thousandths of a hertz, a rate of a mode the display offered it
// ([`RGFX_FEATURE_EXT_DISPLAY_RATE`]). The guest sends it after each `SET_SCANOUT` of a mode.
// The host paces the display's refreshes at that rate while the display offers a mode at it, and
// at its first mode's rate otherwise; a reset forgets it.
typedef struct {
// [`RGFX_CMD_SET_DISPLAY_RATE`].
RgfxMsgHeader header;
// The display's id.
uint32_t display;
// The rate of the mode set, in thousandths of a hertz.
uint32_t refresh_mhz;
} RgfxSetDisplayRate;
// `SET_SCANOUT`: the display shows `height` rows of `width` BGRA8 pixels, each row `stride`
// bytes after the one before, from `offset` in the region. A `width` of 0 blanks the display.
typedef struct {
@@ -8989,8 +8935,8 @@ typedef struct {
// The most consecutive B pictures an encode takes
// ([`RgfxVideoEncodeSettings::b_frames`](crate::ops::video::RgfxVideoEncodeSettings)).
uint32_t max_b_frames;
// `RGFX_VIDEO_ENCODE_CAP_*`: [`RGFX_VIDEO_ENCODE_CAP_IN_PLACE`],
// [`RGFX_VIDEO_ENCODE_CAP_REORDERED`]. Zero from a host older than these.
// `RGFX_VIDEO_ENCODE_CAP_*`: [`RGFX_VIDEO_ENCODE_CAP_IN_PLACE`]. Zero from a host older
// than these.
uint32_t flags;
// Zero.
uint32_t reserved_0c;
@@ -9058,10 +9004,9 @@ typedef struct {
} RgfxVideoEncodeResult;
// An encode session's settings, after an [`RgfxVideoOpEncode`] whose `settings_size` says so.
// A change of the size, format, profile, level, entropy, B-frames, keyframe interval, colour or
// [`RGFX_VIDEO_ENCODE_REORDERED`] starts a new sequence: the next access unit is a keyframe with
// its parameter sets. The bitrates, QPs, quality and frame rate apply from the next frame, with
// no keyframe.
// A change of the size, format, profile, level, entropy, B-frames, keyframe interval or colour
// starts a new sequence: the next access unit is a keyframe with its parameter sets. The
// bitrates, QPs, quality and frame rate apply from the next frame, with no keyframe.
typedef struct {
// The coded picture's width, the sources' size: even.
uint32_t width;
@@ -9108,8 +9053,7 @@ typedef struct {
// The speed and quality trade, 0 the fastest to 100 the best, which the host maps onto its
// API's presets.
uint32_t quality;
// `RGFX_VIDEO_ENCODE_*` settings bits: [`RGFX_VIDEO_ENCODE_HARD_LIMIT`],
// [`RGFX_VIDEO_ENCODE_REORDERED`].
// `RGFX_VIDEO_ENCODE_*` settings bits: [`RGFX_VIDEO_ENCODE_HARD_LIMIT`].
uint32_t flags;
// The VUI's `colour_primaries` (ITU-T H.273), in the SPS the host packs.
uint8_t color_primaries;
@@ -320,7 +320,6 @@ RGFX_WIRE_SIZE(RgfxScroll, 32)
RGFX_WIRE_SIZE(RgfxScrollDevices, 24)
RGFX_WIRE_SIZE(RgfxSetCursor, 48)
RGFX_WIRE_SIZE(RgfxSetDisplayPower, 24)
RGFX_WIRE_SIZE(RgfxSetDisplayRate, 24)
RGFX_WIRE_SIZE(RgfxSetScanout, 40)
RGFX_WIRE_SIZE(RgfxSetVblank, 24)
RGFX_WIRE_SIZE(RgfxSharedEventCreate, 32)
@@ -18,7 +18,7 @@
//! **A paired read, fresh at each conversion** (`pair.rs`): the platform's clock, the device's,
//! and the platform's again, back to back, `TRIES` times, and the pair whose two platform reads
//! lie closest (its bracket) places the times, within half the bracket of the clocks' offset.
//! **Measured** 2026-11-18 on a Ryzen 7 8745H (CachyOS, Linux 7.3.3, the vDSO's
//! **Measured** 2026-11-18 on homelab-um870-1 (Ryzen 7 8745H, CachyOS, Linux 7.3.3, the vDSO's
//! clocks), three runs of 100 000 pairs (`pair.rs`'s `the_bracket_of_a_pair_on_this_host`): the
//! least bracket of three tries was 40 ns at the median, 40 to 100 ns at the 99th percentile and
//! 60 to 140 ns at most, where a single try's reached 5.9 to 12.3 us (a read the host preempted);
+3 -3
View File
@@ -2,15 +2,15 @@
//! a guest's clock does (an x86-64 guest's `mach_absolute_time` counts its TSC; an arm64 guest's
//! counter is the host's). `CLOCK_MONOTONIC` runs at the rate NTP disciplines it to, so it drifts
//! from the guest's clock by the host's frequency correction (**measured** 2026-11-15 against
//! `CLOCK_MONOTONIC_RAW`: +45.1 ppm on one Ryzen 7 7840HS host, -30.1 ppm on another and +5.7
//! ppm on a Ryzen 7 8745H host, systemd-timesyncd, over 5 s; +3.9 ppm on the M3 Max over 10 s).
//! `CLOCK_MONOTONIC_RAW`: +45.1 ppm on homelab-um790-xtx-1, -30.1 ppm on homelab-gem10-1 and
//! +5.7 ppm on homelab-um870-1, systemd-timesyncd, over 5 s; +3.9 ppm on the M3 Max over 10 s).
//!
//! The kext maps the device's times by its reading of `HOST_TIME`, which it takes only at a
//! `VBLANK`, and widens a held reading's bound by 50 ppm of its age
//! (`guest/kext/src/RgfxVblankClock.hpp`): on the raw clock that holds whatever NTP does, where a
//! slew correcting a large offset can pass 50 ppm. On `CLOCK_MONOTONIC` the host's map of the
//! guest's times of its command buffers (`device::guest_times`), by the offset the kext last
//! wrote, showed the first host's 45 ppm as a transport that climbed to 230 us between
//! wrote, showed homelab-um790-xtx-1's 45 ppm as a transport that climbed to 230 us between
//! readings 5 s apart, while `VBLANK`s were off.
/// The host's monotonic clock at the counter's rate, in nanoseconds.
+8 -22
View File
@@ -11,7 +11,7 @@ use zerocopy::{FromBytes, IntoBytes};
use crate::device::{CursorShape, Shared};
use crate::display::cursor_color::CursorColor;
use crate::display::{CursorImage, Scanout, straight_rgba};
use crate::display::{CursorImage, Scanout, offered_modes, straight_rgba};
use crate::ring::{Message, set_size, sized};
use crate::wire::*;
@@ -73,10 +73,6 @@ pub(crate) fn answer(shared: &Shared, message: &Message) -> Option<Vec<u8>> {
.map_or(RGFX_STATUS_INVALID_ARGUMENT, |command| {
set_display_power(shared, &command)
}),
RGFX_CMD_SET_DISPLAY_RATE => read(message)
.map_or(RGFX_STATUS_INVALID_ARGUMENT, |command| {
set_display_rate(shared, &command)
}),
// A command buffer rides a command queue's own ring, never the control ring.
_ => RGFX_STATUS_UNKNOWN_COMMAND,
};
@@ -396,11 +392,11 @@ pub(crate) fn complete(seqno: u64, status: u32) -> Vec<u8> {
/// `GET_DISPLAYS`' answer: each display the guest sees (`Shared::displays_seen`: display 0
/// alone where it did not take [`RGFX_FEATURE_MULTI_DISPLAY`]), in order of id, connected, with
/// the modes it offers (`Shared::offered_modes`): first its screen's mode, which it prefers, then
/// its smaller modes, then each again at the screen's other rates; and, where the guest took
/// [`RGFX_FEATURE_DISPLAY_SCALE`], its screen's scale between the display's record and its modes.
/// The record's count is the modes that follow it. The guest is told each change of those modes
/// from now on (`device`'s refresh).
/// the modes it offers ([`offered_modes`]): first the mode `Shared::offered_mode` gives, which it
/// prefers, then its smaller modes; and, where the guest took [`RGFX_FEATURE_DISPLAY_SCALE`], its
/// screen's scale between the display's record and its modes. The record's count is the modes
/// that follow it. The guest is told each display's first mode from now on (`device`'s
/// refresh), which the smaller modes follow.
fn displays(shared: &Shared, seqno: u64) -> Vec<u8> {
let seen = shared.displays_seen();
let mut bytes = RgfxMsgHeader {
@@ -412,9 +408,9 @@ fn displays(shared: &Shared, seqno: u64) -> Vec<u8> {
.to_vec();
bytes.extend_from_slice(&seen.to_le_bytes());
for (id, display) in (0..seen).zip(shared.displays.iter()) {
let modes = shared.offered_modes(display);
let modes = offered_modes(display.screen.mode(), shared.display_count());
let first = modes[0];
display.state.lock().told = Some(modes.clone());
display.state.lock().told = Some(first);
let mut records = Vec::new();
let mut mode_count = 0;
for mode in &modes {
@@ -730,16 +726,6 @@ fn set_vblank(shared: &Shared, command: &RgfxSetVblank) -> u32 {
RGFX_STATUS_OK
}
/// `SET_DISPLAY_RATE`: the display's refreshes run at the rate of the mode the guest set while
/// the display offers a mode at it (`Shared::refresh_period_ns`), from its next refresh.
fn set_display_rate(shared: &Shared, command: &RgfxSetDisplayRate) -> u32 {
let Some(display) = shared.seen_display(command.display) else {
return RGFX_STATUS_NO_DISPLAY;
};
display.state.lock().rate_mhz = Some(command.refresh_mhz);
RGFX_STATUS_OK
}
/// `SET_DISPLAY_POWER`: the screen is told where the panel's state changes. The display's
/// scanout, presents and `VBLANK`s go on either way (`display`'s module doc).
fn set_display_power(shared: &Shared, command: &RgfxSetDisplayPower) -> u32 {
+296 -101
View File
@@ -27,15 +27,12 @@
//! Every other ring is a command queue's own (below), so each ring keeps a single producer and
//! one consumer at a time, one thread sleeps on each, and their `consumer_idle` handshakes never
//! race.
//! `reims-vgpu.graphics-refresh` runs at the display's refresh rate (`Shared::refresh_period_ns`:
//! its screen's, [`Screen::mode`], or the lower one the guest set where it took
//! `RGFX_FEATURE_EXT_DISPLAY_RATE` and the display offers it): at each
//! `reims-vgpu.graphics-refresh` runs at the display's refresh rate ([`Screen::mode`]): at each
//! refresh it has the screen show the scanout again while the guest has one
//! ([`Screen::present`]), sends `VBLANK` while the guest has it on, stamped with the refresh's
//! time on its grid (`RefreshGrid`) as a panel's hardware stamps its vblank (dropping one the
//! completion ring has no room for), sends
//! `DISPLAY_CHANGED` once the display's modes are not those the guest was last told (its size,
//! scale or rate, or the screen's other rates, `Shared::offered_modes`), and then
//! `DISPLAY_CHANGED` once the display's mode is not the one the guest was last told, and then
//! tells the host of the refresh ([`Host::refreshed`]), which answers there the presents the
//! display first shows at it. A device of several displays has a refresh thread for each, on a
//! grid of its own at its own screen's rate (`reims-vgpu.graphics-refresh-<i>` for display `i`
@@ -250,8 +247,7 @@ use crate::device::gate::{Gate, Look, Offer, Waited};
use crate::device::lanes::{Hand, Key, Lanes};
use crate::display::cursor_color::CursorColor;
use crate::display::{
CursorImage, Mode, Scanout, Screen, fixed_rate_mode, offered_modes, scanout_room,
scanout_room_at,
CursorImage, Mode, Scanout, Screen, offered_in_room, scanout_room, scanout_room_at,
};
use crate::ops::RgfxCommandBuffer;
use crate::region::Region;
@@ -363,8 +359,7 @@ const MIN_QUEUE_RING_DATA: u64 = 4096;
/// The feature bits 64 to 95 a `DRIVER_FEATURES_EXT` write may take, of those `FEATURES_EXT`
/// offers: the `RGFX_FEATURE_EXT_*` that are taken, where the others are used with no take.
pub(crate) const TAKEN_EXT_FEATURES: u32 =
RGFX_FEATURE_EXT_SURFACE_HOLD | RGFX_FEATURE_EXT_DISPLAY_RATE;
pub(crate) const TAKEN_EXT_FEATURES: u32 = RGFX_FEATURE_EXT_SURFACE_HOLD;
/// The feature bits whose meaning the host knows, which a `DRIVER_FEATURES` write may take:
/// `RGFX_FEATURE_*`, bits 0 to 9 and 11 to 63.
@@ -1166,6 +1161,8 @@ pub(crate) struct Shared {
version_watch: guest_drivers::VersionWatch,
/// Set at the device's end.
ending: AtomicBool,
/// Set while quiesced for checkpointing.
quiesced: AtomicBool,
/// The control thread's own wake.
wake: Wake,
/// The host's doorbell file for ring 0, once given.
@@ -1902,9 +1899,6 @@ pub(crate) struct Display {
pub(crate) screen: Box<dyn Screen>,
/// What the guest set of it, and what the device told it.
pub(crate) state: Mutex<DisplayState>,
/// The screen's rate, in thousandths of a hertz, that the display's set rate
/// ([`Screen::fixed_rate`]) was last logged lowered to; 0 while it is not lowered.
pub(crate) lowered_mhz: AtomicU32,
}
/// A display, as the guest has set it, and what the device has told it.
@@ -1918,12 +1912,8 @@ pub(crate) struct DisplayState {
pub(crate) asleep: bool,
/// Refreshes since the last reset.
refreshes: u64,
/// The modes the guest was last told, in a `DISPLAYS` or a `DISPLAY_CHANGED`'s wake.
pub(crate) told: Option<Vec<Mode>>,
/// The rate of the mode the guest set, in thousandths of a hertz, as its last
/// `SET_DISPLAY_RATE` named it: the display's refreshes run at it while it offers a mode at
/// it (`Shared::refresh_period_ns`).
pub(crate) rate_mhz: Option<u32>,
/// The mode the guest was last told, in a `DISPLAYS` or a `DISPLAY_CHANGED`'s wake.
pub(crate) told: Option<Mode>,
/// A `DISPLAY_CHANGED` is owed.
changed: bool,
/// The cursor's image as the guest's last `SET_CURSOR` set it, straight RGBA, before its
@@ -1933,16 +1923,6 @@ pub(crate) struct DisplayState {
pub(crate) cursor_color: Option<CursorColor>,
}
/// A rate in thousandths of a hertz, in hertz: whole, or with as many decimals as it needs.
fn hz(mhz: u32) -> String {
if mhz.is_multiple_of(1000) {
(mhz / 1000).to_string()
} else {
let decimals = format!("{:03}", mhz % 1000);
format!("{}.{}", mhz / 1000, decimals.trim_end_matches('0'))
}
}
impl Device {
/// A device of one display over `region` (BAR 2: [`REGION_SIZE`] bytes, of which what shows
/// the display may hold a reference to read the scanout from), `host` and `screen`, with its
@@ -1988,7 +1968,6 @@ impl Device {
.map(|screen| Display {
screen,
state: Mutex::new(DisplayState::default()),
lowered_mhz: AtomicU32::new(0),
})
.collect();
let mut consumer = Consumer::new(SUBMIT);
@@ -2008,6 +1987,7 @@ impl Device {
reset_owed: AtomicBool::new(false),
version_watch: guest_drivers::VersionWatch::default(),
ending: AtomicBool::new(false),
quiesced: AtomicBool::new(false),
wake: Wake::new()?,
doorbell: OnceLock::new(),
submit: Mutex::new(Submit {
@@ -2296,6 +2276,29 @@ impl Device {
pub fn reset(&self) {
self.shared.reset();
}
/// Quiesces the device for stopped-VM checkpointing.
pub fn quiesce(&self) {
self.shared.quiesce();
}
/// Resumes VBLANK ticks and ring consumption after quiesce.
pub fn unquiesce(&self) {
self.shared.unquiesce();
}
/// Exports the quiescent device's BAR0/ring/display/queue/region state.
pub fn export_snapshot(&self) -> crate::snapshot::DeviceSnapshot {
self.shared.export_snapshot()
}
/// Restores device state on a freshly created device (after QEMU restored BAR2).
pub fn import_snapshot(
&self,
snap: &crate::snapshot::DeviceSnapshot,
) -> Result<(), &'static str> {
self.shared.import_snapshot(snap)
}
}
/// What tells the guest's CPU locks that the host lowered a cached surface's hold word they wait
@@ -2857,10 +2860,233 @@ impl Shared {
}
}
/// The reset (the module doc). It waits for the message the control thread is taking, and
/// for a take of a queue's ring or a post onto one under way, none of which waits for the
/// host, then, last, for the host's settle ([`Host::reset_settles`]); the host is told on the
/// control thread ([`Self::tell_reset`]).
/// Wait for active graphics operations before taking a snapshot.
fn quiesce(&self) {
self.quiesced.store(true, Ordering::Release);
self.wake.wake();
let active_queues: Vec<Arc<QueueShared>> =
{ self.queues.lock().by_obj.values().cloned().collect() };
for q in &active_queues {
q.wake.wake();
}
{
let _taking = self.taking.lock();
}
self.take_messages();
self.lanes.wait_idle();
if self.control_handing.load(Ordering::Acquire) {
self.post_behind_control_handed(None);
}
for q in &active_queues {
let poster = self.queue_poster(q);
self.take_queue_messages(q, &poster);
if q.handing.load(Ordering::Acquire) {
self.post_handed(q);
}
}
self.lanes.wait_idle();
}
fn unquiesce(&self) {
self.quiesced.store(false, Ordering::Release);
self.wake.wake();
let active_queues: Vec<Arc<QueueShared>> =
{ self.queues.lock().by_obj.values().cloned().collect() };
for q in &active_queues {
q.wake.wake();
}
}
fn export_snapshot(&self) -> crate::snapshot::DeviceSnapshot {
use crate::snapshot::{DeviceSnapshot, DisplaySnapshot, QueueSnapshot};
let status = self.status.load(Ordering::Acquire);
let driver_features = self.driver_features.load(Ordering::Acquire);
let control_done = self.control_done.load(Ordering::Acquire);
let (control_submit_count, control_submit_broken) = {
let s = self.submit.lock();
(s.consumer.consumed(), s.broken)
};
let control_completion_count = self.completion.lock().produced();
let vt_ring_count = self.vt_ring.lock().produced();
let pages: Vec<u32> = self
.pages
.iter()
.map(|p| p.load(Ordering::Acquire))
.collect();
let displays: Vec<DisplaySnapshot> = self
.displays
.iter()
.map(|d| {
let st = d.state.lock();
DisplaySnapshot {
scanout: st.scanout,
vblank: st.vblank,
asleep: st.asleep,
refreshes: st.refreshes,
told: st.told,
changed: st.changed,
cursor_image: st.cursor_image.clone(),
}
})
.collect();
let region_blocks = self.region.export_blocks();
let mut queue_list: Vec<Arc<QueueShared>> =
self.queues.lock().by_obj.values().cloned().collect();
queue_list.sort_by_key(|q| q.obj_id);
let queues: Vec<QueueSnapshot> = queue_list
.iter()
.map(|q| {
let s = q.submit.lock();
let c = q.complete.lock();
QueueSnapshot {
create_bytes: q.create.as_bytes().to_vec(),
flags: q.flags,
taken_seqno: q.taken_seqno.load(Ordering::Acquire),
taken_buffer_seqno: q.taken_buffer_seqno.load(Ordering::Acquire),
submit_count: s.consumer.consumed(),
submit_broken: s.broken,
complete_count: c.produced(),
}
})
.collect();
DeviceSnapshot {
status,
driver_features,
driver_features_ext: self.driver_features_ext.load(Ordering::Acquire),
control_done,
control_submit_count,
control_submit_broken,
control_completion_count,
vt_ring_count,
pages,
displays,
region_blocks,
queues,
}
}
fn import_snapshot(&self, snap: &crate::snapshot::DeviceSnapshot) -> Result<(), &'static str> {
self.quiesced.store(true, Ordering::Release);
self.region.import_blocks(&snap.region_blocks);
self.driver_features
.store(snap.driver_features, Ordering::Release);
self.driver_features_ext
.store(snap.driver_features_ext, Ordering::Release);
if snap.driver_features != 0 || snap.driver_features_ext != 0 {
self.host
.driver_ready(snap.driver_features, snap.driver_features_ext);
}
let mut any_page = false;
for (dst, &val) in self.pages.iter().zip(snap.pages.iter()) {
dst.store(val, Ordering::Release);
if val != 0 {
any_page = true;
}
}
if any_page {
self.pages_bound.store(true, Ordering::Release);
}
{
let mut submit = self.submit.lock();
submit.consumer.set_count(snap.control_submit_count);
submit.broken = snap.control_submit_broken;
submit.backlog.clear();
}
self.control_done
.store(snap.control_done, Ordering::Release);
self.completion
.lock()
.set_count(snap.control_completion_count);
self.vt_ring.lock().set_count(snap.vt_ring_count);
self.reset_owed.store(false, Ordering::Release);
for (display, ds) in self.displays.iter().zip(snap.displays.iter()) {
{
let mut st = display.state.lock();
st.scanout = ds.scanout;
st.vblank = ds.vblank;
st.asleep = ds.asleep;
st.refreshes = ds.refreshes;
st.told = ds.told;
st.changed = ds.changed;
st.cursor_image = ds.cursor_image.clone();
}
display.screen.scanout(ds.scanout);
display.screen.cursor_image(ds.cursor_image.clone());
display.screen.power(!ds.asleep);
}
self.status.store(snap.status, Ordering::Release);
let epoch = self.epoch.load(Ordering::Acquire);
for qs in &snap.queues {
let Ok(q) = RgfxQueueCreate::read_from_bytes(&qs.create_bytes) else {
return Err("malformed RgfxQueueCreate in snapshot");
};
let Some((submit_at, complete_at)) = self.validate_rings(&q) else {
return Err("queue rings invalid against restored BAR2 block ledger");
};
let Some(me) = self.weak_self.get().and_then(Weak::upgrade) else {
return Err("device weak_self missing");
};
let Some(wake) = Wake::new() else {
return Err("queue wake allocation failed");
};
let bell = if self.driver_took(RGFX_FEATURE_DOORBELL_ASKS) {
wake::bell()
} else {
None
};
let mut consumer = Consumer::new(submit_at);
consumer.set_count(qs.submit_count);
let mut producer = Producer::new(complete_at);
producer.set_count(qs.complete_count);
let queue = Arc::new(QueueShared {
obj_id: q.obj_id,
context: (q.obj_id >> RGFX_CONTEXT_OBJ_ID_SHIFT) as u32,
create: q,
flags: qs.flags,
epoch,
ring_id: q.submit_offset,
vector: q.vector,
submit: Mutex::new(Submit {
consumer,
broken: qs.submit_broken,
backlog: Backlog::default(),
asleep: false,
}),
taken_seqno: AtomicU64::new(qs.taken_seqno),
taken_buffer_seqno: AtomicU64::new(qs.taken_buffer_seqno),
consuming: Mutex::new(None),
complete: Mutex::new(producer),
room: Room::default(),
full: AtomicBool::new(false),
untold: Mutex::new(Untold::default()),
handed: Mutex::new(Handed::default()),
handing: AtomicBool::new(false),
wake,
bell,
route: AtomicU64::new(0),
route_page: AtomicU32::new(u32::MAX),
ending: AtomicBool::new(false),
context_closed: Mutex::new(false),
trip: trip::Queue::default(),
});
{
let mut queues = self.queues.lock();
queues.by_obj.insert(q.obj_id, Arc::clone(&queue));
queues.by_ring.insert(q.submit_offset, Arc::clone(&queue));
}
let service = Arc::clone(&queue);
std::thread::Builder::new()
.name(format!("reims-vgpu.graphics-queue-{:#x}", q.obj_id))
.spawn(move || me.queue_service_restored(&service))
.map_err(|_| "failed to spawn restored queue thread")?;
self.route(&queue);
self.host.queue_made(&self.queue_poster(&queue));
}
Ok(())
}
/// Reset waits for the current control and queue ring operations and settles the host.
/// The host is told on the control thread ([`Self::tell_reset`]).
fn reset(&self) {
self.status.store(RGFX_STATUS_RESET, Ordering::Release);
self.driver_features.store(0, Ordering::Release);
@@ -2981,12 +3207,6 @@ impl Shared {
self.driver_features.load(Ordering::Acquire) & feature != 0
}
/// Whether the guest's driver took `feature`, a taken bit of `FEATURES_EXT`
/// ([`TAKEN_EXT_FEATURES`]), since the last reset.
pub(crate) fn driver_took_ext(&self, feature: u32) -> bool {
self.driver_features_ext.load(Ordering::Acquire) & feature != 0
}
/// How many displays the device has: 1 to [`RGFX_DISPLAYS_MAX`], fixed at its make.
pub(crate) fn display_count(&self) -> u32 {
u32::try_from(self.displays.len()).unwrap_or(RGFX_DISPLAYS_MAX)
@@ -3530,63 +3750,10 @@ impl Shared {
}
}
/// The modes `display` offers its guest now ([`offered_modes`]): first its screen's
/// ([`Screen::mode`]), sized to its scanout room on a device of more than one display, then
/// its smaller sizes, then, where the guest took `RGFX_FEATURE_EXT_DISPLAY_RATE`, each size
/// again at the screen's other rates ([`Screen::rates`]), and last, where the guest took
/// `DISPLAY_SCALE` and the screen is above 1x, the larger mode at those rates. Where such a
/// guest's display has a rate set ([`Screen::fixed_rate`]), every size is at that one rate
/// alone, at most the screen's ([`fixed_rate_mode`]), which the guest's `SET_DISPLAY_RATE`
/// then has its refreshes run at; a rate lowered to the screen's is logged as a warning,
/// which a host that keeps warnings alone shows, once for each screen rate it is lowered to.
/// A guest that did not take the bit sends no rate, and its display offers the screen's
/// alone, set rate or none, as its refreshes run at the screen's.
pub(crate) fn offered_modes(&self, display: &Display) -> Vec<Mode> {
let screen = &display.screen;
let count = self.display_count();
let told = self.driver_took(RGFX_FEATURE_DISPLAY_SCALE);
if !self.driver_took_ext(RGFX_FEATURE_EXT_DISPLAY_RATE) {
return offered_modes(screen.mode(), &[], count, told);
}
let Some(fixed) = screen.fixed_rate() else {
return offered_modes(screen.mode(), &screen.rates(), count, told);
};
let (mode, lowered) = fixed_rate_mode(screen.mode(), fixed);
let to = if lowered { mode.refresh_mhz } else { 0 };
if display.lowered_mhz.swap(to, Ordering::Relaxed) != to && lowered {
let id = (self.displays.iter())
.position(|d| std::ptr::eq(d, display))
.unwrap_or(0);
log::warn!(
"display {id}: the refresh rate set for it, {} Hz, is above its screen's, {} Hz: \
it offers {} Hz",
hz(fixed),
hz(mode.refresh_mhz),
hz(mode.refresh_mhz)
);
}
offered_modes(mode, &[], count, told)
}
/// The time between `display`'s refreshes, in nanoseconds: the period of the rate the guest
/// set (`SET_DISPLAY_RATE`) while the display offers a mode at it, the modes the guest was
/// last told among them, and otherwise of its screen's mode ([`Screen::mode`]). A rate the
/// display no longer offers (the window moved to a screen that lists it not) gives way to
/// the screen's at the refresh that finds the change.
pub(crate) fn refresh_period_ns(&self, display: &Display) -> u64 {
let screen = display.screen.mode();
let state = display.state.lock();
let offered = |rate: u32| {
(state.told.as_ref()).is_some_and(|told| told.iter().any(|m| m.refresh_mhz == rate))
};
match state.rate_mhz {
Some(rate) if offered(rate) => Mode {
refresh_mhz: rate,
..screen
}
.period_ns(),
_ => screen.period_ns(),
}
/// The mode `display` offers its guest now: its screen's ([`Screen::mode`]), sized to its
/// scanout room on a device of more than one display ([`offered_in_room`]).
pub(crate) fn offered_mode(&self, display: &Display) -> Mode {
offered_in_room(display.screen.mode(), self.display_count())
}
/// Whether `len` bytes at `offset` lie in display `id`'s scanout room
@@ -3686,6 +3853,10 @@ impl Shared {
/// The control thread (the module doc).
fn control_thread(&self) {
while !self.ending() {
if self.quiesced.load(Ordering::Acquire) {
self.wake.sleep_for(None, Some(Duration::from_millis(20)));
continue;
}
// The answers handed over to it, posted first, as a post onto the ring would.
if self.control_handing.load(Ordering::Acquire) {
self.post_behind_control_handed(None);
@@ -4894,6 +5065,23 @@ impl Shared {
/// A queue's service thread (the module doc): it takes the queue's submission ring with the
/// control thread's `consumer_idle` handshake, hands each message to the host, and sleeps on
/// the queue's own wake, woken by its doorbell or its end.
fn queue_service_restored(&self, queue: &Arc<QueueShared>) {
let poster = self.queue_poster(queue);
self.queue_loop(queue, &poster);
self.close_handed(queue);
if !self.ending() && self.epoch.load(Ordering::Acquire) == queue.epoch {
let destroy = RgfxObjectDestroy {
header: RgfxMsgHeader {
r#type: RGFX_CMD_OBJECT_DESTROY,
size: size_of::<RgfxObjectDestroy>() as u32,
seqno: 0,
},
obj_id: queue.obj_id,
};
self.host.stage3_message(&poster, destroy.as_bytes());
}
}
fn queue_service(&self, queue: &Arc<QueueShared>) {
let poster = self.queue_poster(queue);
// The host makes the queue's handle first, so a command buffer on it can name it.
@@ -4932,6 +5120,10 @@ impl Shared {
/// The loop of a queue's service thread: take, then sleep, until the queue or the device ends.
fn queue_loop(&self, queue: &Arc<QueueShared>, poster: &CompletionPoster) {
while !self.ending() && !queue.ended() {
if self.quiesced.load(Ordering::Acquire) {
queue.wake.sleep_for(None, Some(Duration::from_millis(20)));
continue;
}
// The records handed over to it, posted first, as far as its ring has room: those
// left wait for its next look, while it takes the guest's buffers meanwhile.
if queue.handing.load(Ordering::Acquire) {
@@ -5512,14 +5704,14 @@ impl Shared {
/// Display `display`'s refresh thread (the module doc): a refresh at each tick of its grid
/// ([`RefreshGrid`]), stamped with the tick's time however late the thread woke for it.
fn refresh_thread(&self, display: u32) {
let Some(shown) = self.displays.get(display as usize) else {
let Some(screen) = self.displays.get(display as usize).map(|d| &d.screen) else {
return;
};
let mut grid = RefreshGrid::new(now_ns());
let part = u64::try_from(REFRESH_SLEEP_PART.as_nanos()).unwrap_or(u64::MAX);
while !self.ending() {
let now = now_ns();
let tick = grid.next(self.refresh_period_ns(shown), now);
let tick = grid.next(screen.mode().period_ns(), now);
let mut left = tick.saturating_sub(now);
while left > part {
std::thread::sleep(REFRESH_SLEEP_PART);
@@ -5542,6 +5734,9 @@ impl Shared {
/// that sees it ([`Self::displays_seen`]) alone: a guest that did not take
/// [`RGFX_FEATURE_MULTI_DISPLAY`] gets none of a display but 0's.
pub(crate) fn refresh(&self, id: u32, now: u64) {
if self.quiesced.load(Ordering::Acquire) {
return;
}
let Some(display) = self.displays.get(id as usize) else {
return;
};
@@ -5549,13 +5744,13 @@ impl Shared {
self.watch_version_leave(now);
}
let epoch = self.epoch.load(Ordering::Acquire);
let modes = self.offered_modes(display);
let mode = self.offered_mode(display);
let seen = id < self.displays_seen();
let (scanout, vblank, changed) = {
let mut display = display.state.lock();
display.refreshes = display.refreshes.wrapping_add(1);
if display.told.as_ref().is_some_and(|told| *told != modes) {
display.told = Some(modes);
if display.told.is_some_and(|told| told != mode) {
display.told = Some(mode);
display.changed = true;
}
(
+15 -2
View File
@@ -117,8 +117,8 @@
//! contexts and blocks they were: with a thread of each lane's own, made as a job came to a lane
//! with none and gone once the lane had had none for 1 s, every block's first `SURFACE_PAGES` made
//! a thread, and so did every lane's job after a pause of a second, 345 threads in 30 s of a
//! WindowServer probe (car 12's B1, an RTX 5080 Laptop host; measured). A thread is never refused
//! to a lane with a job, so the waits still end.
//! WindowServer probe (car 12's B1, msi RTX 5080 host; measured). A thread is never refused to a
//! lane with a job, so the waits still end.
//!
//! **A command buffer's thread.** A queue's thread that waits at the gate for its context's lane
//! carries out the lane's front job itself where the lane carries none out ([`Lanes::help`]): one
@@ -1035,6 +1035,19 @@ impl Lanes {
}
}
/// Waits until no lane is running or has queued jobs (or the device ends).
pub(super) fn wait_idle(&self) {
let mut state = self.state.lock();
while !state.ended
&& state
.lanes
.values()
.any(|lane| lane.running.is_some() || !lane.jobs.is_empty())
{
self.moved.wait(&mut state);
}
}
/// The device ended: the lanes' threads go at their next look, and so do those that wait for
/// a lane.
pub(super) fn end(&self) {
+10 -341
View File
@@ -34,17 +34,9 @@ pub(super) fn eventually(mut done: impl FnMut() -> bool) -> bool {
}
/// A refresh rate at which the refresh thread never runs during a test: a period of 1000 s. The
/// tests run each refresh themselves ([`Shared::refresh`]). A refresh thread reads its screen's
/// mode for its next refresh's time and sleeps to it, so a rig hands its device over only once
/// each display's thread has read this rate ([`TestScreen::paced`]): a rate a test sets after,
/// as [`rig_of_rates`] does, never paces it, and no refresh of the thread's runs beside the
/// test's own.
/// tests run each refresh themselves ([`Shared::refresh`]).
const NEVER_MHZ: u32 = 1;
/// The prefix of the names of the device's refresh threads (`reims-vgpu.graphics-refresh` and
/// `reims-vgpu.graphics-refresh-<i>`).
const REFRESH_THREAD: &str = "reims-vgpu.graphics-refresh";
/// What the screen was told, in order.
#[derive(Clone, Debug, PartialEq, Eq)]
enum Told {
@@ -55,29 +47,15 @@ enum Told {
Power(bool),
}
/// A screen with a mode, other rates and a set rate the test sets, recording what it is told.
/// A screen with a mode the test sets, recording what it is told.
struct TestScreen {
mode: Arc<Mutex<Mode>>,
rates: Arc<Mutex<Vec<u32>>>,
fixed: Arc<Mutex<Option<u32>>>,
told: Arc<Mutex<Vec<Told>>>,
/// Its display's refresh thread has read its mode, and so paced its next refresh by it.
paced: Arc<AtomicBool>,
}
impl Screen for TestScreen {
fn mode(&self) -> Mode {
let mode = *self.mode.lock();
if (std::thread::current().name()).is_some_and(|name| name.starts_with(REFRESH_THREAD)) {
self.paced.store(true, Ordering::SeqCst);
}
mode
}
fn rates(&self) -> Vec<u32> {
self.rates.lock().clone()
}
fn fixed_rate(&self) -> Option<u32> {
*self.fixed.lock()
*self.mode.lock()
}
fn scanout(&self, scanout: Option<Scanout>) {
self.told.lock().push(Told::Scanout(scanout));
@@ -184,10 +162,6 @@ struct Rig {
device: Device,
/// Display 0's screen's mode.
mode: Arc<Mutex<Mode>>,
/// Display 0's screen's other rates (`Screen::rates`), none at first.
rates: Arc<Mutex<Vec<u32>>>,
/// Display 0's set rate (`Screen::fixed_rate`), none at first.
fixed: Arc<Mutex<Option<u32>>>,
/// What display 0's screen was told.
told: Arc<Mutex<Vec<Told>>>,
/// The screens of displays 1 and up, on a device of more than one display.
@@ -257,52 +231,28 @@ impl Rig {
Rig::with_displays(host, lanes, 1)
}
/// [`Self::with_lanes`], for a device of `count` displays, each screen's mode [`MODE`],
/// handed over once each display's refresh thread has paced its next refresh by it
/// ([`NEVER_MHZ`]).
/// [`Self::with_lanes`], for a device of `count` displays, each screen's mode [`MODE`].
fn with_displays(host: Box<dyn Host>, lanes: Lanes, count: usize) -> Rig {
let mut screens: Vec<ScreenRecord> = (0..count)
.map(|_| (Arc::new(Mutex::new(MODE)), Arc::new(Mutex::new(Vec::new()))))
.collect();
let paced: Vec<Arc<AtomicBool>> = (0..count).map(|_| Arc::default()).collect();
let interrupts = Arc::new(AtomicU32::new(0));
let presented = Arc::new(Mutex::new(Vec::new()));
let region = Arc::new(Region::new(REGION_SIZE as usize).unwrap());
let rates = Arc::new(Mutex::new(Vec::new()));
let fixed = Arc::new(Mutex::new(None));
let boxed = (screens.iter().enumerate())
.map(|(i, (mode, told))| {
let boxed = (screens.iter())
.map(|(mode, told)| {
let screen: Box<dyn Screen> = Box::new(TestScreen {
mode: Arc::clone(mode),
rates: if i == 0 {
Arc::clone(&rates)
} else {
Arc::default()
},
fixed: if i == 0 {
Arc::clone(&fixed)
} else {
Arc::default()
},
told: Arc::clone(told),
paced: Arc::clone(&paced[i]),
});
screen
})
.collect();
let device = Device::with_lanes(region, host, boxed, lanes).unwrap();
for (i, paced) in paced.iter().enumerate() {
assert!(
eventually(|| paced.load(Ordering::SeqCst)),
"display {i}'s refresh thread never read its screen's mode"
);
}
let (mode, told) = screens.remove(0);
Rig {
device,
mode,
rates,
fixed,
told,
more: screens,
interrupts,
@@ -505,47 +455,6 @@ fn vblank(enabled: u32) -> Vec<u8> {
c.as_bytes().to_vec()
}
fn display_rate(display: u32, refresh_mhz: u32) -> Vec<u8> {
let c = RgfxSetDisplayRate {
header: RgfxMsgHeader {
r#type: RGFX_CMD_SET_DISPLAY_RATE,
..Default::default()
},
display,
refresh_mhz,
};
c.as_bytes().to_vec()
}
/// A host that offers `DISPLAY_RATE` ([`RGFX_FEATURE_EXT_DISPLAY_RATE`]), as every host of the
/// library's does.
struct RatesHost;
impl Host for RatesHost {
fn raise_interrupt(&self, _vector: u32) {}
fn features_ext(&self) -> u32 {
RGFX_FEATURE_EXT_DISPLAY_RATE
}
}
/// A rig whose host offers `DISPLAY_RATE`, its display 0's screen at 120 Hz, and whose guest takes
/// the bit where `takes` (a kext that knows it) before it starts the device.
fn rig_of_rates(takes: bool) -> Rig {
let rig = Rig::with_host(Box::new(RatesHost));
*rig.mode.lock() = Mode {
refresh_mhz: 120_000,
..MODE
};
if takes {
rig.device.mmio_write(
RGFX_REG_DRIVER_FEATURES_EXT.into(),
rig.device.mmio_read(RGFX_REG_FEATURES_EXT.into()),
);
}
rig.start();
rig
}
fn display_power(display: u32, on: u32) -> Vec<u8> {
let c = RgfxSetDisplayPower {
header: RgfxMsgHeader {
@@ -928,8 +837,7 @@ fn get_displays_answers_the_screen_s_mode() {
}
/// A guest that took `DISPLAY_SCALE` is told the screen's scale between the display's record and
/// its modes, and on a screen above 1x is offered the larger mode after the others; one that did
/// not gets the answer without either (`get_displays_answers_the_screen_s_mode`)
/// its modes; one that did not gets the answer without it (`get_displays_answers_the_screen_s_mode`)
#[test]
fn a_guest_that_took_display_scale_is_told_the_screen_s_scale() {
struct Scales;
@@ -950,9 +858,9 @@ fn a_guest_that_took_display_scale_is_told_the_screen_s_scale() {
let header = RgfxMsgHeader::read_from_prefix(&bytes).unwrap().0;
assert_eq!(
(header.r#type, header.size, header.seqno),
(RGFX_EVT_DISPLAYS, 104, seqno)
(RGFX_EVT_DISPLAYS, 96, seqno)
);
let words: Vec<u32> = bytes[16..104]
let words: Vec<u32> = bytes[16..92]
.chunks(4)
.map(|c| u32::from_le_bytes(c.try_into().unwrap()))
.collect();
@@ -960,8 +868,7 @@ fn a_guest_that_took_display_scale_is_told_the_screen_s_scale() {
assert_eq!(
words,
[
1, 0, 1, 0, 5, 240, 0, 1280, 800, n, 1120, 700, n, 992, 620, n, 960, 600, n, 1696,
1060, n
1, 0, 1, 0, 4, 240, 0, 1280, 800, n, 1120, 700, n, 992, 620, n, 960, 600, n
]
);
}
@@ -1279,244 +1186,6 @@ fn a_new_scale_is_told_with_display_changed() {
assert!(rig.quiet_for(2000), "told once");
}
/// The modes of display 0 in a `DISPLAYS` answer with no scale, each `[width, height,
/// refresh_mhz]`.
fn modes_of_display_0(bytes: &[u8]) -> Vec<[u32; 3]> {
let word = |at: usize| u32::from_le_bytes(bytes[at..at + 4].try_into().unwrap());
(0..word(32) as usize)
.map(|i| {
let at = 36 + i * 12;
[word(at), word(at + 4), word(at + 8)]
})
.collect()
}
/// For a guest that took `DISPLAY_RATE`, a change of the screen's other rates alone, a borderless
/// window moved to a screen of its size that lists other rates, changes the modes the display
/// offers: told once with `DISPLAY_CHANGED`, and `GET_DISPLAYS` then answers every size again at
/// each rate below the screen's
#[test]
fn a_screen_s_new_rates_are_told_with_display_changed() {
let mut rig = rig_of_rates(true);
rig.send(get_displays());
let alone = modes_of_display_0(&rig.event().unwrap());
assert!(alone.iter().all(|m| m[2] == 120_000), "{alone:?}");
*rig.rates.lock() = vec![120_000, 60_000];
rig.refresh();
let bytes = rig.event().unwrap();
let c = RgfxDisplayChanged::read_from_bytes(&bytes).unwrap();
assert_eq!((c.header.r#type, c.display), (RGFX_EVT_DISPLAY_CHANGED, 0));
rig.refresh();
assert!(rig.quiet_for(2000), "told once");
rig.send(get_displays());
let modes = modes_of_display_0(&rig.event().unwrap());
let again: Vec<[u32; 3]> = (alone.iter()).map(|m| [m[0], m[1], 60_000]).collect();
assert_eq!(modes, [alone.clone(), again].concat());
// The rates gone again: told again, and the display offers its sizes at 120 alone.
rig.rates.lock().clear();
rig.refresh();
let bytes = rig.event().unwrap();
let c = RgfxDisplayChanged::read_from_bytes(&bytes).unwrap();
assert_eq!((c.header.r#type, c.display), (RGFX_EVT_DISPLAY_CHANGED, 0));
rig.send(get_displays());
assert_eq!(modes_of_display_0(&rig.event().unwrap()), alone);
}
/// The next event: display 0's `DISPLAY_CHANGED`.
fn changed(rig: &mut Rig) {
let bytes = rig.event().unwrap();
let c = RgfxDisplayChanged::read_from_bytes(&bytes).unwrap();
assert_eq!((c.header.r#type, c.display), (RGFX_EVT_DISPLAY_CHANGED, 0));
}
/// The period of display 0's refreshes, in nanoseconds.
fn refresh_period(rig: &Rig) -> u64 {
let shared = &rig.device.shared;
shared.refresh_period_ns(&shared.displays[0])
}
/// A guest that took `DISPLAY_RATE` and set a mode at a rate its display offers below the
/// screen's (`SET_DISPLAY_RATE`) has the display's refreshes, its `VBLANK`s and the presents
/// answered at them, run at that rate; at the screen's again where it sets the screen's, where
/// the display stops offering the rate (the window moved to a screen that lists it not), and
/// after a reset; a rate the display does not offer leaves them at the screen's
#[test]
fn a_display_s_refreshes_run_at_the_rate_the_guest_set() {
const AT_120: u64 = 8_333_333;
const AT_60: u64 = 16_666_666;
let mut rig = rig_of_rates(true);
*rig.rates.lock() = vec![60_000];
rig.send(get_displays());
rig.event().unwrap();
assert_eq!(
refresh_period(&rig),
AT_120,
"the screen's until the guest sets a rate"
);
let s = rig.send(display_rate(0, 60_000));
assert_eq!(rig.complete(), (s, RGFX_STATUS_OK));
assert_eq!(refresh_period(&rig), AT_60);
let s = rig.send(display_rate(0, 120_000));
assert_eq!(rig.complete(), (s, RGFX_STATUS_OK));
assert_eq!(refresh_period(&rig), AT_120);
// A rate the display does not offer.
let s = rig.send(display_rate(0, 50_000));
assert_eq!(rig.complete(), (s, RGFX_STATUS_OK));
assert_eq!(refresh_period(&rig), AT_120);
// The rate gone from the screen's list: the screen's at the refresh that finds it gone.
let s = rig.send(display_rate(0, 60_000));
assert_eq!(rig.complete(), (s, RGFX_STATUS_OK));
assert_eq!(refresh_period(&rig), AT_60);
rig.rates.lock().clear();
rig.refresh();
assert_eq!(refresh_period(&rig), AT_120);
changed(&mut rig);
*rig.rates.lock() = vec![60_000];
rig.refresh();
assert_eq!(refresh_period(&rig), AT_60, "offered again");
changed(&mut rig);
// A display the guest does not see.
let s = rig.send(display_rate(1, 60_000));
assert_eq!(rig.complete(), (s, RGFX_STATUS_NO_DISPLAY));
// A reset forgets the rate.
rig.device
.mmio_write(RGFX_REG_STATUS.into(), RGFX_STATUS_RESET);
assert_eq!(refresh_period(&rig), AT_120);
}
/// A kext built before `DISPLAY_RATE`, which never takes it, meets this host as it met one before
/// it: each size at the screen's rate alone, whatever other rates the screen lists, and its
/// display's refreshes at the screen's rate
#[test]
fn an_older_kext_on_this_host_is_offered_the_screen_s_rate_alone() {
let mut rig = rig_of_rates(false);
*rig.rates.lock() = vec![60_000];
assert_eq!(rig.device.mmio_read(RGFX_REG_DRIVER_FEATURES_EXT.into()), 0);
rig.send(get_displays());
let modes = modes_of_display_0(&rig.event().unwrap());
assert!(!modes.is_empty());
assert!(modes.iter().all(|m| m[2] == 120_000), "{modes:?}");
rig.refresh();
assert!(rig.quiet_for(200), "no change told");
assert_eq!(refresh_period(&rig), 8_333_333);
}
/// A display whose rate is set (`Screen::fixed_rate`, a VM's refresh rate) offers a guest that
/// took `DISPLAY_RATE` every size at that one rate alone, whatever other rates its screen lists,
/// and its refreshes run at it once the guest sets it; unset again, the display offers the
/// screen's rates as before, told with `DISPLAY_CHANGED`
#[test]
fn a_display_of_a_set_rate_offers_every_size_at_it_alone() {
const AT_60: u64 = 16_666_666;
let mut rig = rig_of_rates(true);
*rig.rates.lock() = vec![60_000, 50_000];
rig.send(get_displays());
let all = modes_of_display_0(&rig.event().unwrap());
let sizes: Vec<[u32; 2]> = (all.iter().filter(|m| m[2] == 120_000))
.map(|m| [m[0], m[1]])
.collect();
assert!(all.iter().any(|m| m[2] == 60_000) && all.iter().any(|m| m[2] == 50_000));
*rig.fixed.lock() = Some(60_000);
rig.refresh();
changed(&mut rig);
rig.send(get_displays());
let set = modes_of_display_0(&rig.event().unwrap());
let want: Vec<[u32; 3]> = sizes.iter().map(|s| [s[0], s[1], 60_000]).collect();
assert_eq!(set, want, "every size at 60 alone");
let s = rig.send(display_rate(0, 60_000));
assert_eq!(rig.complete(), (s, RGFX_STATUS_OK));
assert_eq!(refresh_period(&rig), AT_60);
// Unset: the screen's rates again.
*rig.fixed.lock() = None;
rig.refresh();
changed(&mut rig);
rig.send(get_displays());
assert_eq!(modes_of_display_0(&rig.event().unwrap()), all);
}
/// A set rate above the screen's is lowered to the screen's: every size at the screen's rate
/// alone, none above it, as the host's screen shows no frame faster than it runs
#[test]
fn a_set_rate_above_the_screen_s_is_lowered_to_it() {
let mut rig = rig_of_rates(true);
*rig.rates.lock() = vec![60_000];
*rig.fixed.lock() = Some(144_000);
rig.send(get_displays());
let modes = modes_of_display_0(&rig.event().unwrap());
assert!(!modes.is_empty());
assert!(modes.iter().all(|m| m[2] == 120_000), "{modes:?}");
let (mode, lowered) = fixed_rate_mode(*rig.mode.lock(), 144_000);
assert_eq!((mode.refresh_mhz, lowered), (120_000, true));
let (mode, lowered) = fixed_rate_mode(*rig.mode.lock(), 50_000);
assert_eq!((mode.refresh_mhz, lowered), (50_000, false));
let unknown = Mode {
refresh_mhz: 0,
..MODE
};
assert_eq!(fixed_rate_mode(unknown, 50_000).0.refresh_mhz, 50_000);
}
/// A kext built before `DISPLAY_RATE` sends no rate, so its display's refreshes run at the
/// screen's: a set rate leaves its modes at the screen's rate alone, as before
#[test]
fn an_older_kext_is_offered_the_screen_s_rate_whatever_rate_is_set() {
let mut rig = rig_of_rates(false);
*rig.fixed.lock() = Some(60_000);
rig.send(get_displays());
let modes = modes_of_display_0(&rig.event().unwrap());
assert!(!modes.is_empty());
assert!(modes.iter().all(|m| m[2] == 120_000), "{modes:?}");
}
/// A kext that takes `DISPLAY_RATE` meets a host older than it, which offers no such bit, as
/// before: its take takes nothing, and its display offers each size at the screen's rate alone
#[test]
fn a_kext_that_takes_display_rate_on_an_older_host_takes_nothing() {
let mut rig = Rig::new();
*rig.mode.lock() = Mode {
refresh_mhz: 120_000,
..MODE
};
*rig.rates.lock() = vec![60_000];
rig.device.mmio_write(
RGFX_REG_DRIVER_FEATURES_EXT.into(),
RGFX_FEATURE_EXT_DISPLAY_RATE,
);
rig.start();
assert_eq!(rig.device.mmio_read(RGFX_REG_FEATURES_EXT.into()), 0);
assert_eq!(
rig.device.mmio_read(RGFX_REG_DRIVER_FEATURES_EXT.into()),
0,
"nothing taken"
);
rig.send(get_displays());
let modes = modes_of_display_0(&rig.event().unwrap());
assert!(modes.iter().all(|m| m[2] == 120_000), "{modes:?}");
}
/// A rig's refresh threads run no refresh by themselves, though a test sets its screen a rate they
/// would run at (as [`rig_of_rates`] does, 120 Hz): each paced its next refresh 1000 s out
/// ([`NEVER_MHZ`]) before the rig was handed over, so the refreshes a test runs
/// ([`Rig::refresh`]) are its display's only ones, and none runs beside them: two refreshes of
/// one display at once may tell the guest one change twice with `DISPLAY_CHANGED`
#[test]
fn a_rig_s_refresh_threads_run_no_refresh_at_a_rate_a_test_sets() {
let rig = Rig::of_displays(2);
let at_120 = Mode {
refresh_mhz: 120_000,
..MODE
};
*rig.mode.lock() = at_120;
*rig.more[0].0.lock() = at_120;
rig.start();
// Twelve periods at 120 Hz.
std::thread::sleep(Duration::from_millis(100));
for display in &rig.device.shared.displays {
assert_eq!(display.state.lock().refreshes, 0);
}
assert_eq!(rig.refreshes.load(Ordering::SeqCst), 0);
}
/// A dropped device lets its region go once its threads see the end, though its refresh comes
/// once in 1000 s ([`NEVER_MHZ`]) and its refresh thread was asleep for it: the thread sleeps
/// that wait in parts ([`REFRESH_SLEEP_PART`]). Windows charges each region to the host's commit
@@ -387,7 +387,7 @@ fn each_display_s_mode_count_is_the_records_that_follow_it() {
let listed = listed(&rig.event().unwrap(), scaled);
assert_eq!(listed.len(), count, "{count} displays");
for (i, (id, scale, modes)) in listed.into_iter().enumerate() {
let offered = crate::display::offered_modes(screens[i], &[], count as u32, scaled);
let offered = crate::display::offered_modes(screens[i], count as u32);
assert_eq!(id, i as u32);
assert_eq!(scale, if scaled { screens[i].scale_120ths } else { 0 });
let want: Vec<[u32; 3]> = (offered.iter())
+51 -450
View File
@@ -5,17 +5,11 @@
//! ([`Screen::mode`]), which for a window is its size in pixels at its host screen's rate, with
//! the host screen's scale, which a guest that took `DISPLAY_SCALE` is told after the display's
//! record (`RgfxDisplayScale`). After it come the smaller modes of its ratio at a Mac's steps
//! ([`offered_modes`]), each at the same rate; a window keeps its size at a smaller mode and shows
//! it scaled to fill it (`reims-vgpu`'s `graphics::sink`). Where the screen lists other rates
//! below its own ([`Screen::rates`]: a borderless window's screen), every size is offered again
//! at each of them, as a Mac lists a screen's rates for each of its sizes. On a screen above 1x,
//! to a guest told its scale, one larger mode follows them all, at the same rates: 4/3 of the
//! first mode's width ([`LARGER_MODE_STEP`]), which the guest's kexts offer HiDPI at half its
//! pixels each way, so a 3840 × 2160 window offers "looks like 2560 × 1440" at 5120 × 2880, and
//! the window shows it scaled down to fill it. When what the display offers changes (the window
//! resized, or moved to a screen of another scale or other rates), the device tells the guest
//! with `DISPLAY_CHANGED`, and the guest asks `GET_DISPLAYS` again (`refresh`); the smaller
//! modes, the larger one and the other rates follow the first.
//! ([`offered_modes`]), each at the same rate: the guest runs at the host screen's rate whichever
//! it picks, and a window keeps its size at a smaller mode and shows it scaled to fill it
//! (`reims-vgpu`'s `graphics::sink`). When the screen's mode changes (the window resized, or
//! moved to a screen of another scale), the device tells the guest with `DISPLAY_CHANGED`, and
//! the guest asks `GET_DISPLAYS` again (`refresh`); the smaller modes follow the first.
//!
//! **Scanout.** `SET_SCANOUT` names the pixels the display shows, in the scanout's room of the
//! region (`RGFX_SCANOUT_SPAN` bytes at `RGFX_ALLOCATIONS_OFFSET`, before the processes' blocks,
@@ -42,7 +36,7 @@
//! ([`scanout_room`], [`scanout_room_at`]), so one display keeps the whole room, as before any
//! display had a room of its own. On a device of more than one display each display offers first
//! a mode whose scanout fits its room ([`offered_in_room`]); with one, the screen's mode as it is.
//! Each smaller mode, and the larger one, is offered only where its scanout fits the room.
//! Each smaller mode is offered only where its scanout fits the room.
pub(crate) mod cursor_color;
@@ -131,64 +125,24 @@ const SMALLER_MODE_STEPS: [(u64, u64); 6] = [(7, 8), (47, 60), (3, 4), (2, 3), (
const SMALLER_MODE_FLOOR: (u32, u32) = (800, 600);
// A host-side bound: the guest reads each display's count from the answer, so cbindgen leaves it out of
// the wire header. The guest's kexts take 64 a display (`ReimsGraphics::kMaxModes`).
/// The most modes a display offers, its first among them: its sizes at up to three rates each.
// the wire header.
/// The most modes a display offers, its first among them.
/// cbindgen:ignore
pub const MODES_MAX: usize = 24;
pub const MODES_MAX: usize = 8;
// The first mode, one for each step and the larger mode fit, at three rates.
const _: () = assert!((SMALLER_MODE_STEPS.len() + 2) * 3 <= MODES_MAX);
// The first mode and one for each step fit.
const _: () = assert!(SMALLER_MODE_STEPS.len() < MODES_MAX);
/// The step of the one mode larger than its first that a display offers on a screen above 1x, to
/// a guest told the screen's scale (`RgfxDisplayScale`): 4/3 of the first mode's width. A
/// 3840 × 2160 screen is offered 5120 × 2880, the backing a Mac draws its "looks like
/// 2560 × 1440" mode at for an external 3840 × 2160 screen and scales down to the panel (from the
/// owner's issue list, item 196; not read on a Mac of ours). The guest's kexts offer each mode of
/// even pixels HiDPI, at half its pixels each way, on such a screen (guest/kext's
/// `RgfxMode::hiDpi`), and at 1x as well, but macOS lists no 1x copy of the larger mode
/// (measured 12-04 on 3840 × 2160 windows: CoreGraphics' list with its low-resolution modes has
/// no 5120 × 2880 on macOS 26.7.2 x86-64 or 26.6.2 arm64, nor has Displays' "Show all
/// resolutions" on the x86-64 guest). The window shows a mode of its ratio at any size scaled to
/// fill it (`reims-vgpu`'s `graphics::sink`, "Sizes").
pub const LARGER_MODE_STEP: (u64, u64) = (4, 3);
/// The scale of a screen whose display is dense, in 120ths, is above this: above 1x. It is the
/// guest's kexts' own rule for a mode they offer HiDPI (`rgfxDisplayHighDensity`, 110 pixels per
/// inch a point, rounded to nearest: 111 at 121), so the larger mode is offered where the guest
/// runs it HiDPI.
const DENSE_ABOVE_120THS: u32 = 120;
/// How far apart two rates of one size a display offers are, in thousandths of a hertz: more
/// than this. The guest's kexts take a mode the device lists for the one they listed where its
/// rate is within 500 mHz of it (`RgfxDisplayModes`' `near`), so two rates of one size closer
/// than that would be one mode to them (60 Hz and 59.94).
const RATES_APART_MHZ: u32 = 500;
/// The modes a display whose screen offers `mode`, and lists `rates` too ([`Screen::rates`]),
/// offers its guest on a device of `count` displays, at most [`MODES_MAX`], where `scale_told`
/// says whether the guest is told the screen's scale (it took `DISPLAY_SCALE`): first the mode
/// [`offered_in_room`] gives, which the guest prefers, then each smaller mode of its ratio at
/// [`SMALLER_MODE_STEPS`] that is at least [`SMALLER_MODE_FLOOR`] and whose scanout fits the
/// display's room ([`scanout_room`], rows laid out as [`laid_out`] says), largest first, all at
/// the first mode's rate. A smaller mode is a multiple of 16 pixels wide and an even number high
/// (the steps of a window's offered modes, `reims-vgpu-window`'s `geometry::offered_mode`): its
/// width is the step's fraction of the first mode's, rounded down to a multiple of 16, and its
/// height the first mode's ratio of that width, rounded down to even. Every mode has the first's
/// scale.
///
/// Then come those sizes again, in the same order, at each other rate the display offers,
/// highest first ([`other_rates`]): the rates of `rates` below the first mode's, never one above
/// it, as the host's screen keeps running at its own, and each more than [`RATES_APART_MHZ`] from
/// the first mode's and from each other. Of rates closer than that the one nearer the first
/// mode's is kept: of 60 Hz and 59.94 below 120, 60. Every size gets the same rates, as many as
/// the bound leaves room for: two besides the first mode's where seven sizes fit.
///
/// Last, on a screen above 1x ([`DENSE_ABOVE_120THS`]) to a guest told its scale, comes the
/// larger mode ([`larger_mode`]), at the first mode's rate and then at each other rate in the
/// same order, where its scanout fits the room and it fits the bound beside every mode before it.
/// So every mode before it keeps its place, and with it the ID the guest's kexts gave it, and
/// the first stays the one the guest prefers.
pub fn offered_modes(mode: Mode, rates: &[u32], count: u32, scale_told: bool) -> Vec<Mode> {
/// The modes a display whose screen offers `mode` offers its guest on a device of `count`
/// displays, at most [`MODES_MAX`]: first the mode [`offered_in_room`] gives, which the guest
/// prefers, then each smaller mode of its ratio at [`SMALLER_MODE_STEPS`] that is at least
/// [`SMALLER_MODE_FLOOR`] and whose scanout fits the display's room ([`scanout_room`], rows laid
/// out as [`laid_out`] says), largest first. A smaller mode is a multiple of 16 pixels wide and an
/// even number high (the steps of a window's offered modes, `reims-vgpu-window`'s
/// `geometry::offered_mode`): its width is the step's fraction of the first mode's, rounded down
/// to a multiple of 16, and its height the first mode's ratio of that width, rounded down to
/// even. Every mode has the first's refresh rate and scale.
pub fn offered_modes(mode: Mode, count: u32) -> Vec<Mode> {
let first = offered_in_room(mode, count);
let mut modes = vec![first];
let (w, h) = (u64::from(first.width), u64::from(first.height));
@@ -216,96 +170,9 @@ pub fn offered_modes(mode: Mode, rates: &[u32], count: u32, scale_told: bool) ->
..first
});
}
let sizes = modes.clone();
let rates = other_rates(first.refresh_mhz, rates, MODES_MAX / sizes.len() - 1);
for &rate in &rates {
modes.extend(sizes.iter().map(|size| Mode {
refresh_mhz: rate,
..*size
}));
}
let dense = scale_told && first.scale_120ths > DENSE_ABOVE_120THS;
if let Some(larger) = larger_mode(first, room).filter(|_| dense)
&& (sizes.len() + 1) * (rates.len() + 1) <= MODES_MAX
{
modes.push(larger);
modes.extend(rates.iter().map(|&rate| Mode {
refresh_mhz: rate,
..larger
}));
}
modes
}
/// The mode larger than `first` a display offers on a screen above 1x ([`offered_modes`]): its
/// width [`LARGER_MODE_STEP`] of `first`'s, rounded down to a multiple of 16, and its height
/// `first`'s ratio of that width, rounded down to even, as a smaller mode's are, at `first`'s
/// rate and scale; `None` where it is no larger than `first` each way (a first mode under 48
/// pixels wide) or its scanout misses the display's `room` ([`laid_out`]).
fn larger_mode(first: Mode, room: u64) -> Option<Mode> {
let (w, h) = (u64::from(first.width), u64::from(first.height));
if w == 0 || h == 0 {
return None;
}
let width = (w * LARGER_MODE_STEP.0 / LARGER_MODE_STEP.1) & !15;
let height = (width * h / w) & !1;
let (Ok(width), Ok(height)) = (u32::try_from(width), u32::try_from(height)) else {
return None;
};
(width > first.width && height > first.height && laid_out(width, height) <= room).then_some(
Mode {
width,
height,
..first
},
)
}
/// The first mode of a display whose rate is set to `fixed` ([`Screen::fixed_rate`]), in
/// thousandths of a hertz, where its screen offers `mode`: `mode` at `fixed`, or at `mode`'s
/// own rate where `fixed` is above it, as the host's screen keeps running at its own and shows
/// no frame faster; `fixed` where the screen gives no rate. With no other rate, every size the
/// display offers is at that one ([`offered_modes`]). Whether `fixed` was above the screen's
/// rate, and so lowered to it, comes back beside the mode.
pub fn fixed_rate_mode(mode: Mode, fixed: u32) -> (Mode, bool) {
let clamped = mode.refresh_mhz > 0 && fixed > mode.refresh_mhz;
let refresh_mhz = if clamped { mode.refresh_mhz } else { fixed };
(
Mode {
refresh_mhz,
..mode
},
clamped,
)
}
/// The rates a display whose first mode runs at `current` offers besides it, of the `listed`
/// rates its screen lists at its size, in thousandths of a hertz: at most `most` of them, highest
/// first, each below `current` and more than [`RATES_APART_MHZ`] below `current` and below the
/// rate kept before it. As they are taken highest first, of rates closer than that the one
/// nearer `current` is kept.
fn other_rates(current: u32, listed: &[u32], most: usize) -> Vec<u32> {
let mut below: Vec<u32> = listed
.iter()
.copied()
.filter(|&rate| rate > 0 && current.saturating_sub(rate) > RATES_APART_MHZ)
.collect();
below.sort_unstable_by(|a, b| b.cmp(a));
let mut kept: Vec<u32> = Vec::new();
for rate in below {
if kept.len() == most {
break;
}
if kept
.last()
.is_none_or(|&last| last - rate > RATES_APART_MHZ)
{
kept.push(rate);
}
}
kept
}
/// A display mode: pixels each way and a refresh rate, and the scale of the host screen that
/// shows it.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
@@ -379,23 +246,6 @@ pub trait Screen: Send + Sync + 'static {
/// refresh, where a change is told to the guest.
fn mode(&self) -> Mode;
/// The other refresh rates, in thousandths of a hertz, that the screen showing the display
/// lists at its size, which the display offers each of its sizes at too ([`offered_modes`]):
/// for a borderless window, those of the screen it fills. Asked with [`Screen::mode`]. None
/// by default: the display offers its modes at [`Screen::mode`]'s rate alone.
fn rates(&self) -> Vec<u32> {
Vec::new()
}
/// The one refresh rate, in thousandths of a hertz, set for the display (a VM's refresh rate,
/// `reims-vgpu-window`'s `REIMS_VGPU_WINDOW_REFRESH_RATE`), which it then offers every size
/// at alone, in place of [`Screen::mode`]'s rate and [`Screen::rates`], and at most the
/// screen's rate ([`fixed_rate_mode`]). Asked with [`Screen::mode`]. None by default: the
/// display offers the screen's rates.
fn fixed_rate(&self) -> Option<u32> {
None
}
/// The guest set the pixels the display shows, or blanked it (`None`). The screen shows
/// them at once, and then at each refresh ([`Screen::present`]), across the device's resets,
/// until the guest sets others.
@@ -553,8 +403,8 @@ mod tests {
}
}
/// The modes a display offers for a screen of `width` x `height` at 2x on a device of `count`
/// displays, to a guest told the screen's scale, as sizes.
/// The modes a display offers for a screen of `width` x `height` on a device of `count`
/// displays, as sizes.
fn sizes(width: u32, height: u32, count: u32) -> Vec<(u32, u32)> {
let mode = Mode {
width,
@@ -562,16 +412,15 @@ mod tests {
refresh_mhz: 59_940,
scale_120ths: 240,
};
offered_modes(mode, &[], count, true)
offered_modes(mode, count)
.iter()
.map(|m| (m.width, m.height))
.collect()
}
/// A 4K screen is offered the modes a Mac lists for an external 4K screen, its own first, and
/// last the 5120 x 2880 a Mac draws "looks like 2560 x 1440" at; a screen of the Mac panel
/// four of the steps were read from is offered that panel's modes at those steps, and two of
/// the external screen's steps between them, then its larger mode
/// A 4K screen is offered the modes a Mac lists for an external 4K screen, its own first; a
/// screen of the Mac panel four of the steps were read from is offered that panel's modes at
/// those steps, and two of the external screen's steps between them
#[test]
fn a_display_offers_its_screen_s_ratio_at_a_mac_s_steps() {
assert_eq!(
@@ -583,8 +432,7 @@ mod tests {
(2880, 1620),
(2560, 1440),
(1920, 1080),
(1440, 810),
(5120, 2880)
(1440, 810)
]
);
assert_eq!(
@@ -596,8 +444,7 @@ mod tests {
(2304, 1440),
(2048, 1280),
(1536, 960),
(1152, 720),
(4096, 2560)
(1152, 720)
]
);
assert_eq!(
@@ -608,17 +455,15 @@ mod tests {
(2000, 1124),
(1920, 1080),
(1696, 954),
(1280, 720),
(3408, 1916)
(1280, 720)
]
);
}
/// Where its screen lists no other rate, every mode a display offers carries its first mode's
/// refresh rate and scale, the guest running at the host screen's rate whichever it picks; a
/// smaller mode is a multiple of 16 pixels wide and even high, smaller each way than the
/// first, and the one larger mode, last, the same steps at 4/3 of the first's width; each is
/// of the first's ratio to within those steps, and there are at most `MODES_MAX`
/// Every mode a display offers carries its first mode's refresh rate and scale, the guest
/// running at the host screen's rate whichever it picks; a smaller mode is a multiple of 16
/// pixels wide and even high, smaller each way than the first, and of its ratio to within
/// those steps; there are at most `MODES_MAX`
#[test]
fn every_mode_has_the_screen_s_rate_and_steps() {
for (w, h) in [
@@ -638,20 +483,14 @@ mod tests {
refresh_mhz: 143_912,
scale_120ths: 180,
};
let modes = offered_modes(mode, &[], count, true);
let modes = offered_modes(mode, count);
assert!(modes.len() <= MODES_MAX, "{w}x{h} on {count}");
assert_eq!(modes[0], offered_in_room(mode, count));
let (fw, fh) = (u64::from(modes[0].width), u64::from(modes[0].height));
for (i, m) in modes.iter().enumerate().skip(1) {
for m in &modes[1..] {
assert_eq!((m.refresh_mhz, m.scale_120ths), (143_912, 180));
assert_eq!((m.width % 16, m.height % 2), (0, 0), "{m:?} of {w}x{h}");
if m.width > modes[0].width {
assert_eq!(i, modes.len() - 1, "{m:?} of {w}x{h} on {count}");
assert_eq!(u64::from(m.width), (fw * 4 / 3) & !15, "{m:?} of {w}x{h}");
assert!(m.height > modes[0].height, "{m:?} of {w}x{h}");
} else {
assert!(m.width < modes[0].width && m.height < modes[0].height);
}
assert!(m.width < modes[0].width && m.height < modes[0].height);
assert!(laid_out(m.width, m.height) <= scanout_room(count));
// The first mode's height for the width, less under two rows.
let exact = u64::from(m.width) * fh / fw;
@@ -661,237 +500,12 @@ mod tests {
}
}
/// The rates of the modes `modes`, each once, in the order they first come.
fn rates_of(modes: &[Mode]) -> Vec<u32> {
let mut rates: Vec<u32> = Vec::new();
for m in modes {
if !rates.contains(&m.refresh_mhz) {
rates.push(m.refresh_mhz);
}
}
rates
}
/// A screen that lists other rates below its own offers every size again at each of them,
/// highest first, after its sizes at its own rate, which come first as they do with no other
/// rate, and its larger size last at each rate: a 3840 x 2400 panel at 120 Hz, which lists
/// 60 too, offers its seven sizes at 120, then the seven at 60, then 5120 x 3200 at 120 and 60
#[test]
fn a_screen_s_other_rates_offer_every_size_again() {
let first = Mode {
width: 3840,
height: 2400,
refresh_mhz: 120_000,
scale_120ths: 240,
};
let alone = offered_modes(first, &[], 1, true);
assert_eq!(alone.len(), 8);
let modes = offered_modes(first, &[120_000, 60_000], 1, true);
assert_eq!(modes.len(), 16);
assert_eq!(modes[0], first, "the default first, at the screen's rate");
assert_eq!(modes[..7], alone[..7]);
for (at_60, at_120) in modes[7..14].iter().zip(&alone[..7]) {
let again = Mode {
refresh_mhz: 60_000,
..*at_120
};
assert_eq!(*at_60, again);
}
let larger = Mode {
width: 5120,
height: 3200,
..first
};
assert_eq!(alone[7], larger);
let larger_at_60 = Mode {
refresh_mhz: 60_000,
..larger
};
assert_eq!(modes[14..], [larger, larger_at_60]);
// With no other rate, or only the screen's own, the display offers what it did.
assert_eq!(offered_modes(first, &[120_000], 1, true), alone);
}
/// Of rates within 0.5 Hz of each other, the guest's kexts' tolerance, the one nearer the
/// screen's rate is kept, whatever order the screen lists them in; one within 0.5 Hz of the
/// screen's own, or above it, is not offered; seven sizes and the larger one take three rates
/// each, the highest: the M3 Max's ProMotion panel at 120 Hz offers 120, 60 and 50, and a
/// 4K screen at 60 Hz 60, 50 and 30
#[test]
fn rates_closer_than_the_kexts_tolerance_keep_the_one_nearer_the_screen_s() {
let mode = |width, height, refresh_mhz| Mode {
width,
height,
refresh_mhz,
scale_120ths: 240,
};
// Below 120 Hz: 60 rather than 59.94, listed either way round; 48 rather than 47.95.
for listed in [
[60_000, 59_940, 48_000, 47_952],
[59_940, 60_000, 47_952, 48_000],
] {
assert_eq!(other_rates(120_000, &listed, 9), [60_000, 48_000]);
}
// Rates more than 0.5 Hz apart are both kept; 0.5 Hz apart, the nearer alone.
assert_eq!(other_rates(120_000, &[60_000, 59_400], 9), [60_000, 59_400]);
assert_eq!(other_rates(120_000, &[60_000, 59_500], 9), [60_000]);
// At 60 Hz: 59.94 is the screen's own to the kexts, and 120 is above it.
assert_eq!(other_rates(60_000, &[120_000, 59_940, 50_000], 9), [50_000]);
// Unknown rates (0) count for nothing.
assert_eq!(other_rates(60_000, &[0, 30_000], 9), [30_000]);
// The M3 Max's panel, as CoreGraphics lists it (macOS 27.0.1).
let promotion = mode(3456, 2234, 120_000);
let listed = [120_000, 60_000, 59_940, 50_000, 48_000, 47_952];
let modes = offered_modes(promotion, &listed, 1, true);
let sizes = offered_modes(promotion, &[], 1, true).len();
assert_eq!(rates_of(&modes), [120_000, 60_000, 50_000]);
assert_eq!(modes.len(), sizes * 3);
// A 4K screen at 60 Hz, as KWin lists its modes of that size (read 2026-12-03).
let uhd = mode(3840, 2160, 60_000);
let listed = [
59_997, 60_000, 60_000, 59_940, 50_000, 30_000, 30_000, 29_970, 25_000, 24_000, 23_976,
];
let modes = offered_modes(uhd, &listed, 1, true);
assert_eq!(rates_of(&modes), [60_000, 50_000, 30_000]);
assert_eq!(modes.len(), 24);
}
/// However many rates a screen lists, a display offers at most `MODES_MAX` modes, and every
/// size it offers at each rate it offers, its first mode first (the larger mode a guest told
/// a dense screen's scale is offered after them:
/// `a_dense_screen_s_display_offers_a_larger_mode_after_every_other`)
#[test]
fn other_rates_hold_the_bound_and_every_size_takes_each() {
let listed: Vec<u32> = (1..=40).map(|hz| hz * 6_000).collect();
for (w, h) in [(3840, 2160), (1366, 768), (2160, 3840), (7680, 4320)] {
for count in 1..=crate::wire::RGFX_DISPLAYS_MAX {
let first = Mode {
width: w,
height: h,
refresh_mhz: 240_000,
scale_120ths: 240,
};
let sizes = offered_modes(first, &[], count, false);
let modes = offered_modes(first, &listed, count, false);
assert!(modes.len() <= MODES_MAX, "{w}x{h} on {count}");
assert_eq!(modes[..sizes.len()], sizes[..], "{w}x{h} on {count}");
assert_eq!(modes.len() % sizes.len(), 0, "{w}x{h} on {count}");
assert!(modes.len() / sizes.len() >= 3, "{w}x{h} on {count}");
for (i, m) in modes.iter().enumerate() {
let size = sizes[i % sizes.len()];
assert_eq!((m.width, m.height), (size.width, size.height));
assert_eq!(m.scale_120ths, 240);
}
}
}
}
/// On a screen above 1x, a display whose guest is told the screen's scale offers one larger
/// mode after every mode it offered before, at each of their rates: 4/3 of its first mode's
/// width, a 3840 x 2160 window's 5120 x 2880, the backing of "looks like 2560 x 1440". Every
/// mode before it keeps its place, the first, which the guest prefers, among them, so the
/// guest's kexts give each the ID they gave it before. At 1x (and before a screen shows the
/// display, at 0), or to a guest not told the scale, the display offers what it did; where
/// the larger mode's scanout misses the room, or it would not fit the bound beside every
/// rate, it is left out, never a rate or a smaller mode
#[test]
fn a_dense_screen_s_display_offers_a_larger_mode_after_every_other() {
let mode = |width, height, refresh_mhz, scale_120ths| Mode {
width,
height,
refresh_mhz,
scale_120ths,
};
// A 4K screen at 2.1 (252), alone and with the rates KWin lists at its size.
let uhd = mode(3840, 2160, 60_000, 252);
let untold = offered_modes(uhd, &[], 1, false);
assert_eq!(untold.len(), 7);
let told = offered_modes(uhd, &[], 1, true);
assert_eq!(told[..7], untold[..]);
assert_eq!(told[7..], [mode(5120, 2880, 60_000, 252)]);
let listed = [60_000, 50_000, 30_000];
let untold = offered_modes(uhd, &listed, 1, false);
let told = offered_modes(uhd, &listed, 1, true);
assert_eq!(told[..21], untold[..]);
assert_eq!(
told[21..],
[
mode(5120, 2880, 60_000, 252),
mode(5120, 2880, 50_000, 252),
mode(5120, 2880, 30_000, 252)
]
);
// At 1x none, from just above it (the kexts' HiDPI rule) one.
for (scale, more) in [(0, 0), (120, 0), (121, 1), (180, 1), (240, 1)] {
let first = mode(3840, 2160, 60_000, scale);
let told = offered_modes(first, &[], 1, true);
assert_eq!(told.len(), 7 + more, "at {scale}");
}
// Too large for the room of three displays (42.6 MiB), not for two (64 MiB).
assert_eq!(sizes(3840, 2160, 2).last(), Some(&(5120, 2880)));
assert_eq!(sizes(3840, 2160, 3).last(), Some(&(1440, 810)));
// Six sizes at four rates fill the bound: the larger mode is left out.
let six = mode(2560, 1440, 120_000, 240);
let listed = [100_000, 60_000, 50_000, 30_000];
let untold = offered_modes(six, &listed, 2, false);
assert_eq!(untold.len(), 24);
assert_eq!(offered_modes(six, &listed, 2, true), untold);
assert_eq!(offered_modes(six, &[], 2, true).len(), 7);
// No larger mode where the step gives no more pixels.
assert_eq!(sizes(16, 12, 1), [(16, 12)]);
// Any screen: the told list starts with the untold one and adds one size at most, larger
// each way, of the first's ratio and steps, in the room, at each of its rates in order.
let many: Vec<u32> = (1..=40).map(|hz| hz * 6_000).collect();
for (w, h) in [
(3840, 2160),
(3456, 2234),
(1366, 768),
(2160, 3840),
(7680, 4320),
] {
for count in 1..=crate::wire::RGFX_DISPLAYS_MAX {
for scale in [0, 120, 121, 180, 252] {
for listed in [&[][..], &[120_000, 60_000, 50_000][..], &many[..]] {
let first = mode(w, h, 144_000, scale);
let untold = offered_modes(first, listed, count, false);
let told = offered_modes(first, listed, count, true);
let case = format!("{w}x{h} on {count} at {scale}, {} rates", listed.len());
assert!(told.len() <= MODES_MAX, "{case}");
assert_eq!(told[..untold.len()], untold[..], "{case}");
let extra = &told[untold.len()..];
if extra.is_empty() {
continue;
}
assert!(scale > 120, "{case}");
assert_eq!(rates_of(extra), rates_of(&untold), "{case}");
assert_eq!(extra.len(), rates_of(&untold).len(), "{case}");
let (fw, fh) = (u64::from(untold[0].width), u64::from(untold[0].height));
for m in extra {
assert_eq!((m.width, m.height), (extra[0].width, extra[0].height));
assert_eq!(u64::from(m.width), (fw * 4 / 3) & !15, "{case}");
assert!(m.height > untold[0].height, "{case}");
assert_eq!((m.height % 2, m.scale_120ths), (0, scale), "{case}");
assert!(laid_out(m.width, m.height) <= scanout_room(count));
let exact = u64::from(m.width) * fh / fw;
assert!(exact - u64::from(m.height) < 2, "{case}");
}
}
}
}
}
}
/// Sizes of odd pixels, a fixed screen's (`resolution=`), take the steps too, each smaller
/// mode on even pixels; and a portrait screen's modes are its own ratio, the floor turned;
/// each larger mode is of the same steps and ratio
/// mode on even pixels; and a portrait screen's modes are its own ratio, the floor turned
#[test]
fn odd_and_portrait_screens_offer_their_own_ratio() {
assert_eq!(
sizes(1366, 768, 1),
[(1366, 768), (1184, 664), (1808, 1016)]
);
assert_eq!(sizes(1001, 777, 1), [(1001, 777), (864, 670), (1328, 1030)]);
assert_eq!(sizes(1366, 768, 1), [(1366, 768), (1184, 664)]);
assert_eq!(sizes(1001, 777, 1), [(1001, 777), (864, 670)]);
assert_eq!(
sizes(1080, 1920, 1),
[
@@ -899,8 +513,7 @@ mod tests {
(944, 1678),
(832, 1478),
(800, 1422),
(720, 1280),
(1440, 2560)
(720, 1280)
]
);
assert_eq!(
@@ -911,26 +524,19 @@ mod tests {
(1120, 1990),
(1072, 1904),
(960, 1706),
(720, 1280),
(1920, 3412)
(720, 1280)
]
);
}
/// No smaller mode is below 800 x 600, the smallest a Mac takes for its desktop (960 x 600
/// is at it); a screen's own mode is offered whatever its size, its smaller modes only where
/// a step reaches the floor, and on a screen above 1x its larger one after them
/// is at it); a screen's own mode is offered whatever its size, and alone where no step
/// reaches the floor
#[test]
fn no_smaller_mode_is_below_the_floor() {
assert_eq!(
sizes(1280, 800, 1),
[
(1280, 800),
(1120, 700),
(992, 620),
(960, 600),
(1696, 1060)
]
[(1280, 800), (1120, 700), (992, 620), (960, 600)]
);
assert_eq!(
sizes(1920, 1080, 1),
@@ -939,22 +545,18 @@ mod tests {
(1680, 944),
(1504, 846),
(1440, 810),
(1280, 720),
(2560, 1440)
(1280, 720)
]
);
assert_eq!(
sizes(1024, 768, 1),
[(1024, 768), (896, 672), (800, 600), (1360, 1020)]
);
assert_eq!(sizes(800, 600, 1), [(800, 600), (1056, 792)]);
assert_eq!(sizes(640, 480, 1), [(640, 480), (848, 636)]);
assert_eq!(sizes(1024, 768, 1), [(1024, 768), (896, 672), (800, 600)]);
assert_eq!(sizes(800, 600, 1), [(800, 600)]);
assert_eq!(sizes(640, 480, 1), [(640, 480)]);
assert_eq!(sizes(0, 0, 1), [(0, 0)]);
}
/// The first mode is sized to the display's room on a device of several, and the smaller
/// modes follow it; on a device of one a screen too large for the room is offered as it is,
/// and of its smaller modes, and its larger one, only those whose scanout the room holds
/// and of its smaller modes only those whose scanout the room holds
#[test]
fn smaller_modes_keep_to_the_display_s_room() {
assert_eq!(sizes(7680, 4320, 4), sizes(3840, 2160, 4));
@@ -970,8 +572,7 @@ mod tests {
(2032, 1142)
]
);
// 7168 x 7168, 6416 x 6416 and 6144 x 6144 miss the room's 128 MiB, and so does the
// larger 10912 x 10912.
// 7168 x 7168, 6416 x 6416 and 6144 x 6144 miss the room's 128 MiB.
assert_eq!(
sizes(8192, 8192, 1),
[(8192, 8192), (5456, 5456), (4096, 4096), (3072, 3072)]
+2 -2
View File
@@ -9,8 +9,8 @@
//! map that a guest vCPU's page fault waits behind. With the device's and the decoder's threads
//! kept 1 s, 345 graphics threads were made in 30 s of a WindowServer probe (car 12's B1), and 7
//! to 10 every 10 s in games, and a vCPU sat 30 ms or more in a page fault while one of those
//! threads was in `munmap` of 0x201000 bytes, inside an 81 ms guest frame (an RTX 5080 Laptop
//! host; measured).
//! threads was in `munmap` of 0x201000 bytes, inside an 81 ms guest frame (msi RTX 5080 host;
//! measured).
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};
+1
View File
@@ -33,6 +33,7 @@ pub mod managed;
pub mod ops;
pub mod region;
mod ring;
pub mod snapshot;
pub mod threads;
// The trip line's histograms are a host diagnostic: cbindgen leaves the module out of the wire header.
/// cbindgen:ignore
+4 -17
View File
@@ -202,17 +202,6 @@ pub const RGFX_VIDEO_RATE_VBR: u32 = 3;
/// [`RgfxVideoEncodeSettings::flags`]: `max_bitrate` over `max_bitrate_window_ms` is a hard
/// limit (VideoToolbox's `DataRateLimits`), not the rate control's peak alone.
pub const RGFX_VIDEO_ENCODE_HARD_LIMIT: u32 = 1 << 0;
/// [`RgfxVideoEncodeSettings::flags`]: the guest sends frames in the order it codes them, each
/// at its own `frame_index`, its place in display order, which may come before the place of a
/// frame sent ahead of it: one frame ahead at most, as a B picture's encoder sends its reference
/// before it. The host codes each frame as it comes, at its place: a reference where the place
/// is past every place since the last keyframe, and a picture no other predicts from where it
/// is not; and its SPS says that one frame may come out of display order. Without it, each
/// frame's place is past the last one's. Taken from a host whose
/// [`RgfxVideoEncodeCaps::flags`](crate::wire::RgfxVideoEncodeCaps) has
/// [`RGFX_VIDEO_ENCODE_CAP_REORDERED`](crate::wire::RGFX_VIDEO_ENCODE_CAP_REORDERED) for the
/// codec.
pub const RGFX_VIDEO_ENCODE_REORDERED: u32 = 1 << 1;
/// [`RgfxVideoEncodeSettings::entropy`]: H.264's CAVLC.
pub const RGFX_VIDEO_ENTROPY_CAVLC: u32 = 1;
@@ -220,10 +209,9 @@ pub const RGFX_VIDEO_ENTROPY_CAVLC: u32 = 1;
pub const RGFX_VIDEO_ENTROPY_CABAC: u32 = 2;
/// An encode session's settings, after an [`RgfxVideoOpEncode`] whose `settings_size` says so.
/// A change of the size, format, profile, level, entropy, B-frames, keyframe interval, colour or
/// [`RGFX_VIDEO_ENCODE_REORDERED`] starts a new sequence: the next access unit is a keyframe with
/// its parameter sets. The bitrates, QPs, quality and frame rate apply from the next frame, with
/// no keyframe.
/// A change of the size, format, profile, level, entropy, B-frames, keyframe interval or colour
/// starts a new sequence: the next access unit is a keyframe with its parameter sets. The
/// bitrates, QPs, quality and frame rate apply from the next frame, with no keyframe.
#[repr(C)]
#[derive(
Clone, Copy, Debug, Default, PartialEq, Eq, FromBytes, IntoBytes, Immutable, KnownLayout,
@@ -274,8 +262,7 @@ pub struct RgfxVideoEncodeSettings {
/// The speed and quality trade, 0 the fastest to 100 the best, which the host maps onto its
/// API's presets.
pub quality: u32,
/// `RGFX_VIDEO_ENCODE_*` settings bits: [`RGFX_VIDEO_ENCODE_HARD_LIMIT`],
/// [`RGFX_VIDEO_ENCODE_REORDERED`].
/// `RGFX_VIDEO_ENCODE_*` settings bits: [`RGFX_VIDEO_ENCODE_HARD_LIMIT`].
pub flags: u32,
/// The VUI's `colour_primaries` (ITU-T H.273), in the SPS the host packs.
pub color_primaries: u8,
+44
View File
@@ -60,6 +60,19 @@ pub struct Region {
}
/// A block's size and who holds it.
/// Serializable snapshot of a granted or shared BAR2 region block.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct RegionBlockSnapshot {
/// Byte offset inside BAR2.
pub offset: u64,
/// Block size in bytes.
pub size: u64,
/// Context IDs holding this block.
pub holders: Vec<u32>,
/// Whether this block was shared (`BLOCK_SHARE`).
pub shared: bool,
}
#[derive(Clone, Debug, PartialEq, Eq)]
struct Held {
size: u64,
@@ -213,6 +226,37 @@ impl Region {
}
/// No block is anyone's any more (the device's reset): the kext grants them again.
/// Exports all currently granted/shared BAR2 blocks for checkpointing.
pub fn export_blocks(&self) -> Vec<RegionBlockSnapshot> {
let blocks = self.blocks.lock();
blocks
.iter()
.map(|(&offset, held)| RegionBlockSnapshot {
offset,
size: held.size,
holders: held.holders.clone(),
shared: held.shared,
})
.collect()
}
/// Replaces the BAR2 block ledger from a checkpoint.
pub fn import_blocks(&self, snap: &[RegionBlockSnapshot]) {
let mut blocks = self.blocks.lock();
blocks.clear();
for b in snap {
blocks.insert(
b.offset,
Held {
size: b.size,
holders: b.holders.clone(),
shared: b.shared,
},
);
}
}
/// Revokes all active BAR2 region grants prior to snapshot restore.
pub fn revoke_all(&self) {
self.blocks.lock().clear();
}
+15
View File
@@ -202,6 +202,11 @@ impl Consumer {
self.count
}
/// Restores the host's consumed byte count from a checkpoint (BAR2 already holds header).
pub(crate) fn set_count(&mut self, count: u64) {
self.count = count;
}
/// The guest's published count (the ring's producer), read with an acquire load.
pub(crate) fn published_count(&self, region: &Region) -> u64 {
region
@@ -555,6 +560,16 @@ impl Producer {
}
/// Back to a ring nothing has passed through ([`RingAt::initialize`]), `consumer_idle` 0.
/// Returns the host's published byte count.
pub(crate) fn produced(&self) -> u64 {
self.count
}
/// Restores the host's published byte count from a checkpoint (BAR2 already holds header).
pub(crate) fn set_count(&mut self, count: u64) {
self.count = count;
}
pub(crate) fn reset(&mut self, region: &Region) {
self.count = 0;
self.at.initialize(region, false);
+367
View File
@@ -0,0 +1,367 @@
//! Binary snapshot codec for [`Device`](crate::Device) state (Layer B).
use crate::display::{CursorImage, Mode, Scanout};
use crate::region::RegionBlockSnapshot;
/// Serializable display state.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct DisplaySnapshot {
/// Active BAR2 scanout, if any.
pub scanout: Option<Scanout>,
/// Whether VBLANK delivery is enabled.
pub vblank: bool,
/// Whether the panel is off (`SET_DISPLAY_POWER`).
pub asleep: bool,
/// Refresh counter since reset.
pub refreshes: u64,
/// Last mode told to the guest.
pub told: Option<Mode>,
/// Whether a `DISPLAY_CHANGED` event is owed.
pub changed: bool,
/// Current guest cursor image, if any.
pub cursor_image: Option<CursorImage>,
}
/// Serializable per-command-queue ring state.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct QueueSnapshot {
/// Raw `RgfxQueueCreate` wire message bytes.
pub create_bytes: Vec<u8>,
/// Accepted `RGFX_QUEUE_*` flags.
pub flags: u32,
/// Highest message seqno taken off the queue's submission ring.
pub taken_seqno: u64,
/// Highest command-buffer seqno taken off the queue's submission ring.
pub taken_buffer_seqno: u64,
/// Host consumer byte count on the queue's submission ring.
pub submit_count: u64,
/// Whether the queue's submission ring was marked broken.
pub submit_broken: bool,
/// Host producer byte count on the queue's completion ring.
pub complete_count: u64,
}
/// Complete serializable snapshot of `reims_vgpu_graphics::Device` (BAR0/rings/displays/queues).
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct DeviceSnapshot {
/// `STATUS` register value.
pub status: u32,
/// Negotiated `DRIVER_FEATURES` bitmask.
pub driver_features: u64,
/// Negotiated `DRIVER_FEATURES_EXT` bitmask.
pub driver_features_ext: u32,
/// Control submission ring `control_done` count.
pub control_done: u64,
/// Control submission ring consumer byte count.
pub control_submit_count: u64,
/// Whether control submission ring is broken.
pub control_submit_broken: bool,
/// Control completion ring producer byte count.
pub control_completion_count: u64,
/// VideoToolbox ring producer byte count.
pub vt_ring_count: u64,
/// Doorbell page context bindings (`RGFX_REG_DOORBELL_PAGE_BIND`).
pub pages: Vec<u32>,
/// Per-display state.
pub displays: Vec<DisplaySnapshot>,
/// Active BAR2 granted/shared blocks.
pub region_blocks: Vec<RegionBlockSnapshot>,
/// Active per-queue rings.
pub queues: Vec<QueueSnapshot>,
}
fn put_u8(o: &mut Vec<u8>, v: u8) {
o.push(v);
}
fn put_u32(o: &mut Vec<u8>, v: u32) {
o.extend_from_slice(&v.to_le_bytes());
}
fn put_u64(o: &mut Vec<u8>, v: u64) {
o.extend_from_slice(&v.to_le_bytes());
}
fn put_bytes(o: &mut Vec<u8>, b: &[u8]) {
put_u64(o, b.len() as u64);
o.extend_from_slice(b);
}
fn get_u8(i: &mut &[u8]) -> Option<u8> {
let (&b, rest) = i.split_first()?;
*i = rest;
Some(b)
}
fn get_u32(i: &mut &[u8]) -> Option<u32> {
if i.len() < 4 {
return None;
}
let (a, rest) = i.split_at(4);
*i = rest;
Some(u32::from_le_bytes(a.try_into().ok()?))
}
fn get_u64(i: &mut &[u8]) -> Option<u64> {
if i.len() < 8 {
return None;
}
let (a, rest) = i.split_at(8);
*i = rest;
Some(u64::from_le_bytes(a.try_into().ok()?))
}
fn get_bytes(i: &mut &[u8]) -> Option<Vec<u8>> {
let n = usize::try_from(get_u64(i)?).ok()?;
if i.len() < n {
return None;
}
let (a, rest) = i.split_at(n);
*i = rest;
Some(a.to_vec())
}
fn checked_count(i: &mut &[u8], min_item_bytes: usize) -> Option<usize> {
let count = usize::try_from(get_u32(i)?).ok()?;
let min_bytes = min_item_bytes.max(1);
if count > i.len() / min_bytes {
return None;
}
Some(count)
}
fn read_vec<T>(
i: &mut &[u8],
min_item_bytes: usize,
mut f: impl FnMut(&mut &[u8]) -> Option<T>,
) -> Option<Vec<T>> {
let count = checked_count(i, min_item_bytes)?;
let mut out = Vec::with_capacity(count);
for _ in 0..count {
out.push(f(i)?);
}
Some(out)
}
impl DeviceSnapshot {
/// Encodes this device snapshot into `out`.
pub fn encode(&self, o: &mut Vec<u8>) {
put_u32(o, 2);
put_u32(o, self.status);
put_u64(o, self.driver_features);
put_u32(o, self.driver_features_ext);
put_u64(o, self.control_done);
put_u64(o, self.control_submit_count);
put_u8(o, u8::from(self.control_submit_broken));
put_u64(o, self.control_completion_count);
put_u64(o, self.vt_ring_count);
put_u32(o, self.pages.len() as u32);
for &p in &self.pages {
put_u32(o, p);
}
put_u32(o, self.displays.len() as u32);
for d in &self.displays {
match d.scanout {
Some(s) => {
put_u8(o, 1);
put_u32(o, s.width);
put_u32(o, s.height);
put_u32(o, s.stride);
put_u64(o, s.offset);
}
None => put_u8(o, 0),
}
put_u8(o, u8::from(d.vblank));
put_u8(o, u8::from(d.asleep));
put_u64(o, d.refreshes);
match d.told {
Some(m) => {
put_u8(o, 1);
put_u32(o, m.width);
put_u32(o, m.height);
put_u32(o, m.refresh_mhz);
put_u32(o, m.scale_120ths);
}
None => put_u8(o, 0),
}
put_u8(o, u8::from(d.changed));
match &d.cursor_image {
Some(c) => {
put_u8(o, 1);
put_u32(o, c.width);
put_u32(o, c.height);
put_u32(o, c.hot_spot.0);
put_u32(o, c.hot_spot.1);
put_bytes(o, &c.rgba);
}
None => put_u8(o, 0),
}
}
put_u32(o, self.region_blocks.len() as u32);
for b in &self.region_blocks {
put_u64(o, b.offset);
put_u64(o, b.size);
put_u8(o, u8::from(b.shared));
put_u32(o, b.holders.len() as u32);
for &h in &b.holders {
put_u32(o, h);
}
}
put_u32(o, self.queues.len() as u32);
for q in &self.queues {
put_bytes(o, &q.create_bytes);
put_u32(o, q.flags);
put_u64(o, q.taken_seqno);
put_u64(o, q.taken_buffer_seqno);
put_u64(o, q.submit_count);
put_u8(o, u8::from(q.submit_broken));
put_u64(o, q.complete_count);
}
}
/// Decodes a device snapshot from `i`.
pub fn decode(i: &mut &[u8]) -> Option<Self> {
let version = get_u32(i)?;
if !matches!(version, 1 | 2) {
return None;
}
let status = get_u32(i)?;
let driver_features = get_u64(i)?;
let driver_features_ext = if version == 2 { get_u32(i)? } else { 0 };
let control_done = get_u64(i)?;
let control_submit_count = get_u64(i)?;
let control_submit_broken = get_u8(i)? != 0;
let control_completion_count = get_u64(i)?;
let vt_ring_count = get_u64(i)?;
let pages = read_vec(i, 4, get_u32)?;
let displays = read_vec(i, 14, |i| {
let scanout = if get_u8(i)? != 0 {
Some(Scanout {
width: get_u32(i)?,
height: get_u32(i)?,
stride: get_u32(i)?,
offset: get_u64(i)?,
})
} else {
None
};
let vblank = get_u8(i)? != 0;
let asleep = get_u8(i)? != 0;
let refreshes = get_u64(i)?;
let told = if get_u8(i)? != 0 {
Some(Mode {
width: get_u32(i)?,
height: get_u32(i)?,
refresh_mhz: get_u32(i)?,
scale_120ths: get_u32(i)?,
})
} else {
None
};
let changed = get_u8(i)? != 0;
let cursor_image = if get_u8(i)? != 0 {
Some(CursorImage {
width: get_u32(i)?,
height: get_u32(i)?,
hot_spot: (get_u32(i)?, get_u32(i)?),
rgba: get_bytes(i)?,
})
} else {
None
};
Some(DisplaySnapshot {
scanout,
vblank,
asleep,
refreshes,
told,
changed,
cursor_image,
})
})?;
let region_blocks = read_vec(i, 21, |i| {
let offset = get_u64(i)?;
let size = get_u64(i)?;
let shared = get_u8(i)? != 0;
let holders = read_vec(i, 4, get_u32)?;
Some(RegionBlockSnapshot {
offset,
size,
holders,
shared,
})
})?;
let queues = read_vec(i, 45, |i| {
Some(QueueSnapshot {
create_bytes: get_bytes(i)?,
flags: get_u32(i)?,
taken_seqno: get_u64(i)?,
taken_buffer_seqno: get_u64(i)?,
submit_count: get_u64(i)?,
submit_broken: get_u8(i)? != 0,
complete_count: get_u64(i)?,
})
})?;
Some(DeviceSnapshot {
status,
driver_features,
driver_features_ext,
control_done,
control_submit_count,
control_submit_broken,
control_completion_count,
vt_ring_count,
pages,
displays,
region_blocks,
queues,
})
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn decode_rejects_oversized_counts_without_allocating() {
// The fixed fields in version 2 occupy 53 bytes.
let mut base = Vec::new();
let empty = DeviceSnapshot {
status: 1,
driver_features: 2,
driver_features_ext: 1,
control_done: 3,
control_submit_count: 4,
control_submit_broken: false,
control_completion_count: 5,
vt_ring_count: 6,
pages: vec![],
displays: vec![],
region_blocks: vec![],
queues: vec![],
};
empty.encode(&mut base);
let mut s = base.as_slice();
assert_eq!(DeviceSnapshot::decode(&mut s), Some(empty.clone()));
assert!(s.is_empty());
let mut legacy = base.clone();
legacy[..4].copy_from_slice(&1u32.to_le_bytes());
legacy.drain(16..20);
let mut legacy = legacy.as_slice();
let mut legacy_device = empty;
legacy_device.driver_features_ext = 0;
assert_eq!(DeviceSnapshot::decode(&mut legacy), Some(legacy_device));
assert!(legacy.is_empty());
// Overwrite each of the 4 top-level collection counts with u32::MAX.
for offset in [53usize, 57, 61, 65] {
let mut bad = base.clone();
bad[offset..offset + 4].copy_from_slice(&u32::MAX.to_le_bytes());
let mut sl = bad.as_slice();
assert!(
DeviceSnapshot::decode(&mut sl).is_none(),
"offset {offset} must fail"
);
}
}
}
+8 -53
View File
@@ -723,20 +723,18 @@ pub const RGFX_REG_POOL_LENGTH_HI: u32 = 0x050;
/// it, and a host then says nothing of the bundle.
pub const RGFX_REG_GUEST_BUNDLE: u32 = 0x054;
/// `FEATURES_EXT`, RO: feature bits 64 to 95 the host offers. The guest uses each with no take,
/// but those [`RGFX_REG_DRIVER_FEATURES_EXT`] takes ([`RGFX_FEATURE_EXT_SURFACE_HOLD`],
/// [`RGFX_FEATURE_EXT_DISPLAY_RATE`]): a guest that sees one of the others may send the messages
/// it names, and the host carries out nothing else for a guest that does, so a guest that never
/// reads it gets the wire it had before. It reads [`RGFX_FEATURE_EXT_SHARED_TEXTURE_NAMES`],
/// [`RGFX_FEATURE_EXT_SURFACE_HOLD`] and [`RGFX_FEATURE_EXT_DISPLAY_RATE`] where the host offers
/// them; 0 from a host older than it, as at any offset a host does not know. A write
/// but those [`RGFX_REG_DRIVER_FEATURES_EXT`] takes ([`RGFX_FEATURE_EXT_SURFACE_HOLD`]): a guest
/// that sees one of the others may send the messages it names, and the host carries out nothing
/// else for a guest that does, so a guest that never reads it gets the wire it had before. It
/// reads [`RGFX_FEATURE_EXT_SHARED_TEXTURE_NAMES`] and [`RGFX_FEATURE_EXT_SURFACE_HOLD`] where the
/// host offers them; 0 from a host older than it, as at any offset a host does not know. A write
/// is ignored. Bit 1 is offered by no host: hosts built before the hold word left the block's
/// header offered `SURFACE_HOLD` there, with the word in the header, and kexts built before it
/// take it; a write of it takes nothing, so such a kext and this host, or this kext and such a
/// host, take no hold.
pub const RGFX_REG_FEATURES_EXT: u32 = 0x058;
/// `DRIVER_FEATURES_EXT`, RW: the feature bits 64 to 95 the guest's driver took of those
/// `FEATURES_EXT` offers that are taken ([`RGFX_FEATURE_EXT_SURFACE_HOLD`],
/// [`RGFX_FEATURE_EXT_DISPLAY_RATE`]). A write takes the
/// `FEATURES_EXT` offers that are taken ([`RGFX_FEATURE_EXT_SURFACE_HOLD`]). A write takes the
/// bits written that `FEATURES_EXT` offers and that are taken, and a read answers the bits taken.
/// As at `DRIVER_FEATURES_LO`, a write while `STATUS` reads [`RGFX_STATUS_DRIVER_READY`] is
/// ignored, and a reset clears it. A guest that never writes it (the option ROM, a kext built
@@ -793,23 +791,6 @@ pub const RGFX_SURFACE_HOLD_RAISED: u32 = 1 << 0;
/// The hold word's bit a read-write CPU lock sets beside [`RGFX_SURFACE_HOLD_RAISED`] while it
/// waits ([`RGFX_FEATURE_EXT_SURFACE_HOLD`]), which the host counts.
pub const RGFX_SURFACE_HOLD_WAITED: u32 = 1 << 1;
/// `FEATURES_EXT` bit 3, feature bit 67, `DISPLAY_RATE`, taken in
/// [`RGFX_REG_DRIVER_FEATURES_EXT`]. Where the guest took it:
/// - **Other rates.** A display whose host screen lists other refresh rates at its size (a
/// borderless window's screen) offers its sizes again at those below the screen's own, after
/// its modes at the screen's rate, each more than 0.5 Hz from the screen's rate and from the
/// others (`display::offered_modes`), and tells the guest with `DISPLAY_CHANGED` when they
/// change, as for a change of its size.
/// - **The rate set.** Ring 0 carries [`RGFX_CMD_SET_DISPLAY_RATE`], the rate of the mode the
/// guest set, which it sends after each `SET_SCANOUT` of a mode. The host paces the display's
/// refreshes at that rate, its `VBLANK`s and the presents it answers at them among them, while
/// the display offers a mode at that rate, and at its first mode's rate otherwise, at once
/// when the display stops offering it.
///
/// A guest that does not take it is offered each size at the first mode's rate alone, and its
/// display runs at that rate, as before. Every host offers it; the x86-64 and arm64e kexts take
/// it.
pub const RGFX_FEATURE_EXT_DISPLAY_RATE: u32 = 1 << 3;
/// A [`RGFX_REG_GUEST_BUNDLE`] value's bundle field: the kext's own version's bundle is on disk,
/// and the accelerator registered for it.
pub const RGFX_GUEST_BUNDLE_OURS: u32 = 1;
@@ -1075,9 +1056,6 @@ pub const RGFX_CMD_SCROLL_DEVICES: u32 = 11;
/// Command `HIDDEN_PLACES` ([`RgfxHiddenPlaces`]), where the guest took
/// [`RGFX_FEATURE_POINTER_MOTION`]: not answered.
pub const RGFX_CMD_HIDDEN_PLACES: u32 = 12;
/// Command `SET_DISPLAY_RATE` ([`RgfxSetDisplayRate`]), where the guest took
/// [`RGFX_FEATURE_EXT_DISPLAY_RATE`]: answered by [`RGFX_EVT_COMPLETE`].
pub const RGFX_CMD_SET_DISPLAY_RATE: u32 = 13;
/// Event `COMPLETE` ([`RgfxComplete`]): a command's answer, with its `seqno`.
pub const RGFX_EVT_COMPLETE: u32 = 0x100;
/// Event `DISPLAYS` ([`RgfxDisplays`]): `GET_DISPLAYS`'s answer, with its `seqno`.
@@ -1972,24 +1950,6 @@ pub struct RgfxSetDisplayPower {
pub on: u32,
}
/// `SET_DISPLAY_RATE`: the mode the guest set on display `display` runs at `refresh_mhz`
/// thousandths of a hertz, a rate of a mode the display offered it
/// ([`RGFX_FEATURE_EXT_DISPLAY_RATE`]). The guest sends it after each `SET_SCANOUT` of a mode.
/// The host paces the display's refreshes at that rate while the display offers a mode at it, and
/// at its first mode's rate otherwise; a reset forgets it.
#[repr(C)]
#[derive(
Clone, Copy, Debug, Default, PartialEq, Eq, FromBytes, IntoBytes, Immutable, KnownLayout,
)]
pub struct RgfxSetDisplayRate {
/// [`RGFX_CMD_SET_DISPLAY_RATE`].
pub header: RgfxMsgHeader,
/// The display's id.
pub display: u32,
/// The rate of the mode set, in thousandths of a hertz.
pub refresh_mhz: u32,
}
/// `DISPLAY_BOUNDS`: display `display` lies at (`min_x`, `min_y`) up to (`max_x`, `max_y`), the
/// corner past it, of the guest's desktop: WindowServer's global space, in points, where the
/// guest arranged its displays (the x86-64 kext's framebuffer's `getBoundingRect`). The guest
@@ -2551,7 +2511,6 @@ const _: () = {
assert!(offset_of!(RgfxPointerMotion, buttons) == 28);
assert!(size_of::<RgfxScrollDevices>() == 24);
assert!(size_of::<RgfxHiddenPlaces>() == 24);
assert!(size_of::<RgfxSetDisplayRate>() == 24);
assert!(size_of::<RgfxPointerLook>() == 24);
assert!(offset_of!(RgfxPointerLook, display) == 16);
assert!(size_of::<RgfxScroll>() == 32);
@@ -5486,8 +5445,8 @@ pub struct RgfxVideoEncodeCaps {
/// The most consecutive B pictures an encode takes
/// ([`RgfxVideoEncodeSettings::b_frames`](crate::ops::video::RgfxVideoEncodeSettings)).
pub max_b_frames: u32,
/// `RGFX_VIDEO_ENCODE_CAP_*`: [`RGFX_VIDEO_ENCODE_CAP_IN_PLACE`],
/// [`RGFX_VIDEO_ENCODE_CAP_REORDERED`]. Zero from a host older than these.
/// `RGFX_VIDEO_ENCODE_CAP_*`: [`RGFX_VIDEO_ENCODE_CAP_IN_PLACE`]. Zero from a host older
/// than these.
pub flags: u32,
/// Zero.
pub reserved_0c: u32,
@@ -5498,10 +5457,6 @@ pub struct RgfxVideoEncodeCaps {
/// no B pictures.
pub const RGFX_VIDEO_ENCODE_CAP_IN_PLACE: u32 = 1 << 0;
/// [`RgfxVideoEncodeCaps::flags`]: the host takes frames in the order the guest codes them
/// ([`RGFX_VIDEO_ENCODE_REORDERED`](crate::ops::video::RGFX_VIDEO_ENCODE_REORDERED)).
pub const RGFX_VIDEO_ENCODE_CAP_REORDERED: u32 = 1 << 1;
/// What the host's hardware takes of one decode codec beside its [`RgfxVideoCodecCaps`], by the
/// same index ([`RgfxVideoCaps::decode`]): the bounds of a picture the host refuses, which the
/// guest's video driver checks before it schedules the picture. All zero for an encode entry,
@@ -56,9 +56,6 @@ CHECK(RGFX_FEATURE_POINTER_MOTION == (1ULL << 51));
CHECK(RGFX_CMD_SCROLL_DEVICES == 11 && sizeof(RgfxScrollDevices) == 24);
CHECK(RGFX_EVT_SCROLL == 0x106 && sizeof(RgfxScroll) == 32);
CHECK(RGFX_CMD_HIDDEN_PLACES == 12 && sizeof(RgfxHiddenPlaces) == 24);
CHECK(RGFX_CMD_SET_DISPLAY_RATE == 13 && sizeof(RgfxSetDisplayRate) == 24);
CHECK(offsetof(RgfxSetDisplayRate, refresh_mhz) == 20);
CHECK(RGFX_FEATURE_EXT_DISPLAY_RATE == (1u << 3));
CHECK(RGFX_EVT_POINTER_LOOK == 0x107 && sizeof(RgfxPointerLook) == 24);
CHECK(offsetof(RgfxPointerLook, display) == 16);
CHECK(offsetof(RgfxScroll, fine_up) == 24);
@@ -1,35 +0,0 @@
//! Writes the self-checking stream's pictures as `yuv420p` raw video on stdout, for an encoder to
//! read (`tools/selfcheck.sh`): `selfcheck-frames WIDTH HEIGHT FRAMES`.
use std::io::Write as _;
use std::process::ExitCode;
use reims_vgpu_video_conformance::selfcheck::picture;
fn main() -> ExitCode {
let args: Vec<String> = std::env::args().skip(1).collect();
let numbers: Vec<u64> = args.iter().filter_map(|a| a.parse().ok()).collect();
let [width, height, frames] = numbers[..] else {
eprintln!("usage: selfcheck-frames WIDTH HEIGHT FRAMES");
return ExitCode::from(2);
};
let (Ok(width), Ok(height)) = (u32::try_from(width), u32::try_from(height)) else {
eprintln!("selfcheck-frames: a size past 2^32");
return ExitCode::from(2);
};
if width % 2 != 0 || height % 2 != 0 || width < 16 || height < 9 {
eprintln!("selfcheck-frames: the size must be even, at least 16 by 9");
return ExitCode::from(2);
}
let mut out = std::io::BufWriter::new(std::io::stdout().lock());
for n in 0..frames {
if out.write_all(&picture(n, width, height).bytes()).is_err() {
eprintln!("selfcheck-frames: stdout closed at frame {n}");
return ExitCode::FAILURE;
}
}
if out.flush().is_err() {
return ExitCode::FAILURE;
}
ExitCode::SUCCESS
}
@@ -1,98 +0,0 @@
//! Judges a file's frames, read as `yuv420p` raw video of WIDTH by HEIGHT from stdin, as ffmpeg
//! decodes them (`tools/selfcheck.sh judge`): each faulty frame a line, then the summary line,
//! and exit 1 where any frame has a fault.
//!
//! ```text
//! selfcheck-judge WIDTH HEIGHT [--recording] [--crop X,Y,W,H] [--frames N]
//! ```
//!
//! `--recording` judges a recording of the stream's playback, its picture in the crop's region
//! of each frame (the whole frame without one); `--frames` is the stream's length.
use std::io::Read as _;
use std::process::ExitCode;
use reims_vgpu_video_conformance::selfcheck::{Frame, Judge, Mode, Region};
/// The lines of faulty frames it prints, before it says only how many more.
const LINES: usize = 200;
fn usage() -> ExitCode {
eprintln!(
"usage: selfcheck-judge WIDTH HEIGHT [--recording] [--crop X,Y,W,H] [--frames N] < yuv420p"
);
ExitCode::from(2)
}
fn main() -> ExitCode {
let args: Vec<String> = std::env::args().skip(1).collect();
let (Some(width), Some(height)) = (
args.first().and_then(|a| a.parse::<u32>().ok()),
args.get(1).and_then(|a| a.parse::<u32>().ok()),
) else {
return usage();
};
let (mut mode, mut region, mut frames) = (Mode::File, None, None);
let mut rest = args.iter().skip(2);
while let Some(arg) = rest.next() {
match arg.as_str() {
"--recording" => mode = Mode::Recording,
"--crop" => {
let parts: Vec<u32> = (rest.next().map(String::as_str).unwrap_or(""))
.split(',')
.filter_map(|p| p.parse().ok())
.collect();
let [x, y, width, height] = parts[..] else {
return usage();
};
region = Some(Region {
x,
y,
width,
height,
});
}
"--frames" => match rest.next().and_then(|n| n.parse().ok()) {
Some(n) => frames = Some(n),
None => return usage(),
},
_ => return usage(),
}
}
let (w, h) = (width as usize, height as usize);
let size = w * h + 2 * (w / 2 * (h / 2));
let mut judge = Judge::new(mode, region, frames);
let mut input = std::io::stdin().lock();
let mut bytes = vec![0; size];
let mut said = 0;
loop {
match input.read_exact(&mut bytes) {
Ok(()) => {}
Err(error) if error.kind() == std::io::ErrorKind::UnexpectedEof => break,
Err(error) => {
eprintln!("selfcheck-judge: stdin: {error}");
return ExitCode::FAILURE;
}
}
let Some(frame) = Frame::from_bytes(width, height, &bytes) else {
return usage();
};
let call = judge.frame(&frame);
if !call.faults.is_empty() {
if said < LINES {
println!("{}", call.line());
}
said += 1;
}
}
if said > LINES {
println!("... {} more faulty frames", said - LINES);
}
let verdict = judge.verdict();
println!("{}", verdict.line);
if verdict.pass {
ExitCode::SUCCESS
} else {
ExitCode::FAILURE
}
}
@@ -7,12 +7,8 @@
//! - [`md5`] hashes frames, as ffmpeg's `framemd5` does.
//! - [`marks`] reads what the conformance suite's scripts say of their streams beside them, the
//! streams the decoder refuses, and holds a test's decode of each to it.
//! - [`selfcheck`] draws the self-checking stream's pictures, each carrying its own frame
//! number, and judges a decode or a recording of it frame by frame
//! (`tools/selfcheck.sh`).
pub mod marks;
pub mod md5;
pub mod mp4;
pub mod mp4_write;
pub mod selfcheck;
@@ -1,861 +0,0 @@
//! A self-checking stream: each picture carries its own frame number and what the rest of it
//! should look like, so that a decode of the stream, or a screen recording of its playback, is
//! judged frame by frame from its pixels alone, with no reference decode. `tools/selfcheck.sh`
//! encodes the pictures [`picture`] draws with ffmpeg's encoders and judges a file's frames, as
//! ffmpeg decodes them, with [`Judge`].
//!
//! **The picture** is a grid of [`COLUMNS`] by [`ROWS`] cells, of any size:
//! - three code bands, at the top (rows 0 and 1), the middle (3 and 4) and the bottom (7 and 8):
//! each a row of a black and a white reference cell and the frame number's [`BITS`] bits,
//! most significant first, white for 1, then a row of a white and a black cell and the bits'
//! complement. Code cells are grey: their chroma is 128;
//! - two rows of flat cells (2 and 5), each cell's luma and chroma levels drawn from its index
//! and the frame's number over eight ([`content_cell`]), at a phase of its own, so a cell keeps
//! its levels eight frames and about four of the 32 change each frame: most of a picture is
//! its references', and a picture built from a wrong or stale reference shows it. A cell's
//! levels are one of [`CELL_COLOURS`], the combinations of the levels whose colour lies inside
//! 8-bit RGB under both the BT.709 and the BT.601 matrix: a player shows a picture in RGB and a
//! screen recording takes it back from RGB, and a colour outside would come back clipped, far
//! from its levels;
//! - a row of stripes (6), [`STRIPES`] across the picture, each of a luma level of its own,
//! moving a fifteenth of a stripe a frame ([`stripe_at`]), for the encoders' motion vectors.
//!
//! The frame number is the frame's index modulo [`PERIOD`]; the judge unwraps it from frame to
//! frame.
//!
//! **The judge** reads a frame's region the picture lies in: the whole frame for a decoded file,
//! or a region of a recording's frame given by its caller. It takes the reference cells' luma for
//! black and white, reads each band's number where its bits and their complement agree, and
//! checks every flat cell and the stripes against the number's picture. Each frame is called
//! ([`Call`]): its number, and its faults: [`Fault::Green`] (most of it the colour of a picture
//! of zeros: luma, Cb and Cr each under 64, as `rec-judge.py` measures a recording),
//! [`Fault::PartGreen`] (some of it), [`Fault::Unreadable`] (no band reads), [`Fault::Torn`] (the
//! bands disagree, or one does not read), [`Fault::Wrong`] (cells whose levels are not the
//! number's picture's), and, from the frames before it, [`Fault::Repeated`] (a number shown
//! before) and [`Fault::OutOfOrder`] (a number below the last). The numbers no frame showed,
//! between the first a pass through the stream showed (a decode's: 0) and its last (a decode's
//! of a stream of known length: the stream's last), are dropped, counted by their runs
//! ([`Verdict`]). A recording shows each picture as many frames as the screen holds it, so a
//! recording's judge takes a number shown again by the frame before as held, not repeated, and
//! the frames before its first number and after its last as outside the stream; and where the
//! stream's length is known, a recording that goes from its last frames to its first has looped,
//! which starts a pass and is no fault.
/// The grid's columns.
pub const COLUMNS: u32 = 16;
/// The grid's rows.
pub const ROWS: u32 = 9;
/// The bits of the frame number each band carries.
pub const BITS: u32 = 14;
/// The frame numbers: a frame's is its index modulo this.
pub const PERIOD: u64 = 1 << BITS;
/// The stripes across the picture in its stripes row.
pub const STRIPES: u64 = 32;
/// A code cell's black and white luma.
const BLACK: u8 = 16;
const WHITE: u8 = 235;
/// A flat cell's or a stripe's luma levels, 50 apart.
const LUMA_LEVELS: [u8; 4] = [40, 90, 140, 190];
/// A flat cell's chroma levels, 48 apart.
#[cfg_attr(
not(test),
expect(dead_code, reason = "only the test of `CELL_COLOURS` reads it")
)]
const CHROMA_LEVELS: [u8; 3] = [80, 128, 176];
/// A flat cell's luma, Cb and Cr: every combination of [`LUMA_LEVELS`] and [`CHROMA_LEVELS`]
/// whose colour, at limited range, lies [`RGB_MARGIN`] or more inside 8-bit RGB's 0 to 255 under
/// both the BT.709 and the BT.601 matrix (`tests::cell_colours_are_the_combinations_inside_rgb`
/// keeps the list equal to that set), so that a player that shows the picture in RGB by either
/// matrix, and a recording that takes it back, leave each cell's levels within the judge's slack.
pub const CELL_COLOURS: [(u8, u8, u8); 18] = [
(40, 128, 128),
(40, 176, 128),
(90, 128, 128),
(90, 128, 176),
(90, 176, 128),
(90, 176, 176),
(140, 80, 80),
(140, 80, 128),
(140, 80, 176),
(140, 128, 80),
(140, 128, 128),
(140, 128, 176),
(140, 176, 80),
(140, 176, 128),
(140, 176, 176),
(190, 80, 128),
(190, 128, 80),
(190, 128, 128),
];
/// How far inside 8-bit RGB's 0 to 255 each of [`CELL_COLOURS`] lies: room for a lossy codec's
/// noise before a channel clips.
pub const RGB_MARGIN: f64 = 8.0;
/// How far a cell's luma may lie from its level, on the scale the references set, and its
/// chroma from its level: half the levels' spacing.
const LUMA_SLACK: f64 = 25.0;
const CHROMA_SLACK: f64 = 24.0;
/// The rows of the bands' numbers; each band's complement is the row below.
const BAND_ROWS: [u32; 3] = [0, 3, 7];
/// The rows of flat cells.
const CONTENT_ROWS: [u32; 2] = [2, 5];
/// The row of stripes.
const STRIPES_ROW: u32 = 6;
/// The frames a flat cell keeps its levels.
const CELL_EPOCH: u64 = 8;
/// A stripe's moves a frame: a fifteenth of its width.
const STRIPE_STEPS: u64 = 15;
/// The share of a frame's samples of zeros' colour that makes it green, and part green.
const GREEN_SHARE: f64 = 0.5;
const PART_GREEN_SHARE: f64 = 0.005;
/// A picture in three planes, 4:2:0, 8 bits: `yuv420p`.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Frame {
/// Its width, even.
pub width: u32,
/// Its height, even.
pub height: u32,
/// Luma, `width` by `height`.
pub y: Vec<u8>,
/// Cb, half each way.
pub u: Vec<u8>,
/// Cr, half each way.
pub v: Vec<u8>,
}
impl Frame {
/// A frame of `width` by `height` of one colour.
pub fn filled(width: u32, height: u32, (y, u, v): (u8, u8, u8)) -> Frame {
let (w, h) = (width as usize, height as usize);
Frame {
width,
height,
y: vec![y; w * h],
u: vec![u; w / 2 * (h / 2)],
v: vec![v; w / 2 * (h / 2)],
}
}
/// Its bytes as `yuv420p` raw video holds a frame: luma, Cb, Cr.
pub fn bytes(&self) -> Vec<u8> {
let mut bytes = Vec::with_capacity(self.y.len() + self.u.len() + self.v.len());
bytes.extend_from_slice(&self.y);
bytes.extend_from_slice(&self.u);
bytes.extend_from_slice(&self.v);
bytes
}
/// The frame `bytes` holds as `yuv420p` raw video of `width` by `height`; `None` where they
/// are not that long.
pub fn from_bytes(width: u32, height: u32, bytes: &[u8]) -> Option<Frame> {
let (w, h) = (width as usize, height as usize);
let (luma, chroma) = (w * h, w / 2 * (h / 2));
if bytes.len() != luma + 2 * chroma {
return None;
}
Some(Frame {
width,
height,
y: bytes[..luma].to_vec(),
u: bytes[luma..luma + chroma].to_vec(),
v: bytes[luma + chroma..].to_vec(),
})
}
/// Its luma at (`x`, `y`).
fn luma(&self, x: u32, y: u32) -> u8 {
self.y[(y * self.width + x) as usize]
}
/// Its chroma (Cb, Cr) at luma's (`x`, `y`).
fn chroma(&self, x: u32, y: u32) -> (u8, u8) {
let at = ((y / 2) * (self.width / 2) + x / 2) as usize;
(self.u[at], self.v[at])
}
}
/// A small mixing hash: the levels a cell or stripe takes.
fn mix(a: u64, b: u64) -> u64 {
let mut x = a.wrapping_mul(0x9e37_79b9_7f4a_7c15) ^ b.wrapping_add(0x632b_e59b_d9b4_e019);
x ^= x >> 31;
x = x.wrapping_mul(0xbf58_476d_1ce4_e5b9);
x ^= x >> 29;
x
}
/// The luma, Cb and Cr of flat cell `cell` (0 to 31, row 2's then row 5's, left to right) in
/// frame `n`, one of [`CELL_COLOURS`]: its levels change every [`CELL_EPOCH`] frames, at a phase
/// of its own.
pub fn content_cell(n: u64, cell: u64) -> (u8, u8, u8) {
let n = n % PERIOD;
let epoch = (n + 3 * cell) / CELL_EPOCH;
let h = mix(cell + 1, epoch);
CELL_COLOURS[(h % CELL_COLOURS.len() as u64) as usize]
}
/// The stripe at `x` of a picture `width` wide in frame `n`, and where in it `x` lies, as a
/// fraction of its width: [`STRIPES`] across the picture, moving a fifteenth of a stripe a frame.
pub fn stripe_at(n: u64, x: f64, width: f64) -> (u64, f64) {
let n = n % PERIOD;
let at = STRIPES as f64 * x / width + n as f64 / STRIPE_STEPS as f64;
(at.floor() as u64, at.fract())
}
/// A stripe's luma.
pub fn stripe_luma(stripe: u64) -> u8 {
LUMA_LEVELS[(mix(0x5717_93e5, stripe) % 4) as usize]
}
/// What a code cell holds: its luma, at `column` of band row `row`, or of the complement row
/// below it where `complement`, in frame `n`.
fn code_cell(n: u64, column: u32, complement: bool) -> u8 {
let n = n % PERIOD;
let white = match column {
0 => complement,
1 => !complement,
_ => {
let bit = (n >> (BITS - 1 - (column - 2))) & 1 == 1;
bit != complement
}
};
if white { WHITE } else { BLACK }
}
/// The first luma column of grid column `column` of a picture `width` wide, and likewise rows.
fn edge(at: u32, cells: u32, size: u32) -> u32 {
(u64::from(at) * u64::from(size) / u64::from(cells)) as u32
}
/// Frame `n`'s picture at `width` by `height`, each even and at least [`COLUMNS`] and [`ROWS`]
/// pixels: the module doc's.
pub fn picture(n: u64, width: u32, height: u32) -> Frame {
let (w, h) = (width as usize, height as usize);
let mut frame = Frame {
width,
height,
y: Vec::with_capacity(w * h),
u: Vec::with_capacity(w / 2 * (h / 2)),
v: Vec::with_capacity(w / 2 * (h / 2)),
};
for row in 0..ROWS {
// One row of luma, and one of each chroma, of the grid's row; each pixel row of it the
// same.
let mut luma = Vec::with_capacity(w);
let mut cb = Vec::with_capacity(w / 2);
let mut cr = Vec::with_capacity(w / 2);
for x in 0..width {
let column = x * COLUMNS / width;
let (y, u, v) = cell_colour(n, row, column, f64::from(x) + 0.5, f64::from(width));
luma.push(y);
if x % 2 == 0 {
cb.push(u);
cr.push(v);
}
}
let (top, bottom) = (edge(row, ROWS, height), edge(row + 1, ROWS, height));
for y in top..bottom {
frame.y.extend_from_slice(&luma);
if y % 2 == 0 {
frame.u.extend_from_slice(&cb);
frame.v.extend_from_slice(&cr);
}
}
}
frame
}
/// The colour at grid cell (`column`, `row`) of frame `n`, at luma column `x` of a picture
/// `width` wide (for the stripes).
fn cell_colour(n: u64, row: u32, column: u32, x: f64, width: f64) -> (u8, u8, u8) {
if let Some(band) = BAND_ROWS.iter().position(|&r| r == row || r + 1 == row) {
let complement = BAND_ROWS[band] + 1 == row;
return (code_cell(n, column, complement), 128, 128);
}
if let Some(at) = CONTENT_ROWS.iter().position(|&r| r == row) {
return content_cell(n, at as u64 * u64::from(COLUMNS) + u64::from(column));
}
debug_assert_eq!(row, STRIPES_ROW);
let (stripe, _) = stripe_at(n, x, width);
(stripe_luma(stripe), 128, 128)
}
/// Where in a frame the picture lies: its left, top, width and height in luma pixels.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Region {
/// Its left column.
pub x: u32,
/// Its top row.
pub y: u32,
/// Its width.
pub width: u32,
/// Its height.
pub height: u32,
}
impl Region {
/// The whole of `frame`.
pub fn whole(frame: &Frame) -> Region {
Region {
x: 0,
y: 0,
width: frame.width,
height: frame.height,
}
}
/// The frame's pixel at the picture's point (`u`, `v`), each a fraction of its side.
fn at(&self, u: f64, v: f64) -> (u32, u32) {
let x = f64::from(self.x) + u * f64::from(self.width);
let y = f64::from(self.y) + v * f64::from(self.height);
(x as u32, y as u32)
}
/// Whether it lies inside `frame`, with room for a cell.
fn fits(&self, frame: &Frame) -> bool {
self.width >= COLUMNS
&& self.height >= ROWS
&& u64::from(self.x) + u64::from(self.width) <= u64::from(frame.width)
&& u64::from(self.y) + u64::from(self.height) <= u64::from(frame.height)
}
}
/// The mean luma, Cb and Cr over the middle half of the picture's region from (`u0`, `v0`) to
/// (`u1`, `v1`), fractions of its sides, sampled on a grid of at most 12 by 12.
fn mean(frame: &Frame, region: &Region, (u0, v0): (f64, f64), (u1, v1): (f64, f64)) -> [f64; 3] {
let (du, dv) = (u1 - u0, v1 - v0);
let (u0, v0, u1, v1) = (u0 + du / 4.0, v0 + dv / 4.0, u1 - du / 4.0, v1 - dv / 4.0);
let (x0, y0) = region.at(u0, v0);
let (x1, y1) = region.at(u1, v1);
let (x1, y1) = (x1.max(x0 + 1), y1.max(y0 + 1));
let step_x = ((x1 - x0) / 12).max(1);
let step_y = ((y1 - y0) / 12).max(1);
let (mut sum, mut n) = ([0.0; 3], 0.0);
let mut y = y0;
while y < y1 {
let mut x = x0;
while x < x1 {
let (cb, cr) = frame.chroma(x, y);
sum[0] += f64::from(frame.luma(x, y));
sum[1] += f64::from(cb);
sum[2] += f64::from(cr);
n += 1.0;
x += step_x;
}
y += step_y;
}
sum.map(|s| s / n)
}
/// A grid cell's region in fractions of the picture's sides.
fn cell_box(column: u32, row: u32) -> ((f64, f64), (f64, f64)) {
let (c, r) = (f64::from(COLUMNS), f64::from(ROWS));
(
(f64::from(column) / c, f64::from(row) / r),
(f64::from(column + 1) / c, f64::from(row + 1) / r),
)
}
/// What is wrong with a frame.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Fault {
/// Most of it the colour of a picture of zeros.
Green,
/// Some of it, a share in thousandths, the colour of a picture of zeros.
PartGreen(u32),
/// No band reads.
Unreadable,
/// The bands disagree, or one does not read: each band's number, top to bottom.
Torn([Option<u64>; 3]),
/// Cells whose levels are not its number's picture's: flat cells (of 32) and stripes
/// sampled.
Wrong {
/// Flat cells off in luma.
luma: u32,
/// Flat cells off in chroma.
chroma: u32,
/// Stripe samples off.
stripes: u32,
},
/// A number a frame before it showed: in a recording, not the one just before.
Repeated,
/// A number below the last frame's.
OutOfOrder,
}
impl Fault {
/// Its class's name, as the summary counts it.
pub fn class(&self) -> &'static str {
match self {
Fault::Green => "GREEN",
Fault::PartGreen(_) => "PART-GREEN",
Fault::Unreadable => "UNREADABLE",
Fault::Torn(_) => "TORN",
Fault::Wrong { .. } => "WRONG",
Fault::Repeated => "REPEAT",
Fault::OutOfOrder => "OUT-OF-ORDER",
}
}
fn says(&self) -> String {
match self {
Fault::PartGreen(share) => format!("PART-GREEN {}.{}%", share / 10, share % 10),
Fault::Torn(bands) => {
let said = bands.map(|band| band.map_or("-".to_owned(), |n| n.to_string()));
format!("TORN (bands {})", said.join("/"))
}
Fault::Wrong {
luma,
chroma,
stripes,
} => format!(
"WRONG ({luma} cells' luma, {chroma} cells' chroma, {stripes} stripe samples)"
),
other => other.class().to_owned(),
}
}
}
/// The classes the summary counts, in its order.
pub const CLASSES: [&str; 8] = [
"REPEAT",
"DROPPED",
"OUT-OF-ORDER",
"TORN",
"WRONG",
"GREEN",
"PART-GREEN",
"UNREADABLE",
];
/// What a frame's pixels say, with no frame before it: its number, unwrapped no further, and
/// its faults.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Read {
/// Its number modulo [`PERIOD`], where a band reads.
pub number: Option<u64>,
/// Its faults of its own: green, part green, unreadable, torn, wrong.
pub faults: Vec<Fault>,
}
/// Reads one frame's picture in `region`.
pub fn read(frame: &Frame, region: &Region) -> Read {
let mut faults = Vec::new();
if !region.fits(frame) {
return Read {
number: None,
faults: vec![Fault::Unreadable],
};
}
// The share of samples of a picture of zeros' colour, on a grid of 64 by 36.
let (mut zeros, mut all) = (0u32, 0u32);
for j in 0..36 {
for i in 0..64 {
let (x, y) = region.at((f64::from(i) + 0.5) / 64.0, (f64::from(j) + 0.5) / 36.0);
let (cb, cr) = frame.chroma(x, y);
all += 1;
if frame.luma(x, y) < 64 && cb < 64 && cr < 64 {
zeros += 1;
}
}
}
let share = f64::from(zeros) / f64::from(all);
if share >= GREEN_SHARE {
return Read {
number: None,
faults: vec![Fault::Green],
};
}
if share >= PART_GREEN_SHARE {
faults.push(Fault::PartGreen((share * 1000.0).round() as u32));
}
let cell = |column: u32, row: u32| {
let (from, to) = cell_box(column, row);
mean(frame, region, from, to)
};
// The references: each band's two black and two white cells.
let mut blacks = Vec::new();
let mut whites = Vec::new();
for &row in &BAND_ROWS {
blacks.push(cell(0, row)[0]);
blacks.push(cell(1, row + 1)[0]);
whites.push(cell(1, row)[0]);
whites.push(cell(0, row + 1)[0]);
}
let median = |values: &mut Vec<f64>| {
values.sort_by(f64::total_cmp);
values[values.len() / 2]
};
let (black, white) = (median(&mut blacks), median(&mut whites));
if white - black < 60.0 {
faults.push(Fault::Unreadable);
return Read {
number: None,
faults,
};
}
let threshold = (black + white) / 2.0;
let bands = BAND_ROWS.map(|row| {
let refs = [
cell(0, row)[0] < threshold,
cell(1, row)[0] > threshold,
cell(0, row + 1)[0] > threshold,
cell(1, row + 1)[0] < threshold,
];
if !refs.iter().all(|&r| r) {
return None;
}
let mut number = 0;
for column in 2..COLUMNS {
let bit = cell(column, row)[0] > threshold;
let complement = cell(column, row + 1)[0] > threshold;
if bit == complement {
return None;
}
number = number << 1 | u64::from(bit);
}
Some(number)
});
let read: Vec<u64> = bands.iter().flatten().copied().collect();
let number = match read.as_slice() {
[] => {
faults.push(Fault::Unreadable);
return Read {
number: None,
faults,
};
}
[a, b, c] if a == b && b == c => *a,
// Torn: the number most bands read, else the top band's that reads.
_ => {
faults.push(Fault::Torn(bands));
let most = (read.iter())
.find(|n| read.iter().filter(|m| m == n).count() >= 2)
.copied();
most.unwrap_or(read[0])
}
};
// The flat cells and the stripes against the number's picture.
let scale = |luma: f64| f64::from(BLACK) + (luma - black) * 219.0 / (white - black);
let (mut luma_off, mut chroma_off) = (0, 0);
for (at, &row) in CONTENT_ROWS.iter().enumerate() {
for column in 0..COLUMNS {
let (y, u, v) =
content_cell(number, at as u64 * u64::from(COLUMNS) + u64::from(column));
let [my, mu, mv] = cell(column, row);
if (scale(my) - f64::from(y)).abs() > LUMA_SLACK {
luma_off += 1;
}
if (mu - f64::from(u)).abs() > CHROMA_SLACK || (mv - f64::from(v)).abs() > CHROMA_SLACK
{
chroma_off += 1;
}
}
}
let mut stripes_off = 0;
let (top, bottom) = cell_box(0, STRIPES_ROW);
for sample in 0..(2 * STRIPES) {
let u = (sample as f64 + 0.5) / (2 * STRIPES) as f64;
let (stripe, within) = stripe_at(number, u, 1.0);
if !(0.3..=0.7).contains(&within) {
continue;
}
// A sample a tenth of a stripe wide, through the middle half of the row.
let half = 0.05 / STRIPES as f64;
let [my, _, _] = mean(frame, region, (u - half, top.1), (u + half, bottom.1));
if (scale(my) - f64::from(stripe_luma(stripe))).abs() > LUMA_SLACK {
stripes_off += 1;
}
}
if luma_off + chroma_off + stripes_off > 0 {
faults.push(Fault::Wrong {
luma: luma_off,
chroma: chroma_off,
stripes: stripes_off,
});
}
Read {
number: Some(number),
faults,
}
}
/// A judged frame: its index in the file, its number unwrapped, and its faults.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Call {
/// Its index among the file's frames.
pub index: u64,
/// Its number, unwrapped across [`PERIOD`], where a band reads.
pub number: Option<u64>,
/// Its faults: none where it is the picture it should be, in its place.
pub faults: Vec<Fault>,
/// In a recording, a frame that shows the number the frame before showed: held, not
/// repeated.
pub held: bool,
}
impl Call {
/// Its line: `FRAME index: n=number faults...`.
pub fn line(&self) -> String {
let number = self.number.map_or("?".to_owned(), |n| n.to_string());
let faults: Vec<String> = self.faults.iter().map(Fault::says).collect();
format!("FRAME {}: n={number} {}", self.index, faults.join(" "))
}
}
/// How a file is judged.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Mode {
/// A decode of the stream: each frame once, in order, from frame 0.
File,
/// A recording of its playback: each picture shown for one frame or more, and frames before
/// and after the stream.
Recording,
}
/// The judge of a file's frames, one at a time, in the file's order.
pub struct Judge {
mode: Mode,
region: Option<Region>,
/// The stream's frames, where known: a decode must hold them all, and a recording that
/// starts again from 0 after its last has looped, which is no fault.
frames: Option<u64>,
calls: Vec<Call>,
/// The last number read, unwrapped.
last: Option<u64>,
/// The pass's highest number, and its first.
high: Option<u64>,
start: u64,
/// The pass's numbers read.
seen: std::collections::BTreeSet<u64>,
/// The runs of numbers no frame showed, of the passes ended: each run's first and length.
missing: Vec<(u64, u64)>,
/// A recording's passes through the stream, past the first.
loops: u64,
}
impl Judge {
/// A judge of a file in `mode`, its picture in `region` of each frame (the whole frame where
/// `None`), of a stream of `frames` frames where known.
pub fn new(mode: Mode, region: Option<Region>, frames: Option<u64>) -> Judge {
Judge {
mode,
region,
frames,
calls: Vec::new(),
last: None,
high: None,
start: 0,
seen: std::collections::BTreeSet::new(),
missing: Vec::new(),
loops: 0,
}
}
/// Judges the file's next frame, and answers its call.
pub fn frame(&mut self, frame: &Frame) -> &Call {
let region = self.region.unwrap_or_else(|| Region::whole(frame));
let Read { number, mut faults } = read(frame, &region);
let index = self.calls.len() as u64;
let mut held = false;
let number = number.map(|n| self.unwrap(n));
if let Some(n) = number {
let looped = self.mode == Mode::Recording
&& self.frames.is_some_and(|frames| {
self.last.is_some_and(|last| last % frames + 3 >= frames) && n % frames < 3
});
if looped {
self.end_pass(None);
self.loops += 1;
self.start = n;
self.last = None;
}
match self.last {
None => {
if self.mode == Mode::Recording {
self.start = n;
}
}
Some(last) if n == last => match self.mode {
Mode::Recording => held = true,
Mode::File => faults.push(Fault::Repeated),
},
Some(last) => {
if n < last {
faults.push(Fault::OutOfOrder);
}
if self.seen.contains(&n) {
faults.push(Fault::Repeated);
}
}
}
self.seen.insert(n);
self.high = Some(self.high.map_or(n, |high| high.max(n)));
self.last = Some(n);
}
self.calls.push(Call {
index,
number,
faults,
held,
});
&self.calls[self.calls.len() - 1]
}
/// Ends a pass through the stream: the runs of numbers from its first to its highest, or to
/// `through` where given and higher, that no frame showed join [`Self::missing`].
fn end_pass(&mut self, through: Option<u64>) {
let Some(high) = self.high.max(through) else {
return;
};
let mut run: Option<(u64, u64)> = None;
for n in self.start..=high {
if self.seen.contains(&n) {
self.missing.extend(run.take());
} else {
run = Some(run.map_or((n, 1), |(first, len)| (first, len + 1)));
}
}
self.missing.extend(run);
self.seen.clear();
self.high = None;
}
/// `n`, a number modulo [`PERIOD`], unwrapped: the one nearest the number after the last.
fn unwrap(&self, n: u64) -> u64 {
let Some(last) = self.last else {
return n;
};
let next = last + 1;
let base = next - next % PERIOD;
[base.checked_sub(PERIOD), Some(base), Some(base + PERIOD)]
.into_iter()
.flatten()
.map(|b| b + n)
.min_by_key(|&m| m.abs_diff(next))
.unwrap_or(n)
}
/// The calls so far, in order.
pub fn calls(&self) -> &[Call] {
&self.calls
}
/// The verdict, which ends the judge's last pass: each class's count, and the summary line.
/// In a recording, the frames before its first number and after its last are outside the
/// stream: an unreadable one there is no fault. A decode of a stream of known length that
/// ends short drops the rest.
pub fn verdict(&mut self) -> Verdict {
let through = match (self.mode, self.frames) {
(Mode::File, Some(frames)) if frames > 0 => Some(frames - 1),
_ => None,
};
if self.mode == Mode::File && self.high.is_none() && through.is_some() {
// No frame read: the whole stream is missing.
self.high = through;
self.seen.clear();
}
self.end_pass(through);
let first = self.calls.iter().position(|c| c.number.is_some());
let last = self.calls.iter().rposition(|c| c.number.is_some());
let mut counts = CLASSES.map(|class| (class, 0u64));
let (mut faulty, mut ok, mut held, mut outside) = (0, 0, 0, 0);
for (i, call) in self.calls.iter().enumerate() {
let inside = match (self.mode, first, last) {
(Mode::Recording, Some(f), Some(l)) => (f..=l).contains(&i),
(Mode::Recording, _, _) => false,
(Mode::File, _, _) => true,
};
let faults: Vec<&Fault> = (call.faults.iter())
.filter(|fault| inside || **fault != Fault::Unreadable)
.collect();
if !inside && faults.is_empty() {
outside += 1;
continue;
}
if faults.is_empty() {
ok += 1;
held += u64::from(call.held);
continue;
}
faulty += 1;
for fault in faults {
if let Some(count) = counts.iter_mut().find(|(c, _)| *c == fault.class()) {
count.1 += 1;
}
}
}
let dropped: u64 = self.missing.iter().map(|(_, n)| n).sum();
if let Some(count) = counts.iter_mut().find(|(c, _)| *c == "DROPPED") {
count.1 = self.missing.len() as u64;
}
let pass = counts.iter().all(|(_, n)| *n == 0) && ok > 0;
let mode = match self.mode {
Mode::File => "file",
Mode::Recording => "recording",
};
let classes: Vec<String> = (counts.iter())
.map(|(class, n)| format!("{class} {n}"))
.collect();
let numbers = (self.calls.iter()).filter_map(|c| c.number);
let range = match (numbers.clone().min(), numbers.max()) {
(Some(low), Some(high)) => format!("numbers {low}..{high}"),
_ => "no number read".to_owned(),
};
let runs: Vec<String> = (self.missing.iter().take(20))
.map(|&(first, n)| match n {
1 => first.to_string(),
n => format!("{first}..{}", first + n - 1),
})
.collect();
let missing = match runs.is_empty() {
true => String::new(),
false => format!(
" ({}{})",
runs.join(", "),
match self.missing.len() > 20 {
true => ", ...",
false => "",
}
),
};
let recording = match self.mode {
Mode::Recording => format!(
"; {held} frames held, {outside} outside the stream, {} loops",
self.loops
),
Mode::File => String::new(),
};
let line = format!(
"SELFCHECK {mode}: {} frames: OK {ok}, faulty {faulty}; {}; {dropped} numbers \
dropped{missing}; {range}{recording}; {}",
self.calls.len(),
classes.join(", "),
if pass { "PASS" } else { "FAIL" }
);
Verdict { counts, pass, line }
}
}
/// A file's verdict.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Verdict {
/// The frames called with each class, in [`CLASSES`]' order.
pub counts: [(&'static str, u64); 8],
/// Whether no frame has a fault, and one is the stream's.
pub pass: bool,
/// The summary line.
pub line: String,
}
impl Verdict {
/// The frames called with `class`.
pub fn count(&self, class: &str) -> u64 {
(self.counts.iter())
.find(|(c, _)| *c == class)
.map_or(0, |(_, n)| *n)
}
}
#[cfg(test)]
mod tests;
@@ -1,537 +0,0 @@
//! The judge on pictures drawn here, each fault class made by hand: frames dropped, repeated and
//! out of order, pictures of zeros, torn, stale and with their chroma swapped, a recording's
//! frames, the picture scaled into a screen and held, and pictures shown in 8-bit RGB and taken
//! back, as a player shows them and a screen recording takes them.
use super::*;
const W: u32 = 320;
const H: u32 = 180;
/// Judges `frames` in `mode`, the picture in `region`, of a stream of `length` frames.
fn judged(
mode: Mode,
region: Option<Region>,
length: Option<u64>,
frames: &[Frame],
) -> (Vec<Call>, Verdict) {
let mut judge = Judge::new(mode, region, length);
for frame in frames {
judge.frame(frame);
}
let verdict = judge.verdict();
(judge.calls().to_vec(), verdict)
}
/// Pictures `range` at the test's size.
fn pictures(range: impl IntoIterator<Item = u64>) -> Vec<Frame> {
range.into_iter().map(|n| picture(n, W, H)).collect()
}
/// `frame` with each sample moved by up to `luma` and `chroma` code values, as a lossy codec
/// leaves a flat area, the same way every run.
fn noisy(frame: &Frame, luma: i32, chroma: i32) -> Frame {
let shift = |bytes: &[u8], by: i32, seed: u64| -> Vec<u8> {
(bytes.iter().enumerate())
.map(|(i, &b)| {
let d = (mix(seed, i as u64) % (2 * by as u64 + 1)) as i32 - by;
(i32::from(b) + d).clamp(0, 255) as u8
})
.collect()
};
Frame {
width: frame.width,
height: frame.height,
y: shift(&frame.y, luma, 1),
u: shift(&frame.u, chroma, 2),
v: shift(&frame.v, chroma, 3),
}
}
/// `frame`'s luma rows from `top` (its chroma's from `top / 2`) on, those of `from`.
fn rows_from(frame: &Frame, from: &Frame, top: u32, bottom: u32) -> Frame {
let mut out = frame.clone();
let w = frame.width as usize;
for y in top as usize..bottom as usize {
out.y[y * w..(y + 1) * w].copy_from_slice(&from.y[y * w..(y + 1) * w]);
}
for y in top as usize / 2..bottom as usize / 2 {
let c = w / 2;
out.u[y * c..(y + 1) * c].copy_from_slice(&from.u[y * c..(y + 1) * c]);
out.v[y * c..(y + 1) * c].copy_from_slice(&from.v[y * c..(y + 1) * c]);
}
out
}
/// A screen of `width` by `height` of the colour `desktop`, with `picture` scaled into
/// `region` of it by its nearest samples, as a recording of its playback shows it.
fn on_screen(picture: Option<&Frame>, width: u32, height: u32, region: Region) -> Frame {
let mut screen = Frame::filled(width, height, (200, 120, 140));
let Some(picture) = picture else {
return screen;
};
let source = |x: u32, y: u32| {
let px =
(u64::from(x - region.x) * u64::from(picture.width) / u64::from(region.width)) as u32;
let py =
(u64::from(y - region.y) * u64::from(picture.height) / u64::from(region.height)) as u32;
(px, py)
};
for y in region.y..region.y + region.height {
for x in region.x..region.x + region.width {
let (px, py) = source(x, y);
screen.y[(y * width + x) as usize] = picture.luma(px, py);
}
}
for cy in region.y.div_ceil(2)..(region.y + region.height) / 2 {
for cx in region.x.div_ceil(2)..(region.x + region.width) / 2 {
let (px, py) = source(2 * cx, 2 * cy);
let (u, v) = picture.chroma(px, py);
let at = (cy * (width / 2) + cx) as usize;
screen.u[at] = u;
screen.v[at] = v;
}
}
screen
}
/// A matrix's Kr and Kb: BT.709's and BT.601's.
const BT709: (f64, f64) = (0.2126, 0.0722);
const BT601: (f64, f64) = (0.299, 0.114);
/// The 8-bit RGB, unrounded and unclipped, of limited-range luma, Cb and Cr by the matrix
/// `(kr, kb)`.
fn to_rgb((y, cb, cr): (u8, u8, u8), (kr, kb): (f64, f64)) -> [f64; 3] {
let y = (f64::from(y) - 16.0) * 255.0 / 219.0;
let u = (f64::from(cb) - 128.0) * 255.0 / 224.0;
let v = (f64::from(cr) - 128.0) * 255.0 / 224.0;
let r = y + 2.0 * (1.0 - kr) * v;
let b = y + 2.0 * (1.0 - kb) * u;
let g = (y - kr * r - kb * b) / (1.0 - kr - kb);
[r, g, b]
}
/// `rgb` as 8-bit samples: rounded, and clipped to 0 to 255 as a display's are.
fn rgb8(rgb: [f64; 3]) -> [u8; 3] {
rgb.map(|c| c.round().clamp(0.0, 255.0) as u8)
}
/// 8-bit RGB back to limited-range luma, Cb and Cr by the matrix `(kr, kb)`, rounded.
fn from_rgb([r, g, b]: [u8; 3], (kr, kb): (f64, f64)) -> (u8, u8, u8) {
let (r, g, b) = (f64::from(r), f64::from(g), f64::from(b));
let y = kr * r + (1.0 - kr - kb) * g + kb * b;
let u = (b - y) / (2.0 * (1.0 - kb));
let v = (r - y) / (2.0 * (1.0 - kr));
let q = |x: f64| x.round().clamp(0.0, 255.0) as u8;
(
q(16.0 + y * 219.0 / 255.0),
q(128.0 + u * 224.0 / 255.0),
q(128.0 + v * 224.0 / 255.0),
)
}
/// `frame` shown in 8-bit RGB by the matrix `shown` and taken back by `captured`, as a player
/// shows a picture and a screen recording takes it: each pixel's luma with its 2x2 block's
/// chroma, and each block's chroma its top left pixel's.
fn through_rgb(frame: &Frame, shown: (f64, f64), captured: (f64, f64)) -> Frame {
let mut out = frame.clone();
for y in 0..frame.height {
for x in 0..frame.width {
let (cb, cr) = frame.chroma(x, y);
let (ly, lu, lv) = from_rgb(rgb8(to_rgb((frame.luma(x, y), cb, cr), shown)), captured);
out.y[(y * frame.width + x) as usize] = ly;
if x % 2 == 0 && y % 2 == 0 {
let at = ((y / 2) * (frame.width / 2) + x / 2) as usize;
out.u[at] = lu;
out.v[at] = lv;
}
}
}
out
}
#[test]
fn each_picture_reads_back_as_its_number_with_nothing_wrong() {
for n in [0, 1, 2, 7, 8, 777, 8191, 16383] {
let read = read(&picture(n, W, H), &Region::whole(&picture(n, W, H)));
assert_eq!(
read,
Read {
number: Some(n),
faults: Vec::new()
},
"picture {n}"
);
}
for (width, height) in [(1920, 1080), (642, 362), (64, 36)] {
let frame = picture(1234, width, height);
let read = read(&frame, &Region::whole(&frame));
assert_eq!(read.number, Some(1234), "{width}x{height}");
assert_eq!(read.faults, Vec::new(), "{width}x{height}");
}
}
/// The frame number wraps at [`PERIOD`]: picture `n` is picture `n % PERIOD`'s.
#[test]
fn the_picture_of_a_number_past_the_period_is_its_remainder_s() {
assert_eq!(picture(PERIOD + 5, W, H), picture(5, W, H));
}
/// At most four of the 32 flat cells change each frame, a cell's levels drawn again every eight
/// frames: a picture is mostly its reference's, and a stale cell shows.
#[test]
fn a_few_flat_cells_change_each_frame() {
let mut all = 0;
for n in 0..64u64 {
let changed = (0..32)
.filter(|&cell| content_cell(n, cell) != content_cell(n + 1, cell))
.count();
assert!(changed <= 4, "frame {n}: {changed} cells changed");
all += changed;
}
assert!(all >= 200, "{all} changes in 64 frames");
}
#[test]
fn a_decode_of_every_frame_in_order_passes() {
let (calls, verdict) = judged(Mode::File, None, Some(40), &pictures(0..40));
assert!(verdict.pass, "{}", verdict.line);
assert!(calls.iter().all(|c| c.faults.is_empty()));
assert!(
verdict.line.contains(": OK 40, faulty 0;"),
"{}",
verdict.line
);
assert!(
verdict.line.ends_with("; numbers 0..39; PASS"),
"{}",
verdict.line
);
}
/// A lossy decode's noise on its flat areas, up to 10 code values of luma and 8 of chroma, is no
/// fault.
#[test]
fn a_lossy_decode_s_noise_is_no_fault() {
let frames: Vec<Frame> = pictures(0..24).iter().map(|f| noisy(f, 10, 8)).collect();
let (_, verdict) = judged(Mode::File, None, Some(24), &frames);
assert!(verdict.pass, "{}", verdict.line);
}
/// Numbers no frame showed are dropped, counted by their runs: two in the middle, and a decode
/// that ends short of its stream's length.
#[test]
fn dropped_frames_are_counted_by_their_runs() {
let shown = (0..38u64).filter(|n| ![5, 6, 20].contains(n));
let (calls, verdict) = judged(Mode::File, None, Some(40), &pictures(shown));
assert!(
calls.iter().all(|c| c.faults.is_empty()),
"each picture right"
);
assert_eq!(verdict.count("DROPPED"), 3, "{}", verdict.line);
assert!(
verdict
.line
.contains("; 5 numbers dropped (5..6, 20, 38..39);"),
"{}",
verdict.line
);
assert!(!verdict.pass);
let (_, verdict) = judged(Mode::File, None, None, &pictures(3..10));
assert!(
verdict.line.contains("3 numbers dropped (0..2)"),
"{}",
verdict.line
);
}
#[test]
fn a_frame_shown_again_is_a_repeat() {
let mut frames = pictures(0..10);
frames.insert(5, picture(4, W, H));
frames.insert(9, picture(2, W, H));
let (calls, verdict) = judged(Mode::File, None, Some(10), &frames);
assert_eq!(calls[5].faults, [Fault::Repeated]);
assert_eq!(calls[9].faults, [Fault::OutOfOrder, Fault::Repeated]);
assert_eq!(verdict.count("REPEAT"), 2, "{}", verdict.line);
assert_eq!(verdict.count("DROPPED"), 0, "{}", verdict.line);
assert!(!verdict.pass);
}
/// Two frames swapped: the later number first, then the earlier, out of order; none dropped.
#[test]
fn frames_out_of_order_are_called() {
let mut frames = pictures(0..20);
frames.swap(10, 11);
let (calls, verdict) = judged(Mode::File, None, Some(20), &frames);
assert_eq!(calls[11].faults, [Fault::OutOfOrder]);
assert_eq!(verdict.count("OUT-OF-ORDER"), 1, "{}", verdict.line);
assert_eq!(verdict.count("DROPPED"), 0, "{}", verdict.line);
assert!(!verdict.pass);
}
/// A picture of zeros, as a surface no picture landed in decodes to, is green.
#[test]
fn a_picture_of_zeros_is_green() {
let mut frames = pictures(0..6);
frames[3] = Frame::filled(W, H, (0, 0, 0));
let (calls, verdict) = judged(Mode::File, None, Some(6), &frames);
assert_eq!(calls[3].faults, [Fault::Green]);
assert_eq!(verdict.count("GREEN"), 1, "{}", verdict.line);
assert_eq!(
verdict.count("DROPPED"),
1,
"frame 3's number: {}",
verdict.line
);
}
/// A picture whose bottom rows are zeros is part green, and torn: its bottom band does not read.
#[test]
fn a_picture_partly_of_zeros_is_part_green_and_torn() {
let mut frames = pictures(0..6);
let zeros = Frame::filled(W, H, (0, 0, 0));
frames[2] = rows_from(&frames[2], &zeros, H - 24, H);
let (calls, verdict) = judged(Mode::File, None, Some(6), &frames);
assert_eq!(calls[2].number, Some(2));
assert!(
matches!(calls[2].faults.as_slice(),
[Fault::PartGreen(share), Fault::Torn([Some(2), Some(2), None])] if *share > 100),
"{:?}",
calls[2].faults
);
assert_eq!(verdict.count("PART-GREEN"), 1, "{}", verdict.line);
assert_eq!(verdict.count("TORN"), 1, "{}", verdict.line);
}
/// A picture whose top half is one frame's and bottom half the frame before's is torn.
#[test]
fn a_picture_of_two_frames_is_torn() {
let mut frames = pictures(0..30);
frames[21] = rows_from(&frames[21], &frames[20], H / 2, H);
let (calls, verdict) = judged(Mode::File, None, Some(30), &frames);
let Fault::Torn(bands) = &calls[21].faults[0] else {
panic!("{:?}", calls[21].faults);
};
assert_eq!((bands[0], bands[2]), (Some(21), Some(20)));
assert_eq!(verdict.count("TORN"), 1, "{}", verdict.line);
}
/// A picture whose flat cells are an earlier frame's, as one built on a stale reference shows,
/// is wrong.
#[test]
fn stale_cells_are_wrong() {
let mut frames = pictures(0..40);
let (top, bottom) = (edge(2, ROWS, H), edge(3, ROWS, H));
frames[30] = rows_from(&frames[30], &picture(14, W, H), top, bottom);
let (calls, verdict) = judged(Mode::File, None, Some(40), &frames);
assert_eq!(calls[30].number, Some(30));
assert!(
matches!(calls[30].faults.as_slice(), [Fault::Wrong { luma, .. }] if *luma > 0),
"{:?}",
calls[30].faults
);
assert_eq!(verdict.count("WRONG"), 1, "{}", verdict.line);
}
/// A picture whose Cb and Cr are swapped is wrong in its chroma alone.
#[test]
fn swapped_chroma_is_wrong() {
let mut frames = pictures(0..12);
let swapped = &mut frames[7];
std::mem::swap(&mut swapped.u, &mut swapped.v);
let (calls, verdict) = judged(Mode::File, None, Some(12), &frames);
assert!(
matches!(calls[7].faults.as_slice(), [Fault::Wrong { luma: 0, chroma, stripes: 0 }]
if *chroma > 0),
"{:?}",
calls[7].faults
);
assert_eq!(verdict.count("WRONG"), 1, "{}", verdict.line);
}
/// [`CELL_COLOURS`] is every combination of the levels whose colour lies [`RGB_MARGIN`] or more
/// inside 8-bit RGB under both BT.709 and BT.601, in the levels' order, and no other.
#[test]
fn cell_colours_are_the_combinations_inside_rgb() {
let mut inside = Vec::new();
for y in LUMA_LEVELS {
for cb in CHROMA_LEVELS {
for cr in CHROMA_LEVELS {
let fits = [BT709, BT601].iter().all(|&matrix| {
(to_rgb((y, cb, cr), matrix).iter())
.all(|&c| (RGB_MARGIN..=255.0 - RGB_MARGIN).contains(&c))
});
if fits {
inside.push((y, cb, cr));
}
}
}
}
assert_eq!(inside, CELL_COLOURS.to_vec());
let lumas: std::collections::BTreeSet<u8> = CELL_COLOURS.iter().map(|c| c.0).collect();
assert_eq!(
lumas.len(),
LUMA_LEVELS.len(),
"every luma level has a colour"
);
}
/// Each cell colour comes back from 8-bit RGB within the judge's slack: shown and taken back by
/// one matrix, or by BT.709 and BT.601 one each way.
#[test]
fn each_cell_colour_comes_back_from_8_bit_rgb_within_slack() {
for colour in CELL_COLOURS {
for shown in [BT709, BT601] {
for captured in [BT709, BT601] {
let (y, cb, cr) = from_rgb(rgb8(to_rgb(colour, shown)), captured);
assert!(
f64::from(y.abs_diff(colour.0)) <= LUMA_SLACK
&& f64::from(cb.abs_diff(colour.1)) <= CHROMA_SLACK
&& f64::from(cr.abs_diff(colour.2)) <= CHROMA_SLACK,
"{colour:?} shown by {shown:?}, taken back by {captured:?}: {:?}",
(y, cb, cr)
);
}
}
}
}
/// A stream shown in 8-bit RGB and taken back, by one matrix or by the two one each way, passes:
/// every picture reads as its number with nothing wrong.
#[test]
fn pictures_shown_in_rgb_and_taken_back_pass() {
for (shown, captured) in [
(BT709, BT709),
(BT601, BT601),
(BT601, BT709),
(BT709, BT601),
] {
let frames: Vec<Frame> = (pictures(0..48).iter())
.map(|frame| through_rgb(frame, shown, captured))
.collect();
let (_, verdict) = judged(Mode::File, None, Some(48), &frames);
assert!(
verdict.pass,
"shown by {shown:?}, taken back by {captured:?}: {}",
verdict.line
);
}
}
/// A picture whose flat cells are an earlier frame's is still wrong once shown in RGB and taken
/// back: the colours' round trip leaves a stale cell showing.
#[test]
fn stale_cells_are_wrong_after_rgb() {
let mut frames = pictures(0..40);
let (top, bottom) = (edge(2, ROWS, H), edge(3, ROWS, H));
frames[30] = rows_from(&frames[30], &picture(14, W, H), top, bottom);
let frames: Vec<Frame> = (frames.iter())
.map(|frame| through_rgb(frame, BT709, BT709))
.collect();
let (calls, verdict) = judged(Mode::File, None, Some(40), &frames);
assert_eq!(calls[30].number, Some(30));
assert!(
matches!(calls[30].faults.as_slice(), [Fault::Wrong { .. }]),
"{:?}",
calls[30].faults
);
assert_eq!(verdict.count("WRONG"), 1, "{}", verdict.line);
}
/// A frame of no picture, all mid grey, does not read.
#[test]
fn a_frame_of_no_picture_is_unreadable() {
let mut frames = pictures(0..5);
frames.push(Frame::filled(W, H, (128, 128, 128)));
let (calls, verdict) = judged(Mode::File, None, Some(5), &frames);
assert_eq!(calls[5].faults, [Fault::Unreadable]);
assert_eq!(verdict.count("UNREADABLE"), 1, "{}", verdict.line);
}
/// A recording of the playback: the picture scaled by 1.37 into a screen at an odd place, each
/// picture held two or three frames, the screen alone before and after. With the region given,
/// it passes: frames held, and those outside the stream, are no faults.
#[test]
fn a_recording_of_the_playback_passes_with_its_frames_held() {
let region = Region {
x: 101,
y: 57,
width: 438,
height: 246,
};
let (sw, sh) = (640, 360);
let mut frames = vec![on_screen(None, sw, sh, region); 3];
for n in 0..20 {
let shown = on_screen(Some(&picture(n, W, H)), sw, sh, region);
for _ in 0..(2 + n % 2) {
frames.push(shown.clone());
}
}
frames.push(on_screen(None, sw, sh, region));
let (_, verdict) = judged(Mode::Recording, Some(region), Some(20), &frames);
assert!(verdict.pass, "{}", verdict.line);
assert!(
verdict
.line
.contains("; 30 frames held, 4 outside the stream, 0 loops;"),
"{}",
verdict.line
);
// The same as a file: each held frame a repeat.
let (_, verdict) = judged(Mode::File, Some(region), Some(20), &frames);
assert_eq!(verdict.count("REPEAT"), 30, "{}", verdict.line);
}
/// A recording's faults are a decode's: a picture shown late, out of order, one shown again
/// after others, out of order and repeated, and one of zeros; a picture shown again by the
/// frame after it is held.
#[test]
fn a_recording_s_faults_are_called() {
let region = Region {
x: 40,
y: 30,
width: 256,
height: 144,
};
let order = [0, 0, 1, 1, 3, 3, 2, 4, 4, 1, 5, 5];
let mut frames: Vec<Frame> = (order.iter())
.map(|&n| on_screen(Some(&picture(n, W, H)), 400, 240, region))
.collect();
frames.insert(
8,
on_screen(Some(&Frame::filled(W, H, (0, 0, 0))), 400, 240, region),
);
// No length: the stream's six frames would take a step back from its last three to its
// first three as a loop.
let (_, verdict) = judged(Mode::Recording, Some(region), None, &frames);
assert_eq!(verdict.count("OUT-OF-ORDER"), 2, "{}", verdict.line);
assert_eq!(verdict.count("REPEAT"), 1, "{}", verdict.line);
assert_eq!(verdict.count("GREEN"), 1, "{}", verdict.line);
assert_eq!(verdict.count("DROPPED"), 0, "{}", verdict.line);
assert!(!verdict.pass);
}
/// A recording that plays the stream again from its first frame after its last has looped,
/// which is no fault; one that wraps past [`PERIOD`] goes on.
#[test]
fn a_recording_that_loops_or_wraps_goes_on() {
let region = Region::whole(&picture(0, W, H));
let frames: Vec<Frame> = pictures((0..10).chain(0..10));
let (_, verdict) = judged(Mode::Recording, Some(region), Some(10), &frames);
assert!(verdict.pass, "{}", verdict.line);
assert!(verdict.line.contains(", 1 loops;"), "{}", verdict.line);
let frames = pictures(PERIOD - 3..PERIOD + 3);
let (calls, verdict) = judged(Mode::Recording, Some(region), None, &frames);
assert!(verdict.pass, "{}", verdict.line);
let numbers: Vec<u64> = calls.iter().filter_map(|c| c.number).collect();
assert_eq!(numbers, (PERIOD - 3..PERIOD + 3).collect::<Vec<_>>());
}
/// A frame's bytes go out and come back as `yuv420p` raw video holds them.
#[test]
fn a_frame_s_bytes_come_back_as_the_frame() {
let frame = picture(9, W, H);
assert_eq!(Frame::from_bytes(W, H, &frame.bytes()), Some(frame));
assert_eq!(Frame::from_bytes(W, H, &[0; 10]), None);
}
@@ -119,7 +119,6 @@ mod linux {
buffer_milliseconds: 1000,
gop_length: None,
b_frames: 0,
coding_order: false,
level: None,
cabac: None,
full_range: false,
@@ -329,13 +329,6 @@ pub struct EncoderSettings {
/// Consecutive B pictures between references when reordering is
/// allowed: none for the encoder's choice.
pub b_frames: Option<u32>,
/// Whether frames come in the order they are coded, each at its own
/// place in display order, their PTS that many durations from 0, as an
/// encoder above this one plans its own B pictures and sends each
/// reference before them (`gop`'s `CodingOrder`). Frames are not
/// reordered then, whatever the settings above, and the SPS says one
/// frame may come out of display order.
pub coding_order: bool,
/// The level as the bitstream numbers it (`level_idc`, or HEVC's
/// `general_level_idc`); none to choose the lowest that fits.
pub level: Option<u8>,
@@ -371,7 +364,6 @@ impl EncoderSettings {
allow_frame_reordering: true,
max_frame_delay: None,
b_frames: None,
coding_order: false,
level: None,
entropy: None,
quality_level: None,
@@ -6,11 +6,6 @@
//! accelerator ([`Accelerator`]) uploads frames and runs the hardware;
//! VA-API's is the VA-API backend's.
//!
//! Frames come in display order, or, where the settings say so
//! ([`EncoderSettings::coding_order`]), in the order an encoder above this
//! one codes them, each at its own place in display order, which
//! [`super::gop`]'s `CodingOrder` plans as they come.
//!
//! A stream without B pictures or a hard limit holds its last picture back
//! from the accelerator's stream ([`Accelerator::keep`]) until the next
//! frame or a flush, so that the caller can have it coded again in its
@@ -21,9 +16,7 @@
use std::collections::VecDeque;
use std::sync::Arc;
use super::gop::{
CODING_ORDER_REFERENCES, CodingOrder, DecodeTimes, GopConfig, GopPlanner, Planned,
};
use super::gop::{DecodeTimes, GopConfig, GopPlanner, Planned};
use super::limit_rate::LimitRate;
use super::record::Record;
use super::{
@@ -267,8 +260,6 @@ struct Pending<I> {
#[derive(Clone, Copy)]
struct SliceAt {
frame_type: FrameType,
/// Whether it is a reference.
reference: bool,
order: i32,
frame_num: u32,
idr_pic_id: u32,
@@ -289,13 +280,7 @@ pub struct Encoder<A: Accelerator> {
/// The configuration record, as the hardware's parameter sets make it.
record: Record,
planner: GopPlanner<Pending<A::Input>>,
/// The planner of frames that come in coding order
/// ([`EncoderSettings::coding_order`]), which then plans every frame.
coding: Option<CodingOrder>,
times: DecodeTimes,
/// In coding order, the next sample's DTS: one duration after the
/// last's, the first one duration before its PTS ([`Self::coded_dts`]).
next_coded_dts: Option<i64>,
dpb: VecDeque<ReferencePicture>,
/// H.264's `frame_num` for the next picture, and the next IDR
/// picture's `idr_pic_id`.
@@ -326,8 +311,6 @@ struct Held {
forward: Option<u64>,
backward: Option<u64>,
pts: i64,
/// Its sample's DTS, which coding it again takes.
dts: i64,
before: Before,
picture: Unkept,
}
@@ -525,9 +508,10 @@ impl<A: Accelerator> Encoder<A> {
)
},
)?;
// Whether a picture may predict from references on both sides.
let bidirectional = s.profile.has_b_slices() && limits.max_l1 >= 1 && limits.max_l0 >= 1;
let reorder = s.allow_frame_reordering && bidirectional && !s.coding_order;
let reorder = s.allow_frame_reordering
&& s.profile.has_b_slices()
&& limits.max_l1 >= 1
&& limits.max_l0 >= 1;
let b_frames = if reorder {
s.b_frames
.unwrap_or(DEFAULT_B_FRAMES)
@@ -536,17 +520,9 @@ impl<A: Accelerator> Encoder<A> {
} else {
0
};
// Whether a frame may come out of display order: a B picture of
// ours, or a frame in coding order sent after a later one.
let reordered = b_frames > 0 || s.coding_order;
// The references, and with the picture being coded, the pictures
// the DPB holds: in coding order, CodingOrder's.
let (max_references, dpb_pictures): (u32, u32) = if reordered {
const _: () = assert!(CODING_ORDER_REFERENCES == 2);
(2, 3)
} else {
(1, 2)
};
// the DPB holds.
let (max_references, dpb_pictures): (u32, u32) = if b_frames > 0 { (2, 3) } else { (1, 2) };
let peak = s.rate_control.peak_bits_per_second();
let fps = s.frame_rate.as_f64();
let intra_period = s.key_frame_interval.unwrap_or(0);
@@ -595,7 +571,7 @@ impl<A: Accelerator> Encoder<A> {
full_range: s.full_range,
colour: s.colour,
timing: timing(s.frame_rate, 2),
max_num_reorder_frames: u32::from(reordered),
max_num_reorder_frames: u32::from(b_frames > 0),
max_dec_frame_buffering: max_references,
},
};
@@ -647,7 +623,7 @@ impl<A: Accelerator> Encoder<A> {
crop_right,
crop_bottom,
max_dec_pic_buffering_minus1: max_references,
max_num_reorder_pics: u32::from(reordered),
max_num_reorder_pics: u32::from(b_frames > 0),
tools,
vui: hevc::Vui {
sample_aspect_ratio: s.sample_aspect_ratio,
@@ -671,9 +647,7 @@ impl<A: Accelerator> Encoder<A> {
settings: &settings,
coded_width: coded_size.0,
coded_height: coded_size.1,
// In coding order, the stream's B pictures run one at a time, and
// nothing waits here.
b_frames: if s.coding_order { 1 } else { b_frames },
b_frames,
max_references,
intra_period,
picture_qp: limit_rate.is_some(),
@@ -683,13 +657,6 @@ impl<A: Accelerator> Encoder<A> {
key_frame_interval_duration: settings.key_frame_interval_duration,
b_frames,
});
let coding = settings.coding_order.then(|| {
CodingOrder::new(
settings.key_frame_interval,
settings.key_frame_interval_duration,
bidirectional,
)
});
Ok(Self {
accelerator,
settings,
@@ -700,9 +667,7 @@ impl<A: Accelerator> Encoder<A> {
max_references: max_references.to_usize(),
record,
planner,
coding,
times: DecodeTimes::new(),
next_coded_dts: None,
dpb: VecDeque::new(),
frame_num: 0,
idr_pic_id: 0,
@@ -731,8 +696,7 @@ impl<A: Accelerator> Encoder<A> {
self.coded_size
}
/// B pictures in a run of ours, which hold frames back; 0 when each
/// frame's sample comes out as it goes in.
/// B pictures in a run; 0 when frames keep their order.
pub fn b_frames(&self) -> u32 {
self.b_frames
}
@@ -758,12 +722,11 @@ impl<A: Accelerator> Encoder<A> {
/// Encodes one frame and returns each frame that comes out, in decode
/// order, with its own result: none while it waits as a B picture, or
/// several when it ends a run. `Err` is a frame not taken: one whose
/// time stamp does not follow the last, or in coding order gives no
/// place ([`Self::takes`]), or that does not upload.
/// time stamp does not follow the last, or that does not upload.
pub fn encode(&mut self, frame: &InputFrame<'_>) -> Result<Vec<Coded<A::Error>>, A::Error> {
let place = self.takes(frame)?;
self.follows(frame.pts)?;
let input = self.accelerator.upload(frame)?;
Ok(self.push(input, frame, place))
Ok(self.push(input, frame))
}
/// [`Self::encode`] of a frame another device already wrote into `input`, an input of the
@@ -774,8 +737,8 @@ impl<A: Accelerator> Encoder<A> {
input: A::Input,
frame: &InputFrame<'_>,
) -> Result<Vec<Coded<A::Error>>, A::Error> {
let place = self.takes(frame)?;
Ok(self.push(input, frame, place))
self.follows(frame.pts)?;
Ok(self.push(input, frame))
}
/// [`Self::encode`] of `frame` in place of the last picture coded, whose
@@ -860,7 +823,6 @@ impl<A: Accelerator> Encoder<A> {
forward,
backward,
pts,
dts,
before,
picture: _,
} = held;
@@ -872,8 +834,9 @@ impl<A: Accelerator> Encoder<A> {
// Rate control goes with it again where it went with the last try,
// and where it changed since.
self.rate_control_changed |= before.rate_control_changed;
// The last try's DTS.
self.times.push(dts);
// Without B pictures a sample's DTS is its PTS, which the last try's
// took.
self.times.push(pts);
let planned = Planned {
frame: Pending {
input,
@@ -920,67 +883,29 @@ impl<A: Accelerator> Encoder<A> {
});
}
/// Whether `frame` is taken: in display order, where its time stamp
/// follows the last frame's; in coding order, where its PTS is a whole
/// number of its durations from 0, its place in display order, which
/// this answers. `Err` where it is not.
fn takes(&self, frame: &InputFrame<'_>) -> Result<Option<u64>, A::Error> {
let pts = frame.pts;
if self.coding.is_none() {
if let Some(last) = self.last_pts {
check(pts > last, || format!("PTS {pts} does not follow {last}"))?;
}
return Ok(None);
/// `Err` where `pts` does not follow the last frame's.
fn follows(&self, pts: i64) -> Result<(), A::Error> {
if let Some(last) = self.last_pts {
check(pts > last, || format!("PTS {pts} does not follow {last}"))?;
}
let duration = frame.duration;
let place = (duration > 0 && pts.checked_rem(duration) == Some(0))
.then(|| pts.checked_div(duration))
.flatten()
.and_then(|n| u64::try_from(n).ok());
check(place.is_some(), || {
format!("a frame in coding order at PTS {pts}, of duration {duration}, has no place")
})?;
Ok(place)
Ok(())
}
/// In coding order, the DTS of the sample of `frame`, the next frame in:
/// one duration after the last sample's, the first one duration before
/// its PTS, so that a reference sent one frame ahead of its place, as
/// the SPS allows, decodes before it shows and a B picture after it its
/// DTS comes no later than its PTS, as Apple's encoders stamp a stream
/// that reorders one frame.
fn coded_dts(&mut self, frame: &InputFrame<'_>) -> i64 {
let dts = (self.next_coded_dts).unwrap_or_else(|| frame.pts.saturating_sub(frame.duration));
self.next_coded_dts = Some(dts.saturating_add(frame.duration));
dts
}
/// Takes `frame`, in `input`, at `place` in display order where it
/// comes in coding order, and encodes what its plan gives.
fn push(
&mut self,
input: A::Input,
frame: &InputFrame<'_>,
place: Option<u64>,
) -> Vec<Coded<A::Error>> {
/// Takes `frame`, in `input`, and encodes what its plan gives.
fn push(&mut self, input: A::Input, frame: &InputFrame<'_>) -> Vec<Coded<A::Error>> {
self.keep_held();
self.last_pts = Some(frame.pts);
let dts = match place {
Some(_) => self.coded_dts(frame),
None => frame.pts,
};
self.times.push(dts);
self.times.push(frame.pts);
let pending = Pending {
input,
pts: frame.pts,
duration: frame.duration,
id: frame.id,
};
let force = frame.force_key_frame || core::mem::take(&mut self.restart);
let planned = match (&mut self.coding, place) {
(Some(coding), Some(place)) => vec![coding.push(pending, place, frame.pts, force)],
_ => self.planner.push(pending, frame.pts, force),
};
let restart = core::mem::take(&mut self.restart);
let planned = self
.planner
.push(pending, frame.pts, frame.force_key_frame || restart);
self.encode_all(planned)
}
@@ -1069,9 +994,6 @@ impl<A: Accelerator> Encoder<A> {
self.settings.key_frame_interval = frames;
self.settings.key_frame_interval_duration = duration;
self.planner.set_key_frame_interval(frames, duration);
if let Some(coding) = &mut self.coding {
coding.set_interval(frames, duration);
}
}
fn reference(&self, number: Option<u64>) -> Result<Option<ReferencePicture>, Unsupported> {
@@ -1141,7 +1063,6 @@ impl<A: Accelerator> Encoder<A> {
> {
let SliceAt {
frame_type,
reference,
order,
frame_num,
idr_pic_id,
@@ -1169,12 +1090,10 @@ impl<A: Accelerator> Encoder<A> {
FrameType::B => h264::SliceType::B,
},
idr: frame_type == FrameType::Idr,
// A B picture is never a reference; a P picture in
// coding order may not be one.
nal_ref_idc: match (frame_type, reference) {
(_, false) => 0,
(FrameType::Idr, true) => 3,
(FrameType::P | FrameType::B, true) => 2,
nal_ref_idc: match frame_type {
FrameType::Idr => 3,
FrameType::P => 2,
FrameType::B => 0,
},
frame_num,
idr_pic_id,
@@ -1262,7 +1181,6 @@ impl<A: Accelerator> Encoder<A> {
let idr_pic_id = self.idr_pic_id;
let slice = |qp| SliceAt {
frame_type,
reference: reference.is_some(),
order,
frame_num,
idr_pic_id,
@@ -1339,7 +1257,6 @@ impl<A: Accelerator> Encoder<A> {
forward,
backward,
pts: frame.pts,
dts,
before,
picture: Unkept {
frame_type,
@@ -1448,9 +1365,6 @@ pub mod tests {
/// Each kept picture's `pic_order_cnt_lsb`, as its slice header
/// says.
lsbs: Vec<u32>,
/// Each kept H.264 picture's `nal_ref_idc`, as its slice header
/// says.
ref_idcs: Vec<u8>,
/// Whether the stream was configured for QPs the encoder picks.
picture_qp: bool,
}
@@ -1508,9 +1422,6 @@ pub mod tests {
_ => 0,
};
self.lsbs.push(lsb);
if let Some(slice) = p.h264_slice {
self.ref_idcs.push(slice.nal_ref_idc);
}
}
}
@@ -1863,157 +1774,6 @@ pub mod tests {
Ok(())
}
/// Frames at `places` in display order, sent in the order given, with
/// a key frame forced at the frames of `keys` (by their place in the
/// list), through an encoder of `settings` in coding order: each result,
/// and the fake once flushed.
fn in_coding_order(
mut settings: EncoderSettings,
places: &[u32],
keys: &[usize],
) -> Result<(Vec<EncodedSample>, Fake), Unsupported> {
settings.coding_order = true;
let mut encoder = Encoder::new(Fake::default(), settings, &limits())?;
let mut coded = Vec::new();
for (n, &place) in places.iter().enumerate() {
coded.extend(encoder.encode(&frame(place, keys.contains(&n)))?);
}
coded.extend(encoder.flush());
let Encoder { accelerator, .. } = encoder;
Ok((samples(coded)?, accelerator))
}
/// AppleGVA's frames with reordering allowed, as its encoders send them:
/// each reference before the B picture shown ahead of it (I0 P2 B1 P4
/// B3 P6 B5 P7, measured on the Mac's own encoders, oracle job
/// m3-max-86942). Each picture's order count follows its place in
/// display order, each B picture between the references either side of
/// it, which nothing predicts from; the SPS says one frame may come out
/// of display order; and each sample comes out as its frame goes in,
/// its DTS one frame after the last, the first one frame before its PTS.
#[test]
fn h264_frames_in_coding_order_keep_their_places() -> Result<(), Unsupported> {
use FrameType::{B, Idr, P};
let places = [0, 2, 1, 4, 3, 6, 5, 7];
let mut settings = EncoderSettings::new(Profile::H264High, 640, 360);
settings.key_frame_interval = None;
let (samples, fake) = in_coding_order(settings, &places, &[])?;
let ids: Vec<u64> = samples.iter().map(|s| s.id).collect();
assert_eq!(ids, places.map(u64::from));
let types: Vec<FrameType> = samples.iter().map(|s| s.frame_type).collect();
assert_eq!(types, [Idr, P, B, P, B, P, B, P]);
assert_eq!(fake.lsbs, places.map(|p| p * 2));
assert_eq!(fake.ref_idcs, [3, 2, 0, 2, 0, 2, 0, 2]);
// B picture 1 predicts from POCs 0 and 4; P picture 4 from 4.
assert_eq!((fake.pictures[2].2, fake.pictures[2].3), (Some(0), Some(4)));
assert_eq!((fake.pictures[3].2, fake.pictures[3].3), (Some(4), None));
for s in &samples {
assert_eq!(s.is_depended_on, s.frame_type != B);
}
let dts: Vec<i64> = samples.iter().map(|s| s.dts).collect();
assert_eq!(dts, (-1..7).map(|n| n * 3000).collect::<Vec<_>>());
assert!(samples.iter().all(|s| s.dts <= s.pts));
let record = samples[0].configuration.clone().unwrap_or_default();
let sps = crate::codec::h264::avcc::DecoderConfiguration::parse(&record)
.ok()
.and_then(|avcc| avcc.sequence_parameter_sets.first().copied())
.and_then(|unit| crate::codec::h264::sps::Sps::parse(unit).ok())
.ok_or_else(|| Unsupported("the record's SPS".into()))?;
assert_eq!(sps.max_num_reorder_frames(), 1);
assert_eq!(sps.max_num_ref_frames, 2);
Ok(())
}
/// [`h264_frames_in_coding_order_keep_their_places`] for HEVC, whose
/// order counts are the places themselves, and which codes no B slices
/// ([`Profile::has_b_slices`]): a frame sent after a later one is a P
/// picture nothing predicts from, predicting from the last reference.
#[test]
fn hevc_frames_in_coding_order_keep_their_places() -> Result<(), Unsupported> {
use FrameType::{Idr, P};
let places = [0, 2, 1, 4, 3, 5];
let (samples, fake) = in_coding_order(
EncoderSettings::new(Profile::HevcMain, 640, 360),
&places,
&[],
)?;
let types: Vec<FrameType> = samples.iter().map(|s| s.frame_type).collect();
assert_eq!(types, [Idr, P, P, P, P, P]);
let depended: Vec<bool> = samples.iter().map(|s| s.is_depended_on).collect();
assert_eq!(depended, [true, true, false, true, false, true]);
assert_eq!(fake.lsbs, places);
assert_eq!((fake.pictures[2].2, fake.pictures[2].3), (Some(2), None));
assert_eq!((fake.pictures[4].2, fake.pictures[4].3), (Some(4), None));
let record = samples[0].configuration.clone().unwrap_or_default();
let sps = crate::codec::hevc::hvcc::DecoderConfiguration::parse(&record)
.ok()
.and_then(|hvcc| {
(hvcc.nal_units.into_iter())
.find(|unit| unit.first().map(|b| (b >> 1) & 0x3f) == Some(33))
})
.and_then(|unit| crate::codec::hevc::sps::Sps::parse(unit).ok())
.ok_or_else(|| Unsupported("the record's SPS".into()))?;
assert_eq!(sps.highest_ordering().max_num_reorder_pics, 1);
Ok(())
}
/// In coding order, a profile or driver without B slices codes a frame
/// sent after a later one as a P picture nothing predicts from, from the
/// last reference; frames that keep display order are all references; a
/// key frame where one is forced, or at a place not past its key
/// frame's or the last reference's, starts again from the frame's place.
#[test]
fn frames_in_coding_order_without_b_slices_and_key_frames() -> Result<(), Unsupported> {
use FrameType::{Idr, P};
let settings = EncoderSettings::new(Profile::H264ConstrainedBaseline, 640, 360);
let (samples, fake) = in_coding_order(settings, &[0, 2, 1, 3, 4, 4, 3, 6, 5], &[4])?;
let types: Vec<FrameType> = samples.iter().map(|s| s.frame_type).collect();
// Frame 4 is forced; the next, at its place, and the one after, at
// one before it, are key frames too.
assert_eq!(types, [Idr, P, P, P, Idr, Idr, Idr, P, P]);
assert_eq!(fake.ref_idcs, [3, 2, 0, 2, 3, 3, 3, 2, 0]);
assert_eq!(fake.lsbs, [0, 4, 2, 6, 0, 0, 0, 6, 4]);
// The P picture at place 1 predicts from place 2's.
assert_eq!(fake.pictures[2].2, Some(4));
Ok(())
}
/// A frame in coding order is coded again in place of the last one as
/// in display order, at its place, its DTS the last try's; a frame whose
/// PTS is not a whole number of its durations has no place and is not
/// taken.
#[test]
fn frames_in_coding_order_are_coded_again_in_place() -> Result<(), Unsupported> {
let mut settings = in_place_settings(Profile::HevcMain);
settings.coding_order = true;
let mut encoder = Encoder::new(Fake::default(), settings, &limits())?;
let mut coded = Vec::new();
for place in [0, 2] {
coded.extend(encoder.encode(&frame(place, false))?);
}
coded.extend(encoder.encode_in_place(&frame(2, false))?);
coded.extend(encoder.encode(&frame(1, false))?);
let mut odd = frame(3, false);
odd.pts += 1;
assert!(encoder.encode(&odd).is_err());
coded.extend(encoder.flush());
let Encoder { accelerator, .. } = encoder;
let samples = samples(coded)?;
let dts: Vec<i64> = samples.iter().map(|s| s.dts).collect();
assert_eq!(dts, [-3000, 0, 0, 3000]);
let types: Vec<FrameType> = samples.iter().map(|s| s.frame_type).collect();
assert_eq!(
types,
[FrameType::Idr, FrameType::P, FrameType::P, FrameType::P]
);
// The kept pictures: the IDR picture, the second try at place 2,
// and the picture at place 1, which predicts from it.
assert_eq!(accelerator.lsbs, [0, 2, 1]);
assert_eq!(accelerator.pictures[2].2, Some(2));
assert!(!samples[3].is_depended_on);
Ok(())
}
#[test]
fn hevc_predicts_from_the_last_picture_in_order() -> Result<(), Unsupported> {
let mut settings = EncoderSettings::new(Profile::HevcMain10, 100, 50);
@@ -12,9 +12,6 @@
//! reference before it. B pictures still waiting when an IDR picture comes,
//! or at a flush, end their run as x264 ends one: the last becomes a P
//! picture, so that none predicts across the IDR picture.
//!
//! Frames that come in the order they are coded, each at its own place in
//! display order, are planned by [`CodingOrder`] instead, as they come.
use std::collections::VecDeque;
@@ -267,158 +264,6 @@ impl<F> GopPlanner<F> {
}
}
/// Plans frames that come in the order they are coded, each with its own
/// place in display order, as an encoder above ours sends them (the
/// guest's, which decides its own B pictures): one picture out for each
/// frame in, at once. A frame is an IDR picture at the first frame, where
/// one is forced, at the first frame past the key-frame interval in places
/// or in time stamp ticks, at one whose order would pass [`MAX_ORDER`], and
/// at one whose place is not past its IDR picture's, or is the last
/// reference's. Its order is its place less its IDR picture's. Otherwise a
/// frame whose order is past every order since its IDR picture is a P
/// picture, a reference predicting from the last reference; and one whose
/// order is not, a frame its encoder sent after a later one, is a picture
/// nothing predicts from: a B picture between the closest references before
/// and after it where `bidirectional` and one before it is held, else a P
/// picture predicting from the last reference. The references held are the
/// last two.
#[derive(Debug)]
pub(crate) struct CodingOrder {
interval: Option<u32>,
interval_duration: Option<i64>,
/// Whether a picture that is not a reference may be a B picture.
bidirectional: bool,
/// The last IDR picture's place and time stamp; none before the first
/// frame.
key: Option<(u64, i64)>,
/// The references held, oldest first: their numbers and orders.
references: VecDeque<(u64, u32)>,
/// The highest order planned since the last IDR picture.
top: u32,
next_reference: u64,
}
/// The references [`CodingOrder`] holds: a P picture's and, for a B
/// picture, the one before it.
pub(crate) const CODING_ORDER_REFERENCES: usize = 2;
impl CodingOrder {
/// A planner with key frames at most `interval` places or
/// `interval_duration` ticks apart, where either is set, before the
/// first frame.
pub(crate) fn new(
interval: Option<u32>,
interval_duration: Option<i64>,
bidirectional: bool,
) -> Self {
Self {
interval,
interval_duration,
bidirectional,
key: None,
references: VecDeque::new(),
top: 0,
next_reference: 0,
}
}
/// Changes the interval, from the next frame on.
pub(crate) fn set_interval(&mut self, frames: Option<u32>, duration: Option<i64>) {
self.interval = frames;
self.interval_duration = duration;
}
/// The order of a frame at `place`, time stamp `pts`, after the last
/// IDR picture; none where it is an IDR picture (the type's doc): a
/// place the last reference has would give two pictures one order
/// count.
fn order(&self, place: u64, pts: i64, force: bool) -> Option<u32> {
let (key_place, key_pts) = self.key?;
let order = u32::try_from(place.checked_sub(key_place)?).ok()?;
let by_count = self
.interval
.is_some_and(|interval| order >= interval.max(1));
let by_time = self
.interval_duration
.is_some_and(|duration| pts.saturating_sub(key_pts) >= duration.max(1));
let key =
force || by_count || by_time || order == 0 || order == self.top || order > MAX_ORDER;
(!key).then_some(order)
}
/// Takes the next frame in the order it is coded, at `place` in display
/// order, with its time stamp and whether a key frame is forced there,
/// and plans it.
pub(crate) fn push<F>(&mut self, frame: F, place: u64, pts: i64, force: bool) -> Planned<F> {
let Some(order) = self.order(place, pts, force) else {
let reference = self.take_reference();
self.key = Some((place, pts));
self.references.clear();
self.references.push_back((reference, 0));
self.top = 0;
return Planned {
frame,
frame_type: FrameType::Idr,
order: 0,
reference: Some(reference),
forward: None,
backward: None,
};
};
let last = self.references.back().map(|&(number, _)| number);
if order > self.top {
let reference = self.take_reference();
self.references.push_back((reference, order));
while self.references.len() > CODING_ORDER_REFERENCES {
self.references.pop_front();
}
self.top = order;
return Planned {
frame,
frame_type: FrameType::P,
order,
reference: Some(reference),
forward: last,
backward: None,
};
}
let before = (self.references.iter())
.filter(|&&(_, o)| o < order)
.max_by_key(|&&(_, o)| o)
.map(|&(number, _)| number);
let after = (self.references.iter())
.filter(|&&(_, o)| o > order)
.min_by_key(|&&(_, o)| o)
.map(|&(number, _)| number);
match (self.bidirectional, before, after) {
(true, Some(before), Some(after)) => Planned {
frame,
frame_type: FrameType::B,
order,
reference: None,
forward: Some(before),
backward: Some(after),
},
_ => Planned {
frame,
frame_type: FrameType::P,
order,
reference: None,
forward: last,
backward: None,
},
}
}
/// A new reference's number.
fn take_reference(&mut self) -> u64 {
let number = self.next_reference;
// As GopPlanner::take_reference's.
self.next_reference = self.next_reference.wrapping_add(1);
number
}
}
/// Decode time stamps for samples in decode order, from the frames' time
/// stamps in the order they were sent, as Apple's encoders give them: the
/// `k`th sample's DTS is the PTS of the `k`th frame sent. Apple's host
@@ -574,80 +419,6 @@ mod tests {
assert_eq!(planned[6].forward, planned[5].reference);
}
/// Plans frames at `places`, sent in that order, under `planner`, a key
/// frame forced at the frames of `forced` (by their place in the list).
fn plan_coded(mut planner: CodingOrder, places: &[u32], forced: &[usize]) -> Vec<Planned<u32>> {
(places.iter().enumerate())
.map(|(n, &place)| {
let pts = i64::from(place) * 3000;
planner.push(place, u64::from(place), pts, forced.contains(&n))
})
.collect()
}
#[test]
fn frames_in_coding_order_are_planned_at_their_places() {
let planned = plan_coded(CodingOrder::new(None, None, true), &[0, 2, 1, 4, 3, 5], &[]);
assert_eq!(types(&planned), "I0 P2 B1 P4 B3 P5");
let orders: Vec<u32> = planned.iter().map(|p| p.order).collect();
assert_eq!(orders, [0, 2, 1, 4, 3, 5]);
// B1 sits between I0 and P2, B3 between P2 and P4; P4 predicts
// from P2, and P5 from P4.
assert_eq!(planned[2].forward, planned[0].reference);
assert_eq!(planned[2].backward, planned[1].reference);
assert_eq!(planned[4].forward, planned[1].reference);
assert_eq!(planned[4].backward, planned[3].reference);
assert_eq!(planned[3].forward, planned[1].reference);
assert_eq!(planned[5].forward, planned[3].reference);
assert!(planned[2].reference.is_none() && planned[4].reference.is_none());
}
#[test]
fn frames_in_coding_order_without_b_pictures_or_past_their_references() {
// Without B pictures, a frame sent after a later one predicts from
// the last reference, as nothing predicts from it.
let planned = plan_coded(CodingOrder::new(None, None, false), &[0, 2, 1, 3], &[]);
assert_eq!(types(&planned), "I0 P2 P1 P3");
assert_eq!(planned[2].forward, planned[1].reference);
assert_eq!(planned[2].reference, None);
assert_eq!(planned[3].forward, planned[1].reference);
// Two frames sent ahead of their place: the oldest reference is let
// go, and the frame before both predicts from the last.
let planned = plan_coded(CodingOrder::new(None, None, true), &[0, 3, 4, 1, 2], &[]);
assert_eq!(types(&planned), "I0 P3 P4 P1 P2");
assert_eq!(planned[3].forward, planned[2].reference);
assert_eq!(planned[4].forward, planned[2].reference);
assert_eq!(planned[4].backward, None);
}
#[test]
fn frames_in_coding_order_start_again_at_key_frames() {
// A forced key frame, a place not past the key frame's or the last
// reference's, and the key-frame interval in places and in ticks.
let planned = plan_coded(
CodingOrder::new(Some(4), None, true),
&[0, 2, 1, 3, 4, 4, 3, 6, 5, 7],
&[3],
);
assert_eq!(types(&planned), "I0 P2 B1 I3 P4 I4 I3 P6 B5 I7");
let orders: Vec<u32> = planned.iter().map(|p| p.order).collect();
assert_eq!(orders, [0, 2, 1, 0, 1, 0, 0, 3, 2, 0]);
let mut planner = CodingOrder::new(None, Some(3 * 3000), true);
planner.set_interval(None, Some(2 * 3000));
let planned = plan_coded(planner, &[0, 1, 2, 3], &[]);
assert_eq!(types(&planned), "I0 P1 I2 P3");
// A place past MAX_ORDER from its key frame.
let far = MAX_ORDER + 1;
let planned = plan_coded(CodingOrder::new(None, None, true), &[0, far - 1, far], &[]);
assert_eq!(
types(&planned)
.split(' ')
.map(|t| &t[..1])
.collect::<String>(),
"IPI"
);
}
#[test]
fn decode_times_are_the_ptses_sent_in_order() {
let config = GopConfig {
+7 -173
View File
@@ -380,121 +380,11 @@ impl Runtime for StdRuntime {
}
}
#[cfg(any(test, feature = "testkit"))]
pub use counted::Counted;
/// Waits in real time, up to `real_timeout`, until `ready` holds, asked every millisecond:
/// whether it came in time. A test's wait for the counts of [`Counted`] and of the tests'
/// virtual runtime.
#[cfg(any(test, feature = "testkit"))]
fn within_real(real_timeout: Duration, ready: impl Fn() -> bool) -> bool {
const SLICE: Duration = Duration::from_millis(1);
let mut left = real_timeout;
loop {
if ready() {
return true;
}
if left.is_zero() {
return false;
}
std::thread::sleep(SLICE);
left = left.saturating_sub(SLICE);
}
}
#[cfg(any(test, feature = "testkit"))]
mod counted {
//! A runtime that counts each thread's waits on another's, for the tests of the crate and of
//! its host (the `testkit` feature's).
use std::collections::HashMap;
use std::thread::ThreadId;
use super::*;
/// `R`'s threads, clock and waits, each thread's waits counted ([`Counted::looks`]): a test
/// that acts once another thread waits on the runtime reads the count, where a real sleep in
/// its place only hopes the thread got there, and a check made behind it passes untested
/// when that thread is late.
#[derive(Debug, Default)]
pub struct Counted<R> {
runtime: R,
looks: Mutex<HashMap<ThreadId, u64>>,
}
impl<R: Runtime> Counted<R> {
/// `runtime`, its waits counted from none.
pub fn new(runtime: R) -> Self {
Self {
runtime,
looks: Mutex::new(HashMap::new()),
}
}
/// How many waits `thread` has made on the runtime so far ([`Runtime::wait_until`]):
/// each [`Bell`] wait's and each poll's pause. Each is counted while the thread holds
/// the bell's lock, which its wait releases as it parks, so a ring made once the count
/// is seen to grow reaches the waiting thread: a test waits for it to grow
/// ([`Self::wait_for_looks`]) to know that thread waits, its question asked and
/// unanswered.
pub fn looks(&self, thread: ThreadId) -> u64 {
self.looks.lock().get(&thread).copied().unwrap_or(0)
}
/// Blocks (in real time, up to `real_timeout`) until `thread` has made at least `n`
/// waits on the runtime in all ([`Self::looks`]), or `or` holds (the thread went on
/// without its wait): whether either came in time.
pub fn wait_for_looks(
&self,
thread: ThreadId,
n: u64,
real_timeout: Duration,
or: impl Fn() -> bool,
) -> bool {
within_real(real_timeout, || self.looks(thread) >= n || or())
}
}
impl<R: Runtime> Runtime for Counted<R> {
fn spawn(&self, name: &'static str, body: Box<dyn FnOnce() + Send>) -> std::io::Result<()> {
self.runtime.spawn(name, body)
}
fn now(&self) -> MonoTime {
self.runtime.now()
}
fn wait_until(
&self,
cv: &Condvar,
rings: &mut MutexGuard<'_, Rings>,
deadline: MonoTime,
) -> TimedOut {
{
let mut looks = self.looks.lock();
let n = looks.entry(std::thread::current().id()).or_default();
*n = n.wrapping_add(1);
}
self.runtime.wait_until(cv, rings, deadline)
}
fn exit_step_at(&self, site: &'static Location<'static>) -> Option<ExitStep> {
self.runtime.exit_step_at(site)
}
fn arm_exit(&self) {
self.runtime.arm_exit();
}
}
}
#[cfg(test)]
pub(crate) mod virtual_time {
//! A runtime on virtual time, for the tests: std's threads, and a clock that moves only
//! when a test advances it.
use std::sync::atomic::{AtomicU64, Ordering};
use super::*;
/// How long a wait on virtual time blocks in real time before it looks at the clock again.
@@ -505,8 +395,6 @@ pub(crate) mod virtual_time {
#[derive(Debug, Default)]
pub(crate) struct VirtualRuntime {
now: Mutex<u64>,
/// The looks at the clock its waits have made ([`VirtualRuntime::looks`]).
looks: AtomicU64,
}
impl VirtualRuntime {
@@ -515,27 +403,6 @@ pub(crate) mod virtual_time {
let mut now = self.now.lock();
*now = now.saturating_add(u64::try_from(d.as_nanos()).unwrap_or(u64::MAX));
}
/// How many times its waits have looked at the clock so far: one each
/// [`Runtime::wait_until`], which blocks a slice and then answers. A wait that looks
/// twice has found its deadline not passed and waits on: a test waits for the count
/// ([`Self::wait_for_looks`]) to know a thread waits on the runtime, where a real sleep
/// only hopes it does.
pub(crate) fn looks(&self) -> u64 {
self.looks.load(Ordering::SeqCst)
}
/// Blocks (in real time, up to `real_timeout`) until its waits have looked at the clock
/// at least `n` times in all ([`Self::looks`]), or `or` holds (the waiting thread
/// ended): whether either came in time.
pub(crate) fn wait_for_looks(
&self,
n: u64,
real_timeout: Duration,
or: impl Fn() -> bool,
) -> bool {
within_real(real_timeout, || self.looks() >= n || or())
}
}
impl Runtime for VirtualRuntime {
@@ -555,7 +422,6 @@ pub(crate) mod virtual_time {
rings: &mut MutexGuard<'_, Rings>,
deadline: MonoTime,
) -> TimedOut {
self.looks.fetch_add(1, Ordering::SeqCst);
if self.now() >= deadline {
return TimedOut(true);
}
@@ -604,26 +470,20 @@ mod tests {
/// A ring from another thread ends the wait with the waiter's answer.
#[test]
fn a_ring_wakes_a_wait() {
let rt = Arc::new(Counted::new(StdRuntime));
let rt = StdRuntime::shared();
let bell = Arc::new(Bell::new());
let flag = Arc::new(Mutex::new(false));
let waiter = std::thread::current().id();
let ringer = {
let (rt, bell, flag) = (Arc::clone(&rt), Arc::clone(&bell), Arc::clone(&flag));
let (bell, flag) = (Arc::clone(&bell), Arc::clone(&flag));
StdRuntime::thread("ringer", move || {
// Once the waiter waits, its question asked and unanswered.
let waits = rt.wait_for_looks(waiter, 1, LONG, || false);
std::thread::sleep(Duration::from_millis(5));
*flag.lock() = true;
bell.ring();
waits
})
};
let got = bell.wait_until(&*rt, rt.deadline_in(LONG), || flag.lock().then_some(7));
assert_eq!(got, Some(7));
assert!(
ringer.is_ok_and(|t| t.join().is_ok_and(|waits| waits)),
"rung before the wait"
);
assert!(ringer.is_ok_and(|t| t.join().is_ok()));
}
/// A wait with no answer ends at its deadline, on the runtime's clock: on virtual time only
@@ -639,10 +499,8 @@ mod tests {
let got = bell.wait_until(&*rt, rt.deadline_in(LONG), || None::<()>);
done.give(got);
})
}
.unwrap();
// It looked at the clock twice: it found its deadline not passed, and waits on.
assert!(rt.wait_for_looks(2, LONG, || waiter.is_finished()));
};
std::thread::sleep(Duration::from_millis(20));
let real = StdRuntime;
assert_eq!(
finished.wait_until(&real, real.deadline_in(Duration::from_millis(1))),
@@ -651,31 +509,7 @@ mod tests {
);
rt.advance(LONG);
assert_eq!(finished.wait_until(&real, real.deadline_in(LONG)), Ok(None));
assert!(waiter.join().is_ok());
}
/// A counted runtime counts each thread's waits apart, each a wait of its runtime's.
#[test]
fn a_counted_runtime_counts_each_thread_s_waits() {
let rt = Arc::new(Counted::new(StdRuntime));
let me = std::thread::current().id();
assert_eq!(rt.looks(me), 0);
// A deadline already passed: one wait, which answers at once.
assert_eq!(Bell::new().wait_until(&*rt, rt.now(), || None::<()>), None);
assert_eq!(rt.looks(me), 1);
let other = {
let rt = Arc::clone(&rt);
StdRuntime::thread("other", move || {
let soon = rt.deadline_in(Duration::from_millis(1));
Bell::new().wait_until(&*rt, soon, || None::<()>);
std::thread::current().id()
})
};
let other = other.unwrap().join().unwrap();
assert!(rt.looks(other) >= 1);
assert_eq!(rt.looks(me), 1);
assert!(!rt.wait_for_looks(me, 2, Duration::ZERO, || false));
assert!(rt.wait_for_looks(me, 2, Duration::ZERO, || true));
assert!(waiter.is_ok_and(|t| t.join().is_ok()));
}
/// An answer given before the deadline is taken, however late; one is taken once; and an
@@ -147,7 +147,6 @@ fn access_units_decode_in_place_and_land_by_the_gpu_as_they_read_back() {
width,
height,
b_frames: 0,
coding_order: false,
..params(profile)
};
let mut encoder = NvencEncoder::new(Arc::clone(&gpu), &params).expect("an NVENC session");
@@ -241,7 +240,6 @@ fn a_plane_past_its_registration_is_never_copied() {
width,
height,
b_frames: 0,
coding_order: false,
..params(EncodeProfile::H264High)
};
let mut encoder = NvencEncoder::new(Arc::clone(&gpu), &params).expect("an NVENC session");
@@ -321,7 +319,6 @@ fn a_stream_started_at_a_p_picture_answers_picture_errors_until_its_idr_picture(
width: 1920,
height: 1080,
b_frames: 0,
coding_order: false,
..params(profile)
};
let mut encoder = NvencEncoder::new(Arc::clone(&gpu), &params).expect("an NVENC session");
@@ -381,7 +378,6 @@ fn a_failed_picture_is_copied_and_decoded_on_from_or_refused() {
width: 1920,
height: 1080,
b_frames: 0,
coding_order: false,
..params(profile)
};
let mut encoder = NvencEncoder::new(Arc::clone(&gpu), &params).expect("an NVENC session");
@@ -468,7 +464,6 @@ fn the_pictures_after_one_that_does_not_decode_come_out() {
width: 1920,
height: 1080,
b_frames: 0,
coding_order: false,
..params(EncodeProfile::H264High)
};
let mut encoder = NvencEncoder::new(Arc::clone(&gpu), &params).expect("an NVENC session");
@@ -592,7 +587,6 @@ fn a_smaller_stream_on_a_kept_larger_decoder_decodes_as_on_its_own() {
width,
height,
b_frames: 0,
coding_order: false,
..params(profile)
};
let small = encoded(&gpu, &sized(400, 258), 8);
@@ -784,7 +778,6 @@ fn a_kept_decoder_short_of_surfaces_is_given_more_and_decodes_as_one_made() {
width: 400,
height: 258,
b_frames: 0,
coding_order: false,
..params(profile)
};
let (sets, units) = encoded(&gpu, &params, 16);
@@ -595,26 +595,6 @@ fn nvenc_checks(checks: &mut Checks) {
"NV_ENC_CODEC_PIC_PARAMS",
size_of::<enc::NV_ENC_CODEC_PIC_PARAMS>(),
);
checks.offset(
"NV_ENC_PIC_PARAMS_H264",
"displayPOCSyntax",
enc::H264_DISPLAY_POC_SYNTAX,
);
checks.offset(
"NV_ENC_PIC_PARAMS_H264",
"refPicFlag",
enc::H264_REF_PIC_FLAG,
);
checks.offset(
"NV_ENC_PIC_PARAMS_HEVC",
"displayPOCSyntax",
enc::HEVC_DISPLAY_POC_SYNTAX,
);
checks.offset(
"NV_ENC_PIC_PARAMS_HEVC",
"refPicFlag",
enc::HEVC_REF_PIC_FLAG,
);
layout!(checks, enc::NV_ENC_PIC_PARAMS, "NV_ENC_PIC_PARAMS" {
version, inputWidth, inputHeight, inputPitch, encodePicFlags, frameIdx, inputTimeStamp,
inputDuration, inputBuffer, outputBitstream, completionEvent, bufferFmt, pictureStruct,
+1 -20
View File
@@ -226,8 +226,7 @@ pub(crate) enum Submission {
/// packet, and `idr` makes it an IDR picture with its parameter sets
/// before it. `unadvanced` codes it without advancing the encoder's
/// state, which state buffer 0 then holds as it would be after it
/// ([`Session::restore_state`]). `planned` is its plan in a session
/// without picture type decision.
/// ([`Session::restore_state`]).
Frame {
input: Buffer,
output: Buffer,
@@ -236,24 +235,11 @@ pub(crate) enum Submission {
timestamp: u64,
idr: bool,
unadvanced: bool,
planned: Option<PicturePlan>,
},
/// The end of the stream: every frame NVENC holds comes out.
End,
}
/// A picture as a session without picture type decision (`enablePTD` 0)
/// plans it: its type (`pictureType`), whether later pictures may predict
/// from it (`refPicFlag`), and its order count in display order
/// (`displayPOCSyntax`), of HEVC's member where `hevc`.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct PicturePlan {
pub(crate) picture_type: ffi::NV_ENC_PIC_TYPE,
pub(crate) reference: bool,
pub(crate) display_poc: u32,
pub(crate) hevc: bool,
}
// SAFETY: an NVENC session may be driven from any thread, one call at a
// time; `&mut self` (or the caller's lock) gives that, since it is not
// `Sync`. The pointers it keeps are the driver's handles and the kept
@@ -794,7 +780,6 @@ impl Session {
timestamp,
idr,
unadvanced,
planned,
} => {
let output = self.output(output, &[BufferKind::Bitstream])?;
self.submitted.borrow().check_free(output)?;
@@ -820,10 +805,6 @@ impl Session {
picture.encodePicFlags |= ffi::NV_ENC_PIC_FLAG_DISABLE_ENC_STATE_ADVANCE;
picture.stateBufferIdx = 0;
}
if let Some(plan) = planned {
picture.pictureType = plan.picture_type;
(picture.codecPicParams).set_order(plan.hevc, plan.display_poc, plan.reference);
}
}
Submission::End => picture.encodePicFlags = ffi::NV_ENC_PIC_FLAG_EOS,
}
@@ -11,13 +11,6 @@
//! length. B pictures are never references here, so a reference is encoded
//! at most one frame ahead of its display order.
//!
//! A session in coding order ([`EncodeParams::coding_order`]) takes frames
//! in the order an encoder above it codes them, each at its place in
//! display order, and plans each picture itself, as the codec crate's
//! encoder does (`gop`'s `CodingOrder`): NVENC's picture type decision is
//! off, and each picture goes with its type, whether it is a reference and
//! its order count in display order.
//!
//! A session made to code frames in place ([`NvencEncoder::new_in_place`])
//! codes each frame without advancing NVENC's state, which a state buffer
//! keeps as it is after the frame, and advances it to that state
@@ -30,9 +23,7 @@ use std::collections::VecDeque;
use std::sync::Arc;
use super::ffi::{self, GUID, Zeroed};
use super::{Buffer, PicturePlan, Session, Submission};
use crate::codec::encode::FrameType;
use crate::codec::encode::gop::CodingOrder;
use super::{Buffer, Session, Submission};
use crate::nvidia::cuda::Gpu;
use crate::nvidia::error::Error;
use crate::nvidia::external::ImportedBuffer;
@@ -152,12 +143,6 @@ pub struct EncodeParams {
pub gop_length: Option<u32>,
/// The B pictures between references; 0 for none.
pub b_frames: u32,
/// Whether frames come in the order they are coded, each at its place
/// in display order, its index (module doc): with no B pictures of
/// NVENC's own (`b_frames` 0), a frame sent after a later one is a B
/// picture where the profile and NVENC have them, else a P picture
/// nothing predicts from.
pub coding_order: bool,
/// The level as the bitstream numbers it, or none for NVENC's choice.
pub level: Option<u32>,
/// H.264's entropy coder: true for CABAC, false for CAVLC, none for the
@@ -240,7 +225,7 @@ pub struct RawFrame<'a> {
/// The chroma plane and its bytes per row.
pub chroma: (&'a [u8], usize),
/// The caller's index for the frame, given back with its packet; each
/// later than the last, or in coding order its place in display order.
/// later than the last.
pub index: u64,
/// Whether it must be an IDR picture.
pub force_idr: bool,
@@ -257,7 +242,7 @@ pub struct DeviceFrame<'a> {
/// Bytes from one row to the next: a multiple of 4, as NVENC takes it.
pub pitch: u32,
/// The caller's index for the frame, given back with its packet; each
/// later than the last, or in coding order its place in display order.
/// later than the last.
pub index: u64,
/// Whether it must be an IDR picture.
pub force_idr: bool,
@@ -307,8 +292,6 @@ pub struct NvencEncoder {
/// The next frame is coded as an IDR picture: NVENC's state is not the
/// one after the last frame the caller has.
restart: bool,
/// The planner of a session in coding order (module doc).
coding: Option<CodingOrder>,
session: Session,
/// The device memory registered as input. After the session, which
/// unregisters it as it drops, so that the imports outlive their
@@ -328,31 +311,6 @@ struct Unkept {
idr: bool,
/// What NVENC coded it as.
picture_type: PictureType,
/// Its plan, in coding order.
planned: Option<PicturePlan>,
}
/// NVENC's plan of a picture `planned` in coding order (module doc), of an
/// HEVC session where `hevc`: its type, a P picture nothing predicts from
/// being NVENC's non-reference P, and its order count in display order,
/// H.264's twice its order, as the codec crate's encoder counts it.
fn plan_of(planned: crate::codec::encode::gop::Planned<()>, hevc: bool) -> PicturePlan {
let reference = planned.reference.is_some();
PicturePlan {
picture_type: match (planned.frame_type, reference) {
(FrameType::Idr, _) => ffi::NV_ENC_PIC_TYPE_IDR,
(FrameType::P, true) => ffi::NV_ENC_PIC_TYPE_P,
(FrameType::P, false) => ffi::NV_ENC_PIC_TYPE_NONREF_P,
(FrameType::B, _) => ffi::NV_ENC_PIC_TYPE_B,
},
reference,
display_poc: if hevc {
planned.order
} else {
planned.order.saturating_mul(2)
},
hevc,
}
}
/// Ours: input and bitstream buffers beyond what NVENC holds, so that a
@@ -387,18 +345,7 @@ impl NvencEncoder {
Tuning::LowLatency => ffi::NV_ENC_TUNING_INFO_LOW_LATENCY,
};
let mut config = session.preset_config(codec, preset, tuning)?.presetCfg;
// In coding order, B pictures one at a time where the profile and
// NVENC have them (module doc), configured as NVENC's own would be.
let bidirectional = params.coding_order
&& params.profile.has_b_slices()
&& session.capability(codec, ffi::caps::NUM_MAX_BFRAMES)? >= 1;
configure(
&mut config,
&EncodeParams {
b_frames: params.b_frames.max(u32::from(bidirectional)),
..params.clone()
},
);
configure(&mut config, params);
let mut init = ffi::NV_ENC_INITIALIZE_PARAMS::zeroed();
init.version = ffi::NV_ENC_INITIALIZE_PARAMS_VER;
init.encodeGUID = codec;
@@ -413,7 +360,7 @@ impl NvencEncoder {
init.frameRateNum = params.frame_rate.0.max(1);
init.frameRateDen = params.frame_rate.1.max(1);
init.enableEncodeAsync = 0;
init.enablePTD = u32::from(!params.coding_order);
init.enablePTD = 1;
init.maxEncodeWidth = params.width;
init.maxEncodeHeight = params.height;
init.tuningInfo = tuning;
@@ -431,9 +378,6 @@ impl NvencEncoder {
holds,
unkept: None,
restart: false,
coding: params
.coding_order
.then(|| CodingOrder::new(params.gop_length, None, bidirectional)),
session,
device_inputs: Vec::new(),
};
@@ -517,7 +461,7 @@ impl NvencEncoder {
pitch,
frame.index,
unkept.idr || frame.force_idr,
(unkept.frame_idx, unkept.planned),
unkept.frame_idx,
)
}
@@ -535,7 +479,7 @@ impl NvencEncoder {
frame.pitch,
frame.index,
unkept.idr || frame.force_idr,
(unkept.frame_idx, unkept.planned),
unkept.frame_idx,
)
}
@@ -718,21 +662,19 @@ impl NvencEncoder {
) -> Result<Vec<Bitstream>, Error> {
self.keep_going();
let frame_idx = self.submitted;
let idr = force_idr || self.restart;
let hevc = self.params.profile.is_hevc();
let planned =
(self.coding.as_mut()).map(|coding| plan_of(coding.push((), index, 0, idr), hevc));
let idr = planned.map_or(idr, |plan| plan.picture_type == ffi::NV_ENC_PIC_TYPE_IDR);
self.code(slot_index, input, pitch, index, idr, (frame_idx, planned))
// In coding order the planner took the frame NVENC did not: the
// next one starts again.
.inspect_err(|_| self.restart |= self.coding.is_some())
self.code(
slot_index,
input,
pitch,
index,
force_idr || self.restart,
frame_idx,
)
}
/// Codes the frame in `input` at `pitch` into `slot_index`'s bitstream
/// buffer as `frame_idx`, with its plan in coding order, and reads what
/// comes out; in a session that codes frames in place, without advancing
/// NVENC's state (module doc).
/// buffer as `frame_idx`, and reads what comes out; in a session that
/// codes frames in place, without advancing NVENC's state (module doc).
fn code(
&mut self,
slot_index: usize,
@@ -740,7 +682,7 @@ impl NvencEncoder {
pitch: u32,
index: u64,
idr: bool,
(frame_idx, planned): (u32, Option<PicturePlan>),
frame_idx: u32,
) -> Result<Vec<Bitstream>, Error> {
let status = self.session.encode_picture(Submission::Frame {
input,
@@ -750,7 +692,6 @@ impl NvencEncoder {
timestamp: index,
idr,
unadvanced: self.holds,
planned,
});
let status = match status {
Ok(status) => status,
@@ -777,7 +718,6 @@ impl NvencEncoder {
frame_idx,
idr,
picture_type: packet.picture_type,
planned,
});
}
Ok(bitstreams)
@@ -977,7 +917,6 @@ pub fn codes_in_place(
buffer_milliseconds: 1000,
gop_length: None,
b_frames: 0,
coding_order: false,
level: None,
cabac: None,
full_range: false,
@@ -1252,7 +1191,6 @@ pub(crate) mod tests {
buffer_milliseconds: 1000,
gop_length: Some(30),
b_frames: 2,
coding_order: false,
level: None,
cabac: None,
full_range: true,
@@ -1321,237 +1259,6 @@ pub(crate) mod tests {
(luma, chroma, row)
}
/// What `pictures_of` answers for each picture, in the order its doc
/// lists.
type PictureOrder = (bool, u32, u32, usize, u8);
/// Each picture of an Annex-B access unit of `hevc` or H.264: whether
/// it is a reference (H.264's `nal_ref_idc` above 0, HEVC's `TRAIL_R`
/// or IRAP), its order count (its `pic_order_cnt_lsb`, or H.264's POC
/// type 2's from its `frame_num`) and the count it wraps at; the
/// stream's `max_num_reorder_frames` (HEVC's
/// `sps_max_num_reorder_pics`); and H.264's `pic_order_cnt_type` (0 for
/// HEVC), from the parameter sets the units before it carried, kept in
/// `sets`.
fn pictures_of(
hevc: bool,
au: &[u8],
sets: &mut (Vec<Vec<u8>>, Vec<Vec<u8>>),
) -> Result<Vec<PictureOrder>, Box<dyn std::error::Error>> {
use crate::codec::{h264, hevc as h265};
let mut out = Vec::new();
for unit in crate::codec::encode::nal::split_annex_b(au) {
let kind = if hevc {
(unit[0] >> 1) & 0x3f
} else {
unit[0] & 0x1f
};
match (hevc, kind) {
(false, 7) | (true, 33) => sets.0 = vec![unit.to_vec()],
(false, 8) | (true, 34) => sets.1 = vec![unit.to_vec()],
(false, 1 | 5) => {
let sps = Arc::new(h264::sps::Sps::parse(&sets.0[0])?);
let pps = Arc::new(h264::pps::Pps::parse(&sets.1[0], |_| {
Some(Arc::clone(&sps))
})?);
let nal = h264::nal::NalUnit::new(unit)?;
let slice = h264::slice::SliceHeader::parse(
nal,
|_| Some(Arc::clone(&pps)),
|_| Some(Arc::clone(&sps)),
)?;
let reorder = sps.max_num_reorder_frames();
let reference = slice.nal_ref_idc > 0;
// POC type 2's count, from frame_num (8.2.1.3), the
// pictures here being within frame_num's first wrap.
let (count, wrap) = if sps.pic_order_cnt_type == 2 {
let frames = 1u32 << (sps.log2_max_frame_num_minus4 + 4);
let count = 2 * slice.frame_num - u32::from(!reference);
(count, 2 * frames)
} else {
let wrap = 1 << (sps.log2_max_pic_order_cnt_lsb_minus4 + 4);
(slice.pic_order_cnt_lsb, wrap)
};
out.push((reference, count, wrap, reorder, sps.pic_order_cnt_type));
}
(true, 0..=21) => {
let sps = Arc::new(h265::sps::Sps::parse(&sets.0[0])?);
let pps = Arc::new(h265::pps::Pps::parse(&sets.1[0])?);
let nal = h265::nal::NalUnit::new(unit)?;
let slice = h265::slice::SliceHeader::parse(
nal,
|_| Some(Arc::clone(&pps)),
|_| Some(Arc::clone(&sps)),
None,
)?;
let reorder = usize::from(sps.highest_ordering().max_num_reorder_pics);
let wrap = 1 << (sps.log2_max_pic_order_cnt_lsb_minus4 + 4);
let reference = kind % 2 == 1 || kind >= 16;
out.push((reference, slice.slice_pic_order_cnt_lsb, wrap, reorder, 0));
}
_ => {}
}
}
Ok(out)
}
/// A session in coding order ([`EncodeParams::coding_order`]) codes
/// frames sent as AppleGVA's encoders send them with reordering allowed,
/// each reference before the frame shown ahead of it (`0 2 1 4 3 ... 14
/// 13 15`): each packet is its frame's, out as the frame goes in; a frame
/// sent after a later one is a B picture, no reference; each picture's
/// order count follows its place (H.264's twice it), and the SPS lets a
/// frame come out of display order. H.264 High and HEVC Main. The same
/// frames sent in display order with `coding_order` set code as
/// references in order, at their places' order counts; Baseline's too,
/// which NVENC codes at POC type 2, whose order counts follow the order
/// frames are coded in, so a Baseline frame sent behind a later one would
/// not be shown before it (docs/video/bugs.md, B103).
#[test]
#[ignore = "needs an NVIDIA GPU: run on the NVIDIA host"]
fn frames_in_coding_order_keep_their_places() -> Result<(), Box<dyn std::error::Error>> {
let gpu = Arc::new(crate::nvidia::cuda::Gpu::open(
&crate::nvidia::cuda::GpuSelector::First,
)?);
let mut reordered = vec![0u64];
for pair in 0..7 {
reordered.extend([pair * 2 + 2, pair * 2 + 1]);
}
reordered.push(15);
let in_order: Vec<u64> = (0..16).collect();
for (profile, places) in [
(EncodeProfile::H264High, &reordered),
(EncodeProfile::HevcMain, &reordered),
(EncodeProfile::H264Baseline, &in_order),
(EncodeProfile::H264High, &in_order),
(EncodeProfile::HevcMain, &in_order),
] {
let what = format!("{profile:?} places {places:?}");
let params = EncodeParams {
b_frames: 0,
coding_order: true,
gop_length: None,
cabac: None,
..params(profile)
};
let hevc = profile.is_hevc();
let mut encoder = NvencEncoder::new(Arc::clone(&gpu), &params)?;
let mut sets = (Vec::new(), Vec::new());
for (n, &place) in places.iter().enumerate() {
let (luma, chroma, row) = noise(&params, place);
let packets = encoder.encode(&RawFrame {
luma: (&luma, row),
chroma: (&chroma, row),
index: place,
force_idr: false,
})?;
assert_eq!(packets.len(), 1, "{what} frame {n}");
let packet = packets.into_iter().next().unwrap()?;
assert_eq!(packet.index, place, "{what} frame {n}");
let pictures = pictures_of(hevc, &packet.data, &mut sets)?;
assert_eq!(pictures.len(), 1, "{what} frame {n}");
let (reference, lsb, wrap, reorder, poc_type) = pictures[0];
// NVENC chooses H.264's POC type itself: 2 for Baseline, whose
// order counts follow the order frames are coded in.
assert_eq!(
poc_type == 2,
profile == EncodeProfile::H264Baseline,
"{what} frame {n}: POC type {poc_type}"
);
let behind = n > 0 && place < places[n - 1];
assert_eq!(reference, !behind, "{what} frame {n}");
let scale = if hevc { 1 } else { 2 };
assert_eq!(
u64::from(lsb),
place * scale % u64::from(wrap),
"{what} frame {n}"
);
assert!(
reorder >= 1 || !profile.has_b_slices(),
"{what} frame {n}: the SPS's reorder {reorder}"
);
let want = match (n, behind, profile.has_b_slices()) {
(0, _, _) => PictureType::Idr,
(_, false, _) => PictureType::Predicted,
(_, true, true) => PictureType::Bidirectional,
(_, true, false) => PictureType::NonReferencePredicted,
};
assert_eq!(packet.picture_type, want, "{what} frame {n}");
}
assert!(encoder.flush()?.is_empty(), "{what}");
}
Ok(())
}
/// A session in coding order that codes frames in place
/// ([`NvencEncoder::new_in_place`]), as the guest's HEVC driver sends the
/// plug-in's frames with reordering allowed (`0 2 1 4 3 6 5`), P picture
/// 2 and B picture 1 each coded again in its place: each try is its
/// frame's, of the first try's picture type, order count and reference
/// flag, and the frames after it keep theirs. HEVC Main.
#[test]
#[ignore = "needs an NVIDIA GPU: run on the NVIDIA host"]
fn frames_in_coding_order_are_coded_again_in_place() -> Result<(), Box<dyn std::error::Error>> {
let gpu = Arc::new(crate::nvidia::cuda::Gpu::open(
&crate::nvidia::cuda::GpuSelector::First,
)?);
let params = EncodeParams {
b_frames: 0,
coding_order: true,
gop_length: None,
cabac: None,
..params(EncodeProfile::HevcMain)
};
let mut encoder = NvencEncoder::new_in_place(Arc::clone(&gpu), &params)?;
let mut sets = (Vec::new(), Vec::new());
let sends: [(u64, bool); 9] = [
(0, false),
(2, false),
(2, true),
(1, false),
(1, true),
(4, false),
(3, false),
(6, false),
(5, false),
];
let mut tries: Vec<(PictureType, bool)> = Vec::new();
for (n, &(place, again)) in sends.iter().enumerate() {
let (luma, chroma, row) = noise(&params, place);
let frame = RawFrame {
luma: (&luma, row),
chroma: (&chroma, row),
index: place,
force_idr: false,
};
let packets = if again {
encoder.encode_in_place(&frame)?
} else {
encoder.encode(&frame)?
};
assert_eq!(packets.len(), 1, "try {n}");
let packet = packets.into_iter().next().unwrap()?;
assert_eq!(packet.index, place, "try {n}");
let pictures = pictures_of(true, &packet.data, &mut sets)?;
assert_eq!(pictures.len(), 1, "try {n}");
let (reference, lsb, _, reorder, _) = pictures[0];
assert_eq!(u64::from(lsb), place, "try {n}");
assert_eq!(reference, place % 2 == 0, "try {n}");
assert!(reorder >= 1, "try {n}: the SPS's reorder {reorder}");
if again {
assert_eq!(
(packet.picture_type, reference),
tries[n - 1],
"try {n} against the first"
);
}
tries.push((packet.picture_type, reference));
}
assert_eq!(tries[0].0, PictureType::Idr);
assert!(encoder.flush()?.is_empty());
Ok(())
}
/// What a raw `nvEncLockBitstream` answers for a 4K picture, in turn:
/// with `doNotWait` as soon as the picture is submitted, with
/// `doNotWait` 40 ms later, and waiting 40 ms later; each with how long
@@ -1570,7 +1277,6 @@ pub(crate) mod tests {
width: 3840,
height: 2160,
b_frames: 0,
coding_order: false,
..params(EncodeProfile::HevcMain)
};
let mut encoder = NvencEncoder::new(Arc::clone(&gpu), &params)?;
@@ -1595,7 +1301,6 @@ pub(crate) mod tests {
timestamp: u64::from(n),
idr: (n / 3) % 2 == 0,
unadvanced: false,
planned: None,
})?;
let submit = StdRuntime.elapsed_since(submitting).as_micros();
let handle = session.output(output, &[BufferKind::Bitstream])?;
@@ -1673,7 +1378,6 @@ pub(crate) mod tests {
width: 3840,
height: 2160,
b_frames: 2,
coding_order: false,
..params(EncodeProfile::HevcMain)
};
let mut encoder = NvencEncoder::new(Arc::clone(&gpu), &params)?;
@@ -681,46 +681,14 @@ pub(crate) struct NV_ENC_PRESET_CONFIG {
pub(crate) reserved2: [*mut c_void; 64],
}
/// `NV_ENC_CODEC_PIC_PARAMS`: the codecs' per-picture parameters, a union of
/// `NV_ENC_PIC_PARAMS_H264` and `NV_ENC_PIC_PARAMS_HEVC` among others, which
/// a session with picture type decision leaves zero, and one without sets
/// the display order count and reference flag of ([`Self::set_order`]).
/// `NV_ENC_CODEC_PIC_PARAMS`: the codecs' per-picture parameters, which a
/// session with picture type decision leaves zero.
#[repr(C)]
#[derive(Clone, Copy, Debug)]
pub(crate) struct NV_ENC_CODEC_PIC_PARAMS {
pub(crate) reserved: [u64; 193],
}
/// Byte offsets in `NV_ENC_PIC_PARAMS_H264`, as `crate::nvidia::layout`'s
/// test checks against the header: `displayPOCSyntax` and `refPicFlag`.
pub(crate) const H264_DISPLAY_POC_SYNTAX: usize = 0;
pub(crate) const H264_REF_PIC_FLAG: usize = 8;
/// The same of `NV_ENC_PIC_PARAMS_HEVC`.
pub(crate) const HEVC_DISPLAY_POC_SYNTAX: usize = 0;
pub(crate) const HEVC_REF_PIC_FLAG: usize = 4;
impl NV_ENC_CODEC_PIC_PARAMS {
/// Sets the codec's member's `displayPOCSyntax` to `display_poc` and its
/// `refPicFlag` to `reference`: HEVC's where `hevc`, else H.264's.
pub(crate) fn set_order(&mut self, hevc: bool, display_poc: u32, reference: bool) {
let (poc, flag) = if hevc {
(HEVC_DISPLAY_POC_SYNTAX, HEVC_REF_PIC_FLAG)
} else {
(H264_DISPLAY_POC_SYNTAX, H264_REF_PIC_FLAG)
};
self.put(poc, display_poc);
self.put(flag, u32::from(reference));
}
/// Writes `value` as the 32-bit word at byte `offset`, a multiple of 4.
fn put(&mut self, offset: usize, value: u32) {
let shift = (offset % 8) * 8;
if let Some(word) = self.reserved.get_mut(offset / 8) {
*word = (*word & !(0xffff_ffff_u64 << shift)) | (u64::from(value) << shift);
}
}
}
/// `NV_ENC_PIC_PARAMS`.
#[repr(C)]
#[derive(Clone, Copy, Debug)]
+9 -29
View File
@@ -301,31 +301,16 @@ pub(crate) mod tests {
ready()
}
/// A call that returns `value` once the test sends on the first channel
/// this gives, as a driver's call returns once the GPU is done, and says
/// on the second as it begins, so that a test knows the call thread is in
/// it ([`in_the_call`]), where a real sleep only hopes it is.
fn held<T: Send + 'static>(
value: T,
) -> (
mpsc::Sender<()>,
mpsc::Receiver<()>,
impl FnOnce() -> T + Send,
) {
/// A call that returns `value` once the test sends on the channel this
/// gives, as a driver's call returns once the GPU is done.
fn held<T: Send + 'static>(value: T) -> (mpsc::Sender<()>, impl FnOnce() -> T + Send) {
let (release, released) = mpsc::channel::<()>();
let (begun, inside) = mpsc::channel::<()>();
(release, inside, move || {
let _ = begun.send(());
(release, move || {
let _ = released.recv();
value
})
}
/// Whether the call [`held`] made began within 5 s.
fn in_the_call(inside: &mpsc::Receiver<()>) -> bool {
inside.recv_timeout(Duration::from_secs(5)).is_ok()
}
fn soon() -> MonoTime {
runtime().deadline_in(Duration::from_millis(20))
}
@@ -333,12 +318,12 @@ pub(crate) mod tests {
#[test]
fn a_call_past_its_deadline_is_kept_with_what_it_holds_until_it_returns() {
let calls = Calls::start("test-calls").expect("a thread");
let (release, inside, call) = held(7);
let (release, call) = held(7);
let answer = calls.call(call);
assert!(in_the_call(&inside), "the call never began");
assert_eq!(answer_by(&answer, soon()).err(), Some(Unanswered::TimedOut));
let holds = Arc::new(());
let mut kept = Unreturned::new(answer, vec![Box::new(Arc::clone(&holds))]);
std::thread::sleep(Duration::from_millis(20));
assert!(!kept.finished());
assert_eq!(Arc::strong_count(&holds), 2);
release.send(()).expect("the call waits");
@@ -350,14 +335,12 @@ pub(crate) mod tests {
#[test]
fn the_thread_takes_the_next_call_only_once_the_last_has_returned() {
let calls = Calls::start("test-calls").expect("a thread");
let (release, inside, call) = held(1);
let (release, call) = held(1);
let first = calls.call(call);
assert!(in_the_call(&inside), "the call never began");
assert_eq!(answer_by(&first, soon()).err(), Some(Unanswered::TimedOut));
let made = Arc::new(AtomicBool::new(false));
let making = Arc::clone(&made);
let second = calls.call(move || making.store(true, Ordering::SeqCst));
// Room for a second call made beside the first to show.
std::thread::sleep(Duration::from_millis(20));
assert!(
!made.load(Ordering::SeqCst),
@@ -372,9 +355,8 @@ pub(crate) mod tests {
#[test]
fn an_order_not_yet_taken_is_replaced_and_answers_that_none_is_to_come() {
let calls = Calls::start("test-calls").expect("a thread");
let (release, inside, call) = held(());
let (release, call) = held(());
let first = calls.call(call);
assert!(in_the_call(&inside), "the call never began");
assert_eq!(answer_by(&first, soon()).err(), Some(Unanswered::TimedOut));
let replaced = calls.call(|| 1);
let next = calls.call(|| 2);
@@ -387,12 +369,10 @@ pub(crate) mod tests {
fn the_thread_ends_once_its_calls_drop_and_its_call_returns() {
let calls = Calls::start("test-calls").expect("a thread");
let shared = Arc::downgrade(&calls.shared);
let (release, inside, call) = held(());
let (release, call) = held(());
let answer = calls.call(call);
assert!(in_the_call(&inside), "the call never began");
assert_eq!(answer_by(&answer, soon()).err(), Some(Unanswered::TimedOut));
drop(calls);
// Room for the thread to end in its call to show.
std::thread::sleep(Duration::from_millis(20));
assert_eq!(shared.strong_count(), 1, "the thread ended in its call");
release.send(()).expect("the call waits");
+1 -2
View File
@@ -30,7 +30,6 @@
)]
pub mod atom;
mod counts;
pub mod decoder;
pub mod encoder;
mod host;
@@ -50,7 +49,7 @@ mod session;
pub mod status;
pub use decoder::{
Backend, BackendDecoder, Decoded, DecoderConfig, LandedBy, OutputAlignment, Stream, TileLimits,
Backend, BackendDecoder, Decoded, DecoderConfig, OutputAlignment, Stream, TileLimits,
TileRegion,
};
pub use encoder::{BackendEncoder, Encoder, EncoderBackend, EncoderConfig, SourceFrame};
@@ -1,102 +0,0 @@
//! What a session's end line is made of ([`super::decoder`]'s and [`super::encoder`]'s module
//! docs, "Its counts"): counts of statuses, and the time its backend took. A line carries totals,
//! statuses and causes alone, nothing of the guest's content.
use std::collections::BTreeMap;
use std::time::Duration;
use crate::paravirt::status::OsStatus;
/// How many times each status came, by status.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub(crate) struct Statuses(BTreeMap<OsStatus, u64>);
impl Statuses {
/// Counts one more of `status`.
pub(crate) fn note(&mut self, status: OsStatus) {
*self.0.entry(status).or_default() += 1;
}
/// How many came, of every status.
pub(crate) fn total(&self) -> u64 {
self.0.values().sum()
}
/// Each status with its count where it came more than once, in ascending order:
/// `-12911 x2, -12909`.
pub(crate) fn says(&self) -> String {
(self.0.iter())
.map(|(status, n)| match n {
1 => status.to_string(),
n => format!("{status} x{n}"),
})
.collect::<Vec<_>>()
.join(", ")
}
/// `n what (statuses)`, or `n what` with none.
pub(crate) fn clause(&self, what: &str) -> String {
match self.total() {
0 => format!("0 {what}"),
n => format!("{n} {what} ({})", self.says()),
}
}
}
/// The calls a backend took, all told and the longest.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(crate) struct Timing {
calls: u64,
total: Duration,
most: Duration,
}
impl Timing {
/// Counts a call that took `took`.
pub(crate) fn note(&mut self, took: Duration) {
self.calls += 1;
self.total = self.total.saturating_add(took);
self.most = self.most.max(took);
}
/// `; 1.250 ms each in the WHERE, 4.000 ms at most`, or nothing where no call was timed.
pub(crate) fn says(&self, place: &str) -> String {
if self.calls == 0 {
return String::new();
}
let ms = |d: Duration| d.as_secs_f64() * 1e3;
let mean = self.total.as_secs_f64() * 1e3 / self.calls as f64;
format!(
"; {mean:.3} ms each in the {place}, {:.3} ms at most",
ms(self.most)
)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn statuses_are_said_in_order_with_their_counts() {
let mut statuses = Statuses::default();
assert_eq!(statuses.clause("failed"), "0 failed");
statuses.note(-12909);
statuses.note(-12911);
statuses.note(-12911);
assert_eq!(statuses.total(), 3);
assert_eq!(statuses.clause("failed"), "3 failed (-12911 x2, -12909)");
}
#[test]
fn a_timing_says_its_mean_and_its_longest() {
let mut timing = Timing::default();
assert_eq!(timing.says("decoder"), "");
timing.note(Duration::from_millis(1));
timing.note(Duration::from_millis(3));
assert_eq!(
timing.says("decoder"),
"; 2.000 ms each in the decoder, 3.000 ms at most"
);
}
}
+90 -320
View File
@@ -76,24 +76,11 @@
//! takes none, is let go of at once (`rels`): the guest's kext holds each surface it lent until
//! the host lets go of it.
//!
//! **Its counts.** A session counts what each of its frames and tiles came to ([`Counts`]), from
//! its own state and the backend's answers, with no pixel read and no query of the hardware, and
//! logs them in one line at `info` as it ends, where it was sent a frame or a tile: totals,
//! statuses and causes alone. Each frame is one of:
//! - **landed**, emitted with the buffer its picture landed in, by what wrote it there
//! ([`LandedBy`]: the hardware, the device's GPU's copy or gather, or the CPU's copy);
//! - **dropped**, emitted with no picture decoded (`kVTDecodeInfo_FrameDropped`);
//! - **failed**, emitted with a status and no buffer, by its cause: no buffer lent in time (the
//! `Dbuf` unanswered within [`BUFFER_REPLY_WAIT`]), the guest's buffer refused (its status, or
//! a reply with no buffer), a sample that does not read, no decoder opened (a reopen the
//! backend refused), or the decoder's failure, each with its statuses;
//! - **answered with no decoder** ([`NO_DECODER`]), with no `Demt`.
//!
//! It also counts its emits the guest did not answer within [`EMIT_REPLY_WAIT`], its messages
//! it could not read, a `dsta` it refused with its status, its tiles landed (by [`LandedBy`]) and
//! failed (by status), and the time each backend decode took. Only landed frames and tiles hand
//! the guest a buffer, so on this route the guest is never handed a buffer no picture landed in,
//! and the line says so.
//! **Its counts.** A session counts what its frames handed the guest ([`Emitted`]), from its own
//! state, with no pixel read, and logs them at `info` as it ends: frames emitted with the buffer
//! their picture landed in, frames emitted dropped with no picture decoded, and frames emitted
//! with a failure status. Only the first hand the guest a picture: the others carry no buffer,
//! so on this route the guest is never handed a buffer no picture landed in.
use std::sync::Arc;
use std::sync::mpsc::Receiver;
@@ -109,7 +96,6 @@ use crate::codec::vp9::{self, config::VpCodecConfiguration};
use crate::core::backend::{Chroma, PixelFormat};
use crate::core::fourcc::FourCc;
use crate::core::runtime::Runtime;
use crate::paravirt::counts::{Statuses, Timing};
use crate::paravirt::host::Codec;
use crate::paravirt::image_description::{
AV1_CONFIGURATION, AVC_CONFIGURATION, HEVC_CONFIGURATION, ImageDescription, VP_CONFIGURATION,
@@ -282,49 +268,12 @@ pub struct DecoderConfig {
/// What a backend's decode of one access unit came to.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Decoded {
/// The picture is in the output surface, written there as it says.
Landed(LandedBy),
/// The picture is in the output surface.
Landed,
/// The stream's random access skips the picture, and the output got nothing.
Skipped,
}
/// What wrote a landed picture into the output surface, as the arm's decoder knows it at its
/// answer: the session counts its pictures by it (the module doc, "Its counts").
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum LandedBy {
/// The hardware decoder's own write: the driver's video processing into the surface's
/// import (VA-API), or CUDA's copies into its registered pages (NVDEC).
Hardware,
/// The device's GPU: a copy or a gather into the surface, from a scratch the hardware wrote
/// or from the hardware decoder's own picture (a Mac host's VideoToolbox IOSurface).
Gpu,
/// The CPU's copy of the picture, read back from the hardware.
Cpu,
}
impl LandedBy {
/// Each, in the order the end line says them.
const ALL: [LandedBy; 3] = [LandedBy::Hardware, LandedBy::Gpu, LandedBy::Cpu];
/// Its place in [`Self::ALL`].
fn index(self) -> usize {
match self {
LandedBy::Hardware => 0,
LandedBy::Gpu => 1,
LandedBy::Cpu => 2,
}
}
/// What the end line says of it.
fn says(self) -> &'static str {
match self {
LandedBy::Hardware => "by the hardware",
LandedBy::Gpu => "by the device's GPU",
LandedBy::Cpu => "copied by the CPU",
}
}
}
/// The part of a tile's picture a `dtil` lands, and where in its output buffer, in luma samples.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct TileRegion {
@@ -472,7 +421,7 @@ pub(crate) fn start(
fragments: Vec::new(),
discarding: false,
tiles: None,
counts: Counts::default(),
emitted: Emitted::default(),
unmade: false,
fragment_surfaces: Vec::new(),
}
@@ -530,8 +479,8 @@ struct Worker {
discarding: bool,
/// The tile session a `dsts` started.
tiles: Option<TileSession>,
/// What its frames and tiles came to, logged at its end.
counts: Counts,
/// What its frames handed the guest, logged at its end.
emitted: Emitted,
/// Whether the decoder is gone because a sample's description did not reopen it: a later
/// sample that carries a description opens it again (module doc).
unmade: bool,
@@ -539,174 +488,41 @@ struct Worker {
fragment_surfaces: Vec<Arc<dyn LentSurface>>,
}
/// Why a frame failed, which the session counts (the module doc, "Its counts").
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Failure {
/// The guest lent no buffer within [`BUFFER_REPLY_WAIT`], or the `Dbuf` was not sent.
BufferUnanswered,
/// The guest refused the buffer with a status, or replied with no buffer.
BufferRefused,
/// The sample's data did not read: none, or NAL units past their lengths.
Sample,
/// No decoder was opened for it: the backend refused a reopen.
Unopened,
/// The decoder failed it.
Decoder,
}
impl Failure {
const ALL: [Failure; 5] = [
Failure::BufferUnanswered,
Failure::BufferRefused,
Failure::Sample,
Failure::Unopened,
Failure::Decoder,
];
fn index(self) -> usize {
match self {
Failure::BufferUnanswered => 0,
Failure::BufferRefused => 1,
Failure::Sample => 2,
Failure::Unopened => 3,
Failure::Decoder => 4,
}
}
fn says(self) -> &'static str {
match self {
Failure::BufferUnanswered => "with no buffer lent in time",
Failure::BufferRefused => "with the guest's buffer refused",
Failure::Sample => "whose sample did not read",
Failure::Unopened => "with no decoder opened",
Failure::Decoder => "failed by the decoder",
}
}
}
/// What a frame's `Demt` hands the guest, and why.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Outcome {
/// The picture, in the buffer `uuid`, written there as `by` says.
Landed(LandedBy, GuestUuid),
/// No picture decoded: noErr, flagged dropped, with no buffer.
Dropped,
/// The status, for the cause, with no buffer.
Failed(Failure, OsStatus),
}
/// What a session's frames and tiles came to (the module doc, "Its counts").
#[derive(Clone, Debug, Default, PartialEq, Eq)]
struct Counts {
/// `dfrm`s carried out: frames landed, dropped, failed and answered with no decoder.
frames: u64,
/// Frames landed, by [`LandedBy`] (its index in [`LandedBy::ALL`]).
landed: [u64; 3],
/// Frames dropped with no picture decoded.
/// What a session's frames handed the guest, by class (the module docs, "Its counts").
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
struct Emitted {
/// Frames emitted with the buffer their picture landed in.
landed: u64,
/// Frames emitted dropped, no picture decoded for them, with no buffer.
dropped: u64,
/// Frames failed, by [`Failure`] (its index in [`Failure::ALL`]).
failed: [Statuses; 5],
/// Frames answered [`NO_DECODER`], with no `Demt`.
no_decoder: u64,
/// `Demt`s and `TDem`s the guest did not answer within [`EMIT_REPLY_WAIT`].
unanswered: u64,
/// Messages it could not read ([`MESSAGE_UNREAD`]).
unread: u64,
/// The status its `dsta` was refused with, where it was.
start_refused: Option<OsStatus>,
/// Tiles landed, by [`LandedBy`].
tiles_landed: [u64; 3],
/// Tiles failed, by status.
tiles_failed: Statuses,
/// The backend's decodes of frames and tiles.
decodes: Timing,
/// Frames emitted with a failure status, with no buffer.
failed: u64,
}
impl Counts {
/// Counts a frame's `outcome`.
fn note(&mut self, outcome: Outcome) {
match outcome {
Outcome::Landed(by, _) => {
if let Some(n) = self.landed.get_mut(by.index()) {
*n += 1;
}
}
Outcome::Dropped => self.dropped += 1,
Outcome::Failed(failure, status) => {
if let Some(statuses) = self.failed.get_mut(failure.index()) {
statuses.note(status);
}
}
impl Emitted {
/// Counts a frame emitted with `status` and `buffer`.
fn note(&mut self, status: OsStatus, buffer: Option<GuestUuid>) {
match buffer {
Some(_) => self.landed += 1,
None if status == status::NO_ERROR => self.dropped += 1,
None => self.failed += 1,
}
}
/// Counts a tile's status, landed `by` where it landed.
fn note_tile(&mut self, landed: Result<LandedBy, OsStatus>) {
match landed {
Ok(by) => {
if let Some(n) = self.tiles_landed.get_mut(by.index()) {
*n += 1;
}
}
Err(status) => self.tiles_failed.note(status),
}
}
/// The session's end line, of a session of `codec`, where it was sent a frame or a tile.
fn line(&self, codec: Codec) -> Option<String> {
let tiles = self.tiles_landed.iter().sum::<u64>() + self.tiles_failed.total();
if self.frames == 0 && tiles == 0 {
return None;
}
let ways = |landed: &[u64; 3]| {
let total: u64 = landed.iter().sum();
let each = (LandedBy::ALL.iter().zip(landed))
.filter(|(_, n)| **n > 0)
.map(|(by, n)| format!("{n} {}", by.says()))
.collect::<Vec<_>>();
match each.is_empty() {
true => format!("{total}"),
false => format!("{total} ({})", each.join(", ")),
}
};
let failed: u64 = self.failed.iter().map(Statuses::total).sum();
let causes = (Failure::ALL.iter().zip(&self.failed))
.filter(|(_, statuses)| statuses.total() > 0)
.map(|(failure, statuses)| statuses.clause(failure.says()))
.collect::<Vec<_>>();
let failed = match causes.is_empty() {
true => format!("{failed} failed"),
false => format!("{failed} failed ({})", causes.join(", ")),
};
let start = match self.start_refused {
Some(status) => format!("; its start refused ({status})"),
None => String::new(),
};
let tiles = match tiles {
0 => String::new(),
_ => format!(
"; tiles: landed {}, {}",
ways(&self.tiles_landed),
self.tiles_failed.clause("failed")
),
};
let unread = match self.unread {
0 => String::new(),
n => format!("; {n} messages it could not read"),
};
Some(format!(
"hardware video: a VideoToolbox decoder session of {} ended after {} frames: landed \
{}; {} dropped with no picture decoded; {failed}; {} answered with no decoder; {} \
emits the guest did not answer{start}{tiles}{unread}{}; no buffer without its \
picture handed the guest",
codec.name(),
self.frames,
ways(&self.landed),
self.dropped,
self.no_decoder,
self.unanswered,
self.decodes.says("decoder"),
))
/// The session's end line, where it emitted a frame.
fn line(&self) -> Option<String> {
let Emitted {
landed,
dropped,
failed,
} = *self;
(landed + dropped + failed > 0).then(|| {
format!(
"hardware video: a VideoToolbox decoder session ended: {landed} frames emitted \
with their picture, {dropped} dropped with no picture decoded, {failed} failed; \
no buffer without its picture handed the guest"
)
})
}
}
@@ -722,7 +538,6 @@ impl Worker {
self.handle(&job.bytes, &mut surfaces)
};
if let Err(error) = handled {
self.counts.unread += 1;
self.shared.count(MESSAGE_UNREAD);
log::warn!(
kind:% = error;
@@ -735,10 +550,8 @@ impl Worker {
}
self.shared
.let_go(&std::mem::take(&mut self.fragment_surfaces));
if let Some(line) = self.counts.line(self.codec) {
if let Some(line) = self.emitted.line() {
log::info!("{line}");
#[cfg(test)]
self.shared.said_at_end(line);
}
}
@@ -811,9 +624,6 @@ impl Worker {
},
None => status::VIDEO_DECODER_UNSUPPORTED_DATA_FORMAT,
};
if status != NO_ERROR {
self.counts.start_refused = Some(status);
}
self.reply_status(message, status)
}
@@ -894,17 +704,6 @@ impl Worker {
.sample_buffer(names::SAMPLE_BUFFER)?
.ok_or(WireError::Malformed("no sample buffer"))?;
let sample = SampleBuffer::parse(&serialization)?;
if let Some(timing) = sample.timings.first() {
let at = timing.presentation;
(self.shared).trace(
"vtdfrm",
&[
frame.cast_unsigned(),
at.value.cast_unsigned(),
u64::from(at.timescale.cast_unsigned()),
],
);
}
let flags = message.u32(names::DECODE_FLAGS)?.unwrap_or(0);
let info = if flags & DECODE_ASYNCHRONOUSLY != 0 {
INFO_ASYNCHRONOUS
@@ -923,9 +722,7 @@ impl Worker {
.format_description
.as_ref()
.is_some_and(|format| config_from_format(format).is_some());
self.counts.frames += 1;
if self.decoder.is_none() && !reopens {
self.counts.no_decoder += 1;
reply.info = 0;
self.send_frame_reply(&mut reply, NO_DECODER);
return Ok(());
@@ -980,9 +777,6 @@ impl Worker {
},
None => status::VIDEO_DECODER_UNSUPPORTED_DATA_FORMAT,
};
if status != NO_ERROR {
self.counts.start_refused = Some(status);
}
self.reply_status(message, status)
}
@@ -1126,12 +920,11 @@ impl Worker {
.sample_buffer(names::SAMPLE_BUFFER)?
.ok_or(WireError::Malformed("no sample buffer"))?;
let sample = SampleBuffer::parse(&serialization)?;
let landed = match tile_region(origin, size, at) {
let status = match tile_region(origin, size, at) {
Some(region) => self.land_tile(&sample, region, surfaces.first()),
None => Err(status::PARAMETER),
None => status::PARAMETER,
};
self.counts.note_tile(landed);
self.emit_tile(tile, landed.err().unwrap_or(NO_ERROR), buffer);
self.emit_tile(tile, status, buffer);
let mut reply = MessageWriter::reply_to(&last, MessageFlags::REPLY_TO_GUEST);
reply.s32(names::ERROR, status::NO_ERROR);
reply.u32(names::INFO_FLAGS, 0);
@@ -1139,41 +932,34 @@ impl Worker {
Ok(())
}
/// Decodes `sample`, a tile, and lands `region` of it in `output`: what wrote it there, or the
/// status its `TDem` carries.
/// Decodes `sample`, a tile, and lands `region` of it in `output`: the status its `TDem`
/// carries.
fn land_tile(
&mut self,
sample: &SampleBuffer,
region: TileRegion,
output: Option<&Arc<dyn LentSurface>>,
) -> Result<LandedBy, OsStatus> {
) -> OsStatus {
let Some(tiles) = self.tiles.as_mut() else {
return Err(NO_DECODER);
return NO_DECODER;
};
let Some(output) = output else {
return Err(status::PARAMETER);
return status::PARAMETER;
};
let access_unit = (sample.data.as_deref())
.ok_or(status::VIDEO_DECODER_BAD_DATA)
.and_then(|data| annex_b(data, tiles.length_size));
let parameter_sets = std::mem::take(&mut tiles.parameter_sets);
let decoded = match access_unit {
Ok(au) => {
let began = self.runtime.now();
let decoded = (tiles.decoder).decode_tile(&parameter_sets, &au, &**output, region);
self.counts.decodes.note(self.runtime.elapsed_since(began));
decoded
}
Err(status) => Err(status),
};
let decoded = access_unit
.and_then(|au| (tiles.decoder).decode_tile(&parameter_sets, &au, &**output, region));
match decoded {
Ok(Decoded::Landed(by)) => Ok(by),
Ok(Decoded::Landed) => NO_ERROR,
// A tile is a picture of its own: one its decode skips landed nothing.
Ok(Decoded::Skipped) => Err(status::VIDEO_DECODER_BAD_DATA),
Ok(Decoded::Skipped) => status::VIDEO_DECODER_BAD_DATA,
Err(status) => {
// The next tile gets the parameter sets this one did not land with.
tiles.parameter_sets = parameter_sets;
Err(status)
status
}
}
}
@@ -1190,9 +976,8 @@ impl Worker {
message.uuid(names::TILE_BUFFER_UUID, uuid);
}
});
match sent {
Ok(reply) => self.shared.let_go(&reply.surfaces),
Err(_) => self.counts.unanswered += 1,
if let Ok(reply) = sent {
self.shared.let_go(&reply.surfaces);
}
}
@@ -1208,19 +993,18 @@ impl Worker {
Some(Err(status)) => {
self.decoder = None;
self.unmade = true;
Err((Failure::Unopened, status))
Err(status)
}
_ => sample
.data
.as_deref()
.ok_or(status::VIDEO_DECODER_BAD_DATA)
.and_then(|data| annex_b(data, self.length_size))
.map_err(|status| (Failure::Sample, status)),
.and_then(|data| annex_b(data, self.length_size)),
};
let buffer = match self.create_pixel_buffer(frame) {
Ok(buffer) => buffer,
Err((failure, status)) => {
self.emit(frame, Outcome::Failed(failure, status), reply.info);
Err(status) => {
self.emit(frame, status, reply.info, None);
return;
}
};
@@ -1228,31 +1012,30 @@ impl Worker {
self.send_frame_reply(reply, status::NO_ERROR);
}
let parameter_sets = std::mem::take(&mut self.parameter_sets);
let decoded = match (access_unit, self.decoder.as_mut()) {
(Err(failed), _) => Err(failed),
(Ok(_), None) => Err((Failure::Unopened, status::VIDEO_DECODER_MALFUNCTION)),
(Ok(au), Some(decoder)) => {
let began = self.runtime.now();
let decoded = decoder.decode(&parameter_sets, &au, &*buffer.surface);
self.counts.decodes.note(self.runtime.elapsed_since(began));
decoded.map_err(|status| (Failure::Decoder, status))
}
};
let decoded = access_unit.and_then(|au| match self.decoder.as_mut() {
Some(decoder) => decoder.decode(&parameter_sets, &au, &*buffer.surface),
None => Err(status::VIDEO_DECODER_MALFUNCTION),
});
if decoded.is_err() {
// The next frame gets the parameter sets this one did not land with, as a tile does:
// an arm that makes its decoder from them at the first decode makes it at the next.
self.parameter_sets = parameter_sets;
}
match decoded {
Ok(Decoded::Landed(by)) => {
self.emit(frame, Outcome::Landed(by, buffer.uuid), reply.info);
Ok(Decoded::Landed) => {
self.emit(frame, status::NO_ERROR, reply.info, Some(buffer.uuid))
}
Ok(Decoded::Skipped) => {
self.emit(frame, Outcome::Dropped, reply.info | INFO_FRAME_DROPPED);
self.emit(
frame,
status::NO_ERROR,
reply.info | INFO_FRAME_DROPPED,
None,
);
self.free_unused(buffer.uuid);
}
Err((failure, status)) => {
self.emit(frame, Outcome::Failed(failure, status), reply.info);
Err(status) => {
self.emit(frame, status, reply.info, None);
self.free_unused(buffer.uuid);
}
}
@@ -1294,19 +1077,16 @@ impl Worker {
(self.shared).request_then(&*self.runtime, id, &[], &last, wait, then)
}
/// `Dbuf`: the buffer the guest lends for frame `frame`, or why there is none: the guest's
/// status, or ours, with its cause.
fn create_pixel_buffer(&mut self, frame: i64) -> Result<GuestBuffer, (Failure, OsStatus)> {
let reply = self
.request_then(
names::CREATE_PIXEL_BUFFER,
BUFFER_REPLY_WAIT,
|message| {
message.s64(names::FRAME, frame);
},
Some(Box::new(free_late_buffer)),
)
.map_err(|status| (Failure::BufferUnanswered, status))?;
/// `Dbuf`: the buffer the guest lends for frame `frame`, or the guest's status, or ours.
fn create_pixel_buffer(&mut self, frame: i64) -> Result<GuestBuffer, OsStatus> {
let reply = self.request_then(
names::CREATE_PIXEL_BUFFER,
BUFFER_REPLY_WAIT,
|message| {
message.s64(names::FRAME, frame);
},
Some(Box::new(free_late_buffer)),
)?;
let mut surfaces = reply.surfaces.into_iter();
let surface = surfaces.next();
// A buffer has one surface; more go back.
@@ -1331,25 +1111,16 @@ impl Worker {
self.shared.let_go(&[surface]);
}
// A buffer is made of its surface, and fails without one.
Err((
Failure::BufferRefused,
lent.err().unwrap_or(status::PARAMETER),
))
Err(lent.err().unwrap_or(status::PARAMETER))
}
}
}
/// `Demt`: the frame's status and info flags, and the buffer it was decoded into, where its
/// picture landed (`outcome`), counted; the guest's answer is waited for and not read.
fn emit(&mut self, frame: i64, outcome: Outcome, info: u32) {
/// `Demt`: the frame's status and info flags, and the buffer it was decoded into; the guest's
/// answer is waited for and not read.
fn emit(&mut self, frame: i64, status: OsStatus, info: u32, buffer: Option<GuestUuid>) {
video_delay::at(Point::Answer).wait();
self.counts.note(outcome);
let (status, buffer, traced) = match outcome {
Outcome::Landed(_, uuid) => (status::NO_ERROR, Some(uuid), 1),
Outcome::Dropped => (status::NO_ERROR, None, 2),
Outcome::Failed(_, status) => (status, None, 3),
};
(self.shared).trace("vtdemt", &[frame.cast_unsigned(), traced]);
self.emitted.note(status, buffer);
let sent = self.request(names::EMIT_DECODED_FRAME, EMIT_REPLY_WAIT, |message| {
message.s64(names::FRAME, frame);
message.s32(names::ERROR, status);
@@ -1358,9 +1129,8 @@ impl Worker {
message.uuid(names::PIXEL_BUFFER_UUID, uuid);
}
});
match sent {
Ok(reply) => self.shared.let_go(&reply.surfaces),
Err(_) => self.counts.unanswered += 1,
if let Ok(reply) = sent {
self.shared.let_go(&reply.surfaces);
}
}
@@ -71,9 +71,6 @@ type Calls = Arc<Mutex<Vec<(Vec<u8>, Vec<u8>, u64)>>>;
/// The regions the fake backend's decoders landed tiles in, a tile each.
type Regions = Arc<Mutex<Vec<TileRegion>>>;
/// What the fake backend's decoders answer their next decodes, in order, before their `result`.
type Script = Arc<Mutex<std::collections::VecDeque<Result<Decoded, OsStatus>>>>;
struct FakeBackend {
calls: Calls,
regions: Regions,
@@ -87,8 +84,6 @@ struct FakeBackend {
gate: Option<Gate>,
/// How many of its decoders were dropped.
dropped: Arc<AtomicUsize>,
/// What its decoders answer their next decodes.
script: Script,
}
/// Where a fake decoder holds each decode before it writes its output ([`FakeDecoder::hold`]): it
@@ -132,7 +127,6 @@ struct FakeDecoder {
first_fails: Option<OsStatus>,
gate: Option<Gate>,
dropped: Arc<AtomicUsize>,
script: Script,
}
impl FakeDecoder {
@@ -157,13 +151,12 @@ impl FakeBackend {
Self {
calls: Calls::default(),
regions: Regions::default(),
result: Ok(Decoded::Landed(LandedBy::Hardware)),
result: Ok(Decoded::Landed),
tiles: None,
first_fails: None,
fail_opens: Arc::default(),
gate: None,
dropped: Arc::default(),
script: Script::default(),
}
}
}
@@ -183,7 +176,6 @@ impl Backend for FakeBackend {
first_fails: self.first_fails,
gate: self.gate.clone(),
dropped: Arc::clone(&self.dropped),
script: Arc::clone(&self.script),
}))
}
}
@@ -232,9 +224,6 @@ impl BackendDecoder for FakeDecoder {
self.calls
.lock()
.push((parameter_sets.to_vec(), access_unit.to_vec(), output.id()));
if let Some(scripted) = self.script.lock().pop_front() {
return scripted;
}
match self.first_fails.take() {
Some(status) => Err(status),
None => self.result,
@@ -276,8 +265,6 @@ struct Guest {
codec: [u8; 4],
/// The codes the session counted on its link.
counted: Counted,
/// What the backend's decoders answer their next decodes.
script: Script,
}
impl Guest {
@@ -327,14 +314,7 @@ impl Guest {
/// asks its output buffers in the pictures' own alignments ([`PicturesOwn`]).
fn in_pictures_own_alignment(tiles: Option<TileLimits>) -> Self {
let arm: fn(FakeBackend) -> Arc<dyn Backend> = |fake| Arc::new(PicturesOwn(fake));
Self::built(
Codec::H264,
Ok(Decoded::Landed(LandedBy::Hardware)),
tiles,
arm,
None,
None,
)
Self::built(Codec::H264, Ok(Decoded::Landed), tiles, arm, None, None)
}
/// An H.264 session whose decoders land every picture and decode `tiles`, each decode held
@@ -343,7 +323,7 @@ impl Guest {
let (gate, held) = gate();
let guest = Self::built(
Codec::H264,
Ok(Decoded::Landed(LandedBy::Hardware)),
Ok(Decoded::Landed),
tiles,
|fake| Arc::new(fake),
None,
@@ -366,7 +346,6 @@ impl Guest {
let regions = Regions::default();
let fail_opens = Arc::<Mutex<usize>>::default();
let dropped = Arc::<AtomicUsize>::default();
let script = Script::default();
let fake = FakeBackend {
calls: Arc::clone(&calls),
regions: Arc::clone(&regions),
@@ -376,7 +355,6 @@ impl Guest {
fail_opens: Arc::clone(&fail_opens),
gate,
dropped: Arc::clone(&dropped),
script: Arc::clone(&script),
};
let backend = arm(fake);
let (fourcc, profiles, max_level) = match codec {
@@ -403,7 +381,6 @@ impl Guest {
dropped,
codec: fourcc,
counted,
script,
};
let answer = guest.send(
b"+dec",
@@ -654,7 +631,7 @@ fn output_rows_are_the_least_alignment_that_makes_the_luma_whole_pages() {
#[test]
fn a_start_sends_the_buffer_attributes_then_its_reply() {
let guest = Guest::new(Ok(Decoded::Landed(LandedBy::Hardware)));
let guest = Guest::new(Ok(Decoded::Landed));
guest.start(&avcc(&SPS, 4));
let (_, dpba) = guest.next_of(b"Dpba");
let attributes = plist_of(&dpba, names::PIXEL_BUFFER_ATTRIBUTES);
@@ -695,7 +672,7 @@ fn a_start_sends_the_buffer_attributes_then_its_reply() {
/// out no further: two starts with no format description, before one with it, which starts.
#[test]
fn each_message_the_session_cannot_read_is_counted_on_its_link() {
let guest = Guest::new(Ok(Decoded::Landed(LandedBy::Hardware)));
let guest = Guest::new(Ok(Decoded::Landed));
for _ in 0..2 {
let flags = MessageFlags::GUEST_EXPECTS_REPLY;
guest.send(b"dsta", flags, 2, Vec::new(), |_| {});
@@ -714,7 +691,7 @@ fn a_start_on_a_record_no_decoder_here_takes_is_refused_without_attributes() {
(avcc(&INTERLACED_SPS, 4), status::VIDEO_DECODER_MALFUNCTION),
(vec![1, 2], status::VIDEO_DECODER_UNSUPPORTED_DATA_FORMAT),
] {
let guest = Guest::new(Ok(Decoded::Landed(LandedBy::Hardware)));
let guest = Guest::new(Ok(Decoded::Landed));
guest.start(&record);
let (_, reply) = guest.next_of(b"dsta");
assert_eq!(status_of(&reply), Some(refused));
@@ -731,7 +708,7 @@ fn a_start_on_a_record_no_decoder_here_takes_is_refused_without_attributes() {
#[test]
fn a_frame_lands_in_the_buffer_the_guest_lends_then_is_emitted_and_let_go() {
let guest = Guest::new(Ok(Decoded::Landed(LandedBy::Hardware)));
let guest = Guest::new(Ok(Decoded::Landed));
guest.start(&avcc(&SPS, 4));
guest.next_of(b"Dpba");
guest.next_of(b"dsta");
@@ -777,13 +754,7 @@ fn a_frame_lands_in_the_buffer_the_guest_lends_then_is_emitted_and_let_go() {
#[test]
fn a_frame_that_does_not_decode_gives_its_parameter_sets_to_the_next() {
let failed = status::VIDEO_DECODER_MALFUNCTION;
let guest = Guest::failing_first(
Codec::H264,
Ok(Decoded::Landed(LandedBy::Hardware)),
None,
false,
Some(failed),
);
let guest = Guest::failing_first(Codec::H264, Ok(Decoded::Landed), None, false, Some(failed));
guest.start(&avcc(&SPS, 4));
guest.next_of(b"Dpba");
guest.next_of(b"dsta");
@@ -815,7 +786,7 @@ fn a_frame_that_does_not_decode_gives_its_parameter_sets_to_the_next() {
#[test]
fn an_asynchronous_frame_is_answered_once_its_buffer_is_in_hand() {
let guest = Guest::new(Ok(Decoded::Landed(LandedBy::Hardware)));
let guest = Guest::new(Ok(Decoded::Landed));
guest.start(&avcc(&SPS, 4));
guest.next_of(b"Dpba");
guest.next_of(b"dsta");
@@ -876,7 +847,7 @@ fn a_frame_that_does_not_decode_is_emitted_without_its_buffer() {
/// back.
#[test]
fn a_buffer_lent_past_its_wait_is_named_unused_and_its_surface_goes_back() {
let guest = Guest::new(Ok(Decoded::Landed(LandedBy::Hardware)));
let guest = Guest::new(Ok(Decoded::Landed));
guest.start(&avcc(&SPS, 4));
guest.next_of(b"Dpba");
guest.next_of(b"dsta");
@@ -925,167 +896,31 @@ fn a_skipped_picture_is_emitted_dropped_and_its_buffer_unused() {
guest.next_of(b"dfrm");
}
/// A session counts each frame by what it came to, which its end line says: landed by what wrote
/// it, dropped, failed by cause with its statuses, answered with no decoder; and its emits the
/// guest did not answer, its start refused, its tiles, and its messages unread. A session sent
/// no frame and no tile says nothing.
/// A session counts each frame it emits by what it handed the guest, which its end line says:
/// with the buffer its picture landed in, dropped with no picture decoded, or failed with a
/// status; a session that emitted none says nothing.
#[test]
fn a_sessions_frames_are_counted_by_what_they_came_to() {
let mut counts = Counts::default();
assert_eq!(counts.line(Codec::Hevc), None);
let buffer = GuestUuid([1; 16]);
counts.frames = 9;
counts.note(Outcome::Landed(LandedBy::Hardware, buffer));
counts.note(Outcome::Landed(LandedBy::Hardware, buffer));
counts.note(Outcome::Landed(LandedBy::Cpu, buffer));
counts.note(Outcome::Dropped);
counts.note(Outcome::Failed(
Failure::BufferUnanswered,
status::PARAMETER,
));
counts.note(Outcome::Failed(
Failure::Decoder,
status::VIDEO_DECODER_MALFUNCTION,
));
counts.note(Outcome::Failed(
Failure::Decoder,
status::VIDEO_DECODER_MALFUNCTION,
));
counts.note(Outcome::Failed(
Failure::Decoder,
status::VIDEO_DECODER_BAD_DATA,
));
counts.no_decoder = 1;
counts.unanswered = 2;
let line = counts.line(Codec::Hevc).expect("its end line");
assert_eq!(
line,
"hardware video: a VideoToolbox decoder session of HEVC ended after 9 frames: landed 3 \
(2 by the hardware, 1 copied by the CPU); 1 dropped with no picture decoded; 4 failed \
(1 with no buffer lent in time (-12902), 3 failed by the decoder (-12911 x2, -12909)); \
1 answered with no decoder; 2 emits the guest did not answer; no buffer without its \
picture handed the guest"
);
counts.start_refused = Some(status::VIDEO_DECODER_UNSUPPORTED_DATA_FORMAT);
counts.note_tile(Ok(LandedBy::Gpu));
counts.note_tile(Err(status::PARAMETER));
counts.unread = 1;
counts.decodes.note(Duration::from_millis(2));
let line = counts.line(Codec::Hevc).expect("its end line");
let says = "2 emits the guest did not answer; its start refused (-12910); tiles: landed 1 (1 \
by the device's GPU), 1 failed (-12902); 1 messages it could not read; \
2.000 ms each in the decoder, 2.000 ms at most; no buffer";
fn a_sessions_frames_are_counted_by_what_they_handed_the_guest() {
let mut emitted = Emitted::default();
assert_eq!(emitted.line(), None);
emitted.note(status::NO_ERROR, Some(GuestUuid([1; 16])));
emitted.note(status::NO_ERROR, None);
emitted.note(status::VIDEO_DECODER_BAD_DATA, None);
emitted.note(-6662, None);
let counted = Emitted {
landed: 1,
dropped: 1,
failed: 2,
};
assert_eq!(emitted, counted);
let line = emitted.line().expect("its end line");
let says = "1 frames emitted with their picture, 1 dropped with no picture decoded, 2 failed";
assert!(line.contains(says), "{line}");
}
/// A session's end line counts what each of its frames came to as the guest was told it, in a
/// session that meets each class: a picture landed by each way, one dropped, one the decoder
/// failed, one whose buffer the guest refused, one whose buffer did not come in time, one whose
/// sample does not read, and one answered with no decoder.
#[test]
fn a_session_s_end_line_counts_each_frame_as_the_guest_was_told() {
let guest = Guest::new(Ok(Decoded::Landed(LandedBy::Hardware)));
guest.start(&avcc(&SPS, 4));
guest.next_of(b"Dpba");
guest.next_of(b"dsta");
let shared = guest.host.session_shared(guest.uuid).expect("the session");
guest.script.lock().extend([
Ok(Decoded::Landed(LandedBy::Hardware)),
Ok(Decoded::Landed(LandedBy::Gpu)),
Ok(Decoded::Landed(LandedBy::Cpu)),
Ok(Decoded::Skipped),
Err(status::VIDEO_DECODER_BAD_DATA),
]);
// How the guest answers each frame's `Dbuf`: with a buffer, a status, or not at all.
enum Lend {
Buffer,
Refused,
Not,
}
let unreadable = [0, 0, 0, 9, 0x65];
let frames: [(&[u8], Lend); 8] = [
(&SAMPLE, Lend::Buffer),
(&SAMPLE, Lend::Buffer),
(&SAMPLE, Lend::Buffer),
(&SAMPLE, Lend::Buffer),
(&SAMPLE, Lend::Buffer),
(&SAMPLE, Lend::Refused),
(&SAMPLE, Lend::Not),
(&unreadable, Lend::Buffer),
];
let mut told = Vec::new();
for (frame, (sample, lend)) in frames.iter().enumerate() {
guest.frame(frame as i64, 0, &one_sample(sample, None, false));
loop {
let bytes = guest.next();
let Ok(header) = read_header(&bytes, 0) else {
continue;
};
match &header.message_type.to_be_bytes() {
b"Dbuf" => match lend {
Lend::Buffer => guest.answer(&header, 0, Some((GuestUuid([0xb1; 16]), 7))),
Lend::Refused => guest.answer(&header, -6662, None),
Lend::Not => {}
},
b"Demt" => {
let message = Message::parse(&bytes).unwrap();
let buffer = message.uuid(names::PIXEL_BUFFER_UUID).unwrap();
told.push((status_of(&bytes), info_of(&bytes), buffer.is_some()));
guest.answer(&header, 0, None);
}
b"dfrm" => break,
_ => {}
}
}
}
let dropped = Some(INFO_FRAME_DROPPED);
assert_eq!(
told,
[
(Some(0), Some(0), true),
(Some(0), Some(0), true),
(Some(0), Some(0), true),
(Some(0), dropped, false),
(Some(status::VIDEO_DECODER_BAD_DATA), Some(0), false),
(Some(-6662), Some(0), false),
(Some(status::PARAMETER), Some(0), false),
(Some(status::VIDEO_DECODER_BAD_DATA), Some(0), false),
],
"what the guest was told"
);
guest.send(
b"dinv",
MessageFlags::GUEST_EXPECTS_REPLY,
9,
Vec::new(),
|_| {},
);
guest.next_of(b"dinv");
guest.frame(8, 0, &one_sample(&SAMPLE, None, false));
let (_, reply) = guest.next_of(b"dfrm");
assert_eq!(status_of(&reply), Some(NO_DECODER));
guest.host.end_sessions();
assert_eq!(guest.host.sessions_left(Duration::from_secs(5)), 0);
let line = shared.end_line().expect("its end line");
let says = "hardware video: a VideoToolbox decoder session of H.264 ended after 9 frames: \
landed 3 (1 by the hardware, 1 by the device's GPU, 1 copied by the CPU); \
1 dropped with no picture decoded; 4 failed (1 with no buffer lent in time \
(-12902), 1 with the guest's buffer refused (-6662), 1 whose sample did not read \
(-12909), 1 failed by the decoder (-12909)); 1 answered with no decoder; 0 emits \
the guest did not answer; ";
assert!(line.starts_with(says), "{line}");
assert!(line.contains(" ms each in the decoder, "), "{line}");
assert!(
line.ends_with("; no buffer without its picture handed the guest"),
"{line}"
);
}
#[test]
fn a_buffer_the_guest_refuses_emits_the_frame_with_its_status() {
let guest = Guest::new(Ok(Decoded::Landed(LandedBy::Hardware)));
let guest = Guest::new(Ok(Decoded::Landed));
guest.start(&avcc(&SPS, 4));
guest.next_of(b"Dpba");
guest.next_of(b"dsta");
@@ -1102,7 +937,7 @@ fn a_buffer_the_guest_refuses_emits_the_frame_with_its_status() {
#[test]
fn a_sample_of_another_record_reopens_the_decoder_with_its_sets() {
let guest = Guest::new(Ok(Decoded::Landed(LandedBy::Hardware)));
let guest = Guest::new(Ok(Decoded::Landed));
guest.start(&avcc(&SPS, 4));
guest.next_of(b"Dpba");
guest.next_of(b"dsta");
@@ -1127,7 +962,7 @@ fn a_sample_of_another_record_reopens_the_decoder_with_its_sets() {
/// session's first one, opens the decoder again and lands.
#[test]
fn a_reopen_the_backend_refuses_is_tried_again_at_the_next_described_sample() {
let guest = Guest::new(Ok(Decoded::Landed(LandedBy::Hardware)));
let guest = Guest::new(Ok(Decoded::Landed));
guest.start(&avcc(&SPS, 4));
guest.next_of(b"Dpba");
guest.next_of(b"dsta");
@@ -1182,7 +1017,7 @@ fn a_reopen_the_backend_refuses_is_tried_again_at_the_next_described_sample() {
#[test]
fn the_properties_are_listed_read_and_set() {
let guest = Guest::new(Ok(Decoded::Landed(LandedBy::Hardware)));
let guest = Guest::new(Ok(Decoded::Landed));
let key = |m: &mut MessageWriter, key: &str| {
m.property_list(names::PROPERTY_KEY, Some(&Value::string(key)));
};
@@ -1270,7 +1105,7 @@ fn the_properties_are_listed_read_and_set() {
#[test]
fn can_accept_answers_whether_the_decoder_goes_on() {
let guest = Guest::new(Ok(Decoded::Landed(LandedBy::Hardware)));
let guest = Guest::new(Ok(Decoded::Landed));
let can = |record: &[u8], width: u16| {
let description = hand_written(b"avc1", width, 48, record);
guest.send(
@@ -1309,7 +1144,7 @@ fn can_accept_answers_whether_the_decoder_goes_on() {
#[test]
fn an_invalidated_decoder_answers_frames_with_no_decoder() {
let guest = Guest::new(Ok(Decoded::Landed(LandedBy::Hardware)));
let guest = Guest::new(Ok(Decoded::Landed));
guest.start(&avcc(&SPS, 4));
guest.next_of(b"Dpba");
guest.next_of(b"dsta");
@@ -1343,7 +1178,7 @@ fn an_invalidated_decoder_answers_frames_with_no_decoder() {
/// is out: its `Demt`, the surface's release and its `dfrm` reply come first.
#[test]
fn a_finish_is_answered_once_every_frame_before_it_is_out() {
let guest = Guest::new(Ok(Decoded::Landed(LandedBy::Hardware)));
let guest = Guest::new(Ok(Decoded::Landed));
guest.start(&avcc(&SPS, 4));
guest.next_of(b"Dpba");
guest.next_of(b"dsta");
@@ -1375,7 +1210,7 @@ fn a_finish_is_answered_once_every_frame_before_it_is_out() {
#[test]
fn a_late_reply_gives_back_what_it_lent_and_a_close_ends_the_session() {
let guest = Guest::new(Ok(Decoded::Landed(LandedBy::Hardware)));
let guest = Guest::new(Ok(Decoded::Landed));
let late = MessageHeader {
message_type: FourCc::new(*b"Dbuf"),
flags: MessageFlags::NONE,
@@ -1417,7 +1252,7 @@ fn a_late_reply_gives_back_what_it_lent_and_a_close_ends_the_session() {
#[test]
fn a_create_of_a_codec_the_list_lacks_is_refused() {
let guest = Guest::new(Ok(Decoded::Landed(LandedBy::Hardware)));
let guest = Guest::new(Ok(Decoded::Landed));
let mut message = MessageWriter::new(
FourCc::new(*b"+dec"),
MessageFlags::GUEST_EXPECTS_REPLY,
@@ -1445,7 +1280,7 @@ const TILES: TileLimits = TileLimits {
#[test]
fn a_tile_session_sends_its_requirements_then_its_reply() {
let guest = Guest::with_tiles(Ok(Decoded::Landed(LandedBy::Hardware)), Some(TILES));
let guest = Guest::with_tiles(Ok(Decoded::Landed), Some(TILES));
guest.start_tiles(&avcc(&SPS, 4));
let (tdrs, requirements) = guest.next_of(b"TDrs");
assert!(!tdrs.flags.contains(MessageFlags::HOST_EXPECTS_REPLY));
@@ -1523,7 +1358,7 @@ fn an_arm_asks_the_output_buffers_in_its_own_alignments() {
#[test]
fn a_tile_session_on_a_backend_that_decodes_no_tiles_is_refused_unimplemented() {
let guest = Guest::new(Ok(Decoded::Landed(LandedBy::Hardware)));
let guest = Guest::new(Ok(Decoded::Landed));
guest.start_tiles(&avcc(&SPS, 4));
let (_, reply) = guest.next_of(b"dsts");
assert_eq!(
@@ -1587,12 +1422,7 @@ fn starts_in(
) {
let named =
format.map(|f| Value::Array(vec![Value::Integer(i64::from(u32::from_be_bytes(*f)))]));
let guest = Guest::on(
codec,
Ok(Decoded::Landed(LandedBy::Hardware)),
Some(TILES),
range_extensions,
);
let guest = Guest::on(codec, Ok(Decoded::Landed), Some(TILES), range_extensions);
guest.start(record);
if let Some(named) = &named {
let (_, dpba) = guest.next_of(b"Dpba");
@@ -1613,12 +1443,7 @@ fn starts_in(
}
assert!(guest.quiet(), "{what}");
let guest = Guest::on(
codec,
Ok(Decoded::Landed(LandedBy::Hardware)),
Some(TILES),
range_extensions,
);
let guest = Guest::on(codec, Ok(Decoded::Landed), Some(TILES), range_extensions);
guest.start_tiles(record);
if let Some(named) = &named {
let (_, tdrs) = guest.next_of(b"TDrs");
@@ -1834,7 +1659,7 @@ fn each_h264_stream_lands_in_its_4_2_0_format_or_is_refused_at_its_start() {
#[test]
fn a_tile_lands_its_region_in_the_surface_it_lends_then_is_emitted_and_let_go() {
let guest = Guest::with_tiles(Ok(Decoded::Landed(LandedBy::Hardware)), Some(TILES));
let guest = Guest::with_tiles(Ok(Decoded::Landed), Some(TILES));
guest.start_tiles(&avcc(&SPS, 4));
guest.next_of(b"TDrs");
guest.next_of(b"dsts");
@@ -1906,7 +1731,7 @@ fn a_tile_lands_its_region_in_the_surface_it_lends_then_is_emitted_and_let_go()
/// frame in flight saw a frame of 11.1 s and two buffer requests time out.
#[test]
fn a_guests_close_ends_the_sessions_wait_for_its_buffer_at_once() {
let guest = Guest::new(Ok(Decoded::Landed(LandedBy::Hardware)));
let guest = Guest::new(Ok(Decoded::Landed));
guest.start(&avcc(&SPS, 4));
guest.next_of(b"Dpba");
guest.next_of(b"dsta");
@@ -1950,7 +1775,7 @@ fn a_guests_close_ends_the_sessions_wait_for_its_buffer_at_once() {
/// dropped, and nothing of it reaches the guest, where it would reach the new session's.
#[test]
fn a_session_a_create_replaces_is_closed_at_once() {
let guest = Guest::new(Ok(Decoded::Landed(LandedBy::Hardware)));
let guest = Guest::new(Ok(Decoded::Landed));
guest.start(&avcc(&SPS, 4));
guest.next_of(b"Dpba");
guest.next_of(b"dsta");
@@ -1995,7 +1820,7 @@ fn a_session_a_create_replaces_is_closed_at_once() {
/// it reaches the guest.
#[test]
fn a_hosts_teardown_closes_each_session() {
let guest = Guest::new(Ok(Decoded::Landed(LandedBy::Hardware)));
let guest = Guest::new(Ok(Decoded::Landed));
guest.start(&avcc(&SPS, 4));
guest.next_of(b"Dpba");
guest.next_of(b"dsta");
@@ -2086,7 +1911,7 @@ fn a_reset_waits_for_the_write_in_hand_and_no_session_writes_past_it() {
/// the tile's reply.
#[test]
fn a_tile_in_fragments_lands_in_the_surface_its_first_fragment_lends() {
let guest = Guest::with_tiles(Ok(Decoded::Landed(LandedBy::Hardware)), Some(TILES));
let guest = Guest::with_tiles(Ok(Decoded::Landed), Some(TILES));
guest.start_tiles(&avcc(&SPS, 4));
guest.next_of(b"TDrs");
guest.next_of(b"dsts");
@@ -2132,7 +1957,7 @@ fn a_tile_in_fragments_lands_in_the_surface_its_first_fragment_lends() {
#[test]
fn a_tile_the_host_cannot_place_is_emitted_with_a_parameter_error_undecoded() {
let guest = Guest::with_tiles(Ok(Decoded::Landed(LandedBy::Hardware)), Some(TILES));
let guest = Guest::with_tiles(Ok(Decoded::Landed), Some(TILES));
guest.start_tiles(&avcc(&SPS, 4));
guest.next_of(b"TDrs");
guest.next_of(b"dsts");
@@ -2225,7 +2050,7 @@ fn each_vp9_stream_lands_in_its_format_or_is_refused_at_its_start() {
#[test]
fn a_vp9_sample_goes_to_the_backend_whole_with_no_parameter_sets() {
let guest = Guest::of(Codec::Vp9, Ok(Decoded::Landed(LandedBy::Hardware)), None);
let guest = Guest::of(Codec::Vp9, Ok(Decoded::Landed), None);
guest.start(&vpcc(0, 8, 1, false));
guest.next_of(b"Dpba");
guest.next_of(b"dsta");
@@ -76,7 +76,7 @@ fn a_record_without_a_sequence_header_is_told_by_its_own_fields() {
#[test]
fn an_av1_session_hands_the_backend_its_config_obus_then_whole_samples() {
let guest = Guest::of(Codec::Av1, Ok(Decoded::Landed(LandedBy::Hardware)), None);
let guest = Guest::of(Codec::Av1, Ok(Decoded::Landed), None);
let (unit, _) = sequence_obu("svt-main8");
guest.start(&record_of("svt-main8"));
guest.next_of(b"Dpba");
+8 -147
View File
@@ -52,18 +52,6 @@
//! The backend's clock runs at [`TICKS_PER_SECOND`]: each frame's times are converted onto it,
//! and each sample's are the guest's own again, as the frame came or, for a decode time, as the
//! frame whose presentation time it is came.
//!
//! **Its counts.** A session counts what each of its frames came to ([`Counts`]), from its own
//! state and the backend's answers, and logs them in one line at `info` as it ends, where it
//! was sent a frame: totals, statuses and causes alone. Of the frames it took (`efrm`s carried
//! out): emitted with a sample, dropped by the encoder (`kVTEncodeInfo_FrameDropped`), failed by
//! the encoder, failed at the stream's format description (an `Efds` refused or unanswered),
//! refused at their take (the `efrm` answered the backend's status), answered with no encoder,
//! lost in the encoder at an `ecfr`, replaced while waiting by a frame of their number, and held
//! by the encoder at the session's end; each failure with its statuses. It also counts its
//! emits the guest did not answer within [`EMIT_REPLY_WAIT`], an `esta` it refused, the
//! property sets its running encoder refused, its messages it could not read, and the time each
//! backend encode took.
mod properties;
#[cfg(target_os = "macos")]
@@ -79,7 +67,6 @@ use crate::codec::encode::{
};
use crate::core::fourcc::FourCc;
use crate::core::runtime::Runtime;
use crate::paravirt::counts::{Statuses, Timing};
use crate::paravirt::host::Codec;
use crate::paravirt::message::{
GuestUuid, MediaTime, Message, MessageFlags, MessageWriter, ValueType,
@@ -223,7 +210,6 @@ pub(crate) fn start(
times: VecDeque::new(),
last_pts: None,
format: None,
counts: Counts::default(),
}
.run();
})
@@ -272,87 +258,6 @@ struct Worker {
/// The last frame's presentation time in ticks.
last_pts: Option<i64>,
format: Option<StreamFormat>,
/// What its frames came to, logged at its end.
counts: Counts,
}
/// What a session's frames came to (the module doc, "Its counts").
#[derive(Clone, Debug, Default, PartialEq, Eq)]
struct Counts {
/// `efrm`s carried out.
frames: u64,
/// Frames emitted with a sample.
sampled: u64,
/// Frames emitted dropped by the encoder, with no sample.
dropped: u64,
/// Frames emitted with the encoder's failure, by status.
failed: Statuses,
/// Frames emitted with the status of the stream's format description, by status.
format_failed: Statuses,
/// Frames whose `efrm` was answered the backend's status, not taken, by status.
refused: Statuses,
/// Frames answered `kVTInvalidSessionErr`, with no encoder.
no_encoder: u64,
/// Frames the encoder took and gave nothing back for at an `ecfr`.
lost: u64,
/// Frames waiting that a frame of their number replaced.
replaced: u64,
/// Frames the encoder took and still held as the session ended, never emitted.
held_at_end: u64,
/// `Eemt`s the guest did not answer within [`EMIT_REPLY_WAIT`].
unanswered: u64,
/// The status its `esta` was refused with, where it was.
start_refused: Option<OsStatus>,
/// Property sets the running encoder refused, by status.
properties_refused: Statuses,
/// Messages it could not read ([`MESSAGE_UNREAD`]).
unread: u64,
/// The backend's encodes.
encodes: Timing,
}
impl Counts {
/// The session's end line, of a session of `codec`, where it was sent a frame.
fn line(&self, codec: Codec) -> Option<String> {
if self.frames == 0 {
return None;
}
let start = match self.start_refused {
Some(status) => format!("; its start refused ({status})"),
None => String::new(),
};
let properties = match self.properties_refused.total() {
0 => String::new(),
_ => format!(
"; {}",
self.properties_refused.clause("property sets refused")
),
};
let unread = match self.unread {
0 => String::new(),
n => format!("; {n} messages it could not read"),
};
Some(format!(
"hardware video: a VideoToolbox encoder session of {} ended after {} frames: {} \
emitted with a sample; {} dropped by the encoder; {}; {}; {}; {} answered with no \
encoder; {} lost in the encoder; {} replaced while waiting; {} held by the encoder \
at the end; {} emits the guest did not answer{start}{properties}{unread}{}",
codec.name(),
self.frames,
self.sampled,
self.dropped,
self.failed.clause("failed by the encoder"),
self.format_failed
.clause("failed at the stream's format description"),
self.refused.clause("refused at their take"),
self.no_encoder,
self.lost,
self.replaced,
self.held_at_end,
self.unanswered,
self.encodes.says("encoder"),
))
}
}
impl Worker {
@@ -367,7 +272,6 @@ impl Worker {
self.handle(&job.bytes, &mut surfaces)
};
if let Err(error) = handled {
self.counts.unread += 1;
self.shared.count(MESSAGE_UNREAD);
log::warn!(
kind:% = error;
@@ -378,16 +282,7 @@ impl Worker {
// What a message lent and the session did not keep goes back.
self.shared.let_go(&surfaces);
}
let held = (self.pending.values())
.filter(|pending| pending.submitted && !pending.emitted)
.count();
self.counts.held_at_end = u64::try_from(held).unwrap_or(u64::MAX);
self.let_go_of_pending();
if let Some(line) = self.counts.line(self.encoder.codec) {
log::info!("{line}");
#[cfg(test)]
self.shared.said_at_end(line);
}
}
fn send(&self, message: &[u8]) {
@@ -530,7 +425,6 @@ impl Worker {
None => Some(status::PROPERTY_NOT_SUPPORTED),
};
if let Some(status) = refused {
self.counts.properties_refused.note(status);
self.shared.count(ENCODER_PROPERTY_REFUSED);
log::warn!(
kind:% = key;
@@ -571,9 +465,6 @@ impl Worker {
},
}
};
if status != status::NO_ERROR {
self.counts.start_refused = Some(status);
}
self.reply_status(message, status)
}
@@ -666,14 +557,6 @@ impl Worker {
.time(names::PRESENTATION_TIME)?
.unwrap_or(MediaTime::INVALID);
let duration = message.time(names::DURATION)?.unwrap_or(MediaTime::INVALID);
(self.shared).trace(
"vtefrm",
&[
frame.cast_unsigned(),
pts.value.cast_unsigned(),
u64::from(pts.timescale.cast_unsigned()),
],
);
let frame_properties = property_list(message, names::FRAME_PROPERTIES)?;
let uuid = message.uuid(names::PIXEL_BUFFER_UUID)?;
message.property_list_bytes(names::PIXEL_BUFFER_ATTACHMENTS)?;
@@ -687,9 +570,7 @@ impl Worker {
.and_then(|properties| properties.get(FORCE_KEY_FRAME))
.and_then(Value::as_boolean)
.unwrap_or(false);
self.counts.frames += 1;
if self.running.is_none() {
self.counts.no_encoder += 1;
self.shared.let_go(&[surface]);
let mut reply = self.reply(message);
reply.s32(names::ERROR, status::INVALID_SESSION);
@@ -717,12 +598,7 @@ impl Worker {
// From its first frame on, the stream keeps its format (the module doc).
self.asked = None;
let encoded = match self.running.as_mut() {
Some(encoder) => {
let began = self.runtime.now();
let encoded = encoder.encode(&*surface, &source);
self.counts.encodes.note(self.runtime.elapsed_since(began));
encoded
}
Some(encoder) => encoder.encode(&*surface, &source),
None => Err(status::INVALID_SESSION),
};
let replaced = self.pending.insert(
@@ -739,7 +615,6 @@ impl Worker {
// A frame of a waiting frame's number takes its place: the one waiting gives back its
// surface, which nothing else would.
if let Some(replaced) = replaced {
self.counts.replaced += 1;
self.shared.let_go(&[replaced.surface]);
}
let status = match encoded {
@@ -749,10 +624,7 @@ impl Worker {
}
status::NO_ERROR
}
Err(status) => {
self.counts.refused.note(status);
status
}
Err(status) => status,
};
let mut reply = self.reply(message);
reply.s32(names::ERROR, status);
@@ -819,7 +691,6 @@ impl Worker {
.collect();
let mut surfaces = Vec::with_capacity(lost.len());
for frame in lost {
self.counts.lost += 1;
log::warn!("hardware video: frame {frame} was lost in the encoder");
let (uuid, taken) = self.frame_emitted(frame);
self.emit_encoded_frame(frame, status::VIDEO_ENCODER_MALFUNCTION, 0, uuid, None);
@@ -834,12 +705,10 @@ impl Worker {
let sample = match coded {
Ok(sample) if !sample.data.is_empty() => sample,
Ok(sample) => {
self.counts.dropped += 1;
return self.emit_unsampled(sample.id, status::NO_ERROR, INFO_FRAME_DROPPED);
}
Err(FailedSample { id, error }) => {
let status = error.unwrap_or(status::VIDEO_ENCODER_MALFUNCTION);
self.counts.failed.note(status);
return self.emit_unsampled(id, status, 0);
}
};
@@ -847,14 +716,8 @@ impl Worker {
let serialization = self.sample_buffer(&sample).map(|buffer| buffer.serialize());
let (uuid, taken) = self.frame_emitted(frame);
match serialization {
Ok(bytes) => {
self.counts.sampled += 1;
self.emit_encoded_frame(frame, status::NO_ERROR, 0, uuid, Some(&bytes));
}
Err(status) => {
self.counts.format_failed.note(status);
self.emit_encoded_frame(frame, status, 0, uuid, None);
}
Ok(bytes) => self.emit_encoded_frame(frame, status::NO_ERROR, 0, uuid, Some(&bytes)),
Err(status) => self.emit_encoded_frame(frame, status, 0, uuid, None),
}
self.shared.let_go(
&taken
@@ -988,10 +851,9 @@ impl Worker {
}
/// `Eemt`: frame `frame`'s status, info flags, UUID and sample buffer, in fragments where
/// it is long (the module doc); the guest's answer is waited for and not read, and counted
/// where it does not come.
/// it is long (the module doc); the guest's answer is waited for and not read.
fn emit_encoded_frame(
&mut self,
&self,
frame: i64,
status: OsStatus,
info: u32,
@@ -1036,9 +898,8 @@ impl Worker {
&message.finish(),
EMIT_REPLY_WAIT,
);
match sent {
Ok(reply) => self.shared.let_go(&reply.surfaces),
Err(_) => self.counts.unanswered += 1,
if let Ok(reply) = sent {
self.shared.let_go(&reply.surfaces);
}
}
}
@@ -61,24 +61,6 @@ enum Mode {
Hold,
}
/// What the fake encoder answers an encode, in place of its mode.
#[derive(Clone, Copy, PartialEq, Eq)]
enum Step {
/// A sample of the frame.
Sample,
/// The frame dropped: a sample of no bytes.
Dropped,
/// The frame failed with the status.
Failed(OsStatus),
/// The frame not taken: the encode answers the status.
Refused(OsStatus),
/// The frame held, nothing given back.
Hold,
}
/// What the fake backend's encoders answer their next encodes, in order, before their mode.
type Script = Arc<Mutex<std::collections::VecDeque<Step>>>;
/// What the fake backend was given.
#[derive(Default)]
struct Calls {
@@ -98,8 +80,6 @@ struct FakeBackend {
gate: Option<Gate>,
/// How many of its encoders were dropped.
dropped: Arc<AtomicUsize>,
/// What its encoders answer their next encodes.
script: Script,
}
/// Where a fake encoder holds each encode before it reads its source ([`FakeEncoder::hold`]): it
@@ -140,7 +120,6 @@ struct FakeEncoder {
configured: bool,
gate: Option<Gate>,
dropped: Arc<AtomicUsize>,
script: Script,
}
impl Drop for FakeEncoder {
@@ -160,7 +139,6 @@ impl EncoderBackend for FakeBackend {
configured: false,
gate: self.gate.clone(),
dropped: Arc::clone(&self.dropped),
script: Arc::clone(&self.script),
}))
}
}
@@ -202,29 +180,6 @@ impl BackendEncoder for FakeEncoder {
) -> Result<Vec<Coded<OsStatus>>, OsStatus> {
self.hold();
self.calls.lock().frames.push((*frame, source.id()));
let step = self.script.lock().pop_front();
match step {
Some(Step::Sample) => return Ok(vec![self.sample(frame, 0)]),
Some(Step::Dropped) => {
let mut dropped = self.sample(frame, 0);
if let Ok(sample) = &mut dropped {
sample.data.clear();
}
return Ok(vec![dropped]);
}
Some(Step::Failed(status)) => {
return Ok(vec![Err(FailedSample {
id: frame.id,
error: Some(status),
})]);
}
Some(Step::Refused(status)) => return Err(status),
Some(Step::Hold) => {
self.held.push(*frame);
return Ok(Vec::new());
}
None => {}
}
match self.mode {
Mode::AtOnce(bytes) => Ok(vec![self.sample(frame, bytes)]),
Mode::Hold => {
@@ -277,8 +232,6 @@ struct Guest {
codec: [u8; 4],
/// The codes the session counted on its link.
counted: Counted,
/// What the backend's encoders answer their next encodes.
script: Script,
}
impl Guest {
@@ -317,14 +270,12 @@ impl Guest {
) -> Self {
let calls = Recorded::default();
let dropped = Arc::<AtomicUsize>::default();
let script = Script::default();
let backend = Arc::new(FakeBackend {
calls: Arc::clone(&calls),
mode,
reconfigure,
gate,
dropped: Arc::clone(&dropped),
script: Arc::clone(&script),
});
let (sender, sent) = mpsc::channel();
let counted = Counted::default();
@@ -337,7 +288,6 @@ impl Guest {
dropped,
codec,
counted,
script,
};
assert_eq!(guest.create(Some(listed)), 0, "the create is taken");
guest
@@ -533,130 +483,6 @@ fn yes_no(value: bool) -> SerializedValue {
SerializedValue::PropertyList(Value::Boolean(value))
}
/// A session counts each frame by what it came to, which its end line says, each failure with
/// its statuses; a session sent no frame says nothing.
#[test]
fn a_sessions_frames_are_counted_by_what_they_came_to() {
let mut counts = Counts::default();
assert_eq!(counts.line(Codec::H264), None);
counts.frames = 12;
counts.sampled = 3;
counts.dropped = 1;
counts.failed.note(status::VIDEO_ENCODER_MALFUNCTION);
counts.format_failed.note(status::PARAMETER);
counts.refused.note(status::PARAMETER);
counts.refused.note(status::PARAMETER);
counts.no_encoder = 1;
counts.lost = 1;
counts.replaced = 1;
counts.held_at_end = 1;
counts.unanswered = 1;
assert_eq!(
counts.line(Codec::Hevc).expect("its end line"),
"hardware video: a VideoToolbox encoder session of HEVC ended after 12 frames: 3 emitted \
with a sample; 1 dropped by the encoder; 1 failed by the encoder (-12912); 1 failed at \
the stream's format description (-12902); 2 refused at their take (-12902 x2); 1 \
answered with no encoder; 1 lost in the encoder; 1 replaced while waiting; 1 held by \
the encoder at the end; 1 emits the guest did not answer"
);
counts.start_refused = Some(status::ENCODER_SIZE_UNSUPPORTED);
counts
.properties_refused
.note(status::PROPERTY_NOT_SUPPORTED);
counts.unread = 2;
counts.encodes.note(Duration::from_millis(4));
let line = counts.line(Codec::Hevc).expect("its end line");
assert!(
line.ends_with(
"1 emits the guest did not answer; its start refused (-19354); 1 property sets \
refused (-12900); 2 messages it could not read; 4.000 ms each in the encoder, 4.000 \
ms at most"
),
"{line}"
);
}
/// A session's end line counts what each of its frames came to as the guest was told it, in a
/// session that meets each class its encoder answers: a frame emitted with a sample, one
/// dropped, one failed, one refused at its take, one held that a frame of its number replaced,
/// and that one held by the encoder at the end.
#[test]
fn a_session_s_end_line_counts_each_frame_as_the_guest_was_told() {
let guest = Guest::new(Mode::AtOnce(0), Ok(()));
guest.started(64, 48);
let shared = guest.host.session_shared(guest.uuid).expect("the session");
guest.script.lock().extend([
Step::Sample,
Step::Dropped,
Step::Failed(status::VIDEO_ENCODER_MALFUNCTION),
Step::Refused(status::PARAMETER),
Step::Hold,
Step::Hold,
]);
let mut told = Vec::new();
for (n, frame) in [0, 1, 2, 3, 4, 4].into_iter().enumerate() {
guest.frame(frame, 10 + n as u64, None);
loop {
let bytes = guest.next();
let Ok(header) = read_header(&bytes, 0) else {
continue;
};
match &header.message_type.to_be_bytes() {
b"Efds" => {
let description = hand_written(b"avc1", 64, 48, &RECORD);
guest.answer(&header, 0, |m| {
m.image_description(names::CREATED_FORMAT_DESCRIPTION, &description);
});
}
b"Eemt" => {
let message = Message::parse(&bytes).unwrap();
let sampled = (message.sample_buffer(names::SAMPLE_BUFFER).unwrap()).is_some();
let info = message.u32(names::ENCODE_INFO_FLAGS).unwrap();
told.push(("Eemt", status_of(&bytes), info, sampled));
guest.answer(&header, 0, |_| {});
}
b"efrm" => {
told.push(("efrm", status_of(&bytes), None, false));
break;
}
_ => {}
}
}
}
let dropped = Some(INFO_FRAME_DROPPED);
assert_eq!(
told,
[
("Eemt", Some(0), Some(0), true),
("efrm", Some(0), None, false),
("Eemt", Some(0), dropped, false),
("efrm", Some(0), None, false),
(
"Eemt",
Some(status::VIDEO_ENCODER_MALFUNCTION),
Some(0),
false
),
("efrm", Some(0), None, false),
("efrm", Some(status::PARAMETER), None, false),
("efrm", Some(0), None, false),
("efrm", Some(0), None, false),
],
"what the guest was told"
);
guest.host.end_sessions();
assert_eq!(guest.host.sessions_left(Duration::from_secs(5)), 0);
let line = shared.end_line().expect("its end line");
let says = "hardware video: a VideoToolbox encoder session of H.264 ended after 6 frames: 1 \
emitted with a sample; 1 dropped by the encoder; 1 failed by the encoder \
(-12912); 0 failed at the stream's format description; 1 refused at their take \
(-12902); 0 answered with no encoder; 0 lost in the encoder; 1 replaced while \
waiting; 1 held by the encoder at the end; 0 emits the guest did not answer; ";
assert!(line.starts_with(says), "{line}");
assert!(line.contains(" ms each in the encoder, "), "{line}");
}
#[test]
fn a_start_asks_for_source_buffers_of_the_profiles_format_at_the_frames_size() {
let guest = Guest::new(Mode::AtOnce(0), Ok(()));
@@ -42,16 +42,6 @@ impl Codec {
})
}
/// Its name, as the log lines say it.
pub const fn name(self) -> &'static str {
match self {
Self::H264 => "H.264",
Self::Hevc => "HEVC",
Self::Av1 => "AV1",
Self::Vp9 => "VP9",
}
}
/// The codec the CoreMedia codec type `fourcc` names, where the host decodes it.
pub fn from_fourcc(fourcc: FourCc) -> Option<Self> {
[Self::H264, Self::Hevc, Self::Av1, Self::Vp9]
@@ -201,15 +191,6 @@ impl Host {
ending.extend(ended.into_iter().map(Session::close));
}
/// What the session of `uuid` and its thread share, where it has one: the tests' view of it.
#[cfg(test)]
pub(crate) fn session_shared(
&self,
uuid: GuestUuid,
) -> Option<Arc<crate::paravirt::session::Shared>> {
self.sessions.lock().get(&uuid).map(Session::shared)
}
/// Waits up to `within` for the threads of the sessions [`Self::end_sessions`] ended, and
/// answers how many have not ended: none once nothing of any of them can write the guest's
/// memory, their messages in hand done and their decoders and encoders dropped.
@@ -57,14 +57,6 @@ pub trait Link: Send + Sync {
/// (docs/conventions.md, "Each degradation is logged once per boot, then counted"). Nothing
/// by default.
fn count(&self, _code: &'static str) {}
/// Writes one event of the host's profiling trace, `kind` and its `values`, timed as it is
/// called: a diagnostic, which changes nothing the session does. The sessions' events: a
/// decoder's `vtdfrm frame value timescale`, a `dfrm` taken, its first sample's presentation
/// time; `vtdemt frame outcome`, its `Demt` about to be sent, 1 landed, 2 dropped, 3 failed;
/// an encoder's `vtefrm frame value timescale`, an `efrm` taken, its presentation time.
/// Nothing by default.
fn trace(&self, _kind: &'static str, _values: &[u64]) {}
}
/// The `rels` box that tells the guest the host holds these surfaces no longer: a big-endian size
@@ -114,10 +106,6 @@ pub(crate) struct Shared {
/// tests' way into the instant a reply may come in.
#[cfg(test)]
at_timeout: Mutex<Option<AtTimeout>>,
/// The line its thread logged as it ended, where it logged one: the tests' view of its
/// counts.
#[cfg(test)]
end_line: Mutex<Option<String>>,
}
/// What a test runs as a request's wait ends with no answer ([`Shared`]'s `at_timeout`).
@@ -136,23 +124,9 @@ impl Shared {
closed: AtomicBool::new(false),
#[cfg(test)]
at_timeout: Mutex::new(None),
#[cfg(test)]
end_line: Mutex::new(None),
}
}
/// Keeps `line`, the one the session's thread logged as it ended, for the tests.
#[cfg(test)]
pub(crate) fn said_at_end(&self, line: String) {
*self.end_line.lock() = Some(line);
}
/// The line the session's thread logged as it ended, where it has ended and logged one.
#[cfg(test)]
pub(crate) fn end_line(&self) -> Option<String> {
self.end_line.lock().clone()
}
/// Sends `message` on the last link; false where there is none, the session is closed, or it
/// was not sent.
pub(crate) fn send(&self, message: &[u8]) -> bool {
@@ -171,15 +145,6 @@ impl Shared {
}
}
/// Writes one event of the host's trace on the last link, where there is one
/// ([`Link::trace`]).
pub(crate) fn trace(&self, kind: &'static str, values: &[u64]) {
let link = self.link.lock().clone();
if let Some(link) = link {
link.trace(kind, values);
}
}
/// Ends the session's exchange with the guest, as the device's reset does: nothing more is
/// sent, and the host's requests waiting for a reply end at once unanswered, as one that
/// begins after this does. Its thread then carries out no further message
@@ -396,12 +361,6 @@ impl Session {
})
}
/// What the session's handle and its thread share: the tests' view of it.
#[cfg(test)]
pub(crate) fn shared(&self) -> Arc<Shared> {
Arc::clone(&self.shared)
}
/// Ends the session as the device's reset does ([`Shared::close`]): its thread carries out
/// no message past the one in hand, and ends once that one is done and its queue let go of,
/// which the [`Ended`] answered waits for.
+7 -54
View File
@@ -442,7 +442,6 @@ mod tests {
use std::time::Duration;
use super::super::gated::GatedRuntime;
use crate::core::runtime::virtual_time::VirtualRuntime;
use crate::core::runtime::{Rings, StdRuntime, TimedOut};
use crate::core::sync::{Condvar, MutexGuard};
@@ -463,50 +462,13 @@ mod tests {
/// A call that waits until the test sends on the channel this gives,
/// as a driver's call waits for the GPU.
fn held<T: Send + 'static>(value: T) -> (mpsc::Sender<()>, impl FnOnce(VADisplay) -> T + Send) {
let (release, _, call) = held_saying(value);
(release, call)
}
/// [`held`]'s, and a channel the call says on as it begins, so that a
/// test knows the call thread is in it, where a real deadline only
/// hopes it is ([`past_the_deadline_in_the_call`]).
fn held_saying<T: Send + 'static>(
value: T,
) -> (
mpsc::Sender<()>,
mpsc::Receiver<()>,
impl FnOnce(VADisplay) -> T + Send,
) {
let (release, released) = mpsc::channel::<()>();
let (begun, inside) = mpsc::channel::<()>();
(release, inside, move |_| {
let _ = begun.send(());
(release, move |_| {
let _ = released.recv();
value
})
}
/// How long a test's caller waits for a call on virtual time
/// ([`past_the_deadline_in_the_call`]).
const SOON: Duration = Duration::from_millis(30);
/// A thread that moves `rt`'s clock [`SOON`] on once the call
/// [`held_saying`] made is in the driver, or after 5 s: a caller that
/// waits [`SOON`] for its answer then passes its deadline with the call
/// in hand, however late the call thread took it. Whether it began.
fn past_the_deadline_in_the_call(
rt: &Arc<VirtualRuntime>,
inside: mpsc::Receiver<()>,
) -> std::thread::JoinHandle<bool> {
let rt = Arc::clone(rt);
StdRuntime::thread("test-deadline", move || {
let began = inside.recv_timeout(Duration::from_secs(5)).is_ok();
rt.advance(SOON);
began
})
.unwrap()
}
fn within_5_s(mut ready: impl FnMut() -> bool) -> bool {
for _ in 0..5000 {
if ready() {
@@ -638,15 +600,13 @@ mod tests {
#[test]
fn a_release_behind_a_call_in_hand_is_made_after_it_and_in_order() {
let rt = Arc::new(VirtualRuntime::default());
let calls = Calls::new(std::ptr::null_mut(), Arc::clone(&rt) as Arc<dyn Runtime>);
let calls = calls();
let order = Arc::new(Mutex::new(Vec::new()));
let (release, inside, call) = held_saying(());
let (release, call) = held(());
let first = Arc::clone(&order);
let in_hand = past_the_deadline_in_the_call(&rt, inside);
assert_eq!(
calls.wait_call(
rt.deadline_in(SOON),
soon(),
move |raw| {
call(raw);
first.lock().push("call");
@@ -655,19 +615,16 @@ mod tests {
),
Err(Late::InFlight)
);
assert!(in_hand.join().unwrap(), "the call never began");
for name in ["destroy", "and then"] {
let order = Arc::clone(&order);
calls.release(move |_| order.lock().push(name));
}
// Room for a release made beside the call to show.
std::thread::sleep(Duration::from_millis(20));
assert!(
order.lock().is_empty(),
"released while the call was in hand"
);
release.send(()).expect("the call waits");
let later = || rt.deadline_in(Duration::from_secs(5));
assert_eq!(calls.call(later, |_| ()), Ok(()));
assert_eq!(*order.lock(), ["call", "destroy", "and then"]);
// Idle, a release is made at once.
@@ -718,18 +675,14 @@ mod tests {
#[test]
fn the_thread_ends_once_its_calls_drop_and_its_orders_are_made() {
let rt = Arc::new(VirtualRuntime::default());
let calls = Calls::new(std::ptr::null_mut(), Arc::clone(&rt) as Arc<dyn Runtime>);
let calls = calls();
let shared = Arc::downgrade(&calls.shared);
let (release, inside, call) = held_saying(());
let in_hand = past_the_deadline_in_the_call(&rt, inside);
let (release, call) = held(());
assert_eq!(
calls.wait_call(rt.deadline_in(SOON), call, |_, ()| {}),
calls.wait_call(soon(), call, |_, ()| {}),
Err(Late::InFlight)
);
assert!(in_hand.join().unwrap(), "the call never began");
drop(calls);
// Room for the thread to end in its call to show.
std::thread::sleep(Duration::from_millis(20));
assert_eq!(shared.strong_count(), 1, "the thread ended in its call");
release.send(()).expect("the call waits");
@@ -25,8 +25,6 @@ use super::super::surface::SurfaceFormat;
use super::super::teardown::Stream;
use super::{Call, PlaneDraw, PlaneTargets, covers};
mod crash_dump;
/// The streams of the directories `RVG_VA_STREAMS` lists (as `PATH` lists them): each H.264
/// (`.264`) and HEVC (`.265`) file, in name order.
fn streams() -> Vec<PathBuf> {
@@ -110,12 +108,10 @@ fn times(draws: &[Duration]) -> String {
/// refusal fails, as does a named stream that decodes whole ([`Marks::judge`]), and a run with
/// no picture drawn. The range extensions' streams are left out, named and counted: the
/// decoders land Main and Main 10 pictures alone. A leading picture the HEVC decoder skips is no
/// refusal. Run holding the GPU, on vaon12 on the default adapter. Where `RVG_CRASH_DUMP_DIR`
/// names a directory, a crash of its process leaves a minidump there ([`crash_dump`]).
/// refusal. Run holding the GPU, on vaon12 on the default adapter.
#[test]
#[ignore = "needs vaon12 and test streams: run on the Windows host"]
fn each_picture_drawn_into_its_targets_is_what_get_image_reads_back() {
crash_dump::arm("each_picture_drawn_into_its_targets_is_what_get_image_reads_back");
// The tests' clock: std's, which the library does not read.
let clock = StdRuntime;
read_back_by(Some(ReadbackWay::GetImage));
@@ -1,395 +0,0 @@
//! A test process's minidump at a crash, on the Windows host: where `RVG_CRASH_DUMP_DIR` names a
//! directory, [`arm`] has an unhandled exception in the process write a minidump there, then lets
//! the process end as it would have, its exit code the exception's, so the test still fails. A
//! fault that a run alone does not repeat (an access violation inside a driver's DLL, say) then
//! leaves its faulting module and its threads' stacks to read. Unset or empty, nothing is armed.
//! A test diagnostic, not a gate of the library: the library never reads the variable.
//!
//! Not Windows Error Reporting's `LocalDumps`: the tests' processes run with
//! `SEM_NOGPFAULTERRORBOX`, which the shell the harness runs them under passes to every process
//! it starts, and WER makes no report for a process in that mode. **Read** on the Windows test
//! machine (2026-12-04, while a winleg's tests ran): Git's bash, cargo, cargo-nextest and the
//! test binary each at error mode 0x3; a test's access violation there (potluck job
//! m3-max-87568) left no Application Error event, while WER logged other programs' crashes. A
//! process's own top-level filter (`SetUnhandledExceptionFilter`) is asked first, whatever the
//! error mode.
//!
//! The filter only hands the exception to a thread [`arm`] started, which writes the dump
//! (`MiniDumpWriteDump`, from Windows' `dbghelp.dll`) and says when it is done; the faulting
//! thread allocates nothing and takes no lock meanwhile, as the fault may have left the heap or
//! a lock in any state. The file's name and the function are had at the arm. The filter waits
//! for the dump up to [`DUMP_WAIT_MS`], then asks the filter it replaced, if any, or answers
//! `EXCEPTION_CONTINUE_SEARCH`, which leaves the process to end.
//!
//! The directory keeps the [`KEPT`] newest dumps: each arm lets go of older ones first
//! ([`prune`]), so a crash adds one to at most [`KEPT`] left by earlier runs.
use std::ffi::{OsStr, c_void};
use std::os::windows::ffi::OsStrExt;
use std::path::{Path, PathBuf};
use std::ptr::{NonNull, null, null_mut};
use std::sync::OnceLock;
use std::sync::atomic::{AtomicBool, AtomicPtr, AtomicU32, Ordering};
use crate::core::runtime::StdRuntime;
use super::super::super::d3d12::{CreateEventW, Handle, WaitForSingleObject, system_function};
/// The variable naming the directory the dumps go to.
const DIR_VARIABLE: &str = "RVG_CRASH_DUMP_DIR";
/// The dumps the directory keeps from earlier runs.
const KEPT: usize = 3;
/// How long a faulting thread waits for its dump before the process ends.
const DUMP_WAIT_MS: u32 = 60_000;
/// The dump's kind: a minidump (threads' stacks, the exception, the modules), with the modules
/// unloaded before the fault and each thread's times and state.
const DUMP_TYPE: u32 = MINI_DUMP_WITH_UNLOADED_MODULES | MINI_DUMP_WITH_THREAD_INFO;
/// `MiniDumpWithUnloadedModules` (dbghelp.h's `MINIDUMP_TYPE`).
const MINI_DUMP_WITH_UNLOADED_MODULES: u32 = 0x20;
/// `MiniDumpWithThreadInfo`.
const MINI_DUMP_WITH_THREAD_INFO: u32 = 0x1000;
/// `EXCEPTION_CONTINUE_SEARCH`: the process goes on to end as it would have.
const EXCEPTION_CONTINUE_SEARCH: i32 = 0;
/// `INFINITE`.
const INFINITE: u32 = u32::MAX;
/// `GENERIC_WRITE`.
const GENERIC_WRITE: u32 = 0x4000_0000;
/// `CREATE_ALWAYS`.
const CREATE_ALWAYS: u32 = 2;
/// `FILE_ATTRIBUTE_NORMAL`.
const FILE_ATTRIBUTE_NORMAL: u32 = 0x80;
/// A top-level exception filter (`LPTOP_LEVEL_EXCEPTION_FILTER`), given the exception's
/// `EXCEPTION_POINTERS`.
type TopLevelFilter = unsafe extern "system" fn(*const c_void) -> i32;
/// `MiniDumpWriteDump` (dbghelp.h).
type MiniDumpWriteDump = unsafe extern "system" fn(
*mut c_void,
u32,
*mut c_void,
u32,
*const ExceptionInformation,
*const c_void,
*const c_void,
) -> i32;
/// `MINIDUMP_EXCEPTION_INFORMATION`, which dbghelp.h packs to 4 bytes.
#[repr(C, packed(4))]
struct ExceptionInformation {
thread_id: u32,
exception_pointers: *mut c_void,
client_pointers: i32,
}
#[link(name = "kernel32")]
unsafe extern "system" {
fn SetUnhandledExceptionFilter(filter: Option<TopLevelFilter>) -> Option<TopLevelFilter>;
fn CreateFileW(
name: *const u16,
access: u32,
share: u32,
security: *const c_void,
disposition: u32,
flags: u32,
template: *mut c_void,
) -> *mut c_void;
fn SetEvent(event: *mut c_void) -> i32;
fn GetCurrentProcess() -> *mut c_void;
fn GetCurrentProcessId() -> u32;
fn GetCurrentThreadId() -> u32;
}
/// What the filter and the dump's thread share, made at the arm.
struct Armed {
/// The dump's path, NUL-terminated UTF-16.
path: Vec<u16>,
write: MiniDumpWriteDump,
/// Set as the filter hands over an exception (auto-reset), and as the dump is done (manual
/// reset, so that every faulting thread's wait sees it).
asked: Handle,
done: Handle,
/// The exception handed over, its thread, and whether one was.
exception: AtomicPtr<c_void>,
thread: AtomicU32,
handed: AtomicBool,
/// The dump's thread, which waits for no dump of its own fault.
dumper: AtomicU32,
/// The filter the arm replaced.
previous: OnceLock<Option<TopLevelFilter>>,
}
static ARMED: OnceLock<Armed> = OnceLock::new();
/// Arms the dump of this process for the test `test` where [`DIR_VARIABLE`] names a directory,
/// saying so on stderr with the dump's path; says why not where it cannot. Never fails the test.
pub(super) fn arm(test: &str) {
let Some(dir) = dump_dir(std::env::var_os(DIR_VARIABLE).as_deref()) else {
return;
};
match arm_in(&dir, test) {
Ok(path) => eprintln!(
"crash dump: armed: an unhandled exception in this process writes a minidump to {} \
before the process ends",
path.display()
),
Err(why) => eprintln!("crash dump: not armed in {}: {why}", dir.display()),
}
}
/// The directory `value` names: `None` where it is unset or empty.
fn dump_dir(value: Option<&OsStr>) -> Option<PathBuf> {
value.filter(|v| !v.is_empty()).map(PathBuf::from)
}
/// The dump's file name for the test `test` in the process `pid`: `rvg-<test>-<pid>.dmp`, each
/// character of the test's name but ASCII letters, digits, `-` and `_` written `_`.
fn dump_name(test: &str, pid: u32) -> String {
let test: String = test
.chars()
.map(|c| {
if c.is_ascii_alphanumeric() || c == '-' || c == '_' {
c
} else {
'_'
}
})
.collect();
format!("rvg-{test}-{pid}.dmp")
}
/// Whether `name` is a dump's file name ([`dump_name`]).
fn is_dump(name: &OsStr) -> bool {
name.to_str()
.is_some_and(|name| name.starts_with("rvg-") && name.ends_with(".dmp"))
}
/// Lets go of the dumps in `dir` past its `kept` newest, by their last write (then by name, last
/// first), leaving every other file; returns those let go of. A dump another process let go of
/// first is not an error.
fn prune(dir: &Path, kept: usize) -> std::io::Result<Vec<PathBuf>> {
let mut dumps = Vec::new();
for entry in std::fs::read_dir(dir)? {
let entry = entry?;
if !is_dump(&entry.file_name()) || !entry.file_type()?.is_file() {
continue;
}
dumps.push((entry.metadata()?.modified()?, entry.path()));
}
// Newest first.
dumps.sort();
dumps.reverse();
let mut gone = Vec::new();
for (_, path) in dumps.into_iter().skip(kept) {
match std::fs::remove_file(&path) {
Ok(()) => gone.push(path),
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
Err(error) => return Err(error),
}
}
Ok(gone)
}
/// [`arm`] in `dir`: the dump's path.
fn arm_in(dir: &Path, test: &str) -> Result<PathBuf, String> {
std::fs::create_dir_all(dir).map_err(|e| format!("its directory: {e}"))?;
prune(dir, KEPT).map_err(|e| format!("letting go of older dumps: {e}"))?;
// SAFETY: `GetCurrentProcessId` takes nothing.
let path = dir.join(dump_name(test, unsafe { GetCurrentProcessId() }));
let write = system_function("dbghelp.dll", c"MiniDumpWriteDump")?;
// SAFETY: the function is `MiniDumpWriteDump` (dbghelp.h), of that signature.
let write = unsafe { std::mem::transmute::<NonNull<c_void>, MiniDumpWriteDump>(write) };
let event = |manual_reset| {
// SAFETY: no attributes, initially unset, unnamed.
let made = unsafe { CreateEventW(null(), manual_reset, 0, null()) };
NonNull::new(made)
.map(Handle)
.ok_or_else(|| format!("CreateEventW: {}", std::io::Error::last_os_error()))
};
let armed = Armed {
path: path.as_os_str().encode_wide().chain([0]).collect(),
write,
asked: event(0)?,
done: event(1)?,
exception: AtomicPtr::new(null_mut()),
thread: AtomicU32::new(0),
handed: AtomicBool::new(false),
dumper: AtomicU32::new(0),
previous: OnceLock::new(),
};
if ARMED.set(armed).is_err() {
return Err("armed already in this process".to_owned());
}
StdRuntime::thread("reims-vgpu-video.crash-dump", dump_when_asked)
.map(drop)
.map_err(|e| format!("its thread: {e}"))?;
// SAFETY: `on_unhandled` is a top-level filter, which lives as long as the process.
let previous = unsafe { SetUnhandledExceptionFilter(Some(on_unhandled)) };
if let Some(armed) = ARMED.get() {
let _ = armed.previous.set(previous);
}
Ok(path)
}
/// The dump's thread: waits for an exception handed over, writes the dump, says it is done.
fn dump_when_asked() {
let Some(armed) = ARMED.get() else {
return;
};
// SAFETY: `GetCurrentThreadId` takes nothing; the events live as long as the process.
unsafe {
armed.dumper.store(GetCurrentThreadId(), Ordering::Release);
WaitForSingleObject(armed.asked.0.as_ptr(), INFINITE);
}
let info = ExceptionInformation {
thread_id: armed.thread.load(Ordering::Acquire),
exception_pointers: armed.exception.load(Ordering::Acquire),
client_pointers: 0,
};
// SAFETY: `path` is NUL-terminated UTF-16; a new file for writing alone.
let file = unsafe {
CreateFileW(
armed.path.as_ptr(),
GENERIC_WRITE,
0,
null(),
CREATE_ALWAYS,
FILE_ATTRIBUTE_NORMAL,
null_mut(),
)
};
// `INVALID_HANDLE_VALUE` is all bits set.
if let Some(file) = NonNull::new(file).filter(|f| f.as_ptr().addr() != usize::MAX) {
let file = Handle(file);
// SAFETY: this process and its id, a file opened for writing, and the exception the
// faulting thread handed over, whose pointers are this process's own; it waits for this.
unsafe {
(armed.write)(
GetCurrentProcess(),
GetCurrentProcessId(),
file.0.as_ptr(),
DUMP_TYPE,
&info,
null(),
null(),
);
}
drop(file);
}
// SAFETY: the event lives as long as the process.
unsafe { SetEvent(armed.done.0.as_ptr()) };
}
/// The process's top-level exception filter while armed (module doc).
unsafe extern "system" fn on_unhandled(exception: *const c_void) -> i32 {
let Some(armed) = ARMED.get() else {
return EXCEPTION_CONTINUE_SEARCH;
};
// SAFETY: `GetCurrentThreadId` takes nothing; the events live as long as the process.
unsafe {
let thread = GetCurrentThreadId();
// The dump's own thread faulting waits for no dump.
if thread != armed.dumper.load(Ordering::Acquire) {
if !armed.handed.swap(true, Ordering::AcqRel) {
armed
.exception
.store(exception.cast_mut(), Ordering::Release);
armed.thread.store(thread, Ordering::Release);
SetEvent(armed.asked.0.as_ptr());
}
WaitForSingleObject(armed.done.0.as_ptr(), DUMP_WAIT_MS);
}
match armed.previous.get().copied().flatten() {
Some(previous) => previous(exception),
None => EXCEPTION_CONTINUE_SEARCH,
}
}
}
/// Nothing is armed where the variable is unset or empty; anything else names the directory.
#[test]
fn a_crash_dump_is_armed_only_where_its_directory_is_named() {
assert_eq!(dump_dir(None), None);
assert_eq!(dump_dir(Some(OsStr::new(""))), None);
assert_eq!(
dump_dir(Some(OsStr::new(r"P:\rvg-crashdumps"))),
Some(PathBuf::from(r"P:\rvg-crashdumps"))
);
}
/// A dump is named for its test and its process, each character of the test's path that a file
/// name might not take written `_`; only such names are dumps.
#[test]
fn a_crash_dump_is_named_for_its_test_and_its_process() {
let name = dump_name("vaapi::va::d3d11::tests::each picture-drawn", 4242);
assert_eq!(
name,
"rvg-vaapi__va__d3d11__tests__each_picture-drawn-4242.dmp"
);
assert!(is_dump(OsStr::new(&name)));
assert!(!is_dump(OsStr::new("rvg-a.txt")));
assert!(!is_dump(OsStr::new("other.dmp")));
}
/// Arming lets go of the dumps past the three newest, by their last write, and of nothing else:
/// files not named as dumps and directories stay.
#[test]
fn arming_keeps_the_three_newest_dumps_and_no_other_file_is_touched() {
use std::time::{Duration, SystemTime};
// SAFETY: `GetCurrentProcessId` takes nothing.
let pid = unsafe { GetCurrentProcessId() };
let dir = std::env::temp_dir().join(format!("rvg-crash-dump-prune-{pid}"));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(dir.join("rvg-a-directory.dmp")).expect("the test's directory");
let write = |name: &str, seconds: u64| {
let path = dir.join(name);
let file = std::fs::File::create(&path).expect("a file");
file.set_modified(SystemTime::UNIX_EPOCH + Duration::from_secs(1_700_000_000 + seconds))
.expect("its time of last write");
};
// Written out of time order, so that the names' order is not the times'.
for (name, seconds) in [
("rvg-e-5.dmp", 10),
("rvg-a-1.dmp", 50),
("rvg-d-4.dmp", 20),
("rvg-b-2.dmp", 40),
("rvg-c-3.dmp", 30),
("other.dmp", 0),
("rvg-notes.txt", 0),
] {
write(name, seconds);
}
let mut gone = prune(&dir, KEPT).expect("the prune");
gone.sort();
assert_eq!(gone, [dir.join("rvg-d-4.dmp"), dir.join("rvg-e-5.dmp")]);
let mut left: Vec<String> = std::fs::read_dir(&dir)
.expect("the directory")
.map(|e| {
e.expect("an entry")
.file_name()
.to_string_lossy()
.into_owned()
})
.collect();
left.sort();
assert_eq!(
left,
[
"other.dmp",
"rvg-a-1.dmp",
"rvg-a-directory.dmp",
"rvg-b-2.dmp",
"rvg-c-3.dmp",
"rvg-notes.txt"
]
);
assert_eq!(
prune(&dir, KEPT).expect("a second prune"),
Vec::<PathBuf>::new()
);
std::fs::remove_dir_all(&dir).expect("the test's directory removed");
}
+1 -2
View File
@@ -391,8 +391,7 @@ mod tests {
let _installed = install(schedule, Arc::clone(&clock) as Arc<dyn Runtime>);
let delay = at(Point::Answer);
let waited = StdRuntime::thread("delay-waiter", move || delay.wait()).unwrap();
// It looked at the clock twice: it found its delay not passed, and waits on.
assert!(clock.wait_for_looks(2, Duration::from_secs(10), || waited.is_finished()));
std::thread::sleep(Duration::from_millis(20));
assert!(!waited.is_finished(), "ended before its delay");
clock.advance(Duration::from_secs(6));
waited.join().unwrap();
-264
View File
@@ -1,264 +0,0 @@
#!/usr/bin/env bash
# The self-checking stream: streams whose every picture carries its own frame
# number and what the rest of it should look like (the conformance crate's
# `selfcheck` module), and the judge of a decode or a screen recording of one,
# frame by frame, with no reference decode.
#
# crates/reims-vgpu-video/tools/selfcheck.sh make [DIR]
# crates/reims-vgpu-video/tools/selfcheck.sh judge [--recording] [--crop X,Y,W,H] [--frames N] FILE...
# crates/reims-vgpu-video/tools/selfcheck.sh selftest [DIR]
#
# make writes DIR (default build/selfcheck) with a stream of each codec the
# host's ffmpeg has an encoder of: H.264 High (libx264), HEVC Main and Main 10
# (libx265), VP9 (libvpx-vp9) and AV1 (libsvtav1, else libaom-av1), each with
# B-frames or their codec's reordering, a key frame every two seconds, at
# SIZE (default 1920x1080), RATE (30) and FRAMES (1200: 40 s). A codec whose
# encoder the host lacks is skipped, saying so. The streams are made from
# scratch, by the crate's selfcheck-frames example, on our hosts; x264, x265,
# libvpx, SVT-AV1, aom and ffmpeg are test oracles alone, and nothing they write
# is committed. Each stream is tagged BT.709 (primaries, transfer and matrix) at
# limited range, so that a player converts it to RGB by the matrix it states.
#
# judge decodes each FILE with ffmpeg in software, each stored frame once
# (-fps_mode passthrough), into 8-bit 4:2:0, and judges its frames: a line for
# each faulty frame (REPEAT, OUT-OF-ORDER, TORN, WRONG, GREEN, PART-GREEN,
# UNREADABLE), then the summary line, with the runs of numbers no frame showed
# (DROPPED). A decode of the stream is judged as a file: every frame once, in
# order, from frame 0; --frames N, the stream's length, makes one that ends
# short drop the rest. A screen recording of its playback is judged with
# --recording, the picture in the --crop region of each frame (the whole frame
# without one): frames that hold a picture are no fault, nor are the frames
# before the stream's first and after its last, nor, with --frames, a loop
# from its last frames to its first. The exit status is 1 where any file has a
# fault.
#
# selftest makes small streams (640x360, 90 frames) into DIR (default
# build/selfcheck-test), judges each codec's decode clean, then each fault
# class made from the H.264 stream by an ffmpeg filter on its decode, each of
# which must be called: frames dropped, repeated and reordered, a picture of
# zeros, one partly of zeros, one torn of two frames, one whose flat cells are
# a later frame's, one whose chroma planes are swapped; a recording of its
# playback (60 fps, scaled into a larger screen, re-encoded) judged clean with
# its crop; and the H.264 stream's decode shown in 8-bit RGB and taken back to
# 4:2:0 by BT.709, as a screen recording takes a player's picture, re-encoded
# and judged clean, shown by BT.709 and, as a player that takes the other
# matrix, by BT.601, and once with frame 60's flat cells of row 2 frame 68's,
# which must still be called WRONG. It needs no GPU.
set -euo pipefail
source "$(dirname "$0")/lib.sh"
examples=$CARGO_TARGET_DIR/release/examples
# encoders: the codecs this host's ffmpeg encodes, a name each:
# h264 hevc hevc10 vp9 av1.
encoders() {
local have
have=$(ffmpeg -hide_banner -encoders 2> /dev/null)
grep -q ' libx264 ' <<< "$have" && echo h264
grep -q ' libx265 ' <<< "$have" && echo hevc hevc10
grep -q ' libvpx-vp9 ' <<< "$have" && echo vp9
if grep -q ' libsvtav1 ' <<< "$have"; then
echo av1:libsvtav1
elif grep -q ' libaom-av1 ' <<< "$have"; then
echo av1:libaom-av1
fi
return 0
}
# The streams' colour: BT.709 primaries, transfer and matrix, limited range,
# said of the raw pictures and of each stream.
tags=(-color_primaries bt709 -color_trc bt709 -colorspace bt709 -color_range tv)
# encode NAME OUT SIZE RATE FRAMES: the stream of codec NAME (encoders'), its
# pictures from selfcheck-frames, into OUT.
encode() {
local name=$1 out=$2 size=$3 rate=$4 frames=$5
local width=${size%x*} height=${size#*x} keyint=$((2 * rate)) args
case $name in
h264) args=(-c:v libx264 -profile:v high -preset medium -crf 18 -bf 3
-g "$keyint" -pix_fmt yuv420p) ;;
hevc) args=(-c:v libx265 -preset medium -crf 20 -tag:v hvc1 -pix_fmt yuv420p
-x265-params "keyint=$keyint:bframes=4:log-level=error") ;;
hevc10) args=(-c:v libx265 -preset medium -crf 20 -tag:v hvc1
-pix_fmt yuv420p10le -x265-params "keyint=$keyint:bframes=4:log-level=error") ;;
vp9) args=(-c:v libvpx-vp9 -crf 24 -b:v 0 -g "$keyint" -row-mt 1 -pix_fmt yuv420p) ;;
av1:libsvtav1) args=(-c:v libsvtav1 -crf 28 -preset 8 -g "$keyint" -pix_fmt yuv420p) ;;
av1:libaom-av1) args=(-c:v libaom-av1 -crf 30 -b:v 0 -cpu-used 6 -g "$keyint"
-pix_fmt yuv420p) ;;
esac
"$examples/selfcheck-frames" "$width" "$height" "$frames" |
ffmpeg -nostdin -hide_banner -loglevel error -y -f rawvideo -pix_fmt yuv420p \
-video_size "$size" -framerate "$rate" "${tags[@]}" -i - "${args[@]}" "${tags[@]}" "$out"
}
# file_of NAME: the stream's file name.
file_of() {
case $1 in
vp9) echo selfcheck-vp9.webm ;;
av1:*) echo selfcheck-av1.mp4 ;;
*) echo "selfcheck-$1.mp4" ;;
esac
}
# make_streams DIR SIZE RATE FRAMES
make_streams() {
local dir=$1 size=$2 rate=$3 frames=$4 name have
mkdir -p "$dir"
have=$(encoders)
for name in h264 hevc hevc10 vp9 av1; do
local found
found=$(tr ' ' '\n' <<< "$have" | grep -E "^$name(:|$)" | head -1 || true)
if [[ -z $found ]]; then
echo "SKIP $name: this host's ffmpeg has no encoder of it"
continue
fi
encode "$found" "$dir/$(file_of "$found")" "$size" "$rate" "$frames"
echo "MADE $dir/$(file_of "$found") ($found, $size, $frames frames at $rate fps)"
done
}
# judge_file FILE FILTER JUDGE-ARGS...: FILE decoded by ffmpeg, through the
# filter FILTER where it is not empty, judged; the judge's output, its status
# the judge's.
judge_file() {
local file=$1 filter=$2 size
shift 2
size=$(ffprobe -v error -select_streams v:0 -show_entries stream=width,height \
-of csv=p=0:s=x "$file")
local vf=()
[[ -n $filter ]] && vf=(-vf "$filter")
ffmpeg -nostdin -hide_banner -loglevel error -i "$file" ${vf[@]+"${vf[@]}"} \
-fps_mode passthrough -pix_fmt yuv420p -f rawvideo - |
"$examples/selfcheck-judge" "${size%x*}" "${size#*x}" "$@"
}
judge() {
local args=() files=()
while (($#)); do
case $1 in
--recording) args+=("$1") ;;
--crop | --frames)
args+=("$1" "$2")
shift
;;
*) files+=("$1") ;;
esac
shift
done
((${#files[@]})) || { echo "selfcheck.sh judge: no file" >&2; exit 2; }
local file
for file in "${files[@]}"; do
echo "== $file"
judge_file "$file" "" ${args[@]+"${args[@]}"} || failed=1
done
}
# expect LABEL CLASS OUTPUT: PASS where the summary line of OUTPUT counts
# CLASS once or more and fails; FAIL otherwise, counted in `failed`.
expect() {
local label=$1 class=$2 out=$3 summary n
summary=$(grep '^SELFCHECK ' <<< "$out" | tail -1)
n=$(sed -nE "s/.*[;,] $class ([0-9]+)[,;].*/\1/p" <<< "$summary")
if [[ ${n:-0} -ge 1 && $summary == *"; FAIL" ]]; then
echo "PASS $label: $class $n called"
else
echo "FAIL $label: $class not called: $summary"
failed=1
fi
}
selftest() {
local dir=$1 size=640x360 rate=30 frames=90 name out file
make_streams "$dir" "$size" "$rate" "$frames"
for file in "$dir"/selfcheck-*; do
out=$(judge_file "$file" "" --frames "$frames" || true)
if [[ $(tail -1 <<< "$out") == *"; PASS" ]]; then
echo "PASS clean $(basename "$file"): $(tail -1 <<< "$out")"
else
echo "FAIL clean $(basename "$file"):"
echo "$out" | tail -20
failed=1
fi
done
local h264=$dir/selfcheck-h264.mp4
if [[ ! -f $h264 ]]; then
echo "FAIL the faults need the H.264 stream, which this host's ffmpeg does not encode"
failed=1
return
fi
# label|class|filter on the decode
local faults=(
"frames 10 and 11 dropped|DROPPED|select='not(between(n\,10\,11))'"
"frame 20 shown twice|REPEAT|loop=loop=1:size=1:start=20"
"frames 8 and 9 of every ten swapped|OUT-OF-ORDER|shuffleframes=0 1 2 3 4 5 6 7 9 8"
"frame 30 of zeros|GREEN|lutyuv=y=0:u=0:v=0:enable='eq(n,30)'"
"frame 40's bottom sixth of zeros|PART-GREEN|split[a][b];[b]crop=iw:ih/6:0:ih*5/6,lutyuv=y=0:u=0:v=0[z];[a][z]overlay=x=0:y=main_h-overlay_h:enable='eq(n,40)'"
"frame 50's bottom half frame 51's|TORN|split[a][b];[b]trim=start_frame=1,setpts=PTS-STARTPTS,crop=iw:ih/2:0:ih/2[bot];[a][bot]overlay=x=0:y=main_h-overlay_h:enable='eq(n,50)':eof_action=pass"
"frame 60's flat cells of row 2 frame 68's|WRONG|split[a][b];[b]trim=start_frame=8,setpts=PTS-STARTPTS,crop=iw:ih/9:0:ih*2/9[row];[a][row]overlay=x=0:y=main_h*2/9:enable='eq(n,60)':eof_action=pass"
"frame 70's chroma planes swapped|WRONG|swapuv=enable='eq(n,70)'"
)
local fault label class filter
for fault in "${faults[@]}"; do
IFS='|' read -r label class filter <<< "$fault"
out=$(judge_file "$h264" "$filter" --frames "$frames" || true)
expect "$label" "$class" "$out"
done
# A recording of its playback: grey before the stream, 60 fps, scaled into a
# larger screen at an even place, re-encoded.
local recording=$dir/recording-h264.mp4
ffmpeg -nostdin -hide_banner -loglevel error -y -i "$h264" \
-vf "tpad=start=12:color=gray,fps=60,scale=480:270,pad=800:450:130:76:color=gray" \
-c:v libx264 -crf 16 -pix_fmt yuv420p "$recording"
out=$(judge_file "$recording" "" --recording --crop 130,76,480,270 --frames "$frames" || true)
if [[ $(tail -1 <<< "$out") == *"; PASS" ]]; then
echo "PASS recording: $(tail -1 <<< "$out")"
else
echo "FAIL recording:"
echo "$out" | tail -20
failed=1
fi
# The same recording with a frame of zeros and a stretch played back out of
# order is called.
out=$(judge_file "$recording" "lutyuv=y=0:u=0:v=0:enable='eq(n,100)',shuffleframes=0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 60 61 62 63 64 65 66 67 68 69 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59" \
--recording --crop 130,76,480,270 --frames "$frames" || true)
expect "the recording's frame of zeros" GREEN "$out"
expect "the recording's stretch out of order" OUT-OF-ORDER "$out"
# The decode in 8-bit RGB by MATRIX and back to 4:2:0 by BT.709, re-encoded.
local rgb=$dir/rgb-h264.mp4 matrix
through_rgb() {
ffmpeg -nostdin -hide_banner -loglevel error -y -i "$h264" \
-vf "${2:+$2,}scale=in_color_matrix=$1:in_range=tv,format=rgb24,scale=out_color_matrix=bt709:out_range=tv,format=yuv420p" \
-c:v libx264 -crf 16 -pix_fmt yuv420p "${tags[@]}" "$rgb"
}
for matrix in bt709 bt601; do
through_rgb "$matrix"
out=$(judge_file "$rgb" "" --frames "$frames" || true)
if [[ $(tail -1 <<< "$out") == *"; PASS" ]]; then
echo "PASS shown in RGB by $matrix, taken back by bt709: $(tail -1 <<< "$out")"
else
echo "FAIL shown in RGB by $matrix, taken back by bt709:"
echo "$out" | tail -20
failed=1
fi
done
through_rgb bt709 "split[a][b];[b]trim=start_frame=8,setpts=PTS-STARTPTS,crop=iw:ih/9:0:ih*2/9[row];[a][row]overlay=x=0:y=main_h*2/9:enable='eq(n,60)':eof_action=pass"
out=$(judge_file "$rgb" "" --frames "$frames" || true)
expect "frame 60's flat cells of row 2 frame 68's, shown in RGB and taken back" WRONG "$out"
}
command=${1:-}
shift || true
build reims-vgpu-video-conformance selfcheck-frames selfcheck-judge
case $command in
make)
make_streams "${1:-$root/build/selfcheck}" "${SIZE:-1920x1080}" "${RATE:-30}" \
"${FRAMES:-1200}"
;;
judge) judge "$@" ;;
selftest) selftest "${1:-$root/build/selfcheck-test}" ;;
*)
echo "usage: selfcheck.sh make [DIR] | judge [--recording] [--crop X,Y,W,H] [--frames N] FILE... | selftest [DIR]" >&2
exit 2
;;
esac
exit "$failed"
@@ -320,6 +320,10 @@ pub trait GpuDevice<P: Platform>: Handle {
/// queue between command queues answers `new_command_queue`'s queue. Never nil-checked; a raise
/// inside it dies at the call, as one inside `newCommandQueue` does.
fn new_command_queue_unshared(&self) -> Option<P::CommandQueue>;
/// The private IOSurface copy FIFO. A cache transaction may record all its copies before
/// it can publish any of them. Allocating a command buffer here must not wait for a
/// previously recorded copy to retire. GPU execution still follows queue order.
fn new_cache_transfer_queue(&self) -> Option<P::CommandQueue>;
/// No Metal counterpart: how many times the platform recovered the device's GPU so far, its
/// lost device made again behind the same device object (the Vulkan platform's runtime makes
/// a new `VkDevice`, `device-recovered`). The textures, pipelines and pooled buffers made
@@ -608,4 +612,44 @@ pub trait GpuDevice<P: Platform>: Handle {
&self,
desc: &FullComputePipelineDesc<'_, P>,
) -> Result<Option<P::ComputePipeline>, NsErrorText>;
/// Waits for all submitted GPU work on this device to complete without tearing down the device.
fn wait_idle(&self) {}
/// Reads the current timeline value of a non-shared `MTLEvent` (0 if unsupported).
fn event_signaled_value(&self, _event: &P::Event) -> u64 {
0
}
/// Restores a non-shared `MTLEvent`'s timeline value across host process restart.
fn event_restore_signaled_value(&self, _event: &P::Event, _value: u64) -> bool {
true
}
/// Reads the contents of a standalone GPU buffer (Shared/Managed/Private) for snapshotting.
/// Returns `Ok(None)` if the buffer has no backed contents or this platform does not support
/// readback; returns `Err(...)` if a GPU transfer fails.
fn read_standalone_buffer(&self, _buffer: &P::Buffer) -> Result<Option<Vec<u8>>, &'static str> {
Ok(None)
}
/// Restores the contents of a standalone GPU buffer from snapshot bytes.
fn write_standalone_buffer(&self, _buffer: &P::Buffer, _data: &[u8]) -> bool {
false
}
/// Reads all mip levels and array/cube slices of a standalone GPU texture into packed bytes.
/// Returns `Ok(None)` for non-transferable formats (MSAA, Memoryless, depth/stencil) or on
/// platforms without readback; returns `Err(...)` if a GPU transfer fails.
fn read_standalone_texture(
&self,
_texture: &P::Texture,
) -> Result<Option<Vec<u8>>, &'static str> {
Ok(None)
}
/// Uploads packed mip/slice bytes back into a standalone GPU texture.
fn write_standalone_texture(&self, _texture: &P::Texture, _data: &[u8]) -> bool {
false
}
}
@@ -560,15 +560,6 @@ pub enum RenderCmd<'a, P: Platform> {
WaitForFence { fence: &'a P::Fence, stages: u64 },
}
// Written out: a derive would require `P: Clone`/`P: Copy`. A command borrows what it names, so a
// platform reads what a refusal of it asks after sending it.
impl<P: Platform> Clone for RenderCmd<'_, P> {
fn clone(&self) -> Self {
*self
}
}
impl<P: Platform> Copy for RenderCmd<'_, P> {}
impl<P: Platform> RenderCmd<'_, P> {
/// The selector this sends.
pub fn selector(&self) -> &'static str {
@@ -17,18 +17,10 @@
//! The one liberty: the timeout notify wakes every thread parked on that condvar, so another
//! waiter on the same condvar whose deadline has not passed (or an untimed one) returns as a
//! spurious wakeup, which `std::condition_variable` allows. It never loses a notify.
//!
//! A test that acts once another thread waits reads the clock's counts: the timed waits made on
//! it ([`VirtualClock::timed_waits`]), where that thread's are the only ones, and each thread's
//! parks ([`VirtualClock::parked`]), where the clock is shared with other waiters (a world's
//! clock, beside its device's timed waits and polls). A real sleep in their place only hopes the
//! thread got there, and a check made behind it passes untested when that thread is late.
#![allow(unsafe_code)] // architecture 17.3: fake/clock.rs (a timed wait's registered condvar and mutex)
use std::collections::HashMap;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::thread::ThreadId;
use std::time::Duration;
use parking_lot::RawMutex;
@@ -92,9 +84,6 @@ pub struct VirtualClock {
/// Parked timed waits. Lock order: `timed`, then `now`; a caller's mutex is only ever
/// try-locked under it.
timed: Mutex<TimedWaits>,
/// How many times each thread has parked in a wait on this clock ([`VirtualClock::parked`]).
/// Taken last, under any of the others, and nothing is taken under it.
parked: Mutex<HashMap<ThreadId, u64>>,
}
struct Waiting<'a>(&'a AtomicUsize);
@@ -188,14 +177,6 @@ impl VirtualClock {
}
}
/// Counts a park of this thread's, made while it still holds the lock its wait releases as
/// it parks.
fn parks(&self) {
let mut parked = self.parked.lock();
let n = parked.entry(std::thread::current().id()).or_default();
*n = n.wrapping_add(1);
}
/// How many threads are blocked in a clock wait now.
pub fn waiters(&self) -> usize {
self.waiters.load(Ordering::SeqCst)
@@ -253,40 +234,6 @@ impl VirtualClock {
}
}
/// How many times `thread` has parked in a wait on this clock so far: a `wait_until` that
/// did not find its deadline passed, a `wait`, and each park of a `sleep_until`. Each is
/// counted while the thread still holds the lock its wait releases as it parks, so what a
/// test changes under that lock once it has read the count grow reaches the parked thread:
/// a test waits for it to grow ([`Self::wait_for_parked`]) to know that thread is parked in
/// its wait, where other threads' waits on the clock leave [`Self::timed_waits`] unable to
/// single it out.
pub fn parked(&self, thread: ThreadId) -> u64 {
self.parked.lock().get(&thread).copied().unwrap_or(0)
}
/// Blocks (in real time, up to `real_timeout`) until `thread` has parked at least `n` times
/// on this clock in all ([`Self::parked`]), or `or` holds (the thread went on without its
/// wait): whether either came in time.
pub fn wait_for_parked(
&self,
thread: ThreadId,
n: u64,
real_timeout: Duration,
or: impl Fn() -> bool,
) -> bool {
let mut left = real_timeout;
loop {
if self.parked(thread) >= n || or() {
return true;
}
if left.is_zero() {
return false;
}
std::thread::sleep(POLL_SLICE);
left = left.saturating_sub(POLL_SLICE);
}
}
fn reached_at(now: u64, d: Deadline) -> bool {
match d {
Deadline::Mono(t) => now >= t.as_nanos(),
@@ -332,7 +279,6 @@ impl Clock for VirtualClock {
deadline,
expired: false,
});
self.parks();
id
};
// Registered while holding the mutex, so `advance` cannot deliver before this parks.
@@ -349,7 +295,6 @@ impl Clock for VirtualClock {
fn wait<T>(&self, cv: &Condvar, g: &mut MutexGuard<'_, T>) {
let _w = Waiting::enter(&self.waiters);
self.parks();
cv.wait(g);
}
@@ -357,7 +302,6 @@ impl Clock for VirtualClock {
let _w = Waiting::enter(&self.waiters);
let mut n = self.now.lock();
while !Self::reached_at(*n, deadline) {
self.parks();
self.tick.wait(&mut n);
}
}
@@ -560,67 +504,6 @@ mod tests {
assert!(c.wait_for_timed_waits(3, Duration::ZERO, || true));
}
/// Each thread's parks count apart, on one clock: a timed wait's, again after a notify, an
/// untimed wait's and each of a sleep's; a deadline already reached parks none, and a thread
/// that never waited reads 0
#[test]
fn parks_are_counted_by_thread() {
let c = Arc::new(VirtualClock::new());
let state = Arc::new((Mutex::new(0u32), Condvar::new()));
let spawn = |timed: bool| {
let (c2, s2) = (c.clone(), state.clone());
std::thread::Builder::new()
.spawn(move || {
let mut g = s2.0.lock();
let d = Deadline::Mono(MonoTime::from_nanos(100));
let seen = *g;
while *g == seen {
if timed {
let _ = c2.wait_until(&s2.1, &mut g, d);
} else {
c2.wait(&s2.1, &mut g);
}
}
})
.unwrap()
};
let (timed, untimed) = (spawn(true), spawn(false));
let (t, u) = (timed.thread().id(), untimed.thread().id());
assert!(c.wait_for_parked(t, 1, REAL, || timed.is_finished()));
assert!(c.wait_for_parked(u, 1, REAL, || untimed.is_finished()));
assert_eq!((c.parked(t), c.parked(u)), (1, 1));
// A notify with nothing changed: each parks again.
{
let _g = state.0.lock();
state.1.notify_all();
}
assert!(c.wait_for_parked(t, 2, REAL, || timed.is_finished()));
assert!(c.wait_for_parked(u, 2, REAL, || untimed.is_finished()));
*state.0.lock() += 1;
state.1.notify_all();
timed.join().unwrap();
untimed.join().unwrap();
assert_eq!((c.parked(t), c.parked(u)), (2, 2));
let me = std::thread::current().id();
assert_eq!(c.parked(me), 0);
let (m, cv) = (Mutex::new(()), Condvar::new());
let at = Deadline::Mono(MonoTime::from_nanos(0));
assert!(c.wait_until(&cv, &mut m.lock(), at).timed_out());
assert_eq!(c.parked(me), 0, "a deadline already reached parks none");
let c2 = c.clone();
let sleeper = std::thread::Builder::new()
.spawn(move || c2.sleep_until(Deadline::Mono(MonoTime::from_nanos(500))))
.unwrap();
let s = sleeper.thread().id();
assert!(c.wait_for_parked(s, 1, REAL, || sleeper.is_finished()));
c.advance(Duration::from_nanos(100));
assert!(c.wait_for_parked(s, 2, REAL, || sleeper.is_finished()));
c.advance(Duration::from_nanos(400));
sleeper.join().unwrap();
assert!(!c.wait_for_parked(s, 3, Duration::ZERO, || false));
assert!(c.wait_for_parked(s, 3, Duration::ZERO, || true));
}
/// A deadline already reached returns at once; the wall deadline uses wall time
#[test]
fn past_deadlines() {
@@ -490,6 +490,11 @@ impl GpuDevice<FakePlatform> for Fk<kind::Device> {
}))
}
fn new_cache_transfer_queue(&self) -> Option<<FakePlatform as Platform>::CommandQueue> {
// Fake queues allocate independent handles immediately.
self.new_command_queue_unshared()
}
/// Unlogged, as the property the platform answers it from: [`World::copy_guest_ram`].
///
/// [`World::copy_guest_ram`]: crate::core::testkit::objects::World::copy_guest_ram
+1 -1
View File
@@ -15,7 +15,7 @@
//! buffered as the process ends are lost, but for a death's ([`flush_before_death`]).
//!
//! A write made holding the events' lock holds every traced thread for as long as the file
//! stalls. In a traced boot (2026-11-15), with the file on a workspace disk
//! stalls. In a traced boot on homelab-um870-1 (2026-11-15), with the file on a workspace disk
//! whose writes stalled for up to 219 ms, the trace went silent for 31 to 219 ms at a time right
//! after an event of the control thread, every traced thread going on within 50 us of the others
//! after it, while the guest's command buffers waited for ring 0 behind the control thread.
@@ -22,7 +22,7 @@
//! cannot present on) is passed over for the next. The loader's order is not the pick: Mesa's
//! device-select layer sorts the devices after the loader and lists its own default first
//! unless its own variables name a device, so with `VK_LOADER_DEVICE_SELECT` alone naming
//! an RTX 3090, the loader's first device was the layer's default, the Radeon 780M beside it
//! um870's RTX 3090, the loader's first device was the layer's default, its Radeon 780M
//! (**measured**, 2026-11-14, m3-max-30538, Mesa 26.2.6 and the loader 1.4.363).
//! `DRI_PRIME`'s index (`DRI_PRIME=1`, with or without its `!`) selects the Nth GPU other than
//! the layer's default, which the library cannot tell, and the layer lists the GPU it selects
@@ -508,9 +508,9 @@ pub(crate) mod tests {
}
}
/// A host's devices in the order Mesa's device-select layer lists them with no variable of
/// its own set (m3-max-30538): a Radeon 780M, an RTX 3090, lavapipe.
fn a_780m_a_3090_and_lavapipe() -> [Seen; 3] {
/// um870's devices in the order Mesa's device-select layer lists them with no variable of its
/// own set (m3-max-30538): the Radeon 780M, the RTX 3090, lavapipe.
fn um870() -> [Seen; 3] {
[
with_ids(integrated(11, 1), (0x1002, 0x1900), 0xc5),
with_ids(discrete(24, 2), (0x10de, 0x2204), 0x67),
@@ -525,7 +525,7 @@ pub(crate) mod tests {
/// `VK_LOADER_DEVICE_SELECT`'s too, which Mesa's layer leaves behind its own default
#[test]
fn the_users_pick_is_the_device_its_variable_names() {
let list = a_780m_a_3090_and_lavapipe();
let list = um870();
let ids = |v, d| Some(Named::Ids(v, d));
let loader = [("VK_LOADER_DEVICE_SELECT", ids(0x10de, 0x2204))];
let picked = choose(&list, &loader);
@@ -564,7 +564,7 @@ pub(crate) mod tests {
/// one
#[test]
fn a_variable_that_names_no_candidate_is_passed_over() {
let list = a_780m_a_3090_and_lavapipe();
let list = um870();
let nothing = Some(Named::Ids(0xdead, 0xbeef));
let pci = Named::Pci(0, 0x67, 0, 0);
let user = [("MESA_VK_DEVICE_SELECT", nothing), ("DRI_PRIME", Some(pci))];
@@ -41,34 +41,6 @@ pub(crate) fn first_bytes(sel: &'static str, range: HostRange<'_>, most: usize)
copy
}
/// `range` as rt's [`HostBytes`](metal2vulkan_runtime::HostBytes), read in place by the rt call
/// it is passed to, with no copy of this platform's own: rt reads each byte at most once, by raw
/// copies, forms no slice over them and keeps no pointer past the call, as guest memory that may
/// change while it is read needs. A range that [`first_bytes`] dies at dies here too, at `sel`.
/// The caller passes it only to a call whose writes cannot land in it: rt's copies out of it are
/// nonoverlapping, so a destination over the same memory (a texture over a buffer of these
/// pages) takes [`first_bytes`] instead.
pub(crate) fn guest_bytes<'a>(
sel: &'static str,
range: HostRange<'a>,
) -> metal2vulkan_runtime::HostBytes<'a> {
let length =
usize::try_from(range.len()).unwrap_or_else(|_| unrepresentable(sel, "that length"));
if length == 0 {
return metal2vulkan_runtime::HostBytes::from(&[][..]);
}
let first = range.ptr().addr();
if first < crate::core::host::ZERO_REGION_END || first.checked_add(length).is_none() {
crate::answer::metal_reads_near_null(sel, &format!("{length} bytes at {first:#x}"));
}
// SAFETY: `HostRange::new`'s contract keeps `first..first + length` mapped and readable for
// as long as the call `range` is passed to runs (`'a`), and the check above puts it past the
// zero region and below the top of the address space; rt reads it in place, through raw
// copies, during that call alone (`HostBytes`' docs), into memory the caller keeps apart from
// it (above).
unsafe { metal2vulkan_runtime::HostBytes::from_raw(range.ptr().as_ptr::<u8>(), length) }
}
#[cfg(all(test, target_os = "linux"))]
mod tests {
use super::*;
+6 -6
View File
@@ -41,16 +41,16 @@
//!
//! A view of many runs is resolved in one pass of the backing table and recorded over its fresh
//! reservation with no run to cut (`files::view_pieces`, `files::record_pieces`), so the kernel's
//! maps are most of what it costs. **Measured** 2026-11-08 on a Ryzen 7 8745H (Linux 7.3.1,
//! release build): a view of 7,261 one-page runs of a registered memfd, three in four the
//! maps are most of what it costs. **Measured** 2026-11-08 on homelab-um870-1 (Ryzen 7 8745H, Linux
//! 7.3.1, release build): a view of 7,261 one-page runs of a registered memfd, three in four the
//! page below the one before (an IOSurface's, as an x86-64 macOS guest hands its pages out), took
//! 1.86 µs a run beside 66,000 one-page views, and 2.06 µs beside 200,000, against 2.06 and 2.29 µs
//! with each run resolved and recorded on its own. On a Core i9-13900H (Linux 7.3.1),
//! with each run resolved and recorded on its own. On homelab-ms01-1 (Core i9-13900H, Linux 7.3.1),
//! beside 66,000, it took 1.21 µs a run on a performance core and 2.11 µs on an efficiency core,
//! against 1.50 and 2.58 µs a run at a time: that processor gives the kernel no capacity to place a
//! thread by (`hints`), so a view is mapped on either. A C loop of the same maps took 2.0 to 2.2 µs
//! a run on a Ryzen 7 7840HS (Linux 7.3.1) beside 66,000 one-page mappings of
//! the file, and 1.09 to 1.26 µs on the Core i9-13900H, each `MAP_FIXED` cutting the reservation it
//! a run on homelab-um790-xtx-1 (Ryzen 7 7840HS, Linux 7.3.1) beside 66,000 one-page mappings of
//! the file, and 1.09 to 1.26 µs on homelab-ms01-1, each `MAP_FIXED` cutting the reservation it
//! lands in (`vms_gather_munmap_vmas` and `__split_vma` in its profile); `MAP_FIXED_NOREPLACE` into
//! a hole took 1.6 to 1.7 µs and 0.90 to 1.01 µs, but a hole is no reservation: another thread's
//! `mmap` may land in it while the runs go in.
@@ -148,7 +148,7 @@ const FAILURE: KernReturn = KernReturn(5);
/// maps or faults in a page waits on, and a view of the guest's scattered pages is a mapping a
/// run of them. One `munmap` of a 1 GiB IOSurface's view, of 254,000 to 262,000 runs, took 0.66
/// to 0.99 s, 2.5 to 3.8 us a mapping. A vCPU waited through it in an `mmap`, and QEMU's main
/// loop waited for QEMU's lock, which that vCPU held, up to 0.89 s (a Ryzen 7 7840HS, Linux 7.2.9,
/// loop waited for QEMU's lock, which that vCPU held, up to 0.89 s (homelab-gem10, Linux 7.2.9,
/// 2026-10-24). A piece of 1 MiB is at most 256 mappings of 4 KiB pages, so the lock is let go
/// about every millisecond, and the backing table's, which `forget` holds, as often.
const DEALLOCATE_PIECE: u64 = 1 << 20;
+8 -11
View File
@@ -111,18 +111,15 @@ struct View {
/// under this lock, one at a time. The backing table, a leaf lock, is changed inside it.
static VIEWS: Mutex<BTreeMap<u64, View>> = Mutex::new(BTreeMap::new());
/// The host's page size, asked of the system once: it does not change while the process runs.
/// The host's page size.
pub(crate) fn page_size() -> u64 {
static PAGE: std::sync::OnceLock<u64> = std::sync::OnceLock::new();
*PAGE.get_or_init(|| {
let mut info: SYSTEM_INFO = SYSTEM_INFO::default();
// SAFETY: a live out-parameter; the call cannot fail.
unsafe { GetSystemInfo(&mut info) };
match info.dwPageSize {
0 => 4096,
size => u64::from(size),
}
})
let mut info: SYSTEM_INFO = SYSTEM_INFO::default();
// SAFETY: a live out-parameter; the call cannot fail.
unsafe { GetSystemInfo(&mut info) };
match info.dwPageSize {
0 => 4096,
size => u64::from(size),
}
}
/// The whole pages `len` bytes at `addr` lie in: the first byte of the first, and their length;
@@ -910,18 +910,17 @@ fn encode(
Ok(())
}
/// Counts the command `sel` that `stopped` stopped under its kind: Metal's refusal, the unbuilt
/// piece's code, or rt's refusal's kind (a texture's pixel format's own). Called for a refused
/// command alone: one rt records counts nothing.
#[cold]
pub(super) fn report(sel: &'static str, stopped: Stop) {
/// Counts the command `sel` that `stopped` stopped, if any, under its kind: Metal's refusal, the
/// unbuilt piece's code, or rt's refusal's kind (a texture's pixel format's own).
pub(super) fn report(sel: &'static str, stopped: Option<Stop>) {
match stopped {
Stop::Metal(what) => refused_as(sel, RtRefusal::Refused, &what),
Stop::Unbuilt(piece) => refuse(piece, sel),
Stop::Rt(error) => {
None => {}
Some(Stop::Metal(what)) => refused_as(sel, RtRefusal::Refused, &what),
Some(Stop::Unbuilt(piece)) => refuse(piece, sel),
Some(Stop::Rt(error)) => {
rt_refused_texture(sel, &error);
}
Stop::Counted => {}
Some(Stop::Counted) => {}
}
}
@@ -950,11 +949,12 @@ impl BlitEncoder<RtPlatform> for RtObj<RtBlitEncoder> {
open.naming.end();
}
drop(open);
let Some(stop) = stopped else {
return Ok(Encoded::RECORDED);
let encoded = match stopped {
None => Encoded::RECORDED,
Some(_) => Encoded::REFUSED,
};
report(sel, stop);
Ok(Encoded::REFUSED)
report(sel, stopped);
Ok(encoded)
});
crate::recorder::rec_done!(recorded_call, recorded_answer);
recorded_answer
@@ -1566,6 +1566,7 @@ impl CommandBuffer<RtPlatform> for RtObj<RtCommandBuffer> {
let default_samples = pass.default_raster_sample_count;
Some(RtObj::new(RtRenderEncoder::new(
encoder,
self.device.rt().clone(),
mark,
kept,
targets,
@@ -588,11 +588,12 @@ impl RtObj<RtComputeEncoder> {
open.naming.end();
}
drop(open);
let Some(stop) = stopped else {
return Encoded::RECORDED;
let encoded = match stopped {
None => Encoded::RECORDED,
Some(_) => Encoded::REFUSED,
};
naming_functions(functions, || report(sel, stop));
Encoded::REFUSED
naming_functions(functions, || report(sel, stopped));
encoded
}
}
@@ -56,32 +56,13 @@
//! own device, the counter's charge stays past the device's last release, and DXGI's
//! `QueryVideoMemoryInfo` does not count it (Intel UHD 630 and WARP, 2026-11-26, potluck job
//! m3-max-75692; reims-vgpu-video's `vaapi::va::d3d12`).
//!
//! **The import's answers.** rt makes each plane's image as the driver's import query answers
//! it (`vkGetPhysicalDeviceImageFormatProperties2` with `VkPhysicalDeviceExternalImageFormatInfo`),
//! and a driver the tests never ran on may answer otherwise. So at each device's make
//! (`super::device::open`) the platform asks the driver the same queries for each plane's
//! formats ([`PLANES`]) and keeps the answers, and the rt platform's diagnostic lines carry them
//! (`super::diag::write`, at each write of the counts, a report's ask among them): one line a
//! plane, `reims-vgpu: rt-diag plane-import <image format> as <view format> (loop usage asked:
//! <bool>): d3d11-texture: ... | d3d12-resource: ...`. For each handle type, `D3D11_TEXTURE`,
//! which rt imports, and `D3D12_RESOURCE`, which it does not, the line gives each usage and format
//! list rt asks of a plane ([`import_lines`]): the usage the planes' bind flags give, with the
//! attachment feedback loop's beside it where rt asks that (its floor's `attachment_reads` and
//! `feedback_loop`), and over the list with the view's sRGB sibling where the view has one. Each
//! answer is the external memory features, the compatible handle types and the handle types the
//! import exports, in hex, and the image's largest extent; or the query's error. A diagnostic:
//! the queries change nothing rt makes.
use std::fmt::Write as _;
use std::sync::Arc;
use ash::vk;
use metal2vulkan_runtime as rt;
use crate::core::platform::resource::{D3d11PlaneDesc, ImportedSurface, ImportedSurfaceMemory};
use crate::core::platform::values::TextureDesc;
use crate::core::sync::Mutex;
use super::descriptor::rt_texture_descriptor;
use super::device::RtDevice;
@@ -207,221 +188,6 @@ pub(super) fn imported_surface(
})
}
/// Each plane's Vulkan formats, as rt makes its image and its views (reims-vgpu's
/// `DRAWN_FORMATS`, rt's `d3d11_plane_form`): the Direct3D 11 texture's element format, the
/// view's, and the view's sRGB sibling where it has one. An 8-bit luma, an 8-bit chroma pair, a
/// 16-bit luma and a 16-bit chroma pair.
const PLANES: [(vk::Format, vk::Format, Option<vk::Format>); 4] = [
(
vk::Format::R8_UNORM,
vk::Format::R8_UNORM,
Some(vk::Format::R8_SRGB),
),
(
vk::Format::R16_UINT,
vk::Format::R8G8_UNORM,
Some(vk::Format::R8G8_SRGB),
),
(vk::Format::R16_UNORM, vk::Format::R16_UNORM, None),
(vk::Format::R32_UINT, vk::Format::R16G16_UNORM, None),
];
/// The handle types the lines ask of, by the name a line gives each: the one rt imports a plane
/// as, and Direct3D 12's resource.
const HANDLES: [(&str, vk::ExternalMemoryHandleTypeFlags); 2] = [
(
"d3d11-texture",
vk::ExternalMemoryHandleTypeFlags::D3D11_TEXTURE,
),
(
"d3d12-resource",
vk::ExternalMemoryHandleTypeFlags::D3D12_RESOURCE,
),
];
/// The lines of the driver's answers ([`import_lines`]) of the latest device made; `None` before
/// one.
static IMPORT_ANSWERS: Mutex<Option<String>> = Mutex::new(None);
/// One ask of the import query: an optimal 2D image of `format` and `usage`, mutable and listing
/// `list` where it is not empty, imported from a handle of type `handle`.
#[derive(Clone, Copy)]
struct Ask<'a> {
handle: vk::ExternalMemoryHandleTypeFlags,
format: vk::Format,
usage: vk::ImageUsageFlags,
list: &'a [vk::Format],
}
/// What the import query answers of an ask: its external memory properties and the image's
/// largest extent, or the query's error.
type Answer = Result<(vk::ExternalMemoryProperties, vk::Extent3D), vk::Result>;
/// The usage rt gives a plane whose Direct3D 11 texture is bound `RENDER_TARGET |
/// SHADER_RESOURCE`, as the host's video makes its targets (rt's `bound_usage`): copied from and
/// into, sampled and rendered.
fn bound_usage() -> vk::ImageUsageFlags {
vk::ImageUsageFlags::TRANSFER_SRC
| vk::ImageUsageFlags::TRANSFER_DST
| vk::ImageUsageFlags::SAMPLED
| vk::ImageUsageFlags::COLOR_ATTACHMENT
}
/// What the driver of `physical` answers of `ask` (`vkGetPhysicalDeviceImageFormatProperties2`),
/// asked as rt asks it (rt's `import_query`).
///
/// # Safety
///
/// `physical` is `instance`'s, and `ask` names the feedback loop's usage only where the device
/// takes `VK_EXT_attachment_feedback_loop_layout`.
unsafe fn query(instance: &ash::Instance, physical: vk::PhysicalDevice, ask: &Ask<'_>) -> Answer {
let mut external = vk::PhysicalDeviceExternalImageFormatInfo::default().handle_type(ask.handle);
let mut listed = vk::ImageFormatListCreateInfo::default().view_formats(ask.list);
let mut info = vk::PhysicalDeviceImageFormatInfo2::default()
.format(ask.format)
.ty(vk::ImageType::TYPE_2D)
.tiling(vk::ImageTiling::OPTIMAL)
.usage(ask.usage)
.push_next(&mut external);
if !ask.list.is_empty() {
info = info
.flags(vk::ImageCreateFlags::MUTABLE_FORMAT)
.push_next(&mut listed);
}
let mut external_out = vk::ExternalImageFormatProperties::default();
let mut out = vk::ImageFormatProperties2::default().push_next(&mut external_out);
// SAFETY: the caller's contract; the structures chained are core at rt's instance's version.
unsafe { instance.get_physical_device_image_format_properties2(physical, &info, &mut out) }?;
let largest = out.image_format_properties.max_extent;
Ok((external_out.external_memory_properties, largest))
}
/// `format` as a line names it: Vulkan's name of each format [`PLANES`] holds, the number of any
/// other. The workspace's ash has no names of its formats (its `debug` feature is off).
fn format_name(format: vk::Format) -> String {
let name = match format {
vk::Format::R8_UNORM => "R8_UNORM",
vk::Format::R8_SRGB => "R8_SRGB",
vk::Format::R16_UINT => "R16_UINT",
vk::Format::R16_UNORM => "R16_UNORM",
vk::Format::R32_UINT => "R32_UINT",
vk::Format::R8G8_UNORM => "R8G8_UNORM",
vk::Format::R8G8_SRGB => "R8G8_SRGB",
vk::Format::R16G16_UNORM => "R16G16_UNORM",
other => return other.as_raw().to_string(),
};
name.to_owned()
}
/// `list` as a line names it: each format's name ([`format_name`]) in brackets, comma-separated.
fn list_names(list: &[vk::Format]) -> String {
let names: Vec<String> = list.iter().map(|&format| format_name(format)).collect();
format!("[{}]", names.join(", "))
}
/// `answer` as a line says it: the external memory features, the compatible handle types and
/// the handle types the import exports, in hex, and the largest extent; or the query's error.
fn said(answer: &Answer) -> String {
match answer {
Ok((properties, largest)) => format!(
"features {:#x} compatible {:#x} exports {:#x} max {}x{}",
properties.external_memory_features.as_raw(),
properties.compatible_handle_types.as_raw(),
properties.export_from_imported_handle_types.as_raw(),
largest.width,
largest.height
),
Err(result) => format!("{result:?}"),
}
}
/// The plane-import lines (the module doc, "The import's answers") of a driver that answers each
/// ask as `answer` does, on a device where rt asks a plane the attachment feedback loop's usage
/// where `looped`: one a plane of [`PLANES`], each handle type of [`HANDLES`] with the asks rt
/// makes of a plane: the bound usage over the list of the image's and the view's formats (none
/// where they are one), with the feedback loop's usage where `looped`, and that usage over the
/// list with the view's sRGB sibling, where it has one.
fn import_lines(looped: bool, mut answer: impl FnMut(&Ask<'_>) -> Answer) -> String {
let bound = bound_usage();
let usage = match looped {
true => bound | vk::ImageUsageFlags::ATTACHMENT_FEEDBACK_LOOP_EXT,
false => bound,
};
let mut lines = String::new();
for (image, view, sibling) in PLANES {
let pair = match image == view {
true => Vec::new(),
false => vec![image, view],
};
let mut asks = vec![(bound, pair.clone())];
if looped {
asks.push((usage, pair));
}
if let Some(sibling) = sibling {
let mut list = vec![image];
for listed in [view, sibling] {
if !list.contains(&listed) {
list.push(listed);
}
}
asks.push((usage, list));
}
let handles: Vec<String> = (HANDLES.iter())
.map(|&(name, handle)| {
let each: Vec<String> = (asks.iter())
.map(|(usage, list)| {
let ask = Ask {
handle,
format: image,
usage: *usage,
list: list.as_slice(),
};
format!(
"usage {:#x} list {}: {}",
usage.as_raw(),
list_names(list),
said(&answer(&ask))
)
})
.collect();
format!("{name}: {}", each.join("; "))
})
.collect();
let _ = writeln!(
lines,
"reims-vgpu: rt-diag plane-import {} as {} (loop usage asked: {looped}): {}",
format_name(image),
format_name(view),
handles.join(" | ")
);
}
lines
}
/// Asks the driver of `physical`, `instance`'s, the import queries of every plane (the module
/// doc, "The import's answers") and keeps its answers for the rt platform's diagnostic lines, in
/// place of an earlier device's. `floor` is rt's floor answers of the device, by which rt asks a
/// plane the attachment feedback loop's usage.
pub(super) fn note_import_answers(
instance: &ash::Instance,
physical: vk::PhysicalDevice,
floor: &rt::floor::Capabilities,
) {
let looped = floor.attachment_reads && floor.feedback_loop;
// SAFETY: `physical` is `instance`'s, and the asks name the feedback loop's usage only where
// rt's floor found the device takes the loop.
let lines = import_lines(looped, |ask| unsafe { query(instance, physical, ask) });
*IMPORT_ANSWERS.lock() = Some(lines);
}
/// Adds the kept answers' lines ([`note_import_answers`]) to `out`, the rt platform's diagnostic
/// lines (`super::diag::write`); nothing before a device's make.
pub(super) fn write_import_answers(out: &mut String) {
if let Some(lines) = IMPORT_ANSWERS.lock().as_ref() {
out.push_str(lines);
}
}
#[cfg(test)]
mod tests {
use std::os::windows::io::BorrowedHandle;
@@ -523,65 +289,4 @@ mod tests {
assert!(matches!(made, Ok(None)));
assert_eq!(counted(D3D11_SURFACE_REFUSED_CODE), before + 1);
}
/// The plane-import lines (the module doc, "The import's answers") give, for each plane and
/// handle type, each ask rt makes of a plane with the driver's answer: the feedback loop's
/// usage only where rt asks it, and the list with the view's sRGB sibling only for a view
/// that has one. Here a driver that imports every ask from a Direct3D 11 texture, dedicated,
/// and none from a Direct3D 12 resource.
#[test]
fn the_import_lines_give_each_ask_with_its_answer() {
let answer =
|ask: &Ask<'_>| match ask.handle == vk::ExternalMemoryHandleTypeFlags::D3D11_TEXTURE {
true => Ok((
vk::ExternalMemoryProperties::default()
.external_memory_features(
vk::ExternalMemoryFeatureFlags::DEDICATED_ONLY
| vk::ExternalMemoryFeatureFlags::IMPORTABLE,
)
.compatible_handle_types(ask.handle),
vk::Extent3D {
width: 16384,
height: 16384,
depth: 1,
},
)),
false => Err(vk::Result::ERROR_FORMAT_NOT_SUPPORTED),
};
let ok = "features 0x5 compatible 0x8 exports 0x0 max 16384x16384";
let no = "ERROR_FORMAT_NOT_SUPPORTED";
let looped = import_lines(true, answer);
let lines: Vec<&str> = looped.lines().collect();
assert_eq!(lines.len(), PLANES.len(), "{looped}");
assert_eq!(
lines[1],
format!(
"reims-vgpu: rt-diag plane-import R16_UINT as R8G8_UNORM (loop usage asked: \
true): d3d11-texture: usage 0x17 list [R16_UINT, R8G8_UNORM]: {ok}; usage \
0x80017 list [R16_UINT, R8G8_UNORM]: {ok}; usage 0x80017 list [R16_UINT, \
R8G8_UNORM, R8G8_SRGB]: {ok} | d3d12-resource: usage 0x17 list [R16_UINT, \
R8G8_UNORM]: {no}; usage 0x80017 list [R16_UINT, R8G8_UNORM]: {no}; usage \
0x80017 list [R16_UINT, R8G8_UNORM, R8G8_SRGB]: {no}"
)
);
let plain = import_lines(false, answer);
let lines: Vec<&str> = plain.lines().collect();
assert_eq!(
lines[2],
format!(
"reims-vgpu: rt-diag plane-import R16_UNORM as R16_UNORM (loop usage asked: \
false): d3d11-texture: usage 0x17 list []: {ok} | d3d12-resource: usage 0x17 \
list []: {no}"
)
);
assert!(
lines[0].contains("d3d11-texture: usage 0x17 list []: "),
"{plain}"
);
assert!(
lines[0].contains("; usage 0x17 list [R8_UNORM, R8_SRGB]: "),
"{plain}"
);
assert!(!plain.contains("0x80017"), "{plain}");
}
}
@@ -1507,10 +1507,6 @@ pub fn open(page_size: u64) -> Result<RtObj<RtDevice>, Unopened> {
"{}",
RtForms::of(floor, &device, facts.unified_memory)
);
// The driver's answers to a video plane's import queries, for the diagnostic lines
// (`super::d3d11_surface`, "The import's answers").
#[cfg(windows)]
super::d3d11_surface::note_import_answers(raw, physical.raw(), floor);
let shared = device.memory_types().shared;
// SAFETY: the instance listed the device and is alive.
let types = unsafe { raw.get_physical_device_memory_properties(physical.raw()) };
@@ -1708,6 +1704,35 @@ fn memory_flags(flags: vk::MemoryPropertyFlags) -> String {
parts.join(" | ")
}
#[cfg(test)]
thread_local! {
static FORCE_MULTI_DRAW_INDIRECT: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
}
#[cfg(test)]
pub(crate) fn with_multi_draw_indirect<T>(enabled: bool, run: impl FnOnce() -> T) -> T {
struct Reset(bool);
impl Drop for Reset {
fn drop(&mut self) {
FORCE_MULTI_DRAW_INDIRECT.with(|flag| flag.set(self.0));
}
}
let previous = FORCE_MULTI_DRAW_INDIRECT.with(|flag| flag.replace(enabled));
let _reset = Reset(previous);
run()
}
fn multi_draw_indirect_enabled() -> bool {
#[cfg(test)]
if FORCE_MULTI_DRAW_INDIRECT.with(std::cell::Cell::get) {
return true;
}
matches!(
std::env::var("REIMS_VGPU_MULTI_DRAW_INDIRECT").as_deref(),
Ok("1" | "true" | "on")
)
}
/// The options a device on `physical`, one of `instance`'s, is opened with both in the VM's
/// process ([`open`]) and in a stage's helper (`super::stage::helper_main`), where rt takes the
/// helper's compile only from a device that enabled what the VM's did (its `StageFill::Enables`
@@ -1721,6 +1746,7 @@ pub(crate) fn shared_options(
physical: &rt::PhysicalDevice,
) -> (rt::DeviceOptions, Option<&'static std::ffi::CStr>) {
let mut options = rt::DeviceOptions::default();
options.multi_draw_indirect = multi_draw_indirect_enabled();
options.stage_memory_ceiling = crate::os::compile_helper::Limits::of_host().memory;
let (_, raw) = instance.raw();
// SAFETY: the instance listed the device and is alive.
@@ -2248,6 +2274,18 @@ impl GpuDevice<RtPlatform> for RtObj<RtDevice> {
recorded_answer
}
fn new_cache_transfer_queue(&self) -> Option<RtObj<RtQueue>> {
let call = crate::recorder::rec_call!("m2v.newCacheTransferQueue", self);
let queue = crate::recorder::run(|| {
Some(RtObj::new(RtQueue::new(
self.rt.new_host_batch_queue(),
self.clone_ref(),
)))
});
crate::recorder::rec_done!(call, queue);
queue
}
/// No: rt copies no guest RAM by its host addresses.
fn copies_guest_ram(&self) -> bool {
false
@@ -2794,6 +2832,331 @@ impl GpuDevice<RtPlatform> for RtObj<RtDevice> {
crate::recorder::rec_done!(recorded_call, recorded_answer);
recorded_answer
}
fn wait_idle(&self) {
let _ = self.rt().wait_idle();
}
fn event_signaled_value(&self, event: &<RtPlatform as Platform>::Event) -> u64 {
event.signaled_value()
}
fn event_restore_signaled_value(
&self,
event: &<RtPlatform as Platform>::Event,
value: u64,
) -> bool {
if value > 0 {
event.restore_signaled_value(value).is_ok()
} else {
true
}
}
fn read_standalone_buffer(
&self,
buffer: &<RtPlatform as Platform>::Buffer,
) -> Result<Option<Vec<u8>>, &'static str> {
let Some(rt_buf) = buffer.made_rt() else {
return Ok(None);
};
let len = rt_buf.length();
if len == 0 {
return Ok(Some(Vec::new()));
}
if let Some(ptr) = rt_buf.contents() {
return Ok(Some(unsafe {
std::slice::from_raw_parts(ptr.as_ptr(), len as usize).to_vec()
}));
}
let rt = self.rt();
let alloc_len = (len.max(4096) + 4095) & !4095;
let stage = rt
.take_block(rt::MemoryClass::Shared, alloc_len)
.map_err(|_| "standalone buffer readback: staging take_block failed")?;
let res = (|| -> Result<Vec<u8>, &'static str> {
let dst_buf = rt
.new_buffer(stage.id, 0, len, None)
.map_err(|_| "standalone buffer readback: staging new_buffer failed")?;
let q = rt
.new_command_queue(4)
.map_err(|_| "standalone buffer readback: new_command_queue failed")?;
let cb = q
.command_buffer()
.map_err(|_| "standalone buffer readback: command_buffer failed")?;
let mut blit = cb
.blit_command_encoder()
.map_err(|_| "standalone buffer readback: blit_command_encoder failed")?;
blit.copy_from_buffer_to_buffer(rt_buf, 0, &dst_buf, 0, len)
.map_err(|_| "standalone buffer readback: copy_from_buffer_to_buffer failed")?;
blit.end_encoding();
cb.commit()
.map_err(|_| "standalone buffer readback: commit failed")?;
cb.wait_until_completed()
.map_err(|_| "standalone buffer readback: wait_until_completed failed")?;
let ptr = stage
.contents
.ok_or("standalone buffer readback: staging block not host-mapped")?;
let out = unsafe { std::slice::from_raw_parts(ptr.as_ptr(), len as usize).to_vec() };
drop(dst_buf);
Ok(out)
})();
let _ = rt.release_block(stage);
res.map(Some)
}
fn write_standalone_buffer(
&self,
buffer: &<RtPlatform as Platform>::Buffer,
data: &[u8],
) -> bool {
let Some(rt_buf) = buffer.made_rt() else {
return false;
};
let len = rt_buf.length();
if data.len() as u64 != len {
return false;
}
if len == 0 {
return true;
}
if let Some(ptr) = rt_buf.contents() {
unsafe {
std::ptr::copy_nonoverlapping(data.as_ptr(), ptr.as_ptr(), len as usize);
}
let _ = rt_buf.did_modify_range(0, len);
return true;
}
let rt = self.rt();
let alloc_len = (len.max(4096) + 4095) & !4095;
let Ok(stage) = rt.take_block(rt::MemoryClass::Shared, alloc_len) else {
return false;
};
if let Some(ptr) = stage.contents {
unsafe {
std::ptr::copy_nonoverlapping(data.as_ptr(), ptr.as_ptr(), len as usize);
}
} else {
let _ = rt.release_block(stage);
return false;
}
let ok = (|| -> Result<(), rt::Error> {
let src_buf = rt.new_buffer(stage.id, 0, len, None)?;
let q = rt.new_command_queue(4)?;
let cb = q.command_buffer()?;
let mut blit = cb.blit_command_encoder()?;
blit.copy_from_buffer_to_buffer(&src_buf, 0, rt_buf, 0, len)?;
blit.end_encoding();
cb.commit()?;
cb.wait_until_completed()?;
drop(src_buf);
Ok(())
})()
.is_ok();
let _ = rt.release_block(stage);
ok
}
fn read_standalone_texture(
&self,
texture: &<RtPlatform as Platform>::Texture,
) -> Result<Option<Vec<u8>>, &'static str> {
let rt_tex = texture.rt();
let desc = rt_tex.descriptor();
let Some((plan, total)) = texture_copy_plan(self.rt(), desc) else {
return Ok(None);
};
if total == 0 {
return Ok(Some(Vec::new()));
}
let rt = self.rt();
let alloc_len = (total.max(4096) + 4095) & !4095;
let stage = rt
.take_block(rt::MemoryClass::Shared, alloc_len)
.map_err(|_| "standalone texture readback: staging take_block failed")?;
let res = (|| -> Result<Vec<u8>, &'static str> {
let dst_buf = rt
.new_buffer(stage.id, 0, total, None)
.map_err(|_| "standalone texture readback: staging new_buffer failed")?;
let q = rt
.new_command_queue(4)
.map_err(|_| "standalone texture readback: new_command_queue failed")?;
let cb = q
.command_buffer()
.map_err(|_| "standalone texture readback: command_buffer failed")?;
let mut blit = cb
.blit_command_encoder()
.map_err(|_| "standalone texture readback: blit_command_encoder failed")?;
for step in &plan {
blit.copy_from_texture_to_buffer(
rt_tex,
rt::TexturePlace {
slice: step.slice,
level: step.level,
origin: [0, 0, 0],
},
step.size,
&dst_buf,
rt::BufferLayout {
offset: step.offset,
bytes_per_row: step.bytes_per_row,
bytes_per_image: step.bytes_per_image,
},
)
.map_err(|_| "standalone texture readback: copy_from_texture_to_buffer failed")?;
}
blit.end_encoding();
cb.commit()
.map_err(|_| "standalone texture readback: commit failed")?;
cb.wait_until_completed()
.map_err(|_| "standalone texture readback: wait_until_completed failed")?;
let ptr = stage
.contents
.ok_or("standalone texture readback: staging block not host-mapped")?;
let out = unsafe { std::slice::from_raw_parts(ptr.as_ptr(), total as usize).to_vec() };
drop(dst_buf);
Ok(out)
})();
let _ = rt.release_block(stage);
res.map(Some)
}
fn write_standalone_texture(
&self,
texture: &<RtPlatform as Platform>::Texture,
data: &[u8],
) -> bool {
let rt_tex = texture.rt();
let desc = rt_tex.descriptor();
let Some((plan, total)) = texture_copy_plan(self.rt(), desc) else {
return false;
};
if data.len() as u64 != total {
return false;
}
if total == 0 {
return true;
}
let rt = self.rt();
let alloc_len = (total.max(4096) + 4095) & !4095;
let Ok(stage) = rt.take_block(rt::MemoryClass::Shared, alloc_len) else {
return false;
};
if let Some(ptr) = stage.contents {
unsafe {
std::ptr::copy_nonoverlapping(data.as_ptr(), ptr.as_ptr(), total as usize);
}
} else {
let _ = rt.release_block(stage);
return false;
}
let ok = (|| -> Result<(), rt::Error> {
let src_buf = rt.new_buffer(stage.id, 0, total, None)?;
let q = rt.new_command_queue(4)?;
let cb = q.command_buffer()?;
let mut blit = cb.blit_command_encoder()?;
for step in &plan {
blit.copy_from_buffer(
&src_buf,
rt::BufferLayout {
offset: step.offset,
bytes_per_row: step.bytes_per_row,
bytes_per_image: step.bytes_per_image,
},
step.size,
rt_tex,
rt::TexturePlace {
slice: step.slice,
level: step.level,
origin: [0, 0, 0],
},
)?;
}
blit.end_encoding();
cb.commit()?;
cb.wait_until_completed()?;
drop(src_buf);
Ok(())
})()
.is_ok();
let _ = rt.release_block(stage);
ok
}
}
struct TextureCopyStep {
slice: u32,
level: u32,
size: [u32; 3],
offset: u64,
bytes_per_row: u64,
bytes_per_image: u64,
}
fn texture_copy_plan(
rt: &rt::Device,
desc: &rt::TextureDescriptor,
) -> Option<(Vec<TextureCopyStep>, u64)> {
if desc.sample_count > 1 || desc.storage_mode == rt::StorageMode::Memoryless {
return None;
}
let raw_fmt = u64::from(desc.pixel_format.as_raw());
if (250..=262).contains(&raw_fmt) {
return None;
}
let info = rt.pixel_format_info(u64::from(desc.pixel_format.as_raw()));
let block_bytes = info.words[0];
if block_bytes == 0 {
return None;
}
let (block_w, block_h, block_d) = if info.flags & 0x400 != 0 {
(
info.words[1].max(1),
info.words[2].max(1),
info.words[3].max(1),
)
} else {
(1, 1, 1)
};
let slices = match desc.texture_type {
rt::TextureType::Cube | rt::TextureType::CubeArray => desc.array_length.checked_mul(6)?,
rt::TextureType::Type3D => 1,
_ => desc.array_length.max(1),
};
let levels = desc.mipmap_level_count.max(1);
let mut plan = Vec::with_capacity((slices as usize).saturating_mul(levels as usize));
let mut offset: u64 = 0;
for slice in 0..slices {
for level in 0..levels {
let w = (desc.width >> level).max(1);
let h = match desc.texture_type {
rt::TextureType::Type1D | rt::TextureType::Type1DArray => 1,
_ => (desc.height >> level).max(1),
};
let d = match desc.texture_type {
rt::TextureType::Type3D => (desc.depth >> level).max(1),
_ => 1,
};
let bx = u64::from(w).div_ceil(block_w);
let by = u64::from(h).div_ceil(block_h);
let bz = u64::from(d).div_ceil(block_d);
let raw_bpr = bx.checked_mul(block_bytes)?;
let bpr = (raw_bpr + 15) & !15;
let bpi = bpr.checked_mul(by)?;
let step_bytes = bpi.checked_mul(bz)?;
offset = (offset + 15) & !15;
plan.push(TextureCopyStep {
slice,
level,
size: [w, h, d],
offset,
bytes_per_row: bpr,
bytes_per_image: bpi,
});
offset = offset.checked_add(step_bytes)?;
}
}
Some((plan, offset))
}
/// The identity of `device` ([`answers::identity`]): rt's linear and texture-buffer alignments
@@ -2813,6 +3176,56 @@ mod tests {
use crate::core::platform::device::relaying_gaps;
use crate::core::platform::values::{OptionSet, TextureDesc};
#[test]
fn a_cache_transfer_batch_publishes_its_bytes_to_a_waiting_queue() {
use crate::core::platform::command::{CommandBuffer as _, CommandQueue as _};
let platform = RtPlatform::new();
let device = platform.system_default_device().expect("a Vulkan device");
let copies = device.new_cache_transfer_queue().expect("cache transfers");
let consumer = device.new_command_queue().expect("a guest queue");
let shared = || {
device
.new_buffer_of_length(OnFault::Return, 16, 0)
.unwrap()
.unwrap()
};
let (source, destination) = (shared(), shared());
let filled = device.rt().new_event().unwrap();
let done = device.rt().new_shared_event().unwrap();
let mut batch = Vec::new();
for value in 1..=3 {
let copy = copies.command_buffer(OnFault::Return).unwrap().unwrap();
let mut blit = copy.rt().blit_command_encoder().unwrap();
blit.fill_buffer(source.rt(), 0..16, value).unwrap();
blit.end_encoding();
copy.rt()
.encode_signal_event(&filled, u64::from(value))
.unwrap();
batch.push(copy);
}
let read = consumer.command_buffer(OnFault::Return).unwrap().unwrap();
read.rt().encode_wait_for_event(&filled, 3).unwrap();
let mut blit = read.rt().blit_command_encoder().unwrap();
blit.copy_from_buffer_to_buffer(source.rt(), 0, destination.rt(), 0, 16)
.unwrap();
blit.end_encoding();
read.rt().encode_signal_event(done.as_event(), 1).unwrap();
read.commit(OnFault::Return).unwrap();
for copy in batch {
copy.commit(OnFault::Return).unwrap();
}
assert!(
done.wait_until_signaled_value(1, std::time::Duration::from_secs(10))
.unwrap()
);
let at = destination.rt().contents().expect("shared storage");
// SAFETY: the GPU signal covers the final copy, the allocation is 16 bytes and kept
// alive by destination, and there are no further writers.
let bytes = unsafe { std::slice::from_raw_parts(at.as_ptr(), 16) };
assert_eq!(bytes, &[3; 16]);
}
/// The options a device is opened with carry the helper's memory ceiling on this host, the
/// one a memory breach is kept under.
#[test]
@@ -134,10 +134,6 @@
//! total, in one line written on the rt platform. An index given back is taken again only once
//! every command buffer its device committed before the give-back has completed, by the
//! device's commit order, so none is taken while work committed before its release reads it.
//! - **Plane imports' answers**, on Windows: the driver's answers to the import queries a
//! video plane's image over a Direct3D 11 texture rests on, and to the same of a Direct3D 12
//! resource, asked at the device's make, a line a plane format (`super::d3d11_surface`, "The
//! import's answers").
//!
//! Totals, numbers, formats, sizes and usages only: no name, label or byte of the guest's leaves
//! the process, but through the switch below. A diagnostic, which the contract leaves free:
@@ -1345,33 +1341,23 @@ pub struct Target {
pub made: Arc<Made>,
}
/// The textures a render encoder bound whose image a target of its pass renders, by stage (vertex,
/// fragment) and slot: the only bound textures [`attachment_read`] reads, a slot of any other
/// holding none. A bind of a texture of another image takes no hold of it.
/// The textures a render encoder bound, by stage (vertex, fragment) and slot.
#[derive(Default)]
pub struct Bound([Vec<Option<Arc<Made>>>; 2]);
impl Bound {
/// Slot `slot` of stage `stage` (0 vertex, 1 fragment) holds the texture `made` is, in a pass
/// of `targets`.
pub fn set(&mut self, stage: usize, slot: u32, made: Option<&Arc<Made>>, targets: &[Target]) {
let meets = made.filter(|made| targets.iter().any(|t| t.made.image == made.image));
/// Slot `slot` of stage `stage` (0 vertex, 1 fragment) holds `texture`.
pub fn set(&mut self, stage: usize, slot: u32, texture: Option<&RtObj<RtTexture>>) {
let (Some(slots), Ok(slot)) = (self.0.get_mut(stage), usize::try_from(slot)) else {
return;
};
match meets {
Some(made) if slot < 256 => {
if slots.len() <= slot {
slots.resize(slot + 1, None);
}
slots[slot] = Some(Arc::clone(made));
}
_ => {
if let Some(held) = slots.get_mut(slot) {
*held = None;
}
}
if slot >= 256 {
return;
}
if slots.len() <= slot {
slots.resize(slot + 1, None);
}
slots[slot] = texture.map(|t| Arc::clone(t.made()));
}
}
@@ -2721,8 +2707,6 @@ pub fn write() {
"reims-vgpu: rt-diag presenters: contexts {presenters:?}"
);
}
#[cfg(windows)]
super::d3d11_surface::write_import_answers(&mut out);
if !out.is_empty() {
say(&out);
}
@@ -3382,51 +3366,6 @@ mod tests {
assert_eq!(counted.map(|(_, &n)| n), Some(2), "{:?}", fetches.keys());
}
/// A render encoder's bound textures keep those whose image a target of its pass renders (the
/// target's own texture, a view of its image), the only ones an attachment read through a
/// texture reads, and take no hold of another: its bind, or nil's, empties the slot.
#[test]
fn bound_textures_keep_those_a_target_renders() {
let shape = Shape {
format: 80,
width: 4,
height: 4,
storage: 2,
usage: 0x5,
};
let rendered = Made::new(Call::Plain, &shape);
let view = Made::view(&rendered, 80, (0, 0));
let apart = Made::new(Call::Plain, &shape);
let targets = [Target {
point: Point::Color(0),
level: 0,
slice: 0,
texture_type: 2,
format: rt::PixelFormat::BGRA8Unorm,
samples: 1,
index: 0,
name: super::super::fault::Name::default(),
made: Arc::clone(&rendered),
}];
let held = |bound: &Bound, stage: usize, slot: usize| {
(bound.0[stage].get(slot)).and_then(|m| m.as_ref().map(|m| m.id))
};
let mut bound = Bound::default();
bound.set(1, 3, Some(&view), &targets);
assert_eq!(held(&bound, 1, 3), Some(view.id));
bound.set(1, 3, Some(&apart), &targets);
assert_eq!(held(&bound, 1, 3), None);
assert_eq!(Arc::strong_count(&apart), 1);
bound.set(0, 2, Some(&apart), &targets);
assert!(bound.0[0].is_empty());
bound.set(0, 2, Some(&rendered), &targets);
assert_eq!(held(&bound, 0, 2), Some(rendered.id));
bound.set(0, 2, None, &targets);
assert_eq!(held(&bound, 0, 2), None);
bound.set(1, 300, Some(&rendered), &targets);
assert_eq!(bound.0[1].len(), 4);
}
/// Each sampler state made is counted, and one that clamps to its border colour in some
/// direction by its border colour.
#[test]
@@ -3216,8 +3216,6 @@ mod tests {
fn a_settle_waits_for_the_platform_s_command_buffers_through_its_number() {
use std::time::Duration;
use crate::core::testkit::clock::VirtualClock;
let flights = Arc::new(Flights::default());
let add = |by| {
flights.add(Flight {
@@ -3261,30 +3259,27 @@ mod tests {
"1 command buffers committed before it had not completed and run their completed \
handlers: the oldest has run its first completed handler, and not its last"
);
// The one off the list settles once a settle on a thread of its own waits for it: the
// settle made a timed wait on a clock of its own, the only one on it.
let waits = Arc::new(VirtualClock::new());
let settle = {
let (flights, waits) = (Arc::clone(&flights), Arc::clone(&waits));
let settler = {
let flights = Arc::clone(&flights);
std::thread::Builder::new()
.spawn(move || {
let bound = within(Duration::from_secs(10));
(flights.settle(through, bound, &mut |_| {}, &*waits)).map(|s| s.waited)
std::thread::sleep(Duration::from_millis(20));
flights.settled(third);
})
.expect("a thread")
};
const REAL: Duration = Duration::from_secs(10);
assert!(
waits.wait_for_timed_waits(1, REAL, || settle.is_finished()),
"the settle neither waited nor ended"
assert_eq!(
flights
.settle(
through,
within(Duration::from_secs(10)),
&mut |_| {},
&clock
)
.map(|s| s.waited),
Ok(1)
);
assert!(!settle.is_finished(), "it waits for the one off the list");
flights.settled(third);
assert!(
waits.wait_for_timed_waits(2, REAL, || settle.is_finished()),
"the settle neither took up the settle nor ended"
);
assert_eq!(settle.join().expect("the settle ends"), Ok(1));
settler.join().expect("the settler ends");
// The clear, and the one committed after, are not waited for.
let at_once = |through| {
(flights.settle(through, within(Duration::ZERO), &mut |_| {}, &clock))
@@ -137,7 +137,9 @@ use crate::core::platform::{Encoded, Handle, ObjId};
use crate::core::raise::{OnFault, RaiseResult};
use crate::core::sync::ReentrantMutex;
use super::blit::{Stop, report};
use super::blit::Stop;
#[cfg(not(test))]
use super::blit::report;
use super::command::{Kept, OpenMark};
use super::compute::{declared, resource_usage, slots, small};
use super::copied::Used;
@@ -147,6 +149,8 @@ use super::render_pipeline::{Formats, Raster, RtRenderPipeline};
use super::texture::RtTexture;
use super::unbuilt::{Named, Unbuilt, naming_functions, refuse};
use super::{RtBuffer, RtObj, RtPlatform};
#[cfg(test)]
use tests::report;
/// A count, a base or an index past rt's 32 bits.
const WIDE: Stop = Stop::Metal("a count, a base or an index past 32 bits");
@@ -158,6 +162,7 @@ pub struct RtRenderEncoder {
/// it again on the thread that holds it, with no atomic operation. A command another thread
/// sends meanwhile waits for the run to end.
open: ReentrantMutex<RefCell<Open>>,
device: rt::Device,
/// Its command buffer's mark of it open, until it ends.
mark: OpenMark,
/// What its command buffer keeps until it completes.
@@ -200,6 +205,7 @@ impl RtRenderEncoder {
/// naming its operands where `operands` (`super::fault`'s `Operands`).
pub fn new(
encoder: rt::RenderCommandEncoder,
device: rt::Device,
mark: OpenMark,
kept: Kept,
targets: Vec<Target>,
@@ -217,6 +223,7 @@ impl RtRenderEncoder {
seen: Seen::default(),
naming: Naming::new(kept.encoded(), names),
})),
device,
mark,
kept,
targets,
@@ -239,8 +246,7 @@ impl RtRenderEncoder {
/// Notes `texture` bound to slot `slot` of stage `stage` (0 vertex, 1 fragment) for the boot
/// diagnostics, and as a tiled texture's use (`super::tiled`).
fn bound(&self, seen: &mut Seen, stage: usize, slot: u32, texture: Option<&RtObj<RtTexture>>) {
let made = texture.map(|t| t.made());
seen.bound.set(stage, slot, made, &self.targets);
seen.bound.set(stage, slot, texture);
if let Some(t) = texture {
self.kept.used(t, Use::Sampled);
}
@@ -307,33 +313,6 @@ impl RtRenderEncoder {
functions
}
/// What the count of a refusal of `cmd`, which `stopped` stopped, names, read under the
/// encoder's hold with what it set, `seen`: the command's selector and the functions
/// ([`Self::refusal_functions`]), the first line of each kind of rt's refusals of a draw or of
/// an execution of an indirect command buffer written. Read only where a command is refused:
/// a command rt records pays for none of it.
#[cold]
fn refusal(
&self,
seen: &Seen,
cmd: &RenderCmd<'_, RtPlatform>,
stopped: &Stop,
) -> (&'static str, Named) {
let sel = cmd.selector();
let (draw, primitive) = (draws(cmd), drawn_primitive(cmd));
let functions =
self.refusal_functions(seen, sel, stopped, draw, primitive, set_viewports(cmd));
if let (Stop::Rt(error), Some(what)) = (stopped, execution(cmd))
&& matches!(
error,
rt::Error::Unsupported(rt::Gap::IndirectCommandBuffers { .. })
)
{
super::unbuilt::refusal_detail(sel, error, Some(&what));
}
(sel, functions)
}
/// Encodes `cmd` but `endEncoding`, which the caller ends.
fn command(&self, open: &mut Open, cmd: RenderCmd<'_, RtPlatform>) -> Result<(), Stop> {
let Open {
@@ -829,6 +808,40 @@ fn draw_primitives(
Ok(())
}
/// Probes a run without changing the encoder or reporting refusals.
fn indirect_run<'a>(
draws: &[VertexDraw<'a, RtPlatform>],
items: &mut [rt::VertexOffsetDraw; 32],
) -> Option<(&'a RtObj<RtBuffer>, u32, PrimitiveType, usize)> {
let first = draws.first()?;
let buffer = first.buffer?;
let slot = small(first.index).ok()?;
let topology = primitive(first.primitive_type).ok()?;
let mut count = 0;
for (draw, item) in draws.iter().zip(items) {
if draw.buffer.map(Handle::id) != Some(buffer.id())
|| draw.index != first.index
|| draw.primitive_type != first.primitive_type
{
break;
}
let (Ok(vertex_start), Ok(vertex_count)) =
(small(draw.vertex_start), small(draw.vertex_count))
else {
break;
};
*item = rt::VertexOffsetDraw {
offset: draw.offset,
vertex_start,
vertex_count,
instance_count: 1,
base_instance: 0,
};
count += 1;
}
Some((buffer, slot, topology, count))
}
/// `Ok` where a setting rt has none of is at Metal's default (`at_default`); unbuilt otherwise.
fn unbuilt_unless(at_default: bool) -> Result<(), Stop> {
match at_default {
@@ -1248,64 +1261,195 @@ impl RtObj<RtRenderEncoder> {
if crate::recorder::on() {
return None;
}
let held = self.open.lock();
let mut open = held.borrow_mut();
let Open {
rt,
pipeline,
seen,
naming,
} = &mut *open;
let (Some(encoder), Some(_), Some(names)) = (rt, pipeline, naming.names()) else {
return None;
};
let used = self.kept.copies();
let mut last = None;
let mut buffer = None;
for (i, draw) in draws.iter().enumerate() {
if let Some(bound) = draw.buffer {
names.bound_buffers.add_named(bound.named());
}
let key = draw.buffer.map(std::ptr::from_ref);
if key != last {
last = key;
buffer = draw.buffer.map(|b| b.rt());
draw.buffer.iter().for_each(|b| used.buffer(b));
}
let bound = small(draw.index).and_then(|index| {
encoder
.set_vertex_buffer(buffer, draw.offset, index)
.map_err(Stop::from)
});
// A refusal is reported once. After a refused bind, the draw still sees the
// encoder's existing binding, and only commands that have yet to run go to encode.
if let Err(stop) = bound {
let mut items = [rt::VertexOffsetDraw {
offset: 0,
vertex_start: 0,
vertex_count: 0,
instance_count: 1,
base_instance: 0,
}; 32];
let mut i = 0;
let mut p0_until = 0;
let mut p0_init = false;
let mut pending_draw = false;
let mut encoded = Encoded::RECORDED;
while i < draws.len() {
let held = self.open.lock();
let mut open = held.borrow_mut();
let Open {
rt,
pipeline,
seen,
naming,
} = &mut *open;
let (Some(encoder), Some(_), Some(names)) = (rt, pipeline, naming.names()) else {
drop(open);
drop(held);
report(draw.vertex_buffer().selector(), stop);
if let Err(raise) = self.encode(on, draw.primitives()) {
return Some(Err(raise));
if i == 0 && !pending_draw {
return None;
}
// The bind was refused: so is the run, whatever the rest answer.
return Some(encode_each(self, on, &draws[i + 1..]).map(|_| Encoded::REFUSED));
if pending_draw {
match self.encode(on, draws[i].primitives()) {
Ok(ans) => {
if ans == Encoded::REFUSED {
encoded = Encoded::REFUSED;
}
}
Err(raise) => return Some(Err(raise)),
}
i += 1;
}
return Some(encode_each(self, on, &draws[i..]).map(|rest| {
if encoded == Encoded::REFUSED {
Encoded::REFUSED
} else {
rest
}
}));
};
if !p0_init {
let mdi = !super::copied::any()
&& self.device.draw_indirect_limit() > 0
&& names.operands.is_none();
p0_until = if mdi { 0 } else { draws.len() };
p0_init = true;
}
if let Err(stop) = draw_primitives(
encoder,
draw.primitive_type,
draw.vertex_start,
draw.vertex_count,
) {
let sel = draw.primitives().selector();
let functions =
self.refusal_functions(seen, sel, &stop, true, Some(draw.primitive_type), None);
let (bind, stop) = if pending_draw {
pending_draw = false;
let draw = &draws[i];
if let Err(stop) = draw_primitives(
encoder,
draw.primitive_type,
draw.vertex_start,
draw.vertex_count,
) {
(false, stop)
} else {
i += 1;
continue;
}
} else {
let mut last = None;
let mut buffer = None;
loop {
if i == draws.len() {
return Some(Ok(encoded));
}
if i >= p0_until
&& draws.len() - i >= 9
&& let Some((bound, slot, topology, count)) =
indirect_run(&draws[i..], &mut items)
&& count != 0
{
p0_until = i + count;
let result = encoder.draw_primitives_batch(
topology,
slot,
bound.rt(),
&items[..count],
);
let named = match &result {
Ok(done) => *done,
Err(
rt::BatchStop::Bind { index, .. }
| rt::BatchStop::Draw { index, .. },
) => index + 1,
Err(rt::BatchStop::Device { completed, .. }) => *completed,
};
for _ in 0..named {
names.bound_buffers.add_named(bound.named());
}
match result {
Ok(0) => {}
Ok(1) => {
i += 1;
continue;
}
Ok(done) => {
i += done;
p0_until = i;
continue;
}
Err(rt::BatchStop::Bind { index, error }) => {
i += index;
break (true, Stop::Rt(error));
}
Err(rt::BatchStop::Draw { index, error }) => {
i += index;
break (false, Stop::Rt(error));
}
Err(rt::BatchStop::Device { error, .. }) => {
break (false, Stop::Rt(error));
}
}
}
let draw = &draws[i];
if let Some(bound) = draw.buffer {
names.bound_buffers.add_named(bound.named());
}
let key = draw.buffer.map(Handle::id);
if key != last {
last = key;
buffer = draw.buffer.map(|b| b.rt());
draw.buffer.iter().for_each(|b| used.buffer(b));
}
let bound = small(draw.index).and_then(|index| {
encoder
.set_vertex_buffer(buffer, draw.offset, index)
.map_err(Stop::from)
});
if let Err(stop) = bound {
break (true, stop);
}
if let Err(stop) = draw_primitives(
encoder,
draw.primitive_type,
draw.vertex_start,
draw.vertex_count,
) {
break (false, stop);
}
i += 1;
}
};
let draw = &draws[i];
if let Stop::Rt(rt::Error::Vulkan { call, result }) = &stop
&& *result == ash::vk::Result::ERROR_DEVICE_LOST
{
let loss = rt::DeviceLoss {
call,
result: *result,
fault: None,
};
drop(open);
drop(held);
naming_functions(functions, || report(sel, stop));
// The draw was refused: so is the run, whatever the rest answer.
return Some(encode_each(self, on, &draws[i + 1..]).map(|_| Encoded::REFUSED));
self.device.report_loss(loss);
return Some(Ok(Encoded::REFUSED));
}
encoded = Encoded::REFUSED;
// A refused bind leaves the prior binding in place for this item's draw.
let sel = if bind {
draw.vertex_buffer()
} else {
draw.primitives()
}
.selector();
let functions = if bind {
Vec::new()
} else {
self.refusal_functions(seen, sel, &stop, true, Some(draw.primitive_type), None)
};
drop(open);
drop(held);
naming_functions(functions, || report(sel, Some(stop)));
if bind {
pending_draw = true;
} else {
i += 1;
}
}
Some(Ok(Encoded::RECORDED))
Some(Ok(encoded))
}
}
@@ -1317,15 +1461,33 @@ impl RenderEncoder<RtPlatform> for RtObj<RtRenderEncoder> {
let recorded_call = crate::recorder::rec_call!(@cmd self, cmd);
let recorded_answer = crate::recorder::run(|| -> RaiseResult<Encoded> {
let _ = on;
let sel = cmd.selector();
let ending = matches!(cmd, RenderCmd::EndEncoding);
note_copies(self.kept.copies(), &cmd);
let primitive = drawn_primitive(&cmd);
let execution = execution(&cmd);
let draw = draws(&cmd);
let viewports = set_viewports(&cmd);
let held = self.open.lock();
let mut open = held.borrow_mut();
if let Some(names) = open.naming.names() {
note_names(names, &cmd);
}
let refused = (self.command(&mut open, cmd).err())
.map(|stop| (self.refusal(&open.seen, &cmd, &stop), stop));
let stopped = self.command(&mut open, cmd).err();
let functions = stopped.as_ref().map_or_else(Vec::new, |stop| {
self.refusal_functions(&open.seen, sel, stop, draw, primitive, viewports)
});
let icb_gap = |error: &rt::Error| {
matches!(
error,
rt::Error::Unsupported(rt::Gap::IndirectCommandBuffers { .. })
)
};
if let (Some(Stop::Rt(error)), Some(what)) = (&stopped, &execution)
&& icb_gap(error)
{
super::unbuilt::refusal_detail(sel, error, Some(what));
}
if ending && let Some(e) = open.rt.take() {
e.end_encoding();
self.mark.end();
@@ -1333,11 +1495,12 @@ impl RenderEncoder<RtPlatform> for RtObj<RtRenderEncoder> {
}
drop(open);
drop(held);
let Some(((sel, functions), stop)) = refused else {
return Ok(Encoded::RECORDED);
let encoded = match stopped {
None => Encoded::RECORDED,
Some(_) => Encoded::REFUSED,
};
naming_functions(functions, || report(sel, stop));
Ok(Encoded::REFUSED)
naming_functions(functions, || report(sel, stopped));
Ok(encoded)
});
crate::recorder::rec_done!(recorded_call, recorded_answer);
recorded_answer
@@ -1442,6 +1605,25 @@ mod tests {
/// `MTLPrimitiveTypeTriangle`.
const TRIANGLE: u64 = 3;
thread_local! {
static DRAW_REFUSALS: RefCell<Option<Vec<(&'static str, String)>>> =
const { RefCell::new(None) };
}
pub(super) fn report(sel: &'static str, stop: Option<Stop>) {
DRAW_REFUSALS.with_borrow_mut(|seen| {
if let (Some(seen), Some(stop)) = (seen, &stop) {
let why = match stop {
Stop::Metal(why) => (*why).to_owned(),
Stop::Rt(error) => error.to_string(),
Stop::Unbuilt(_) | Stop::Counted => unreachable!("only draw and bind refusals"),
};
seen.push((sel, why));
}
});
super::super::blit::report(sel, stop);
}
fn counted(code: &str) -> u64 {
(crate::answer::degradation_counts().into_iter())
.find(|(c, _)| c == code)
@@ -1906,6 +2088,7 @@ mod tests {
);
}
let before = codes.map(counted);
let before_mdi = device.rt().counters().metrics();
let answer = if batch {
encoder.encode_draws(on, draws)
} else {
@@ -1926,6 +2109,8 @@ mod tests {
assert_eq!(cb.commit(on), Ok(()));
assert_eq!(cb.wait_until_completed(on), Ok(()));
assert_eq!(cb.status(), CommandBufferStatus::COMPLETED);
let after_mdi = device.rt().counters().metrics();
assert_eq!(after_mdi.multi_draw_calls, before_mdi.multi_draw_calls);
let mut pixels = [0; 64];
target.read_pixels(&mut pixels, 16);
// SAFETY: the Shared result buffer is mapped for eight bytes and the GPU has finished.
@@ -2070,15 +2255,276 @@ mod tests {
/// (`super::super::copied`) is taken as a batch, not one at a time, and its draw reads the
/// bytes the CPU wrote into the pages before the commit, which the commit copied in.
#[test]
fn draw_batches_sync_a_copied_vertex_buffer_on_vulkan() -> Result<(), &'static str> {
fn indirect_draw_batches_match_pixels_refusals_and_binding_on_vulkan()
-> Result<(), &'static str> {
use crate::core::platform::command::WorkNames;
use std::sync::Arc;
let platform = RtPlatform::new();
let device = crate::rt_platform::device::with_multi_draw_indirect(true, || {
platform.system_default_device()
})
.ok_or("no Vulkan device")?;
let queue = device.new_command_queue().ok_or("no command queue")?;
let counters = device.rt().counters();
let vbuf = include_bytes!("../../../../tests/shaders/render_vbuf.metallib");
let flat = include_bytes!("../../../../tests/shaders/render_flat.metallib");
let vertex = function(&device, vbuf, "render_vbuf");
let fragment = function(&device, flat, "render_flat");
let mut desc = FullRenderPipelineDesc::new(&vertex, Some(&fragment));
desc.colors = vec![(
0,
ColorAttachmentDesc {
pixel_format: 70,
blending_enabled: true,
destination_rgb_blend_factor: 1,
..ColorAttachmentDesc::default()
},
)];
let state = device
.new_render_pipeline_state_full(&desc)
.unwrap()
.unwrap();
let floats = |values: &[f32]| {
values
.iter()
.flat_map(|v| v.to_le_bytes())
.collect::<Vec<_>>()
};
let positions = |x, right| [x, -1., 0., 1., right, -1., 0., 1., x, 3., 0., 1.];
let vertices = floats(&[positions(-1., 1.), positions(-0.5, 2.5)].concat());
let a = shared(&device, &vertices);
let b_vertices = floats(&positions(0., 2.));
let b = shared(&device, &b_vertices);
let increment = shared(&device, &floats(&[0., 1. / 255., 0., 1.]));
let marker = shared(&device, &floats(&[0., 0., 1., 1.]));
let results = shared(&device, &[0; 8]);
let other_platform = RtPlatform::new();
let other_device = other_platform
.system_default_device()
.ok_or("no second Vulkan device")?;
let foreign = shared(&other_device, &b_vertices);
let draw = VertexDraw {
buffer: Some(&a),
offset: 0,
index: 0,
primitive_type: TRIANGLE,
vertex_start: 0,
vertex_count: 3,
};
let on = OnFault::Return;
let target = device
.new_texture(
on,
&platform.texture_descriptor(&TextureDesc {
width: 4,
height: 4,
usage: 5,
..TextureDesc::default()
}),
)
.unwrap()
.unwrap();
let render = |draws: &[VertexDraw<'_, RtPlatform>], batch, visibility, operands: bool| {
let pass = pass(&target, 2);
if visibility {
pass.set_pass(&PassSet {
visibility_result_buffer: Some(Some(&results)),
..PassSet::default()
});
}
let cb = queue.command_buffer(on).unwrap().unwrap();
if !operands {
cb.names_work(&Arc::new(WorkNames::new(1)));
}
let encoder = cb.render_encoder(on, &pass).unwrap().unwrap();
encoder
.encode(
on,
RenderCmd::SetRenderPipelineState {
pipeline_state: Some(&state),
},
)
.unwrap()
.go_on();
let fragment = |buffer| RenderCmd::SetFragmentBuffer {
buffer: Some(buffer),
offset: 0,
index: 0,
};
encoder.encode(on, fragment(&increment)).unwrap().go_on();
encoder
.encode(
on,
RenderCmd::SetVertexBuffer {
buffer: Some(&increment),
offset: 0,
index: 1,
},
)
.unwrap()
.go_on();
encoder.encode(on, draw.vertex_buffer()).unwrap().go_on();
let before = counters.metrics();
DRAW_REFUSALS.set(Some(Vec::new()));
let encoded = if batch {
encoder.encode_draws(on, draws).unwrap()
} else {
encode_each(&encoder, on, draws).unwrap()
};
let bound = encoder
.open
.lock()
.borrow_mut()
.naming
.names()
.unwrap()
.bound_buffers
.clone();
encoder.encode(on, fragment(&marker)).unwrap().go_on();
encoder.encode(on, draw.primitives()).unwrap().go_on();
let refusals = DRAW_REFUSALS.take().unwrap();
encoder.encode(on, RenderCmd::EndEncoding).unwrap().go_on();
cb.commit(on).unwrap();
cb.wait_until_completed(on).unwrap();
assert_eq!(cb.status(), CommandBufferStatus::COMPLETED);
let mut pixels = [0; 64];
target.read_pixels(&mut pixels, 16);
let after = counters.metrics();
(
(pixels, refusals, bound, encoded),
(
after.multi_draw_calls - before.multi_draw_calls,
after.multi_draw_items - before.multi_draw_items,
),
)
};
let long: [_; 68] = std::array::from_fn(|i| VertexDraw {
offset: if i % 2 == 0 { 0 } else { 48 },
..draw
});
let (direct, _) = render(&long, false, false, false);
let (batched, mdi) = render(&long, true, false, false);
assert_eq!(batched, direct);
assert!(
direct
.0
.as_chunks::<4>()
.0
.iter()
.any(|pixel| (2..255).contains(&pixel[1]))
);
match device.rt().draw_indirect_limit() {
0..8 => assert_eq!(mdi, (0, 0)),
8..31 => assert!(mdi.0 > 0 && mdi.1 > 0),
_ => assert_eq!(mdi, (2, 63)),
}
println!(
"68 draws: 16/16 identical pixels, {} MDI calls, {} indirect draws",
mdi.0, mdi.1
);
for (draws, visibility, operands) in [
(&long[..8], false, false),
(&long[..], true, false),
(&long[..], false, true),
] {
let (batched, mdi) = render(draws, true, visibility, operands);
assert_eq!(batched, render(draws, false, visibility, operands).0);
assert_eq!(mdi, (0, 0));
}
let wide = u64::from(u32::MAX) + 1;
let switched = VertexDraw {
buffer: Some(&b),
..draw
};
let foreign = VertexDraw {
buffer: Some(&foreign),
..draw
};
for at in [0, 15, 31, 32, long.len() - 1] {
for exceptional in [
VertexDraw {
index: wide,
vertex_start: wide,
..draw
},
VertexDraw { index: 31, ..draw },
VertexDraw {
vertex_start: wide,
..switched
},
VertexDraw {
vertex_count: wide,
..switched
},
VertexDraw {
primitive_type: u64::MAX,
..switched
},
VertexDraw { offset: 1, ..draw },
VertexDraw {
offset: a.length() + 16,
..draw
},
VertexDraw {
vertex_count: 0,
..draw
},
switched,
VertexDraw {
buffer: None,
..draw
},
] {
let mut draws = long;
draws[at] = exceptional;
assert_eq!(
render(&draws, true, false, false).0,
render(&draws, false, false, false).0,
"position {at}"
);
}
}
for draw in [VertexDraw { offset: 1, ..draw }, foreign] {
let draws = [draw; 10];
let (direct, _) = render(&draws, false, false, false);
assert!(!direct.1.is_empty());
assert_eq!(render(&draws, true, false, false).0, direct);
}
let mut draws = long;
draws[31] = VertexDraw {
index: wide,
vertex_start: wide,
..switched
};
draws[32] = VertexDraw {
primitive_type: u64::MAX,
..switched
};
assert_eq!(
render(&draws[..33], true, false, false).0,
render(&draws[..33], false, false, false).0
);
let copied = copied_vertex_buffer(&device, &vertices)?;
let draws = long.map(|draw| VertexDraw {
buffer: Some(&copied),
..draw
});
let (batched, mdi) = render(&draws, true, false, false);
assert_eq!(batched, render(&draws, false, false, false).0);
assert_eq!(mdi, (0, 0));
Ok(())
}
fn copied_vertex_buffer(
device: &RtObj<RtDevice>,
data: &[u8],
) -> Result<RtObj<RtBuffer>, &'static str> {
use crate::core::host::HostPtr;
use crate::core::num::ToUsize as _;
use crate::core::platform::HostRange;
use std::alloc::{Layout, alloc_zeroed, dealloc};
let platform = RtPlatform::new();
let device = platform.system_default_device().ok_or("no Vulkan device")?;
let queue = device.new_command_queue().ok_or("no command queue")?;
let on = OnFault::Return;
let page = device.facts().page_size;
let layout =
@@ -2104,14 +2550,23 @@ mod tests {
.ok_or("no copied buffer")?;
assert!(buffer.copied().is_some());
assert!(super::super::copied::any());
let green = [0, 255, 0, 255];
let data = vertices(&[green]);
// SAFETY: the vertices fit in the mapped page, and the copy was already initialized.
unsafe {
memory
.as_ptr::<u8>()
.copy_from_nonoverlapping(data.as_ptr(), data.len())
};
Ok(buffer)
}
#[test]
fn draw_batches_sync_a_copied_vertex_buffer_on_vulkan() -> Result<(), &'static str> {
let platform = RtPlatform::new();
let device = platform.system_default_device().ok_or("no Vulkan device")?;
let queue = device.new_command_queue().ok_or("no command queue")?;
let on = OnFault::Return;
let green = [0, 255, 0, 255];
let buffer = copied_vertex_buffer(&device, &vertices(&[green]))?;
let state = vdesc_state(&device, &function(&device, COLOR, "render_color"));
let target = device
.new_texture(
@@ -10,12 +10,6 @@
//! content's lines, for its points and for a state's main pipeline its finish had not made
//! among them, and the longest since the device was made (rt keeps no longest of a period); its
//! waits for a lowering are left out;
//! - its makes at encode, the translations a draw or dispatch waits for on its encoding thread
//! (all six kinds, made or refused), their count and time in all, and the longest since the
//! device was made;
//! - its contents made for a 4:2:2 texture (`GBGR422`, `BGRG422`), also counted in the makes at
//! encode, the draws and dispatches that ran one, and the 4:2:2 textures alive now; left out
//! where none was made or ran and none lives, so a camera closed reads as none;
//! - its `vkQueueSubmit2` calls, their count and time inside the driver in all, those longer than
//! 100 ms, and the longest since the device was made; then the submit thread's waits for rt's
//! queue lock before them, their time in all and the longest since the device was made;
@@ -185,15 +179,6 @@ pub(crate) fn line(before: &rt::Metrics, now: &rt::Metrics, gauges: &rt::Gauges)
rose!(resolve_copy_bytes),
);
let staging = copied.saturating_sub(attachments + over + resolve);
let (chroma_contents, chroma_launches) = (rose!(chroma_contents), rose!(chroma_launches));
let chroma = if chroma_contents == 0 && chroma_launches == 0 && gauges.chroma_textures == 0 {
String::new()
} else {
format!(
"4:2:2 contents {chroma_contents}, launches {chroma_launches}, textures {}; ",
gauges.chroma_textures
)
};
// What rose, and the gauges as they are, each by its field's name.
macro_rules! rose_by_name {
($($field:ident),* $(,)?) => {
@@ -247,8 +232,7 @@ pub(crate) fn line(before: &rt::Metrics, now: &rt::Metrics, gauges: &rt::Gauges)
format!(
"rt: pipelines made {}, finished {} in {:.1} ms; first-use waits {} in {:.1} ms (variants \
{} in {:.1} ms, lines {} in {:.1} ms, points {} in {:.1} ms, unfinished {} in {:.1} ms), \
the longest since the device was made {:.1} ms; makes at encode {} in {:.1} ms, the \
longest since the device was made {:.1} ms; {chroma}\
the longest since the device was made {:.1} ms; \
submits {} in {:.1} ms ({} over 100 ms), the longest since the device was made {:.1} \
ms; queue-lock waits {:.1} ms, the longest since the device was made {:.1} ms; own \
command buffers {} in {:.1} ms on the GPU; bytes copied {copied}: staging {staging}, \
@@ -268,9 +252,6 @@ pub(crate) fn line(before: &rt::Metrics, now: &rt::Metrics, gauges: &rt::Gauges)
rose!(first_use_unfinished_waits),
ms(rose!(first_use_unfinished_wait_nanos)),
ms(now.first_use_wait_max_nanos),
rose!(translations_at_encode),
ms(rose!(translation_at_encode_nanos)),
ms(now.translation_at_encode_max_nanos),
rose!(submissions),
ms(rose!(submit_call_nanos)),
rose!(submit_calls_over_100_ms),
@@ -330,17 +311,6 @@ mod tests {
now.first_use_unfinished_waits = 1;
now.first_use_unfinished_wait_nanos = 800_000;
now.first_use_wait_max_nanos = 4_200_000;
before.translations_at_encode = 2;
before.translation_at_encode_nanos = 40_000_000;
// The longest is since the device was made: written as it is, not as a rise.
before.translation_at_encode_max_nanos = 30_000_000;
now.translations_at_encode = 2 + 3;
now.translation_at_encode_nanos = 40_000_000 + 61_200_000;
now.translation_at_encode_max_nanos = 38_400_000;
before.chroma_contents = 1;
before.chroma_launches = 10;
now.chroma_contents = 1 + 2;
now.chroma_launches = 10 + 45;
before.submissions = 100;
before.submit_call_nanos = 50_000_000;
before.queue_lock_wait_nanos = 1_000_000;
@@ -411,14 +381,11 @@ mod tests {
gauges.private_take_sparse_allocations = 1;
gauges.surface_imports = 2;
gauges.surface_import_bytes = 12_441_600;
gauges.chroma_textures = 1;
assert_eq!(
line(&before, &now, &gauges),
"rt: pipelines made 3, finished 2 in 3.4 ms; first-use waits 3 in 7.5 ms (variants 2 \
in 6.0 ms, lines 1 in 1.5 ms, points 1 in 0.5 ms, unfinished 1 in 0.8 ms), the \
longest since the device was made 4.2 ms; makes at encode 3 in 61.2 ms, the longest \
since the device was made 38.4 ms; 4:2:2 contents 2, launches 45, textures 1; \
submits 60 \
longest since the device was made 4.2 ms; submits 60 \
in 312.5 ms (2 over 100 ms), the longest since the device was made 140.0 ms; \
queue-lock waits 2.3 ms, the longest since the device was made 0.9 ms; own command \
buffers 12 in 1.7 ms on the GPU; bytes copied 6720: staging 64, attachment reads 512, \
@@ -445,13 +412,6 @@ mod tests {
part.starts_with("rt: pipelines made 2, finished 0 in 0.0 ms; first-use waits 0 in"),
"{part}"
);
assert!(
part.contains(
"the longest since the device was made 0.0 ms; makes at encode 0 in 0.0 ms, the \
longest since the device was made 0.0 ms; submits 0 in"
),
"{part}"
);
assert!(
part.ends_with(
"over-copies 0, resolve copies 0; counted texture_clears 0, texture_clear_bytes 0, \
@@ -471,51 +431,6 @@ mod tests {
);
}
/// A part says the 4:2:2 textures' contents and launches where either rose, or the textures
/// where one lives, with 0 for the others; and leaves them out where none was made or ran and
/// none lives, as after a camera closes.
#[test]
fn an_rt_part_says_4_2_2_textures_only_where_one_was_made_ran_or_lives() {
let mut before = rt::Metrics::default();
before.chroma_contents = 4;
before.chroma_launches = 300;
let mut gauges = rt::Gauges::default();
let four_two_two = |part: &str| -> Option<String> {
let (_, rest) = part.split_once("; 4:2:2 ")?;
Some(rest.split_once("; ")?.0.to_owned())
};
let mut launched = before;
launched.chroma_launches += 60;
gauges.chroma_textures = 2;
let part = line(&before, &launched, &gauges);
assert_eq!(
four_two_two(&part).as_deref(),
Some("contents 0, launches 60, textures 2"),
"{part}"
);
let part = line(&launched, &launched, &gauges);
assert_eq!(
four_two_two(&part).as_deref(),
Some("contents 0, launches 0, textures 2"),
"{part}"
);
gauges.chroma_textures = 0;
let mut made = launched;
made.chroma_contents += 1;
let part = line(&launched, &made, &gauges);
assert_eq!(
four_two_two(&part).as_deref(),
Some("contents 1, launches 0, textures 0"),
"{part}"
);
let part = line(&made, &made, &gauges);
assert_eq!(four_two_two(&part), None, "{part}");
assert!(
part.contains("the longest since the device was made 0.0 ms; submits 0 in"),
"{part}"
);
}
/// The copied pages' part says what rose for each kind, a kind with none as 0, and the
/// read-only copies by the guest's why, the whys that rose alone; a count that fell, or one
/// counted first since the part before, reads as it is.
@@ -14,12 +14,10 @@
//! complete, from present fences or Vulkan's rules ([`Presents`], [`Fences`]), and the one lock
//! every call into the window system runs under ([`WSI`]), which the two platforms' windows share.
//!
//! **Which window systems the device presents to** is asked before a display's window opens, of a
//! window the asker makes for the question and never shows ([`RtSwapchain::presents_to`]): a
//! surface of it is made and asked what a swapchain asks of a window's surface ([`presents`]),
//! then destroyed. On Linux the windows open through a window system whose windows the device's
//! queue family presents to (reims-vgpu-window's choice), since a window whose surface it does not
//! present to gets no swapchain and stays empty.
//! **Which window systems the device presents to** is asked before a window opens, with no
//! surface ([`RtSwapchain::presents_to`]): on Linux the window opens through a window system whose
//! windows the device's queue family presents to (reims-vgpu-window's choice), since a window
//! whose surface it does not present to gets no swapchain and stays empty.
//!
//! **The present mode is logged** at info at the first swapchain made, with the images asked
//! for and the images made; a later make logs it again only where its counts differ from the
@@ -88,6 +86,8 @@
//! are destroyed before their device, which rt destroys at the host's let-go of it. None waits
//! first: nothing runs on a lost device any more.
use std::ffi::{c_ulong, c_void};
use ash::{khr, vk};
use metal2vulkan_runtime as rt;
@@ -138,87 +138,6 @@ fn retire_clear(texture: &RtObj<RtTexture>) -> Flight {
}
}
/// Whether queue family `family` of `physical` presents to `surface` as a swapchain over it asks
/// ([`RtSwapchain::new`], and [`RtSwapchain::presents_to`] before any window opens): the surface
/// supports presenting from the family (`vkGetPhysicalDeviceSurfaceSupportKHR`), and offers
/// `B8G8R8A8_UNORM` in `SRGB_NONLINEAR`; why not where it does not.
///
/// # Safety
///
/// `surface` and `physical` are live, of the instance `api` is of.
unsafe fn presents(
api: &khr::surface::Instance,
physical: vk::PhysicalDevice,
family: u32,
surface: vk::SurfaceKHR,
) -> Result<(), Refused> {
// SAFETY: the caller's.
let presents = unsafe { api.get_physical_device_surface_support(physical, family, surface) }
.map_err(|e| refused("vkGetPhysicalDeviceSurfaceSupportKHR", e))?;
if !presents {
return Err(Refused(format!(
"queue family {family} does not present to the window's surface"
)));
}
// SAFETY: as above.
let formats = unsafe { api.get_physical_device_surface_formats(physical, surface) }
.map_err(|e| refused("vkGetPhysicalDeviceSurfaceFormatsKHR", e))?;
if !formats
.iter()
.any(|f| f.format == FORMAT && f.color_space == COLOR_SPACE)
{
return Err(Refused(
"the window's surface offers no B8G8R8A8_UNORM in SRGB_NONLINEAR".to_owned(),
));
}
Ok(())
}
/// [`RtSwapchain::presents_to`]'s question, on the instance whose commands `entry` and `instance`
/// load: a surface of `system`'s window (`vkCreateWaylandSurfaceKHR` or `vkCreateXlibSurfaceKHR`),
/// [`presents`] of it for queue family `family` of `physical`, and the surface destroyed, whatever
/// the answer. Why not where it does not present, or no surface is made.
///
/// # Safety
///
/// The instance is live, with the window system's surface extension enabled, `physical` is a
/// physical device of it, and `system`'s connection and window are live and used by no other
/// thread during the call.
unsafe fn presents_to_window(
entry: &ash::Entry,
instance: &ash::Instance,
physical: vk::PhysicalDevice,
family: u32,
system: WindowSystem,
) -> Result<(), Refused> {
let surface = match system {
WindowSystem::Wayland { display, surface } => {
let info = vk::WaylandSurfaceCreateInfoKHR::default()
.display(display)
.surface(surface);
let made = khr::wayland_surface::Instance::new(entry, instance);
// SAFETY: the caller's live connection and surface, on the caller's instance.
unsafe { made.create_wayland_surface(&info, None) }
.map_err(|e| refused("vkCreateWaylandSurfaceKHR", e))?
}
WindowSystem::Xlib { display, window } => {
let info = vk::XlibSurfaceCreateInfoKHR::default()
.dpy(display)
.window(window);
let made = khr::xlib_surface::Instance::new(entry, instance);
// SAFETY: the caller's live connection and window, on the caller's instance.
unsafe { made.create_xlib_surface(&info, None) }
.map_err(|e| refused("vkCreateXlibSurfaceKHR", e))?
}
};
let api = khr::surface::Instance::new(entry, instance);
// SAFETY: the surface just made, and the caller's physical device of its instance.
let answer = unsafe { presents(&api, physical, family, surface) };
// SAFETY: the surface is this call's, and nothing was made of it.
unsafe { api.destroy_surface(surface, None) };
answer
}
/// One image of the swapchain.
struct Image {
/// rt's drawable texture over it.
@@ -381,7 +300,25 @@ impl RtSwapchain {
reason
};
// SAFETY: `surface` and `physical` are live, of one instance.
unsafe { presents(&surface_api, physical, family, surface) }.map_err(destroy)?;
let presents =
unsafe { surface_api.get_physical_device_surface_support(physical, family, surface) }
.map_err(|e| destroy(refused("vkGetPhysicalDeviceSurfaceSupportKHR", e)))?;
if !presents {
return Err(destroy(Refused(format!(
"queue family {family} does not present to the window's surface"
))));
}
// SAFETY: as above.
let formats = unsafe { surface_api.get_physical_device_surface_formats(physical, surface) }
.map_err(|e| destroy(refused("vkGetPhysicalDeviceSurfaceFormatsKHR", e)))?;
if !formats
.iter()
.any(|f| f.format == FORMAT && f.color_space == COLOR_SPACE)
{
return Err(destroy(Refused(
"the window's surface offers no B8G8R8A8_UNORM in SRGB_NONLINEAR".to_owned(),
)));
}
// SAFETY: as above.
let modes =
unsafe { surface_api.get_physical_device_surface_present_modes(physical, surface) }
@@ -439,47 +376,73 @@ impl RtSwapchain {
}
/// Whether `device`'s queue family, the one a swapchain presents on ([`RtSwapchain::new`]),
/// presents to `system`'s window, a window made for the question before any display's window
/// opens: a surface of the window made on rt's instance, asked what a swapchain over a
/// window's surface asks ([`presents`]), and destroyed, whatever the answer; why not where it
/// does not. Vulkan's per-platform question (`vkGetPhysicalDeviceWaylandPresentationSupportKHR`
/// and its Xlib twin), which names no window, can answer otherwise: in a user's report a
/// laptop's NVIDIA GPU answered yes to it for the Wayland compositor, and no for a Wayland
/// window's surface. Refused where rt's instance did not enable the window system's surface
/// extension (the loader lists none), as no window of it can then have a surface on the
/// instance. Asked under [`WSI`], as every call into the window system.
/// presents to windows of `system`, asked before any window is made and with no surface:
/// Vulkan's per-platform question, `vkGetPhysicalDeviceWaylandPresentationSupportKHR` or
/// `vkGetPhysicalDeviceXlibPresentationSupportKHR`. `false` where rt's instance did not enable
/// the window system's surface extension (the loader lists none), as no window of it can then
/// have a surface on the instance. Asked under [`WSI`], as every call into the window system.
///
/// # Safety
///
/// `system`'s connection and window are live, and no other thread uses them during the call.
pub unsafe fn presents_to(
device: &RtObj<RtDevice>,
system: WindowSystem,
) -> Result<(), Refused> {
let extension = match system {
WindowSystem::Wayland { .. } => khr::wayland_surface::NAME,
WindowSystem::Xlib { .. } => khr::xlib_surface::NAME,
/// `system`'s connection is live, and no other thread uses it during the call.
pub unsafe fn presents_to(device: &RtObj<RtDevice>, system: WindowSystem) -> bool {
let (extension, command) = match system {
WindowSystem::Wayland { .. } => (
khr::wayland_surface::NAME,
c"vkGetPhysicalDeviceWaylandPresentationSupportKHR",
),
WindowSystem::Xlib { .. } => (
khr::xlib_surface::NAME,
c"vkGetPhysicalDeviceXlibPresentationSupportKHR",
),
};
if !(device.instance().extensions().iter()).any(|e| e.as_c_str() == extension) {
return Err(Refused(format!(
"the runtime's instance has no {}",
extension.to_string_lossy()
)));
return false;
}
let (entry, instance) = device.instance().raw();
let raw = device.rt().raw();
let (physical, family) = (raw.physical_device, raw.queue_family_index);
let _wsi = WSI.lock();
// SAFETY: the instance is live, and so are the physical device of it and the caller's
// window.
unsafe {
presents_to_window(
entry,
instance,
raw.physical_device,
raw.queue_family_index,
system,
)
}
// SAFETY: a live instance, which enabled the extension the command is of.
let found = unsafe { entry.get_instance_proc_addr(instance.handle(), command.as_ptr()) };
let Some(found) = found else {
return false;
};
let answer = match system {
WindowSystem::Wayland { display } => {
// SAFETY: the command of that name, of this type (vulkan_wayland.h), called with a
// physical device and a queue family of the instance's, and the caller's live
// `wl_display`.
unsafe {
let ask = std::mem::transmute::<
unsafe extern "system" fn(),
unsafe extern "system" fn(
vk::PhysicalDevice,
u32,
*mut c_void,
) -> vk::Bool32,
>(found);
ask(physical, family, display)
}
}
WindowSystem::Xlib { display, visual } => {
// SAFETY: as above (vulkan_xlib.h, whose `VisualID` is Xlib's, an unsigned long),
// with the caller's live `Display`.
unsafe {
let ask = std::mem::transmute::<
unsafe extern "system" fn(),
unsafe extern "system" fn(
vk::PhysicalDevice,
u32,
*mut c_void,
c_ulong,
) -> vk::Bool32,
>(found);
ask(physical, family, display, visual)
}
}
};
answer == vk::TRUE
}
/// Whether the swapchain presents with MAILBOX (else FIFO).
@@ -1922,163 +1885,4 @@ mod tests {
loss
});
}
/// The surfaces the fake driver of [`refusing_driver`] made, and those it destroyed.
static FAKE_SURFACES: [std::sync::atomic::AtomicU32; 2] =
[const { std::sync::atomic::AtomicU32::new(0) }; 2];
/// The fake driver's Wayland surface, which its queue family 0 does not present to.
const FAKE_WAYLAND: u64 = 0x5701;
/// The fake driver's Xlib surface, which its queue family 0 presents to.
const FAKE_XLIB: u64 = 0x5801;
/// A driver answering as the user's report's did (an RTX 4060 Laptop GPU beside the Intel GPU
/// KWin composites on, NVIDIA 620.73.04): yes to Vulkan's per-platform questions, of Wayland
/// and of Xlib, which name no window; no for a Wayland window's surface and yes for an X11
/// window's (`vkGetPhysicalDeviceSurfaceSupportKHR`, as vulkaninfo's per-surface lists showed),
/// each surface offering `B8G8R8A8_UNORM` in `SRGB_NONLINEAR`. Its `vkGetInstanceProcAddr`,
/// answering those commands and no others; it counts the surfaces made and destroyed
/// ([`FAKE_SURFACES`]).
unsafe extern "system" fn refusing_driver(
_instance: vk::Instance,
name: *const std::ffi::c_char,
) -> vk::PFN_vkVoidFunction {
use std::ffi::{c_ulong, c_void};
use std::sync::atomic::Ordering;
use ash::vk::Handle as _;
unsafe extern "system" fn per_platform_wayland(
_: vk::PhysicalDevice,
_: u32,
_: *mut c_void,
) -> vk::Bool32 {
vk::TRUE
}
unsafe extern "system" fn per_platform_xlib(
_: vk::PhysicalDevice,
_: u32,
_: *mut c_void,
_: c_ulong,
) -> vk::Bool32 {
vk::TRUE
}
/// A surface made: `made` written to `surface`.
unsafe fn create(made: u64, surface: *mut vk::SurfaceKHR) -> vk::Result {
FAKE_SURFACES[0].fetch_add(1, Ordering::Relaxed);
// SAFETY: the command's out pointer.
unsafe { surface.write(vk::SurfaceKHR::from_raw(made)) };
vk::Result::SUCCESS
}
unsafe extern "system" fn create_wayland(
_: vk::Instance,
_: *const vk::WaylandSurfaceCreateInfoKHR<'_>,
_: *const vk::AllocationCallbacks<'_>,
surface: *mut vk::SurfaceKHR,
) -> vk::Result {
// SAFETY: the command's out pointer.
unsafe { create(FAKE_WAYLAND, surface) }
}
unsafe extern "system" fn create_xlib(
_: vk::Instance,
_: *const vk::XlibSurfaceCreateInfoKHR<'_>,
_: *const vk::AllocationCallbacks<'_>,
surface: *mut vk::SurfaceKHR,
) -> vk::Result {
// SAFETY: the command's out pointer.
unsafe { create(FAKE_XLIB, surface) }
}
unsafe extern "system" fn support(
_: vk::PhysicalDevice,
_: u32,
surface: vk::SurfaceKHR,
supported: *mut vk::Bool32,
) -> vk::Result {
// SAFETY: the command's out pointer.
unsafe { supported.write(vk::Bool32::from(surface.as_raw() == FAKE_XLIB)) };
vk::Result::SUCCESS
}
unsafe extern "system" fn formats(
_: vk::PhysicalDevice,
_: vk::SurfaceKHR,
count: *mut u32,
formats: *mut vk::SurfaceFormatKHR,
) -> vk::Result {
let format = vk::SurfaceFormatKHR {
format: FORMAT,
color_space: COLOR_SPACE,
};
// SAFETY: the command's out pointers, `formats` of `*count` entries where given.
unsafe {
if !formats.is_null() && *count >= 1 {
formats.write(format);
}
count.write(1);
}
vk::Result::SUCCESS
}
unsafe extern "system" fn destroy(
_: vk::Instance,
_: vk::SurfaceKHR,
_: *const vk::AllocationCallbacks<'_>,
) {
FAKE_SURFACES[1].fetch_add(1, Ordering::Relaxed);
}
// SAFETY: the command's name, a C string.
let name = unsafe { std::ffi::CStr::from_ptr(name) };
let found: *const () = match name.to_bytes() {
b"vkGetPhysicalDeviceWaylandPresentationSupportKHR" => per_platform_wayland as _,
b"vkGetPhysicalDeviceXlibPresentationSupportKHR" => per_platform_xlib as _,
b"vkCreateWaylandSurfaceKHR" => create_wayland as _,
b"vkCreateXlibSurfaceKHR" => create_xlib as _,
b"vkGetPhysicalDeviceSurfaceSupportKHR" => support as _,
b"vkGetPhysicalDeviceSurfaceFormatsKHR" => formats as _,
b"vkDestroySurfaceKHR" => destroy as _,
_ => return None,
};
// SAFETY: a function of the named command's type, which its caller calls as that type.
Some(unsafe { std::mem::transmute::<*const (), unsafe extern "system" fn()>(found) })
}
/// A device whose queue family a window's surface refuses, while Vulkan's per-platform
/// question of its window system, which names no window, answers yes: a user's report, a
/// laptop's NVIDIA GPU under KWin, whose window opened through Wayland on that yes and stayed
/// empty, its swapchain refused ([`refusing_driver`]). Asked of a window before any display's
/// window opens, it presents to no Wayland window, saying why as the swapchain does, and to
/// X11 windows, so the windows open through X11; each surface the question made is destroyed,
/// the refused one too. Fake commands: no GPU
#[test]
fn a_device_whose_queue_family_a_wayland_surface_refuses_presents_to_x11_windows_alone() {
use ash::vk::Handle as _;
let commands = ash::StaticFn {
get_instance_proc_addr: refusing_driver,
};
// SAFETY: the fake driver's commands, which live for the process.
let entry = unsafe { ash::Entry::from_static_fn(commands.clone()) };
// SAFETY: as above.
let instance = unsafe { ash::Instance::load(&commands, vk::Instance::from_raw(0x1)) };
let physical = vk::PhysicalDevice::from_raw(0x2);
let (display, window) = (std::ptr::NonNull::dangling().as_ptr(), 0x40_0001);
let wayland = WindowSystem::Wayland {
display,
surface: std::ptr::NonNull::dangling().as_ptr(),
};
let x11 = WindowSystem::Xlib { display, window };
let asked = |system| {
// SAFETY: the fake driver's instance and physical device; it reads none of the
// windows' pointers.
unsafe { presents_to_window(&entry, &instance, physical, 0, system) }
};
assert_eq!(
asked(wayland),
Err(Refused(
"queue family 0 does not present to the window's surface".to_owned()
))
);
assert_eq!(asked(x11), Ok(()));
let counted = FAKE_SURFACES
.each_ref()
.map(|n| n.load(std::sync::atomic::Ordering::Relaxed));
assert_eq!(counted, [2, 2], "surfaces made, destroyed");
}
}
@@ -98,13 +98,11 @@
//! (`rt-refused-metal`), where Metal aborts. A `replaceRegion:` rt refuses changes nothing, counted
//! likewise.
//!
//! **The bytes.** `replaceRegion:`'s bytes are guest memory, which the guest writes while they are
//! read, so no shared slice may cover them. rt reads them in place through their pointer
//! (`crate::gpu::resource::guest_bytes`, rt's `HostBytes::from_raw`), as Metal does. Two kinds
//! copy them into memory of their own first (`crate::gpu::resource::first_bytes`), a copy Metal
//! does not make, counted per call ([`COPY_CODE`]) and by bytes ([`COPY_BYTES_CODE`]): a tiled
//! texture's level 0, whose writer takes a slice, and a texture over a buffer, which may lie over
//! the very bytes it is given, where rt's write into it is a nonoverlapping copy.
//! **A copy.** `replaceRegion:`'s bytes are guest memory, which the guest writes while they are
//! read, so no shared slice may cover them, and rt takes a slice: the platform copies them into
//! memory of its own first (`crate::gpu::resource::first_bytes`), a copy Metal does not make,
//! counted per call ([`COPY_CODE`]) and by bytes ([`COPY_BYTES_CODE`]), until rt reads them through
//! their pointer.
use std::collections::VecDeque;
use std::ops::Range;
@@ -1813,9 +1811,8 @@ impl Texture<RtPlatform> for RtObj<RtTexture> {
self.protection_options
}
/// rt's, of the bytes in place or of a copy of them (the module's docs, "The bytes"): a range
/// at or near NULL dies, as Metal's read of it faults (`crate::gpu::resource::guest_bytes` and
/// `first_bytes`). What rt refuses (a Private
/// rt's, of a copy of the bytes (the module's docs, "A copy"): a range at or near NULL dies, as
/// Metal's read of it faults (`crate::gpu::resource::first_bytes`). What rt refuses (a Private
/// texture, a region outside the level or off its format's block grid, rows that do not cover
/// it) changes nothing, counted, where Metal's validation aborts. Of a tiled texture's level 0
/// the bytes go into its buffer's bytes, which its next use takes (`super::tiled`).
@@ -1848,12 +1845,11 @@ impl Texture<RtPlatform> for RtObj<RtTexture> {
refused_as(REPLACE, RtRefusal::Refused, &why);
return Ok(());
};
let bytes = crate::gpu::resource::first_bytes(REPLACE, pixel_bytes, usize::MAX);
counted_copy(bytes.len());
if level == 0
&& let Some(tiled) = self.tiled()
{
// The tiled path takes a slice: its bytes are copied first (the module's docs).
let bytes = crate::gpu::resource::first_bytes(REPLACE, pixel_bytes, usize::MAX);
counted_copy(bytes.len());
if let Err((kind, why)) =
tiled.replace(region, u64::from(slice), &bytes, bytes_per_row)
{
@@ -1861,21 +1857,14 @@ impl Texture<RtPlatform> for RtObj<RtTexture> {
}
return Ok(());
}
// A texture over a buffer may lie over the very bytes it is given, and rt writes it
// with a nonoverlapping copy: those bytes are copied first, as before (the module's
// docs, "The bytes"); any other texture's rt reads in place.
let copied;
let bytes = if self.over().is_some() {
copied = crate::gpu::resource::first_bytes(REPLACE, pixel_bytes, usize::MAX);
counted_copy(copied.len());
rt::HostBytes::from(copied.as_slice())
} else {
crate::gpu::resource::guest_bytes(REPLACE, pixel_bytes)
};
if let Err(error) =
self.rt()
.replace_region(r, level, slice, bytes, bytes_per_row, bytes_per_image)
{
if let Err(error) = self.rt().replace_region(
r,
level,
slice,
rt::HostBytes::from(bytes.as_slice()),
bytes_per_row,
bytes_per_image,
) {
rt_refused(REPLACE, &error);
}
Ok(())
@@ -2578,8 +2567,7 @@ mod tests {
let shared = make(&small).expect("a Shared texture");
let pixels = HostRange::of_slice(&bytes);
assert_eq!(shared.replace_region(region, 0, 0, pixels, 16, 0), Ok(()));
// A texture over no buffer: rt reads the bytes in place, with no copy counted.
assert_eq!(counted(COPY_CODE), copies);
assert_eq!(counted(COPY_CODE), copies + 1);
assert_eq!(counted(RtRefusal::Refused.code()), metal);
// An image for views takes no index; a view of it at the guest's index reads its texels.
+7 -11
View File
@@ -279,26 +279,22 @@ impl Presents {
}
}
/// A window of a window system of the host's session, made for a question about presenting to its
/// windows before any display's window opens (the rt platform's swapchain's `presents_to`): on
/// Linux a window of the Wayland compositor's or the X server's, which a display's windows may
/// open through, never shown. The question makes a surface of it, as a display's window's
/// swapchain makes one of the window it presents to.
/// A connection to a window system of the host's session, which a question about presenting to its
/// windows names before any window is made (the rt platform's swapchain's `presents_to`): on Linux
/// the Wayland compositor's or the X server's, which a window may open through.
#[derive(Clone, Copy, Debug)]
pub enum WindowSystem {
/// A Wayland compositor: its `wl_display`, and a `wl_surface` of it.
/// A Wayland compositor: its `wl_display`.
Wayland {
/// The compositor's `wl_display`.
display: *mut std::ffi::c_void,
/// A `wl_surface` of the connection's, given no role, so never shown.
surface: *mut std::ffi::c_void,
},
/// An X server, through Xlib: its `Display`, and a window of it.
/// An X server, through Xlib: its `Display`, and the visual a window takes there.
Xlib {
/// The server's Xlib `Display`.
display: *mut std::ffi::c_void,
/// An unmapped window of the connection's, Xlib's `Window`.
window: std::ffi::c_ulong,
/// The visual's ID, Xlib's `VisualID`.
visual: std::ffi::c_ulong,
},
}
+44 -133
View File
@@ -23,11 +23,12 @@ them; its `manual` checks are on a Linux host's guest boot.
|---|---|
| `REIMS_VGPU_WINDOW=0` | QEMU stays headless under `-display none` (QEMU reads it) |
| `REIMS_VGPU_WINDOW_BORDERLESS=1` | borderless windows that fill their screens |
| `REIMS_VGPU_WINDOW_REFRESH_RATE=60` | every display offers the guest each size at that one rate, in Hz, at most its screen's ("Matching the host's screen") |
| `REIMS_VGPU_WINDOW_SCREENS=1,0` | display i opens on the host screen the list's i-th entry names |
| `resolution=2560x1600` | the mode the window opens for, and the guest is offered until the window's pixels are known (QEMU's reims-graphics-pci property; 1920x1080 by default); with several displays, every window's |
| `displays=2` | the reims-graphics device's displays, 1 to 4, a window each (QEMU's reims-graphics-pci property; 1 by default) |
| `REIMS_VGPU_WINDOW_IMPL=sdl` | macOS, built with the `macos-sdl` feature (on by default): SDL3's window in place of AppKit's ("On macOS through SDL3" below) |
| `REIMS_VGPU_WINDOW_RELEASE_KEYS=Ctrl+Shift+F12` | additional release shortcut for SDL windows on Windows and Linux; when unset, `REIMS_PLUGIN_LOCAL_CAPTURE_SHORTCUT_KEYS` can supply it |
| `REIMS_PLUGIN_LOCAL_CAPTURE_SHORTCUT_RELEASE_ON_LEAVE=1` | on Windows and Linux, release the keyboard grab while the mouse is out of the SDL window |
Unset or unparsable values give the defaults below.
`test: env::unset_or_unparsable_values_are_the_defaults`,
@@ -48,27 +49,10 @@ Unset or unparsable values give the defaults below.
`reims-vgpu: window shown: display N` at its first frame presented, or
`reims-vgpu: no window:` and why, where it stays empty, drawing no more
before a frame (no swapchain, swapchains that end again and again, a lost
device), or where its opening has not returned 10 s after it began ("has
not opened yet: it opens once a screen is on; if a screen is on and it
does not, this GPU may not show a window on this desktop"): SDL's opening
waits for the window system to show the window with no bound, and KWin
shows no X window while every screen is off, so the UI thread waits until
a screen comes on, the window's later work and every other display's with
it, and at QEMU's exit the quiesce waits its 5 s for it, then the exit goes
on (four X11 opens on a KWin session, its one screen off,
m3-max-87109 to m3-max-87130). Where the GPU the desktop is drawn on is
known (the Wayland compositor's, from its dma-buf feedback, where the GPU
does not present to its window), a no-window line ends naming its DRM
node, and reims-ctl's start names that GPU's number in `reims-ctl gpus`
and the `reims-ctl set NAME --gpu N` that gives it to the VM; for a window
not opened yet it says first that the window opens once a screen is on.
reims-ctl's start says a VM's window is open only after the first line,
and otherwise why there is none, on every host.
device). reims-ctl's start says a VM's window is open only after the first
line, and otherwise why there is none, on every host.
`test: present::the_host_is_told_once_whether_the_window_shows`,
`test: told::the_window_s_lines_start_as_the_host_reads_them`,
`test: told::a_no_window_line_names_the_desktop_s_gpu_where_it_is_known`,
`test: reims-ctl::runtime::a_no_window_reason_names_the_gpu_the_desktop_is_drawn_on`,
`manual` (the not-opened line, on a session whose screens are off)
`test: told::the_window_s_lines_start_as_the_host_reads_them`
- A new window shows its mode a guest pixel per host point, shrunk to fit
the screen's visible area, on whole pixels, a multiple of 16 wide and even
high (the steps of the guest's modes, below): on a Retina screen the
@@ -154,7 +138,7 @@ Unset or unparsable values give the defaults below.
row of black. 16 BGRA8 pixels are a 64-byte line of the GPU's memory: on
Intel's Vulkan driver a guest surface over the guest's RAM is drawn in
place only where each row starts and ends on a line, and the guest's
desktop surfaces are the mode's width (on an Iris Xe the
desktop surfaces are the mode's width (on homelab-ms01's Iris Xe the
3662-pixel desktop stayed a copy, 2.54 ms of GPU time a plain frame and
3.94 ms a frame that reads its own pixels; the owner's ruling of
2026-11-07 removes the cause). The guest's kext offers a mode HiDPI only
@@ -187,27 +171,6 @@ Unset or unparsable values give the defaults below.
`manual` (choose a smaller mode in the guest's Displays settings: the
window keeps its size, the image fills it, and a click lands under the
pointer)
- On a screen above 1x that guest is offered one larger mode after every
other, at each of their rates: 4/3 of the window's width, rounded down to
a multiple of 16 pixels, its height the window's ratio of that rounded
down to even, where its scanout fits the display's share of the 128 MiB
of scanout and it fits the 24 modes beside every other. The guest's kexts
offer it HiDPI, at half its pixels each way, so a 3840 × 2160 window
offers "looks like 2560 × 1440" at 5120 × 2880, as a Mac offers for an
external 4K screen (from the owner's issue list, item 196, not read on a
Mac of ours). macOS lists no 1x copy of it: "Show all resolutions" in
Displays adds no 5120 × 2880. Every other mode
keeps its place, so the guest keeps the mode it had. At the larger mode
the window keeps its size, and the guest's frame is drawn scaled down to
fill it, filtered linearly; the pointer lands on the guest pixel drawn
under it, and the guest's cursor is drawn at the image's scale.
`test: reims-vgpu-graphics::display::a_dense_screen_s_display_offers_a_larger_mode_after_every_other`,
`test: geometry::a_larger_mode_of_the_window_s_ratio_fills_it`,
`test: reims-vgpu::graphics::sink::a_frame_larger_than_its_place_is_sampled_over_it`,
`test: reims-vgpu::graphics::sink::on_vulkan_a_larger_frame_fills_its_place`,
`manual` (on a 3840 × 2160 window above 1x, choose 2560 × 1440 in the
guest's Displays settings: the window keeps its size, the image fills it,
and a click lands under the pointer)
- That guest is told the scale of the screen the window was last drawn on,
and its display is as dense as that screen, 110 pixels per inch a point
of it. An arm64 guest runs at 1x on a screen at 1x and HiDPI on one above
@@ -239,26 +202,9 @@ Unset or unparsable values give the defaults below.
set to 60 Hz gives the guest 60, not the 120 it offers; where the current
mode gives no rate, the highest of the screen's modes of its size, else
60 Hz. With no host screen (as for a VM started from an ssh shell, with no
window system to reach), 60 Hz. A titled window offers that rate alone.
window system to reach), 60 Hz.
`test: screens::a_screen_runs_at_its_current_mode_s_rate`,
`test: reims-vgpu::graphics::tests::displays::a_borderless_window_s_display_offers_the_rates_of_the_screen_it_fills`,
`manual` (a VM boot from an ssh shell)
- Where a refresh rate is set (`REIMS_VGPU_WINDOW_REFRESH_RATE`, a VM's
`reims-ctl set --refresh-rate`), every display offers the guest each of its
sizes at that one rate and no other, titled or borderless, and its
refreshes run at it once the guest sets it. A rate above the screen's is
lowered to the screen's, which the log says as a warning; one the screen's
rate does not divide judders, as a lower rate the guest picks does
("Borderless"). Unset, the display offers what the entries above and below
say. A guest whose kext was built before the display's rates is offered
the screen's rate alone.
`test: env::the_refresh_rate_is_a_positive_number_of_hertz`,
`test: reims-vgpu-graphics::device::tests::a_display_of_a_set_rate_offers_every_size_at_it_alone`,
`test: reims-vgpu-graphics::device::tests::a_set_rate_above_the_screen_s_is_lowered_to_it`,
`test: reims-vgpu-graphics::device::tests::an_older_kext_is_offered_the_screen_s_rate_whatever_rate_is_set`,
`test: reims-vgpu::graphics::tests::displays::a_display_s_screen_passes_on_the_rate_set_for_it`,
`manual` (a borderless boot on a 120 Hz screen with the rate set to 60, and
one with it set to 120 on a disk new to the display)
## Borderless
@@ -270,27 +216,6 @@ Unset or unparsable values give the defaults below.
- The window takes keys and clicks as a titled one does. `manual`
- When screens change (rearranged, resized, unplugged), each window re-fills
its screen, or the main screen when its own is gone. `manual`
- The guest is offered the refresh rates of the screen the window fills, as a
Mac lists a screen's: each of its sizes at the screen's rate, then again at
each lower rate the screen lists at its size, more than 0.5 Hz apart, the
rate nearer the screen's kept of two closer than that, three rates each at
most with seven sizes. A rate above the screen's own is not offered, as the
host's screen keeps its mode. When the window fills another screen (it
moved, or its own is gone), or the screen's modes change, the guest is
offered that screen's rates. A guest whose kext was built before this is
offered the screen's rate alone.
`test: screens::a_screen_s_rates_are_those_of_its_size`,
`test: reims-vgpu::graphics::tests::displays::a_borderless_window_s_display_offers_the_rates_of_the_screen_it_fills`,
`test: reims-vgpu-graphics::display::rates_closer_than_the_kexts_tolerance_keep_the_one_nearer_the_screen_s`,
`manual` (a borderless boot on a screen of two rates or more)
- Where the guest sets a lower rate, its display runs at it: its frames, its
vertical blanks and the presents answered at them come at that rate, and the
window draws them on the screen at the screen's own, so a rate that does not
divide the screen's judders (the screen shows frames for uneven counts of
its refreshes). Where the screen stops listing the rate, the display runs at
the screen's again at once, and the guest moves to its default mode.
`test: reims-vgpu-graphics::device::tests::a_display_s_refreshes_run_at_the_rate_the_guest_set`,
`manual` (a borderless boot: the guest set to 60 Hz on a 120 Hz screen)
## Pointer
@@ -575,14 +500,9 @@ and QEMU's `usb-tablet`, which has no sideways wheel, gets none of it:
puts it, at the image's scale and clipped to it, and the host's cursor is
invisible over the image. A show, a hide or a glyph change that leaves the
cursor where it was moves nothing. The window's next pointer move gives the
cursor back to the host's pointer. The cursor's changes alone are drawn at
most once a refresh of the window's screen: several inside one refresh are
drawn once, where the guest last put the cursor, at most a refresh after
the window's last draw, and a frame drawn meanwhile shows it there at once.
cursor back to the host's pointer.
`test: handle::the_guest_leads_its_cursor_when_nothing_of_the_window_s_moved_it`,
`test: handle::a_cursor_the_guest_moves_on_its_own_is_the_window_s_to_draw`,
`test: pace::the_cursor_is_drawn_at_most_once_a_refresh`,
`test: native::macos::render::guest_cursor_moves_inside_one_refresh_are_drawn_once`,
`test: reims-vgpu::graphics::tests::the_window_draws_the_cursor_the_guest_moves_on_its_own`,
`test: reims-vgpu::graphics::sink::the_guest_s_cursor_is_drawn_over_the_frame_in_a_pass_of_its_own`,
`test: reims-vgpu::graphics::sink::on_vulkan_the_cursor_s_pass_blends_the_glyph_over_the_frame`,
@@ -625,34 +545,24 @@ runtime's own device. The switches above apply, and `resolution=` too.
Ctrl+C in QEMU's terminal ends QEMU as before. Without a Wayland
compositor or an X server, no window opens, the guest runs headless, and
the reason is logged once. `manual`
- The window system: once, before the first window opens, its GPU is asked
whether it presents to a window of the session's Wayland compositor, and
where it does not, to one of its X server: a window made for the question
and never shown (a `wl_surface` with no role, an unmapped X window), of
which a Vulkan surface is made and asked what the window's swapchain asks
(surface support for its queue family, and the swapchain's format), then
destroyed with the window and its connection, whatever the answer. The X
window is not mapped for the question: KWin shows no X window while every
screen is off, and a bound on its showing refused the X route on a
blanked screen (m3-max-87158, m3-max-87192), where SDL's window opens
once a screen comes on.
Vulkan's per-platform question, which names no window, is not asked: a
laptop's NVIDIA GPU beside the Intel GPU KWin composites on, in a user's
reports, answered it yes for Wayland and no for the window's own surface,
and its window stayed empty. Where it presents to the compositor's window,
SDL picks the window system as it does on its own (Wayland, or XWayland
where the compositor has no fifo-v1); where it does not, the windows open
through X11, XWayland's under a Wayland compositor, where it presents to
the X server's window (that laptop). Where it presents to neither, no
window opens, the guest runs headless, and QEMU's stderr says so in a
`reims-vgpu: no window:` line ("this GPU cannot show a window on this
desktop"): a window it does not present to would stay empty, and on
Wayland would never appear, its task bar entry alone showing. SDL's own
`SDL_VIDEO_DRIVER` still names its driver over the choice. One log line
gives each answer, why each no, and the route taken.
- The window system: before the first window opens, its GPU is asked, with
no window, whether it presents to the session's Wayland compositor, and
where it does not, to its X server (Vulkan's per-platform
presentation-support questions). Where it presents to the compositor, SDL
picks the window system as it does on its own (Wayland, or XWayland where
the compositor has no fifo-v1); where it does not, the windows open through
X11, XWayland's under a Wayland compositor, where it presents to the X
server (a laptop's NVIDIA
GPU beside the Intel GPU KWin composites on, in a user's report). Where it
presents to neither, no window opens, the guest runs headless, and QEMU's
stderr says so in a `reims-vgpu: no window:` line ("this GPU cannot show a
window on this desktop"): a window it does not present to would stay
empty, and on Wayland would never appear, its task bar entry alone
showing. SDL's own
`SDL_VIDEO_DRIVER` still names its driver over the choice. The answers and
the choice are logged.
`test: winsys::the_window_opens_through_a_window_system_its_gpu_presents_to`,
`test: winsys::a_gpu_presenting_to_x11_alone_opens_its_window_through_x11`,
`test: reims-vgpu-vulkan::rt_platform::swapchain::a_device_whose_queue_family_a_wayland_surface_refuses_presents_to_x11_windows_alone`,
`manual` (a window through X11 on an NVIDIA GPU beside the compositor's)
- The title, the first size (a guest point per host point, shrunk to fit
the screen less 48 points for the title bar and a panel, on whole pixels)
@@ -681,17 +591,6 @@ runtime's own device. The switches above apply, and `resolution=` too.
screen rounded to whole points, so its pixels can pass the screen's by one
(3841 × 2161 on a 3840 × 2160 screen at 2.1); the reims-graphics guest is
offered the screen's own 3840 × 2160 (above). `manual`
- A borderless window's screen that SDL lists no rate of but its current one
(on Wayland SDL keeps a screen's current mode alone) takes the rates its
DRM connector lists at the screen's size ("Borderless", above). Each
card's connectors are read as the compositor's last probe left them, with
no new probe, and the one connected connector that lists the screen's size
within 0.5 Hz of its rate is the screen's. Where none does, two do (two
screens of one model at one mode), or a card cannot be opened or read, the
guest is offered the screen's rate alone.
`test: native::linux::connectors::a_screen_takes_the_rates_of_the_one_connector_listing_its_mode`,
`test: native::linux::connectors::two_connectors_listing_the_mode_or_none_give_no_rates`,
`manual` (a borderless boot on Wayland on a screen of two rates)
- On a Windows host a borderless window is SDL's full screen, and it tells
the shell so (`ITaskbarList2::MarkFullscreenWindow`) from when it shows
until it hides at the display's end: a taskbar set to hide itself stays
@@ -936,6 +835,19 @@ runtime's own device. The switches above apply, and `resolution=` too.
GNOME asks once whether the window may take its shortcuts, the answer
kept for the installed app's entry, and Super+Escape gives GNOME its
shortcuts until the window is focused again)
- An additional release shortcut uses at least one modifier and one to three
ordinary keys, and releases as the release chord does. The title names it
in place of the chord, which still works. An empty or invalid setting
leaves the chord alone.
`test: native::sdl_thread::input::a_custom_shortcut_releases_the_grab_and_keeps_its_last_key`,
`test: native::sdl_thread::input::a_custom_shortcut_can_hold_two_regular_keys`,
`test: native::sdl_thread::input::an_invalid_shortcut_keeps_the_default`
- With release on mouse leave on, the mouse leaving the window lifts the held
keys and buttons and releases the keyboard grab until the mouse comes back
or the window next gains the keyboard. The setting also turns off a game's
pointer lock and a drag gone on onto another display.
`test: native::sdl_thread::input::the_mouse_leaving_releases_the_grab_until_it_returns_when_enabled`,
`manual` (move the pointer out of the window and back)
- Scrolling: the wheel's notches, or, where the host takes smooth
scrolling, its lines at 10 points each, in no gesture (SDL gives no
phases); the guest gets the device's own direction.
@@ -949,8 +861,7 @@ runtime's own device. The switches above apply, and `resolution=` too.
the bars and the title bar. Where the guest's
cursor position changes with no pointer move of the window's in the second
before, the window draws the cursor into the image where the guest puts it,
and hides the host's over the image, as on macOS, its changes alone at most
once a refresh of the window's screen.
and hides the host's over the image, as on macOS.
`test: sdl::cursor::a_cursor_is_handed_sdl_at_the_guest_s_size_in_sdl_s_units`,
`test: native::sdl_thread::ui::sdl_draws_a_cursor_at_the_size_it_is_given`,
`test: sdl::cursor::a_glyph_is_resampled_by_nearest_pixel`,
@@ -958,8 +869,6 @@ runtime's own device. The switches above apply, and `resolution=` too.
`test: handle::a_cursor_the_guest_moves_on_its_own_is_the_window_s_to_draw`,
`test: reims-vgpu::graphics::tests::the_window_draws_the_cursor_the_guest_moves_on_its_own`,
`test: reims-vgpu::graphics::sink::on_vulkan_the_cursor_s_pass_blends_the_glyph_over_the_frame`,
`test: pace::the_cursor_is_drawn_at_most_once_a_refresh`,
`test: native::sdl_thread::render::guest_cursor_moves_inside_one_refresh_are_drawn_once`,
`manual` (a Windows host at 150%)
- With several displays' windows open, the cursor is set only by the window
the pointer is in: SDL's cursor is the process's, so another window's guest
@@ -987,9 +896,11 @@ runtime's own device. The switches above apply, and `resolution=` too.
own X11 dialog. zenity's question is a window of another process, which
the window does not own, so the display's end (the guest's own
shutdown, the host's stop) ends it, as Cancel, and none stays on the
screen after the VM. On Windows the system's message box, which the
window owns, its OK named Turn Off, left of Cancel; the display's end
ends it as Cancel too. Turn Off asks the host
screen after the VM. On Windows, Reims-Go can handle the close in its
own dialog with Shut down, Suspend and Cancel. When the handoff is
unavailable, the system shows a message box owned by the window,
with Turn Off left of Cancel. The display's end cancels it as well.
Turn Off asks the host
to end the VM; Cancel, or the question dismissed, leaves the window and
the VM running, nothing held in the guest and the input released. From
the close to the answer nothing of the window's input reaches the guest:
@@ -1039,7 +950,7 @@ runtime's own device. The switches above apply, and `resolution=` too.
`test: present::a_lost_device_s_presenter_is_kept_and_asked_no_more`,
`test: reims-vgpu-vulkan::rt_platform::swapchain::a_lost_device_s_swapchain_makes_no_vulkan_call_but_its_end_s_destroys_on_vulkan`,
`test: reims-vgpu::graphics::rt_window::on_vulkan_a_lost_device_s_sink_asks_for_no_surface`,
`manual` (a boot whose rt device is lost: a UHD 630 under Windows)
`manual` (a boot whose rt device is lost: the Windows mini's UHD 630)
Not on Linux: a menu bar, Dock icon or ⌘Tab entry (the compositor's task
bar shows the window, as `reims-vgpu`), the camera-housing fit, and trackpad
+15
View File
@@ -4,6 +4,8 @@
//! shutdown request with the power-off action, which the guest is not asked about). So the window
//! asks first, in a question of the host OS's own over the window ([`QUESTION`], [`DETAIL`]), with
//! two answers: [`CANCEL`], the default, keeps the VM running, and [`TURN_OFF`] tells the host.
//! A Windows VM started by Reims-Go can hand the question to its client
//! instead. The client then handles the chosen action.
//!
//! **When it asks** ([`Asks::request`]): only where the host would hear of the close, while the
//! window lives (the display's release takes the host's callbacks back) and the host gave a close
@@ -58,6 +60,9 @@ pub(crate) enum Answer {
Cancel,
/// No question could show: nothing happens, as for Cancel, and the OS's side logs why.
Unshown,
/// Reims-Go's dialog handles the close.
#[cfg(target_os = "windows")]
Delegated,
}
/// The process's questions: whether one is open, and whether the person has chosen Turn Off.
@@ -111,6 +116,8 @@ pub(crate) fn answered(answer: Answer) -> bool {
Answer::TurnOff => "the person chose Turn Off: the host turns the VM off",
Answer::Cancel => "the close is cancelled, or its window ended: the host is not told",
Answer::Unshown => "no question showed: the host is not told, and the VM runs on",
#[cfg(target_os = "windows")]
Answer::Delegated => "the close question was handed to Reims-Go",
};
log::info!(target: "reims_vgpu_window", "{said}");
tell
@@ -147,5 +154,13 @@ mod tests {
assert_eq!(unshown.request(true), Step::Ask);
assert!(!unshown.answered(Answer::Unshown));
assert_eq!(unshown.request(true), Step::Ask);
#[cfg(target_os = "windows")]
{
let mut delegated = Asks::default();
assert_eq!(delegated.request(true), Step::Ask);
assert!(!delegated.answered(Answer::Delegated));
assert_eq!(delegated.request(true), Step::Ask);
}
}
}
+562
View File
@@ -0,0 +1,562 @@
//! Collects a window's SDL file or text drop and forwards it to the local host bridge.
use std::fmt::Write as _;
use std::io::{self, Write as _};
use std::net::{SocketAddr, TcpStream};
use std::sync::OnceLock;
use std::sync::mpsc::{self, SyncSender, TrySendError};
use std::time::Duration;
use crate::geometry::{self, Rect};
/// Maximum number of files forwarded in a single drop.
const MAX_DROP_PATHS: usize = 256;
/// Maximum joined UTF-8 text size forwarded in a single drop.
const MAX_DROP_TEXT_BYTES: usize = 128 << 10;
/// Drop contents and guest-image coordinates for one completed host drop.
#[derive(Debug)]
pub(crate) struct DropPayload {
/// Guest display port that received the drop.
pub display_index: u64,
/// Horizontal position, clamped to the guest image.
pub norm_x: f64,
/// Vertical position, clamped to the guest image.
pub norm_y: f64,
/// Whether the original position was inside the guest image.
pub in_image: bool,
/// Host paths in the order SDL delivered them.
pub paths: Vec<String>,
/// Joined text for a drop without files.
pub text: Option<String>,
}
/// Maps a window point to the guest image, using its center when geometry is unavailable.
pub(crate) fn normalize_point(point: Option<(f64, f64)>, image: Rect) -> (f64, f64, bool) {
let Some((x, y)) = point else {
return (0.5, 0.5, false);
};
if ![x, y, image.x, image.y, image.width, image.height]
.into_iter()
.all(f64::is_finite)
|| image.width <= 0.0
|| image.height <= 0.0
{
return (0.5, 0.5, false);
}
(
((x - image.x) / image.width).clamp(0.0, 1.0),
((y - image.y) / image.height).clamp(0.0, 1.0),
geometry::contains(image, (x, y)),
)
}
/// Drop state for one SDL window, active from begin or the first file, text or position.
#[derive(Debug, Default)]
pub(crate) struct DropBatch {
/// Host paths collected for this batch.
paths: Option<Vec<String>>,
/// Nonempty input chunks in delivery order, bounded before joining.
texts: Option<Vec<String>>,
/// Joined bytes consumed, saturated at the limit once a chunk is truncated.
text_bytes: usize,
/// Most recent finite position, in SDL window coordinates.
last_pos: Option<(f64, f64)>,
}
impl DropBatch {
/// Starts a new batch, discarding an unfinished drop.
pub(crate) fn begin(&mut self) {
self.paths = Some(Vec::new());
self.texts = None;
self.text_bytes = 0;
self.last_pos = None;
}
/// Records the most recent usable position.
pub(crate) fn position(&mut self, x: f64, y: f64) {
if x.is_finite() && y.is_finite() {
self.last_pos = Some((x, y));
}
}
/// Accepts a file even if SDL omitted begin, taking its position as a fallback.
pub(crate) fn file(&mut self, path: String, pos: Option<(f64, f64)>) {
if path.is_empty() {
return;
}
let paths = self.paths.get_or_insert_with(Vec::new);
if paths.len() < MAX_DROP_PATHS {
paths.push(path);
}
if self.last_pos.is_none()
&& let Some((x, y)) = pos
{
self.position(x, y);
}
}
/// Collects UTF-8 text up to the byte limit, including separators between chunks.
pub(crate) fn text(&mut self, chunk: String, pos: Option<(f64, f64)>) {
if chunk.is_empty() {
return;
}
if self.last_pos.is_none()
&& let Some((x, y)) = pos
{
self.position(x, y);
}
if self.text_bytes == MAX_DROP_TEXT_BYTES {
return;
}
let separator = usize::from(self.texts.is_some());
let remaining = MAX_DROP_TEXT_BYTES - self.text_bytes - separator;
let texts = self.texts.get_or_insert_with(Vec::new);
if chunk.len() > remaining {
let kept = &chunk[..chunk.floor_char_boundary(remaining)];
if !kept.is_empty() {
texts.push(kept.to_owned());
}
self.text_bytes = MAX_DROP_TEXT_BYTES;
} else {
self.text_bytes += separator + chunk.len();
texts.push(chunk);
}
}
/// Finishes this batch and yields its files or text and normalized drop position.
pub(crate) fn complete(
&mut self,
display_index: u64,
image: Rect,
pos: Option<(f64, f64)>,
) -> Option<DropPayload> {
let point = self.last_pos.take().or(pos);
let paths = self.paths.take().unwrap_or_default();
let texts = self.texts.take();
self.text_bytes = 0;
let text = if paths.is_empty() {
Some(texts.filter(|chunks| !chunks.is_empty())?.join("\n"))
} else {
None
};
let (norm_x, norm_y, in_image) = normalize_point(point, image);
Some(DropPayload {
display_index,
norm_x,
norm_y,
in_image,
paths,
text,
})
}
/// Discards drop contents and position when the window closes.
pub(crate) fn reset(&mut self) {
*self = Self::default();
}
}
/// Appends one quoted string with RFC 8259 escapes.
fn push_json_string(json: &mut String, value: &str) {
json.push('"');
for ch in value.chars() {
match ch {
'"' => json.push_str("\\\""),
'\\' => json.push_str("\\\\"),
'\u{8}' => json.push_str("\\b"),
'\u{c}' => json.push_str("\\f"),
'\n' => json.push_str("\\n"),
'\r' => json.push_str("\\r"),
'\t' => json.push_str("\\t"),
'\0'..='\u{1f}' => {
// Writing to a String is infallible.
let _ = write!(json, "\\u{:04x}", u32::from(ch));
}
_ => json.push(ch),
}
}
json.push('"');
}
/// Encodes a file or text drop as UTF-8 JSON.
pub(crate) fn encode_drop_json(payload: &DropPayload) -> String {
let mut json = format!(
r#"{{"display_index":{},"norm_x":{},"norm_y":{},"in_image":{}"#,
payload.display_index, payload.norm_x, payload.norm_y, payload.in_image,
);
if !payload.paths.is_empty() {
json.push_str(r#","paths":["#);
for (i, path) in payload.paths.iter().enumerate() {
if i != 0 {
json.push(',');
}
push_json_string(&mut json, path);
}
json.push(']');
} else if let Some(text) = &payload.text {
json.push_str(r#","text":"#);
push_json_string(&mut json, text);
}
json.push('}');
json
}
/// Parses the explicit IPv4 loopback endpoint used by the host drop bridge.
fn parse_loopback_drop_url(raw: &str) -> Option<(SocketAddr, String)> {
let rest = raw.strip_prefix("http://127.0.0.1:")?;
let (port, path) = match rest.find('/') {
Some(i) => (&rest[..i], &rest[i..]),
None => (rest, "/v1/host-drop"),
};
if !port.bytes().all(|b| b.is_ascii_digit())
|| path.bytes().any(|b| b.is_ascii_control() || b == b' ')
{
return None;
}
let port: u16 = port.parse().ok()?;
(port != 0).then(|| (SocketAddr::from(([127, 0, 0, 1], port)), path.to_owned()))
}
/// SDL's bounded queue to the HTTP worker.
static DROP_TX: OnceLock<SyncSender<DropPayload>> = OnceLock::new();
/// Starts the HTTP worker when the runtime provides a valid local URL and bearer token.
#[cfg_attr(
not(any(target_os = "linux", target_os = "windows")),
expect(
dead_code,
reason = "only the SDL thread starts the host drop forwarder"
)
)]
pub(crate) fn install_host_drop_forwarder() {
let Ok(url) = std::env::var("REIMS_GO_DROP_URL") else {
return;
};
let Ok(token) = std::env::var("REIMS_GO_DROP_TOKEN") else {
return;
};
if token.is_empty() || token.contains(['\r', '\n']) || DROP_TX.get().is_some() {
return;
}
let Some((addr, path)) = parse_loopback_drop_url(&url) else {
log::warn!(target: "reims_vgpu_window", "ignoring invalid REIMS_GO_DROP_URL");
return;
};
let (tx, rx) = mpsc::sync_channel(16);
match std::thread::Builder::new()
.name("reims-vgpu.drop".into())
.spawn(move || {
for payload in rx {
if let Err(err) = post_loopback_drop(addr, &path, &token, &payload) {
log::warn!(target: "reims_vgpu_window", "could not forward file drop: {err}");
}
}
}) {
Ok(_) => {
let _ = DROP_TX.set(tx);
}
Err(err) => log::warn!(target: "reims_vgpu_window", "could not start drop worker: {err}"),
}
}
/// Enqueues a drop without waiting for network I/O or queue space on the UI thread.
pub(crate) fn submit(payload: DropPayload) {
if let Some(tx) = DROP_TX.get()
&& let Err(TrySendError::Full(_)) = tx.try_send(payload)
{
log::warn!(target: "reims_vgpu_window", "file drop queue is full");
}
}
/// Posts one complete JSON payload to the authenticated IPv4 loopback bridge.
fn post_loopback_drop(
addr: SocketAddr,
path: &str,
token: &str,
payload: &DropPayload,
) -> io::Result<()> {
let mut stream = TcpStream::connect_timeout(&addr, Duration::from_millis(500))?;
stream.set_write_timeout(Some(Duration::from_millis(2000)))?;
let body = encode_drop_json(payload);
write!(
stream,
"POST {path} HTTP/1.1\r\nHost: 127.0.0.1\r\nAuthorization: Bearer {token}\r\n\
Content-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",
body.len()
)?;
stream.write_all(body.as_bytes())
}
/// Offline tests for window drops and the host bridge protocol.
#[cfg(test)]
mod tests {
use super::*;
use std::io::Read;
use std::net::TcpListener;
/// Guest image offset from the window edges.
const IMAGE: Rect = Rect {
x: 10.0,
y: 20.0,
width: 40.0,
height: 80.0,
};
/// Coordinates use half-open image bounds and clamp outside those bounds.
#[test]
fn normalizes_window_points() {
for (point, expected) in [
((20.0, 80.0), (0.25, 0.75, true)),
((10.0, 20.0), (0.0, 0.0, true)),
((50.0, 100.0), (1.0, 1.0, false)),
((0.0, 120.0), (0.0, 1.0, false)),
] {
assert_eq!(normalize_point(Some(point), IMAGE), expected);
}
let center = (0.5, 0.5, false);
for point in [None, Some((f64::NAN, 40.0)), Some((20.0, f64::INFINITY))] {
assert_eq!(normalize_point(point, IMAGE), center);
}
for bad in [0.0, -1.0, f64::NAN, f64::INFINITY] {
for image in [
Rect {
width: bad,
..IMAGE
},
Rect {
height: bad,
..IMAGE
},
] {
assert_eq!(normalize_point(Some((20.0, 80.0)), image), center);
}
}
}
/// Position events override file and completion coordinates, retaining file order.
#[test]
#[allow(clippy::expect_used)]
fn batch_completes_with_latest_position() {
let mut batch = DropBatch::default();
batch.begin();
batch.file("first".into(), Some((50.0, 100.0)));
batch.position(20.0, 80.0);
batch.position(f64::NAN, 90.0);
batch.file("second".into(), Some((40.0, 30.0)));
let p = batch
.complete(42, IMAGE, Some((30.0, 60.0)))
.expect("two files");
assert_eq!(p.display_index, 42);
assert_eq!(p.paths, ["first", "second"]);
assert_eq!((p.norm_x, p.norm_y, p.in_image), (0.25, 0.75, true));
assert!(batch.complete(42, IMAGE, None).is_none());
}
/// Missing begin, invalid file coordinates, completion fallback and reset are independent.
#[test]
#[allow(clippy::expect_used)]
fn handles_partial_batches() {
let mut batch = DropBatch::default();
batch.file("".into(), Some((10.0, 20.0)));
batch.file("first".into(), Some((1.0, f64::NAN)));
batch.file("second".into(), Some((20.0, 80.0)));
batch.file("third".into(), Some((40.0, 30.0)));
let p = batch.complete(1, IMAGE, None).expect("file-only drop");
assert_eq!(p.paths, ["first", "second", "third"]);
assert_eq!((p.norm_x, p.norm_y, p.in_image), (0.25, 0.75, true));
batch.file("abandoned".into(), Some((20.0, 80.0)));
batch.begin();
assert!(batch.complete(1, IMAGE, None).is_none());
batch.file("closed".into(), Some((20.0, 80.0)));
batch.reset();
assert!(batch.complete(1, IMAGE, None).is_none());
batch.position(20.0, 80.0);
assert!(batch.complete(1, IMAGE, None).is_none());
batch.file("next".into(), None);
let p = batch
.complete(2, IMAGE, Some((60.0, 60.0)))
.expect("fresh drop");
assert_eq!((p.norm_x, p.norm_y, p.in_image), (1.0, 0.5, false));
}
/// Oversized drops retain the first 256 paths in order.
#[test]
#[allow(clippy::expect_used)]
fn caps_paths() {
let mut batch = DropBatch::default();
for i in 0..260 {
batch.file(i.to_string(), None);
}
let p = batch.complete(0, IMAGE, None).expect("bounded drop");
assert_eq!(p.paths, (0..256).map(|i| i.to_string()).collect::<Vec<_>>());
}
/// URL drops keep their position and subsequent batches join chunks in order.
#[test]
#[allow(clippy::expect_used)]
fn collects_url_and_multiline_text() {
let mut batch = DropBatch::default();
let url = "https://example.org/路径";
batch.text(url.into(), Some((20.0, 80.0)));
let p = batch.complete(1, IMAGE, None).expect("URL drop");
assert_eq!(p.text.as_deref(), Some(url));
assert!(p.paths.is_empty());
assert_eq!((p.norm_x, p.norm_y, p.in_image), (0.25, 0.75, true));
batch.text("abandoned".into(), None);
batch.begin();
batch.text("one\ntwo".into(), None);
batch.text(String::new(), None);
batch.text("three".into(), None);
let p = batch.complete(1, IMAGE, None).expect("multiline drop");
assert_eq!(p.text.as_deref(), Some("one\ntwo\nthree"));
}
/// A split UTF-8 character ends collection even when a smaller chunk would fit.
#[test]
#[allow(clippy::expect_used)]
fn truncates_text_at_utf8_boundary() {
let mut batch = DropBatch::default();
let prefix = "a".repeat(MAX_DROP_TEXT_BYTES - 6);
batch.text(prefix.clone(), None);
batch.text("界界".into(), None);
batch.text("x".into(), None);
let p = batch.complete(0, IMAGE, None).expect("bounded text drop");
assert_eq!(p.text, Some(format!("{prefix}\n界")));
let prefix = "a".repeat(MAX_DROP_TEXT_BYTES - 3);
batch.text(prefix.clone(), None);
batch.text("界".into(), None);
let p = batch.complete(0, IMAGE, None).expect("two bytes remaining");
assert_eq!(p.text, Some(prefix));
}
/// Files take precedence over text regardless of arrival order.
#[test]
#[allow(clippy::expect_used)]
fn files_take_precedence() {
let mut batch = DropBatch::default();
batch.text("before".into(), None);
batch.file("path".into(), None);
batch.text("after".into(), None);
let p = batch.complete(0, IMAGE, None).expect("mixed drop");
assert_eq!(p.paths, ["path"]);
assert_eq!(p.text, None);
assert!(batch.complete(0, IMAGE, None).is_none());
}
/// Text JSON preserves Unicode and escapes quotes, backslashes and newlines.
#[test]
fn encodes_json_text() {
let p = DropPayload {
text: Some("你好 \"\\\n".into()),
paths: Vec::new(),
..sample()
};
assert_eq!(
encode_drop_json(&p),
concat!(
r#"{"display_index":17,"norm_x":0.25,"norm_y":0.75,"in_image":true,"#,
r#""text":"你好 \"\\\n"}"#,
)
);
}
/// An example drop containing Unicode, delimiters and control characters.
fn sample() -> DropPayload {
DropPayload {
display_index: 17,
norm_x: 0.25,
norm_y: 0.75,
in_image: true,
text: None,
paths: vec![
r"D:\Downloads\测试.pdf".into(),
"\"\u{8}\u{c}\n\r\t\0\u{10}".into(),
],
}
}
/// Checks UTF-8 preservation and each class of RFC 8259 escape.
#[test]
fn encodes_json_paths() {
assert_eq!(
encode_drop_json(&sample()),
concat!(
r#"{"display_index":17,"norm_x":0.25,"norm_y":0.75,"in_image":true,"paths":["#,
r#""D:\\Downloads\\测试.pdf","\"\b\f\n\r\t\u0000\u0010"]}"#,
)
);
}
/// Only the literal loopback host, a numeric nonzero port and a safe path are accepted.
#[test]
fn validates_loopback_urls() {
let addr = SocketAddr::from(([127, 0, 0, 1], 42));
assert_eq!(
parse_loopback_drop_url("http://127.0.0.1:42"),
Some((addr, "/v1/host-drop".into()))
);
assert_eq!(
parse_loopback_drop_url("http://127.0.0.1:42/drop?q=1"),
Some((addr, "/drop?q=1".into()))
);
for raw in [
"https://127.0.0.1:42/drop",
"http://localhost:42/drop",
"http://127.0.0.2:42/drop",
"http://[::1]:42/drop",
"http://127.0.0.1:/drop",
"http://127.0.0.1:0/drop",
"http://127.0.0.1:65536/drop",
"http://127.0.0.1:+42/drop",
"http://127.0.0.1:42@evil/drop",
"http://127.0.0.1:42/a b",
"http://127.0.0.1:42/a\rheader",
"http://127.0.0.1:42/a\nheader",
" http://127.0.0.1:42",
"http://127.0.0.1:42/drop\r\n",
] {
assert!(parse_loopback_drop_url(raw).is_none(), "{raw:?}");
}
}
/// A real loopback peer receives the authenticated request and exact UTF-8 byte count.
#[test]
#[allow(clippy::expect_used)]
fn posts_the_complete_drop_to_loopback() -> io::Result<()> {
let listener = TcpListener::bind((std::net::Ipv4Addr::LOCALHOST, 0))?;
listener.set_nonblocking(true)?;
let payload = sample();
post_loopback_drop(
listener.local_addr()?,
"/custom/drop",
"test-token",
&payload,
)?;
let (mut stream, _) = listener.accept()?;
stream.set_nonblocking(false)?;
stream.set_read_timeout(Some(Duration::from_secs(2)))?;
let mut request = String::new();
stream.read_to_string(&mut request)?;
let (headers, body) = request.split_once("\r\n\r\n").expect("HTTP headers");
assert_eq!(headers.lines().next(), Some("POST /custom/drop HTTP/1.1"));
for field in [
"Host: 127.0.0.1",
"Authorization: Bearer test-token",
"Content-Type: application/json",
"Connection: close",
] {
assert!(headers.lines().any(|line| line == field), "{field}");
}
assert!(
headers
.lines()
.any(|line| line == format!("Content-Length: {}", body.len()))
);
assert_eq!(body, encode_drop_json(&payload));
Ok(())
}
}
+57 -43
View File
@@ -6,14 +6,21 @@
//! - `REIMS_VGPU_WINDOW_SCREENS`: a comma-separated list of host screen indices (spaces
//! allowed): display i opens on the screen the list's i-th entry names. One bad entry unsets
//! the whole list. Default: display i on screen i (`screens::pick_screen`).
//! - `REIMS_VGPU_WINDOW_REFRESH_RATE`: a refresh rate in hertz, above 0 and at most 1000, such
//! as `60` or `59.94`: each window's display offers every size at that one rate alone, at most
//! its screen's (reims-vgpu-graphics' `Screen::fixed_rate`), titled or borderless. Default: the
//! screen's rates.
//! - `REIMS_VGPU_WINDOW_IMPL`: on macOS, `sdl`, in any case, opens SDL3's window (`sdl`) in
//! place of AppKit's, in a build with the `macos-sdl` feature, on by default (one without it
//! logs that, and opens AppKit's). Default: AppKit's. Linux has SDL3's alone, and reads no
//! value.
//! - `REIMS_VGPU_WINDOW_CAPTURE`: `0`, `false`, `no` or `off`, in any case, turns capture off:
//! the window leaves the keyboard and pointer ungrabbed. `1`, `true`,
//! `yes` or `on` turns it on. Default: [`CAPTURE_DEFAULT`]. reims-ctl sets it from a VM's
//! settings.
//! - `REIMS_VGPU_WINDOW_FIXED_MODE`: `1`, `true`, `yes` or `on`, in any case, decouples the
//! guest's display mode from the window's pixel size so the display keeps offering the
//! configured resolution (e.g. 5120x2880 HiDPI supersampled into a 4K borderless window) and
//! scales the frame on the GPU. Default: off.
//! - `REIMS_VGPU_WINDOW_RELEASE_KEYS`: an additional release shortcut for SDL's windows on
//! Windows and Linux, such as `Ctrl+Shift+F12`. Reims-Go's capture shortcut plugin can supply
//! it through its own namespace. The built-in release chord remains available.
use std::sync::OnceLock;
@@ -23,10 +30,20 @@ pub const BORDERLESS_VAR: &str = "REIMS_VGPU_WINDOW_BORDERLESS";
pub const SCREENS_VAR: &str = "REIMS_VGPU_WINDOW_SCREENS";
/// The window implementation's variable (macOS).
pub const IMPL_VAR: &str = "REIMS_VGPU_WINDOW_IMPL";
/// The set refresh rate's variable.
pub const REFRESH_RATE_VAR: &str = "REIMS_VGPU_WINDOW_REFRESH_RATE";
/// The highest refresh rate the variable takes, in hertz.
pub const REFRESH_RATE_MAX_HZ: f64 = 1000.0;
/// The capture switch's variable.
pub const CAPTURE_VAR: &str = "REIMS_VGPU_WINDOW_CAPTURE";
/// The fixed guest mode switch's variable.
pub const FIXED_MODE_VAR: &str = "REIMS_VGPU_WINDOW_FIXED_MODE";
/// The extra release shortcut for Windows and Linux SDL windows.
pub const RELEASE_KEYS_VAR: &str = "REIMS_VGPU_WINDOW_RELEASE_KEYS";
/// The same shortcut supplied through the Reims-Go capture shortcut plugin.
const PLUGIN_RELEASE_KEYS_VAR: &str = "REIMS_PLUGIN_LOCAL_CAPTURE_SHORTCUT_KEYS";
/// The plugin's switch for releasing input when the mouse leaves the window.
const PLUGIN_RELEASE_ON_LEAVE_VAR: &str = "REIMS_PLUGIN_LOCAL_CAPTURE_SHORTCUT_RELEASE_ON_LEAVE";
/// Whether the window may grab the keyboard and lock the game pointer by default.
pub const CAPTURE_DEFAULT: bool = true;
/// What the variables say.
#[derive(Clone, Debug, PartialEq)]
pub struct Settings {
@@ -36,8 +53,14 @@ pub struct Settings {
pub screens: Vec<usize>,
/// Which window a display opens on macOS.
pub window_impl: WindowImpl,
/// The one refresh rate each display offers, in thousandths of a hertz; `None` when unset.
pub refresh_mhz: Option<u32>,
/// Whether the window may grab the keyboard and lock the game pointer.
pub capture: bool,
/// Keep offering the configured guest resolution instead of following the window's pixels.
pub fixed_mode: bool,
/// Additional release shortcut text for the SDL window.
pub release_keys: Option<String>,
/// Release input when the mouse leaves the SDL window.
pub release_on_leave: bool,
}
impl Default for Settings {
@@ -46,7 +69,10 @@ impl Default for Settings {
borderless: false,
screens: Vec::new(),
window_impl: WindowImpl::AppKit,
refresh_mhz: None,
capture: CAPTURE_DEFAULT,
fixed_mode: false,
release_keys: None,
release_on_leave: false,
}
}
}
@@ -79,21 +105,6 @@ pub fn parse(borderless: Option<&str>, screens: Option<&str>) -> Settings {
}
}
/// A refresh rate in hertz, spaces aside, in thousandths of a hertz: `None` for one that is not
/// a number above 0 and at most [`REFRESH_RATE_MAX_HZ`].
pub fn parse_refresh_rate(value: Option<&str>) -> Option<u32> {
let hz = value?.trim().parse::<f64>().ok()?;
if !(hz.is_finite() && hz > 0.0 && hz <= REFRESH_RATE_MAX_HZ) {
return None;
}
#[expect(
clippy::as_conversions,
reason = "a rate above 0 and at most 1000 Hz, rounded to nearest: at most 1 000 000"
)]
let mhz = (hz * 1000.0).round() as u32;
(mhz > 0).then_some(mhz)
}
/// Whether a switch's value turns it on.
fn parse_switch(value: &str) -> bool {
let value = value.trim();
@@ -110,6 +121,20 @@ fn parse_screens(value: &str) -> Option<Vec<usize>> {
.collect()
}
/// Whether the window may grab the keyboard and lock the game pointer. Default on.
pub fn parse_capture(value: Option<&str>) -> bool {
value.is_none_or(|value| {
!["0", "false", "no", "off"]
.iter()
.any(|off| value.trim().eq_ignore_ascii_case(off))
})
}
/// Whether fixed guest mode is on (`1`, `true`, `yes` or `on`, in any case); default off.
pub fn parse_fixed_mode(value: Option<&str>) -> bool {
value.is_some_and(parse_switch)
}
/// The process's settings, read from its environment the first time they are asked for. A
/// value that is not UTF-8 counts as unset.
pub fn settings() -> &'static Settings {
@@ -119,7 +144,12 @@ pub fn settings() -> &'static Settings {
let (borderless, screens) = (var(BORDERLESS_VAR), var(SCREENS_VAR));
Settings {
window_impl: parse_impl(var(IMPL_VAR).as_deref()),
refresh_mhz: parse_refresh_rate(var(REFRESH_RATE_VAR).as_deref()),
capture: parse_capture(var(CAPTURE_VAR).as_deref()),
fixed_mode: parse_fixed_mode(var(FIXED_MODE_VAR).as_deref()),
release_keys: var(RELEASE_KEYS_VAR).or_else(|| var(PLUGIN_RELEASE_KEYS_VAR)),
release_on_leave: var(PLUGIN_RELEASE_ON_LEAVE_VAR)
.as_deref()
.is_some_and(parse_switch),
..parse(borderless.as_deref(), screens.as_deref())
}
})
@@ -163,22 +193,6 @@ mod tests {
}
}
/// The refresh rate is a number of hertz above 0 and at most 1000, decimals and spaces
/// allowed; anything else is unset
#[test]
fn the_refresh_rate_is_a_positive_number_of_hertz() {
assert_eq!(parse_refresh_rate(Some("60")), Some(60_000));
assert_eq!(parse_refresh_rate(Some(" 120 ")), Some(120_000));
assert_eq!(parse_refresh_rate(Some("59.94")), Some(59_940));
assert_eq!(parse_refresh_rate(Some("1000")), Some(1_000_000));
assert_eq!(parse_refresh_rate(None), None);
for bad in [
"", "0", "-60", "0.0001", "1000.5", "nan", "inf", "60Hz", "sixty", "6O",
] {
assert_eq!(parse_refresh_rate(Some(bad)), None, "{bad:?}");
}
}
/// The window is AppKit's unless the variable names SDL3's
#[test]
fn the_window_is_appkits_unless_sdl_is_named() {
+3 -59
View File
@@ -7,9 +7,8 @@
//!
//! The image is the guest mode aspect-fit into the view, less its insets (a screen's camera
//! housing), centred between black bars; a guest mode of the view's ratio to within its steps (a
//! smaller mode the reims-graphics display offers, or its larger one, `reims-vgpu-graphics`'
//! `display::offered_modes`) fills it. It is fitted in the drawable's pixels, so its edges fall on
//! whole pixels, and
//! smaller mode the reims-graphics display offers, `reims-vgpu-graphics`' `display::offered_modes`)
//! fills it. It is fitted in the drawable's pixels, so its edges fall on whole pixels, and
//! [`Layout::image`] is that pixel rectangle again in points. The pointer is mapped through the
//! same rectangle, so the guest pixel under the host's pointer is the one drawn there, and the
//! guest's cursor is drawn at the image's scale ([`cursor_points_per_pixel`]).
@@ -19,7 +18,7 @@
//! surface over the guest's RAM is drawn in place only where each of its rows starts and ends on
//! a line of the GPU's memory: on Intel's Vulkan driver (ANV) a render pass writes back whole
//! 64-byte lines, so the bytes past a row's last pixel on its last line would be written too.
//! 16 pixels are 64 bytes. Measured by metal2vulkan's lane on an Iris Xe
//! 16 pixels are 64 bytes. Measured by metal2vulkan's lane on homelab-ms01's Iris Xe
//! (2026-11-07): the guest's 3662-pixel desktop surface, 14648 bytes a row (ending 56 bytes
//! into a line), stayed a copy of the guest's pages, 2.54 ms of the GPU's time a plain frame and
//! 3.94 ms a frame that reads its own pixels. Padding a row's bytes alone does not help: the
@@ -658,61 +657,6 @@ mod tests {
);
}
/// A mode larger than the window, of its ratio as the reims-graphics display offers it (the
/// backing of a HiDPI mode: 4/3 of the window's width, a multiple of 16, and the ratio's
/// height rounded down to even, 5120 × 2880 for 3840 × 2160), fills the window that keeps its
/// size, on a window whose pixels are a mode's and on a borderless one a pixel past it; the
/// pointer maps through it to the guest pixel drawn under it, and the guest's cursor is drawn
/// at its scale, less than a drawable pixel a guest pixel
#[test]
fn a_larger_mode_of_the_window_s_ratio_fills_it() {
let whole = |width, height| PixelRect {
x: 0,
y: 0,
width,
height,
};
for (window, larger) in [
((3840, 2160), (5120, 2880)),
((3840, 2400), (5120, 3200)),
((1920, 1080), (2560, 1440)),
((1712, 1148), (2272, 1522)),
((3456, 2234), (4608, 2978)),
((1080, 1920), (1440, 2560)),
] {
for scale in [1.0, 2.0] {
let bounds = (window.0 as f64 / scale, window.1 as f64 / scale);
let l = layout(bounds, scale, NO_INSETS, Some(larger));
assert_eq!(
l.pixels,
whole(window.0, window.1),
"{larger:?} in {window:?}"
);
let far = (bounds.0 - 0.1, bounds.1 - 0.1);
let at = pointer_to_guest(far, l.image, larger);
assert_eq!(at, (larger.0 - 1, larger.1 - 1), "{larger:?} in {window:?}");
let mid = (bounds.0 / 2.0, bounds.1 / 2.0);
assert_eq!(
pointer_to_guest(mid, l.image, larger),
(larger.0 / 2, larger.1 / 2),
"{larger:?} in {window:?}"
);
let per_pixel = cursor_points_per_pixel(l.image, larger);
let want = window.0 as f64 / scale / f64::from(larger.0);
assert!((per_pixel - want).abs() < 1e-9, "{larger:?} in {window:?}");
assert!(per_pixel * scale < 1.0, "{larger:?} in {window:?}");
}
}
// Borderless at 2.1 on a 3840 × 2160 screen, 3841 × 2161 pixels: filled.
let l = layout(
(1829.0, 1029.0),
3841.0 / 1829.0,
NO_INSETS,
Some((5120, 2880)),
);
assert_eq!(l.pixels, whole(3841, 2161));
}
/// With no guest mode yet, the image is the whole area inside the insets
#[test]
fn with_no_mode_the_image_is_the_inset_area() {
+21 -1
View File
@@ -98,6 +98,8 @@ pub fn pointer_outside_image(dragging: bool) -> bool {
/// Whether the window holds the keyboard grab (the module doc).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Grab {
/// The VM's capture setting rejects the keyboard grab.
disabled: bool,
/// The release chord gave the shell its keys, until the window next gains the keyboard.
released: bool,
}
@@ -108,10 +110,18 @@ impl Grab {
Grab::default()
}
/// The VM keeps the host's keyboard shortcuts.
pub fn disabled() -> Grab {
Grab {
disabled: true,
..Grab::default()
}
}
/// Whether the window on `host` asks for the keyboard grab: where its OS takes one, until the
/// release chord (the module doc). The OS holds it only while the window has the keyboard.
pub fn holds_keyboard(&self, host: HostOs) -> bool {
host.grabs_the_keyboard() && !self.released
host.grabs_the_keyboard() && !self.disabled && !self.released
}
/// The window gained the keyboard: the grab is held again after a release. Whether it was
@@ -164,6 +174,16 @@ mod tests {
assert!(!grab.holds_keyboard(HostOs::MacOs));
}
#[test]
fn a_disabled_keyboard_grab_stays_disabled_after_refocusing() {
let mut grab = Grab::disabled();
assert!(!grab.holds_keyboard(HostOs::Windows));
grab.release();
grab.focus_gained();
assert!(!grab.holds_keyboard(HostOs::Windows));
assert!(!grab.release_chord(CHORD, HostOs::Windows, false));
}
/// ⌃⌥⌘ together, with or without Shift, gives the shell its keys until the window next
/// gains the keyboard; fewer keys do not; once released, the chord releases nothing more
/// but a game's lock
+5 -43
View File
@@ -37,8 +37,7 @@
//! else moves it: a mouse the host passed through to the guest, which the host's pointer never
//! sees, or the guest placing its own. The window then draws the guest's cursor into its image
//! itself, at the place it was told ([`DrawnCursor`], which the render thread hands the sink with
//! each draw), each change drawing again at most once a refresh of the window's screen, where the
//! guest last put it (`crate::pace`), and the host's cursor is invisible over the image. The
//! each draw), each move drawing again, and the host's cursor is invisible over the image. The
//! window's next pointer event gives the cursor back to the host's pointer. A move the guest
//! reports soon after a pointer event of the window's is the guest following it, however late its
//! report comes within that time.
@@ -54,8 +53,6 @@ pub use crate::present::FrameSink;
use crate::config::{WindowCallbacks, WindowConfig};
use crate::native::{self, Surface};
use crate::pace;
use crate::screens::HostScreen;
/// The next window's id.
static NEXT_ID: AtomicU64 = AtomicU64::new(1);
@@ -248,9 +245,6 @@ pub struct Window {
guest: Mutex<GuestState>,
/// The first mode the display offers the guest, once it offers one.
offered: Mutex<Option<(u16, u16)>>,
/// The host screen a borderless window fills, as the OS's side last found it
/// ([`Window::filled_screen`]); `None` for a titled window.
filled: Mutex<Option<HostScreen>>,
/// What draws the display's frames, once the display exists.
sink: Mutex<Option<Arc<dyn FrameSink>>>,
/// Set at the window's end.
@@ -304,7 +298,6 @@ impl Window {
callbacks: Mutex::new(Some(config.callbacks)),
guest: Mutex::new(GuestState::default()),
offered: Mutex::new(None),
filled: Mutex::new(None),
sink: Mutex::new(None),
closed: AtomicBool::new(false),
attached: AtomicBool::new(false),
@@ -407,7 +400,7 @@ impl Window {
};
self.post_cursor_refresh();
if drawn {
self.surface.request_cursor_draw();
self.surface.request_draw();
}
}
@@ -427,15 +420,14 @@ impl Window {
};
self.post_cursor_refresh();
if drawn {
self.surface.request_cursor_draw();
self.surface.request_draw();
}
}
/// The guest put its cursor's hot spot at `at`, in its mode's pixels (a display's move of the
/// guest's cursor): where it moved, with no pointer event of the window's in the
/// [`POINTER_LEADS_FOR`] before, the window draws the guest's cursor there, and hides the
/// host's over the image (the module doc). Each move then draws again, at most once a refresh
/// of the window's screen (`crate::pace`).
/// host's over the image (the module doc). Each move then draws again.
pub fn cursor_at(&self, at: (u16, u16)) {
let (changed, drawn) = {
let mut guest = self.guest.lock();
@@ -452,7 +444,7 @@ impl Window {
self.post_cursor_refresh();
}
if drawn {
self.surface.request_cursor_draw();
self.surface.request_draw();
}
}
@@ -537,36 +529,6 @@ impl Window {
pub fn keeps_its_size(&self) -> bool {
self.keeps_its_size
}
/// The host screen the window fills where it is borderless, as the OS's side last found it:
/// at its opening, and each time the screens change or it moves to another screen. Its rate
/// and the other rates it lists are those the display offers its guest; `None` for a titled
/// window, whose display offers the rate of the screen it opened on alone, and before a
/// borderless one opens.
pub fn filled_screen(&self) -> Option<HostScreen> {
self.filled.lock().clone()
}
/// The OS's side found the borderless window filling `screen` (or no screen it knows), as it
/// tells at the window's opening and when the window fills another screen; a test of the
/// display stands in for it. The guest's cursor's changes are drawn at most once a refresh
/// of that screen (`crate::pace`).
pub fn fills(&self, screen: Option<HostScreen>) {
if let Some(s) = &screen {
self.surface.set_refresh(pace::refresh_of(s.refresh_hz));
}
*self.filled.lock() = screen;
}
/// The display was told the window's screen runs at `mhz` thousandths of a hertz (the screen
/// it opens on): the guest's cursor's changes are drawn at most once a refresh of it
/// (`crate::pace`), until the window fills a screen ([`Window::fills`]), whose rate it takes.
pub fn screen_refresh(&self, mhz: u32) {
if self.filled.lock().is_none() {
self.surface
.set_refresh(pace::refresh_of(f64::from(mhz) / 1000.0));
}
}
}
/// What the window's backend reads of it.
+2 -1
View File
@@ -59,7 +59,6 @@ pub mod handle;
pub mod keymap;
pub mod keys;
mod native;
mod pace;
mod present;
pub mod screens;
pub mod scroll;
@@ -69,6 +68,8 @@ pub mod winsys;
// The SDL3 window: Linux's and Windows's (`native/sdl_thread.rs`), and macOS's with the
// `macos-sdl` feature, behind `REIMS_VGPU_WINDOW_IMPL`.
#[cfg(any(target_os = "linux", target_os = "windows", feature = "macos-sdl"))]
mod drop;
#[cfg(any(target_os = "linux", target_os = "windows", feature = "macos-sdl"))]
mod sdl;
pub use config::{
Loaded 100 of 239 files, more files were not shown because too many files have changed in this diff. Show more