Compare commits

...
Author SHA1 Message Date
Anees Iqbal e8cabf95a1 ✅ Hold stage-in on a Mac's Intel GPU to the quotient
test_stage_in_matches_metal runs on every GPU of the Mac since the commit
before. On a UHD 630 under macOS 26.7.1 (a probe of all 65 cases, every thread
compared), 56 cases match Metal's [[stage_in]] kernel bit for bit and 9 do not:

- The unsigned 8-bit normalized formats (UCharNormalized to UChar4Normalized,
  UChar4Normalized_BGRA; 6 cases): Metal's lane is the code times f32(1/255)
  in every lane, where the M3's Metal answers the correctly rounded quotient,
  and ours is within 1 ULP of that quotient in every lane. On a Mac's own
  Intel GPU, a component lane of ours that differs from Metal's now passes
  within 1 ULP of the quotient the test computes on the CPU, the M3's answer,
  and each case that used this prints a line with the count of such lanes.
- Int1010102Normalized: on this GPU our lanes read as the unmasked word; the
  M3 and our device are exact.
- UInt1010102Normalized: far off on this GPU, cause not found; the M3 and our
  device are exact.
- FloatRG11B10: this GPU's Metal answers 2^31 for a NaN code; the M3's quiet
  NaN is the reference.

Those three formats are not compared on a Mac's own Intel GPU: each case still
makes and runs both pipelines, and prints a SKIP line with its reason. Every
other lane on every GPU stays bit for bit, and the lowering does not change.

The GPU is told apart as in the commit before: the PCI vendor-id, 0x8086,
read from the IORegistry upward from the device's registryID (the probe read
0x8086 on the UHD 630 and 0x1002 on the Radeon Pro 5300M), never on our
device. Test code only.
2026-12-05 03:26:16 -08:00
Anees Iqbal 9a5ad80ab7 ✅ Run stage-in on each GPU; skip compare on a Mac's AMD
test_stage_in_matches_metal ran on MTLCreateSystemDefaultDevice alone, which
on a Mac with two GPUs is the discrete one, so the integrated GPU never ran its
cases. It now runs them on every device MTLCopyAllDevices lists.

On a Mac's own AMD GPU, our specialized stage input kernel's lanes 2 and 3
read 0 where Metal's [[stage_in]] kernel fetches the attribute's values or its
fill (measured on a Radeon Pro 5300M under macOS 26.7.1, at every thread from
the first case on). The lowering's IR stores every lane, and the M3 matches
Metal on all 65 cases, so the cause lies past our IR; the row is parked. A
test that fails run after run is disabled where it fails, visibly: on such a
GPU every case still makes Metal's pipeline and ours and runs them, but the
lanes are not compared, and the test prints a SKIP line naming the reason and
the parked row. Every other device, our device in a guest among them, compares
every case as before; nothing is loosened.

The GPU is told apart by the IORegistry, not by its name: the PCI vendor-id
(0x1002) of the device's registry entry, found by its registryID, or of the
nearest entry above it in the service plane, which is the PCI device its driver
matched. Apple's own GPUs have none and answer 0. Our device is ruled out
first, by its class. Each device ends with a line counting the cases compared.
Test code only.
2026-12-05 03:26:16 -08:00
Anees Iqbal 750a6d09fd ✅ Take any NaN for a guest's half and RG11B10 stage-in
test_stage_in_matches_metal compares, bit for bit, what our specialized
stage input fetch stores with what Metal's own [[stage_in]] kernel stores on
the same device. In an x86 guest on a Radeon 780M (one boot, 65 cases), 64
cases matched on every thread. The FloatRG11B10 case differed only in NaN
lanes: through the guest's device, Metal's fetch (metal2vulkan's runtime)
kept the small float's mantissa as the NaN's payload (0x7fe80000, 0x7fd00000),
where ours stores the quiet NaN 0x7fc00000.

NaN bits are the device's own answer under the contract (AGENTS.md, "The
contract"), and the runtime records PrecisionNote::DeviceNanEncoding for
every fetch of a 16-bit float or FloatRG11B10 attribute read as float lanes.
So on our device, in a guest, a lane of a Half to Half4 or FloatRG11B10 case
where Metal's is a NaN now matches any NaN of ours; every other lane, and
every lane of every case on a Mac's own Metal device, stays bit for bit.

Our device is told apart by its class: RgfxMetalDevice, the bundle's device
shell, which tools/cb_probe.m and tools/surface_probe.m find it by. The test
binary links no device shell, so the class exists only where Metal loaded
the bundle; no Mac's own device is one, whatever its name. Test code only.
2026-12-05 03:26:16 -08:00
Anees Iqbal 84c88597a8 ✅ Ask forwardProgressUsage only where Metal has it
test_pipeline_state_members expected a compute pipeline state made from an
Automatic descriptor to answer Weak for forwardProgressUsage, as macOS 27.0.1
answers. The state reads the member only where the guest's
MTLComputePipelineDescriptor responds to it, and macOS 26.7.1's does not, so
there it answers Automatic (0) and the check failed on an x86-64 Mac, stopping
the shell tests at rgfxProtocolTests.

Where the guest's release lacks the member, no program of that release can set
or read it, so the answer there is not observable. The check now asks it only
where the descriptor responds to forwardProgressUsage, as the shell tests' own
forwardProgressUsage checks already do, and expects Weak there as before. Test
code only; the bundle is unchanged.
2026-12-05 03:26:16 -08:00
Anees Iqbal 6c38355e24 ✅ Pin a dylib's write onto a directory to 27's error
test_dynamic_library_routing compared each refused serializeToURL: with the
error Foundation's atomic write answers on the Mac that runs it. At a directory
at the path, the dynamic library answers macOS 27.0.1 Foundation's error there
(writeError: NSCocoaErrorDomain 4, NSFileNoSuchFileError over ENOENT), but
macOS 26.7.1's Foundation answers 512, NSFileWriteUnknownError, "couldn't be
saved in the folder". So on an x86-64 Mac on 26.7.1 the check failed, and the
shell tests stopped there with 141 of their test functions unrun.

The guest takes the latest release's answers on every release, so that case
now expects the dynamic library's own answer, on every Mac: domain and code,
the path, its file URL and the POSIX cause, and no other key. The read-only
folder and the name too long still compare with this Mac's Foundation, which
answers alike on 26.7.1 and 27. Test code only; the bundle is unchanged.
2026-12-05 03:26:16 -08:00
Anees Iqbal 3f8a0945c5 ✅ Reach the three-channel death check on macOS 26
The shell tests' death case texture-three-channel made its descriptor with
texture2DDescriptorWithPixelFormat:, whose pixelFormat setter on the x86 Macs'
macOS 26.7.1 ends the process at a three-channel format ("pixelFormat (45) is
not a valid MTLPixelFormat.", docs/graphics-kext/dgpu-oracle.md, Q12) before
the heap's creator sees it. The case expects the creator's validation words,
which macOS 27 on Apple silicon reaches, so on an x86-64 Mac the case failed
and the shell tests stopped there, leaving the cases after it unrun.

The case now builds its descriptor with neither the factory nor the setter:
a plain descriptor of 64 x 64 Private, whose class is swapped for a subclass
that answers 45 at the pixelFormat getter, which the creators' validation
reads. It reaches the heap's validation and expects the same words on every
Mac. Test code only; the bundle is unchanged.
2026-12-05 03:26:15 -08:00
Anees Iqbal d3a3a3000f 📝 Name the hardware, not the lab's machines, in comments and docs
Comments, docs and tests attributed measurements and readings to the lab's
own host names. A reader outside the lab learns nothing from a host name, and
the hosts' cards move between them, so the name stops saying which card a
number came from. Each such attribution now names what the reading depends
on, as the text around it states it: the card and its driver, the CPU, the
SSD or the screen. Potluck job ids stay.

Three test helpers and the locals that held their lists, named for the host
they were read on, are renamed for the hardware they model. Their lists and
every check are unchanged.

Text that says where a check or a boot runs is left as it is, and so are the
comments in guest sources that the prebuilt kext sets record by hash, which
would need both sets rebuilt.
2026-12-05 01:48:14 -08:00
Anees Iqbal 6bbcb4f69f ⬆️ Build on metal2vulkan development 08848fd8a5
Pin AF, from b0c9c9f0c9 (AE): 6 commits. SEMANTICS_VERSION 2397,
ARTIFACT_FORMAT_VERSION 618 and RUNTIME_VERSION 2580 are unchanged, so no
state is translated again.

The move alone. What it changes for the guest:
- A content's later pipelines (its line, point and raster states) are made in
  cells of their own outside the content map's lock, so a draw of one class
  no longer waits behind another thread's make of a different class. A draw
  that waits on another thread's make of its own class counts as a first-use
  wait at its site.
No public API that this tree names changes, so no call site here changes.
2026-12-05 01:03:39 -08:00
Anees Iqbal e107fb4a6e 🆕 Write rt's 4:2:2 and encode-time makes in the summary's rt part
The camera's first-open stall work needs these numbers in users' logs: the
stall at a preview layer's first open is the makes at encode of the contents
rt lowers for a 4:2:2 texture, and nothing the host wrote counted them. rt
prints no summary of its own, so the rt part now carries them, read from the
device's counters:
- the makes at encode (all six kinds, made or refused) since the line before,
  their time in ms and the longest since the device was made;
- the contents made for a 4:2:2 texture and the draws and dispatches that ran
  one, since the line before, and the 4:2:2 textures alive now. This clause is
  left out where none was made or ran and none lives, as the over-copy causes
  are, so a camera closed reads as none and a texture left alive shows.

Where the contents' rise equals the makes' rise, the whole time is 4:2:2.
A diagnostic, free under the contract.
2026-12-05 00:09:54 -08:00
Anees Iqbal 8fdbb5b1f2 ⬆️ Build on metal2vulkan development b0c9c9f0c9
Pin AE, from ea428bca8b (AC): 17 commits. SEMANTICS_VERSION 2397 (from
2395), so a guest's states are translated again on their first boot;
ARTIFACT_FORMAT_VERSION 618 and RUNTIME_VERSION 2580 are unchanged.

The move alone. What it changes for the guest:
- A 4:2:2 texture's decode is smaller: it clamps its taps to the edge, fetches
  each row once and gives a constexpr sampler its one filter. A camera
  preview layer's first open holds frames about a second on a Radeon 780M
  (RADV) with a cold driver cache, where it held them about 1.6 s; its state's
  driver make takes 870 ms where it took 1438 ms. A second open waits for
  nothing.
- A speculated load through a wide pointer is checked against its binding's
  slot, so it no longer reads outside a short binding.
- rt counts the total time of its makes at encode
  (Metrics::translation_at_encode_nanos), which the host's summary can print.
No public API that this tree names changes, so no call site here changes.
2026-12-05 00:08:59 -08:00
Anees Iqbal c9bab26a5b ⬆️ Build on metal2vulkan development ea428bca8b
Pin AC, from 9e7034c214 (AB): 52 commits, through AB' (PR 30 and its
fix-forwards). SEMANTICS_VERSION 2395, ARTIFACT_FORMAT_VERSION 618,
RUNTIME_VERSION 2580 (from 2390, 616 and 2579).

The move alone. What it changes for the guest:
- 4:2:2 textures (GBGR422 and BGRG422) are made in place over their bytes and
  decoded as Metal decodes them, by functions lowered for their bindings, where
  rt refused the format before; a passed-through camera's 'yuvs' frames now
  reach the guest's preview layers. While a 4:2:2 texture lives, a state that
  reaches a float texture through a handle is lowered again once at its next
  draw or dispatch.
- Behind the agx flag, a fragment input of more or fewer components than its
  vertex output links as Metal links it, where rt refused the pair.
- A sampler of two filters on a texture of one level filters as Metal chooses.
- The translator accepts memory intrinsics declared with an alignment operand,
  and refuses a malformed one as a malformed record (PR 30).
No public API that this tree names changes, so no call site here changes.
2026-12-04 21:57:39 -08:00
Anees Iqbal b98ed24d1b 🐎 Draw the guest's cursor at most once a refresh
What changes for the host: where the window draws the guest's cursor (the
guest leads it: a mouse passed through to the guest, or scripted input), a
change of the cursor alone now draws the window at most once a refresh of
the window's screen. Several moves inside one refresh are drawn once, where
the guest last put the cursor; a frame, a layout or the window showing again
still draws at once, with the cursor where it is then.

The trade: in the guest-led case the cursor shows at most one refresh later
than the guest put it, against whole draws that no screen shows. Each move
asked for a draw of the whole image, and the swapchain presents MAILBOX
where offered, so nothing paced them: a scripted drag of 1620 moves at 125 a
second drew 1620 frames more than the guest presented, 78 to 145 ms of GPU a
second on a Radeon 780M (RADV) and an Iris Xe (ANV).

The refresh is the window's screen's: the one a borderless window fills,
else the one the display is told at its make, else 60 Hz (crate::pace). It
is the same on every host and present mode, with no setting. The window's
own pointer path is untouched: its moves draw nothing of the cursor (the
host's cursor shows the glyph over the image), and its pointer event that
takes the cursor back still draws at once.

The test of the previous commit now passes; it reads the crate's clock in
place of Instant::now, which clippy.toml disallows, and is rustfmt's.
2026-12-04 21:45:11 -08:00
Anees Iqbal 225c021c3e ✅ Count the window's draws for guest cursor moves
Where the guest moves its cursor on its own (a mouse passed through to the
guest, or scripted input), the window draws the cursor itself, and each move
asks the render thread for a whole draw. The swapchain presents MAILBOX where
offered, so nothing paces those draws: a scripted drag of 1620 moves at 125 a
second drew the window 1620 times more than the guest presented, 78 to 145 ms
of GPU a second on a Radeon 780M (RADV) and an Iris Xe (ANV) that no screen
shows.

The test moves the guest's cursor eight times inside one refresh of the
window's screen and counts the render thread's draws, on each window
implementation's surface (SDL's on Linux and Windows, the macOS one). It
fails here: eight draws, one a move. The fix that follows draws once, at
the last place.
2026-12-04 21:45:11 -08:00
Anees Iqbal f908586499 ⬆️ Build on metal2vulkan development 9e7034c214
Pin AB, from f0c64c3b1d (AA'): 3 commits. SEMANTICS_VERSION 2390,
ARTIFACT_FORMAT_VERSION 616, RUNTIME_VERSION 2579 (from 2389, 616 and 2579).

The move alone. The translator now splits a whole-struct load or store of stack
memory into its members' accesses, as it already did for device, constant and
threadgroup memory, so a vertex function that builds its return value in a
stack slot translates where lowering refused it before (Lowering(Access)
AccessType). A volatile access, an aggregate holding a pointer and one with more
members than the split takes stay whole and refused as before. The other two
commits are comments and the golden hashes the split changes. No public API
changes, so no call site here changes.
2026-12-04 21:04:55 -08:00
Anees Iqbal 12c1a2f5ec 📦 Build the guest's kext sets again for the drawable answer
guest/prebuilt and guest/prebuilt-arm64e, rebuilt on a Mac from this tree
(make -C guest prebuilt, prebuilt-arm64e; prebuilt-check passes). Their
sources changed in the Metal bundle, whose textures now answer isDrawable as
the descriptor they were made from says, so a CAMetalLayer drawable's texture
answers YES. Only RgfxGate's binary changes, since it carries the bundle;
ReimsGraphics and Graft are byte for byte as before.
2026-12-04 21:04:55 -08:00
Anees Iqbal deaa249ba0 🐛 Answer a drawable's texture's isDrawable as its descriptor says
What changes for the guest: a texture now answers isDrawable YES when
the descriptor it was made from says isDrawable, which a CAMetalLayer
sets for its drawables' textures, and NO for every other texture, as
before. Metal answers the same on the AMD 5300M and the Intel UHD 630
(macOS 26.7.1): YES for a CAMetalLayer drawable's texture, NO for the
textures an app makes. The device answered NO for every texture.

CoreImage reads isDrawable of the texture it renders to and takes a
texture that answers NO as one whose rows run from the picture's
bottom. Rendering a camera's frames into a CAMetalLayer drawable, as
the system camera app's viewfinder does, it then drew them upside
down (its kernel ci_affine with a vertical flip, where Metal's own
answer gets ci_point with none). With the answer forced to YES for
CoreImage alone, the guest's picture came out upright (probe boot
m3-max-87744 on the 780M); no other differing device answer changed
it. The protocol members' register says the new answer.
2026-12-04 21:04:55 -08:00
Anees Iqbal defda86c9b ✅ Check a texture answers its descriptor's isDrawable
A CAMetalLayer makes its drawables' textures from descriptors whose
private isDrawable is YES, and Metal's textures answer it: YES for a
drawable's texture, NO for every texture an app makes (measured on the
AMD 5300M and the Intel UHD 630, macOS 26.7.1). The device's textures
answer NO for every one, so CoreImage, which reads it of the texture it
renders to, takes a drawable's rows as running from the picture's
bottom and draws a camera picture upside down in the system camera
app's viewfinder. This check fails until the textures take the answer
from their descriptor.
2026-12-04 21:04:55 -08:00
Anees Iqbal 451ad495b9 📝 Name the cards the 12-04 measurements ran on, not their machines [ci skip]
The surface_pages module doc named two lab machines for its 12-04 measurements.
A committed text names the card and its driver instead: a machine's name is about
the owner's network.
2026-12-04 20:41:51 -08:00
Anees Iqbal 537860c1a9 ✅ Dump a crash of the d3d11 stream guard to a named directory
The Direct3D 11 stream guard ended once in an access violation on the Windows
test machine (potluck job m3-max-87568, at gaps2-ref4) and passed alone, and
nothing was left to read: its process runs with SEM_NOGPFAULTERRORBOX, which
the job's bash passes to every process it starts, so Windows Error Reporting
writes no LocalDumps and logs no Application Error for it, and a job could not
write LocalDumps' keys anyway.

So the guard arms a top-level exception filter of the tests' own where
RVG_CRASH_DUMP_DIR names a directory: an unhandled exception is handed to a
thread made at the arm, which writes a minidump with dbghelp's
MiniDumpWriteDump, and the process then ends as before, its exit code the
exception's, so the guard still fails. The arm says so on stderr with the
dump's path, and keeps the directory's three newest dumps. Unset, nothing is
armed. Test code only: the library never reads the variable.
2026-12-04 20:38:51 -08:00
Anees Iqbal e507e6b28f 📝 Say what keeping pages views saves, by 87539 and 87721 [ci skip]
The module doc credited keeping a released pages block's view with saving its
import's make and free, citing 87443's p99 rise, and gave an 11-12 RTX 3090
figure (11.4 ms a free) whose log is no longer held. On ms01's Iris, 87539
measured the cost of a view made again as its mapping (280 of 293 ms for 41
views of 4 MiB or more), with frees overlapping 10 and 11 of about 14,800
submissions in the two forms. On gem10's RTX 3090, 87721 timed the driver's
host-pointer imports with a Vulkan layer: imports of 4 MiB or more took 3.2 ms
to make and 1.9 to 2.9 ms to free (medians). The doc now states those.
2026-12-04 20:38:51 -08:00
Anees Iqbal 8bd7dbf2df 🐛 Walk the frame-fills test's pixels through a mutable iterator
The test the commit before shared between a smaller and a larger frame looked
for a black pixel with find on an iterator it had not declared mutable, so
reims-vgpu's tests did not build (potluck m3-max-87512).
2026-12-04 19:27:12 -08:00
Anees Iqbal 157c681c7f 📝 Say macOS lists no 1x copy of the larger mode [ci skip]
The x86-64 and arm64 boots on 3840 x 2160 windows (macOS 26.7.2 and
26.6.2) list "looks like 2560 x 1440" at 5120 x 2880 and no 5120 x 2880
at 1x: CoreGraphics' list with its low-resolution modes has none, and
Displays' "Show all resolutions" on the x86-64 guest adds only the low
resolution copies of 2560 x 1440, 1920 x 1080 and 1440 x 810. The known
issue the behaviour commit added for that 1x copy does not happen, so it
goes, and display.rs, design.md and features.md say what the guests list.
2026-12-04 19:27:12 -08:00
Anees Iqbal 2ba50fb506 🆕 Offer a HiDPI mode's backing above the window on a dense screen
What the guest sees: on a host screen above 1x, a guest that took
DISPLAY_SCALE is now offered one more mode, after every mode it was offered
before and at each of their rates: 4/3 of the window's width, rounded down to
a multiple of 16, at the window's ratio with the height rounded down to even.
On a 3840x2160 window that is 5120x2880, which the kexts offer HiDPI as
"looks like 2560x1440", the backing a Mac draws that mode at for an external
4K screen and scales down to the panel (owner's issue list, item 196). Before,
the guest could pick 2560x1440 only at 1x, from the smaller modes.

Every mode offered before keeps its place in the list, so the kexts give it
the ID they gave it before, and the first mode stays the default. The larger
mode is left out where its scanout misses the display's room (three or four
displays) or where it would not fit the 24-mode bound beside every rate, so it
never displaces a mode. At 1x, and to a guest not told the scale, the list is
as it was. The window already draws a frame larger than its place scaled down
into it, as the tests of the commit before hold.

The x86-64 framebuffer lists the mode at 1x as well, as it lists every mode;
docs/known-issues.md says so (the planner's ruling). The tests that held the
old lists change with it: the display's mode lists for screens at 2x and 1.5x,
the rates' counts beside the larger mode, and the DISPLAYS answer to a guest
told the scale. The register (features.md) gains the entry, with its guards.
2026-12-04 19:27:12 -08:00
Anees Iqbal e5b5104bc3 ✅ Hold that a frame larger than its window fills it
The display is to offer a mode above its window's size on a screen above 1x,
the backing of a HiDPI mode ("looks like 2560x1440" draws 5120x2880 for a
3840x2160 window). The window already shows such a frame scaled down into its
place, as it shows a smaller mode's scaled up: the layout fills the window with
a mode of its ratio at any size, and the draw samples any frame not of its
place's size. These tests hold that before the mode is offered:

- geometry: a larger mode of the window's ratio fills it, the pointer maps to
  the guest pixel under it and the cursor is drawn at its scale;
- sink: a larger scanout and a larger surface are sampled over their place,
  never copied;
- sink, on Vulkan: an 8x8 frame of four blocks drawn over a 6x6 place (the
  4/3 step) gives each quarter its block's colour, for the scanout and a
  surface. The smaller frame's test shares its body.

They pass at once: they hold what the host already does.
2026-12-04 19:27:12 -08:00
Anees Iqbal 32c0e71794 ⬆️ Build on metal2vulkan development f0c64c3b1d
Pin AA', from a71ba816e3 (Z): 44 commits, the last a test-only move of the API
tests' slot helper (CI's per-feature clippy at 69664cbc1a). SEMANTICS_VERSION
2389, ARTIFACT_FORMAT_VERSION 616, RUNTIME_VERSION 2579 (from 2386, 615 and
2579).

The move alone. It carries the constant-reference hoist (a kernel's
constant-reference loads made in its entry block, ahead of its bounds branch),
with its containment: a load made where the program did not run it is checked
in the address form, so a short or unbound binding reads nothing outside it.
A failed wait for a batch is made again, so no restore write-back runs after
the make returns; its tests check that an import's pages hold the pending
work's bytes after its release, and nothing later. The translator drops
variants and analyses the runtime never asks for (swizzled_storage,
open_cl_lines, the swizzle and offset-base slots, the nil-arm census, a heap's
storage conversions); none is named in this tree, so no call site changes.
2026-12-04 19:15:25 -08:00
Anees Iqbal fd205588c9 🎨 Name a pages view's import's type and its tests' rig's
clippy's type_complexity refused the import's answer, (address, forget,
switch), written out in ViewImports and in the rt platform's import_view, and
the rt pages tests' rig's tuple. Each is now a type of its own: ViewImport
beside ViewImports, and the tests' RtPagesRig. Nothing the guest or the host
sees changes.
2026-12-04 19:10:50 -08:00
Anees Iqbal 4ba367291f 🐎 Keep a released pages block's view with its import unknown
6c43e73eac let go of a pages block's view and its import at the block's
release, so that no pin resolved in the import once the kext gave the pages
back. A pages block made again over the same runs then imported its view anew,
and every such import was freed again: on ms01's Iris Xe (job m3-max-87443),
22 more views of 4 to 16 MiB a boot were imported again, and the pages' p99
frame time rose from 21 to 26.75 ms (scroll) and from 23 to 29 ms
(autoscroll), at the same frame rate. An import's free is a vkFreeMemory that
the driver may hold a vkQueueSubmit beside for its length (11.4 ms on an RTX
3090; metal2vulkan-runtime's submit_calls docs).

The cache keeps a released pages block's view of at most 32 MiB with its
import again, within the cache's bounds as they were (32 views, 1 GiB, 10 s
unheld plus two looks). The platform that knows the import as a block now
forgets it for now at the release, before the answer, and at its context's
close, unless another live block holds the view: the view import answers a
KnownSwitch, which on rt takes the block's handle out of the device's known
blocks and keeps it. A block over the same runs that takes the view knows the
import again, at the same address.

What changes for the guest: a pages block made again over the runs of a
released one takes the released view again, so the address IMPORT_ADDRESSES
answers and the gpuAddress of the no-copy buffers over it are the released
block's import's, as before 6c43e73eac. A buffer the guest pins at an address
in a cached view's import is still made apart. What the host keeps: the import
maps the pages the guest reuses until the cache lets the view go, so a GPU
address the guest kept of a buffer it destroyed reaches them from a shader for
at most about 12 s, where a Mac's GPU faults. The views' line counts the pages
views taken from the cache again.

Tests: released_pages_views_are_kept_at_most_32_none_of_their_imports_known
(33 views, and one of 32 MiB plus a page),
on_vulkan_released_pages_views_past_1_gib_leave_at_most_1_gib_cached_none_known
and on_vulkan_a_pin_in_a_cached_pages_view_lies_outside_its_pages_until_a_block_takes_it
are red where the cache keeps the import known and where it keeps no view;
a_pages_block_s_address_is_its_view_s_known_import_s_where_the_platform_knows_one
checks the import unknown while cached and known again as it is taken. The
tests that held views made anew are back to the cached forms.
2026-12-04 19:10:50 -08:00
Anees Iqbal 62f35c3f72 📝 Say a shader can reach freed memory for about 12 s [ci skip]
The pages views' cache keeps a released block's view with its import, so a
GPU address the guest kept of a buffer it destroyed reaches the guest pages it
reuses for at most about 12 s, where a Mac's GPU faults (the next commit).
Users read it here, as the ledger's residual row of that change.
2026-12-04 19:10:50 -08:00
Anees Iqbal f66449a2d9 ✅ Check the session's ordering once its picture waits at its gate
Two of the video session's tests slept 50 ms for its threads to wait: for the
landing thread to hold the first picture at its gate, before checking that no
value is signalled ahead of it, and for the session's end to wait for its last
picture, before opening that picture's gate. With the waiting thread 200 ms
late (forced, scratch) both checks went untested: a landing that signals each
value before it lands passed the first (the run failed only later, its
counts read racing the landing), and an end that does not wait for its last
picture passed the second.

A gated picture now says as it reaches its gate, and the first test checks
once it has; the second opens the gate once its thread has parked on the
world's clock in the end's wait, by the clock's count of that thread's parks
(its device's other waits share the clock). Under the same late starts they
pass, and both breaks fail them. Test only.
2026-12-04 18:45:55 -08:00
Anees Iqbal 96ab8216f2 ✅ Check the call threads' tests once their call is in hand
The tests of NVIDIA's and VA-API's call threads hold a call as a driver's call
waits for the GPU, and stood for "the thread is in the call" with real time: a
20 ms deadline for NVIDIA's, which answers the same whether the call was taken
or is still queued, and a 30 ms one for VA-API's wait_call. With the call
thread 200 ms late (forced, scratch), NVIDIA's checks went untested (an order
dropped untaken passed; calls made on threads of their own passed the thread's
"ended in its call" check) or failed on their own (the next order replaced the
first before it was taken, and the release found no call), and VA-API's failed
on their own (NotMade for InFlight).

held() now says as its call begins, and each test waits for that before it
checks; VA-API's two run on the tests' VirtualRuntime, the caller's deadline
passed only once the call is in hand. Under the same late start they pass, and
each break fails them: an order dropped untaken, calls made beside the one in
flight, a pending order kept and the next dropped while a call is in flight,
a release made at once beside the call, a call thread that ends with its call
in flight. The 20 ms left after the signal are room for a wrong call or
release to show, behind a known state. Test only.
2026-12-04 18:45:55 -08:00
Anees Iqbal 8dde142faa ✅ Count the video runtime's waits where tests slept for them
Five video tests slept in real time for another thread to be waiting on the
video crate's runtime before they checked it: the tests' VirtualRuntime (a
wait at its deadline on virtual time, video_delay's wait), std's runtime (a
ring that wakes a wait) and the holds of a stalled picture's work (the
session's landing, and VideoToolbox's paravirtual decode, done_while). With
the waiting thread late by more than the sleep (forced late starts, scratch:
200 ms, and 400 ms for done_while's 300 ms) each check went untested or
failed:
- the waits on virtual time and the ring passed with the wait broken: taken
  as ended at its first wake, video_delay's wait returning at once, a ring
  that ends the wait with no answer; the deadline's test failed on its own,
  its waiter starting after the advance and its deadline never passing;
- the holds lost their count, the kept work done before the hold began, so
  nothing was held ([4, 0] for [4, 4]; 0 for 1). Neither old test saw a hold
  that never waited even on time: done_while joined its setter before its
  checks, and the landing's test checked counts alone.

The tests' VirtualRuntime counts its looks at the clock, and Counted<R> (the
testkit's, for reims-vgpu's tests too) counts each thread's waits on a runtime;
each test now acts once the count shows the other thread waiting: two looks
for a wait on virtual time (it found its deadline not passed), one wait for the
ring, and one for each hold, whose device is done only then. Under the same
late starts they pass, and each break above fails them, a hold that never
waits among them. Test and testkit only.
2026-12-04 18:45:55 -08:00
Anees Iqbal 0249839a1f ✅ Settle the off-list command buffer once the settle waits
a_settle_waits_for_the_platform_s_command_buffers_through_its_number settled
the command buffer that had left the list from a thread that slept 20 ms
first, a real sleep standing for "the settle waits for it" on the OS clock.
Started 200 ms late (a forced late start, scratch), the settle began after the
buffer had settled, counted none to wait for and answered Ok(0): the test
failed for its own timing. With the settle's wake-up taken out (settled() made
to notify no one, scratch) it passed, 10 s on: the settle's wait ended at its
bound and found the buffer settled.

The settle now runs on a thread of its own on a VirtualClock of its own, and
the buffer settles once the clock has counted the settle's timed wait, the
only one made on it; the settle then takes it up and answers Ok(1). Under the
same late start it passes, and without the wake-up it fails, at its bounded
real wait for the settle to take it up, since virtual time does not move.
Test only.
2026-12-04 18:45:55 -08:00
Anees Iqbal dad198fe0f ✅ Count each thread's parks on the testkit's virtual clock
A test that acts once another thread waits on a VirtualClock reads the timed
waits made on it (timed_waits), which single that thread out only where its
waits are the clock's only ones. A world's clock is shared: its device's timed
waits and polls park on it beside the thread a test waits for, so such tests
slept in real time instead, and the check behind the sleep passed untested
whenever that thread came late.

parked(thread) counts each thread's parks on the clock (a wait_until that did
not find its deadline passed, a wait, each park of a sleep_until), each 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 seen the count grow reaches the parked
thread; wait_for_parked waits for it to grow. The testkit's alone: nothing the
guest or the host observes changes.
2026-12-04 18:45:55 -08:00
Anees Iqbal 8f395eacf2 🐛 Answer every block's release after the buffers posted before it
A command buffer its process published before a block's release, and begun
after the release's answer, still reaches an object the process destroyed
before the release: the table keeps the object for it ("After the buffers
posted before it"). For a pages block the release waited for such buffers
already. An IOSurface's block did not, and on a GPU whose memory is the host's
a texture over a shape of the block's device cache lies in place over the
surface's pages, which the buffer reaches through the texture's resource index
in an argument buffer. The kext unwires the pages at the answer, so that
buffer's writes could land in pages macOS had taken back.

Every block's release now waits as a pages block's did, for the buffers its
context's queues published before it to be committed, stood in for or failed,
or for their queue to end, and then to finish. What the guest sees: a surface
block's BLOCK_RELEASE answer can come later than before, by as long as the
buffers its process had published and not yet begun take to be committed and
to finish. No guest thread waits on the answer. The tests that held the
pages-only wait now hold both kinds.
2026-12-04 18:08:04 -08:00
Anees Iqbal 6a0340009c ✅ Build the bundle's shell tests on a macOS 26 SDK
The guest's x86_64 checks run natively on an x86-64 Mac whose Command Line
Tools carry the macOS 26.5 SDK. The bundle itself builds there
(src/RgfxSdkCompat.h), but the shell tests did not: shell_tests.mm,
protocol_tests.mm and files_tests.mm use names only the macOS 27 SDK
declares, so `make test` stopped at their build, before any of the bundle's
checks ran.

tests/rgfx_test_sdk_compat.hpp declares those names for an older SDK, as
RgfxSdkCompat.h declares the bundle's: MTLForwardProgressUsage's
enumerators and MTLContentionRelief with contentionRelief on
MTLComputePipelineDescriptor, forwardProgressUsage on our compute pipeline
state and minLOD on our texture, which the classes implement, and five
system call numbers. Every value is the macOS 27.2 SDK's (Xcode 27.2):
- Metal.framework/Headers/MTLPipeline.h: MTLForwardProgressUsageAutomatic 0,
  Weak 1, SIMDGroupParallel 2;
- Metal.framework/Headers/MTLTypes.h: MTLContentionReliefAutomatic 0,
  None 1;
- usr/include/sys/syscall.h: SYS_fchflagsat 214, SYS_aio_readv 246,
  SYS_aio_writev 247, SYS_fsctlat 249, SYS_guarded_ftruncate_np 352.
The Metal names sit under __MAC_OS_X_VERSION_MAX_ALLOWED < 270000 and each
system call number under #ifndef, so a build on the 27 SDK sees nothing new.
One check reads minLOD through the texture's class on an older SDK, whose
MTLTexture protocol lacks it; on the 27 SDK it reads the protocol's as
before.

Test sources alone: the guest sets' sources, and so the sets, are unchanged.
2026-12-04 18:03:41 -08:00
Anees Iqbal f6f2b2c32a 🎨 Format draw_cost's figures closure as rustfmt does
rustfmt breaks the closure's map onto its own line (lint job m3-max-87051).
2026-12-04 17:44:09 -08:00
Anees Iqbal a1263fb656 🐎 Hold no bound texture the attachment-read diagnostic cannot read
A render encoder kept every texture bound to a vertex or fragment slot (an Arc
of its diag::Made, taken at each bind and let go at the next), for the boot
diagnostics' count of a draw rt refuses as an attachment read through a
texture. That count reads only the slots whose texture's image a target of the
pass renders, so every other bind took and dropped a reference for nothing: one
pair of atomic operations a draw on a compositor's stream.

A bind now keeps the texture only where its image is a target's, and empties
the slot otherwise. The attachment-read lines count the same draws by the same
classes. A texture the guest releases while bound to an encoder's slot no
longer stays live in the plane diagnostics until the slot is bound again; those
counts are diagnostics alone.
2026-12-04 17:44:09 -08:00
Anees Iqbal 4cccbc9b0c 🐎 Read a render command's refusal details only where it is refused
Every command a render encoder sent paid for what only a refusal reads: its
selector, its primitive type, its viewports and an execution's detail were read
before rt saw it, and after it the encoder built the refusal's function list
and moved the command's whole Option<Stop> into report's closure, which then
counted nothing. On draw_cost's compositor stream (shape ws, platform path) that
work was about a twentieth of a draw's instructions (IBS profile, job
m3-max-87033).

The encoder now reads them only where rt or Metal stopped the command, after
the send, under the same hold, in the same order: RenderCmd is Copy, as every
field already was, so the command is still there to read. report takes the Stop
itself, and the compute and blit encoders call it only for a refused command
too. What is counted and logged for a refusal does not change.
2026-12-04 17:44:09 -08:00
Anees Iqbal 4f920d34f6 ✅ Count draw_cost's allocations a draw beside its instructions
draw_cost printed a path's CPU time, instructions and cycles a draw, but not
how often the thread called the allocator, so a change that removes per-draw
allocations had no figure to show it. Each path's span now runs under the unit
tests' counting allocator (crate::counted), and the test prints allocations and
frees a draw beside the counters, zero included.

The platform path alone (DRAW_COST_ONLY=platform) no longer builds the
decoder's messages it never reads: they were made outside the counted span, so
the figures do not move, but a profile of that path no longer samples the
bench building bytes.
2026-12-04 17:44:09 -08:00
Anees Iqbal 880ef506b3 📝 Say Intel Mac guests restart bluetoothd every 32 s [ci skip]
An x86-64 guest has no Bluetooth controller. bluetoothd starts BlueTool,
which finds no transport, falls back to UART and times out its boot script
after about 30 s. bluetoothd then exits cleanly and launchd starts it again
at once. That is about 1,600 log lines per round and about 50 a second:
6,160 to 6,208 bluetoothd lines in a 120 s window (seen on 26.7.2, walks
btoff26 m3-max-87404 and btverify26 m3-max-87455). arm64 guests start it
once: five Ambrosia boots, 14.6.1 to 27.2.1, show one bluetoothd process
each.

No way to turn it off was found on a SIP-on guest. `sudo launchctl disable
system/com.apple.bluetoothd` answered 0, and print-disabled then listed the
service as disabled. After the guest restarted, print-disabled no longer
listed it, launchd's record held no entry for it, and bluetoothd cycled
again: 10 processes in 300 s (btverify26, 26.7.2). So the page states what
happens and offers no command.
2026-12-04 17:44:09 -08:00
Anees Iqbal 6a786e84c7 🎨 Clear the rest of coding-order encode's clippy findings
Batch p5's second lint run found one more line of db84a87a85 that clippy
refuses once the video crate compiles: the VA-API encode test read a 10-bit
plane with chunks_exact(2), which chunks_exact_to_as_chunks refuses; it now
reads as_chunks::<2>(), the same pairs. NVENC's test helper pictures_of now
names its five-field answer with the type alias PictureOrder, as the crate's
other tests name their tuples, in place of f571d2da19's allow.
2026-12-04 17:31:32 -08:00
Anees Iqbal f571d2da19 🎨 Keep coding-order encode's division and test helper clippy-clean
Batch p5's lint legs failed clippy on two lines of db84a87a85: the place
of a frame sent in coding order divided its PTS with `/`, which
arithmetic_side_effects refuses, and NVENC's test helper pictures_of
returns a five-field tuple, which type_complexity refuses. The division is
now checked_div, with the same answer where the duration is above 0, and
the helper carries the allow with its reason, as the crate's other tuples
do.
2026-12-04 17:27:35 -08:00
Anees Iqbal 6afc8afdf8 📦 Build the guest's kext sets again for coding-order encode
guest/prebuilt and guest/prebuilt-arm64e, rebuilt on a Mac from this tree
(make -C guest prebuilt, prebuilt-arm64e; prebuilt-check passes). Their
sources changed in two places: the wire header, which gained the coding-order
flags, and the Metal bundle's video driver, which sends AppleGVA's frames in
coding order at their places. Only RgfxGate's binary changes, since it
carries the bundle; ReimsGraphics and Graft are byte for byte as before.
2026-12-04 17:20:21 -08:00
Anees Iqbal 83253f60ea 📝 Say what outlives a surface block's release on rt [ci skip]
The cache paragraph read as if the platform kept IOSurface views past
BLOCK_RELEASE. On metal2vulkan-runtime's platform it keeps none, so the cache
holds nothing there. What can outlive the answer is the device cache's
import of the block's pages, on a GPU whose memory is the host's, held by
the shapes in place and the textures over them. No pin lies in it, but a
command buffer published before the release and begun after its answer still
reaches a texture destroyed meanwhile, through an argument buffer, as the
table keeps its entry, and the release waits only for buffers begun before
it.
2026-12-04 17:20:21 -08:00
Anees Iqbal 5d401b9a5c 🐛 Send AppleGVA's frames in coding order at their places
What changes for the guest: where an x86-64 guest's encode session allows
frame reordering, AppleGVA's H.264 encoder and the HEVC plug-in send each
reference frame before the B frame shown ahead of it (places 0 2 1 4 3 ...).
The driver now reads each picture's order count: for H.264 the first slice
header's pic_order_cnt_lsb, which the command names through a table of
pointers to its slice headers, and for HEVC the plug-in's PicOrderCntVal.
Where the stream's SPS says it reorders and the host answers
RGFX_VIDEO_ENCODE_CAP_REORDERED, it sends each frame with
RGFX_VIDEO_ENCODE_REORDERED and the frame's place in display order as its
frame_index. The host codes each frame at its place, so a player that orders
frames by POC shows them in display order. Before, the driver counted frames
up as they came, the host coded each one as a P picture in that order, and a
screen recording made with reordering allowed showed every pair of frames
swapped in any player that orders by POC (ffmpeg and the players built on
it). A stream that codes in display order, and every stream to a host
without the cap (the VideoToolbox arm, which serves arm64 guests), is sent
as before. Each encode context logs its decision once, with the fields it
read.

The guest checks cover H.264 and HEVC streams that reorder, wrap their
order counts, turn to coding order and back, or say they do not reorder,
H.264 at POC type 2 and in the other SPS layout, and a host without the cap.
The driver before this commit fails them (frame 1, lsb 4, sent at place 0).

Measured on a macOS 26.7.2 guest, 2026-12-04: the toolbar's screen
recording read in POC order has 0 frames backwards on an RX 7900 XTX
(VA-API) and on an RTX 3090 (NVENC), against 579 before. VideoToolbox
encodes with reordering allowed, H.264 and HEVC, 300 frames each, read in
POC order against their source frames, have 0 frames out of place on both,
where H.264 had 144 before.
2026-12-04 17:20:21 -08:00
Anees Iqbal db84a87a85 🐛 Code frames a guest sends in coding order at their places
What changes for the guest: both Linux arms now answer
RGFX_VIDEO_ENCODE_CAP_REORDERED for H.264 and HEVC. A session whose
settings carry RGFX_VIDEO_ENCODE_REORDERED has each frame coded as it
comes, at its frame_index's place in display order. The arm makes a
frame an IDR picture at the stream's first frame, a forced keyframe, the
interval, or a place not past its IDR picture's. It makes a frame a
reference P picture where its place is past every place since its IDR
picture. Any other frame is a picture nothing predicts from: a B picture
between the references either side of it where the profile has B
slices, else a P picture. Each picture's order count is its place's
(twice it for H.264), and the SPS says one frame may come out of display
order, so a decoder shows the frames in their places. Before, every
frame was coded in the order it came, and the stream showed each frame
sent behind a later one after it.

The VA crate's encoder plans such frames with CodingOrder (gop.rs,
EncoderSettings::coding_order). NVENC's session plans them the same way
with its picture type decision off, and sets each picture's type, order
count and reference flag (EncodeParams::coding_order). Without the flag
nothing changes. The tests that held the caps answer (in place alone)
now expect the new flag too. Card tests cover both arms: on a radeonsi
XTX, 30 frames in AppleGVA's order (0 2 1 4 3 ...) decode back with
none out of order for H.264 Baseline, Main and High and HEVC Main and
Main 10, where development shows every pair swapped. On an RTX 3090
they cover H.264 High and HEVC, and HEVC coded again in place in coding
order.

NVENC codes H.264 Baseline at POC type 2, which cannot place such a
frame. No guest sends one, since Baseline has no B pictures; it is
docs/video/bugs.md B103. The VideoToolbox arm, which serves arm64
guests, answers no such cap and is unchanged.
2026-12-04 17:20:20 -08:00
Anees Iqbal f81fcf163a 🆕 Add the wire's flags for frames sent in coding order
A guest whose encoder codes B pictures sends each frame in the order it
is coded, which is not the order it is shown in. The device has no way to
say so: frame_index counts the frames as they come, and the host codes
them in that order.

RGFX_VIDEO_ENCODE_REORDERED, a settings flag, says the guest sends frames
in coding order, each at its place in display order as its frame_index,
at most one frame ahead. RGFX_VIDEO_ENCODE_CAP_REORDERED, a caps flag,
says the host takes them so. No host answers the cap here, so nothing
changes for the guest yet. The option ROM's record takes the header's new
hash; the ROM's bytes are the same.
2026-12-04 17:20:20 -08:00
Anees Iqbal 985ecd39f0 🎨 Format the prepared writer's two tests as rustfmt does
The batch's lint leg (m3-max-87318) found two asserts in graphics/tests.rs, from
the commit that holds a prepared writer's readers to one GPU wait first, wider
than rustfmt's call width. rustfmt's own layout, no change to the tests.
2026-12-04 16:35:36 -08:00
Anees Iqbal a5df74361c 👷 Try the lavapipe job's pacman download three times
Run 47448102351's lavapipe job failed before any test ran: the archive's
server reset pacman's download of the cc and git packages (curl: HTTP/2
stream reset, PROTOCOL_ERROR). The step now runs pacman -S up to three
times, 15 s apart, and the package cache keeps what each try fetched.
2026-12-04 16:29:50 -08:00
Anees Iqbal 7c050a500a 📦 Build the guest's kext sets again for the merged pull requests
Pull request 226 changed ReimsGraphics (each client's GPU time in AppUsage and
PerformanceStatistics), RgfxGate (the thread charge) and the Metal bundle (its
sum and the shadow-library cache), and the fixes after it changed RgfxGate's
look-up and the bundle's cache again; neither set was rebuilt, so
prebuilt-check failed on the tree. Both sets are built again from this tree on
the M3 with Xcode alone (make -C guest prebuilt and prebuilt-arm64e, then
prebuilt-check), in potluck job m3-max-87156, which also ran the kext's,
RgfxGate's (gpu_stat_test among them) and the bundle's arm64 checks. Graft's
binaries are unchanged.
2026-12-04 16:29:49 -08:00
Anees Iqbal 6476576af8 📝 Name the call that maps a pool block in the arm64 pool comment
Pull request 224's comment said vmapple under TCG on Windows maps each pool
block with memory_region_init_ram_ptr. reims_graphics_pool_add in
hw/display/reims-graphics-pci.c makes each piece with
memory_region_init_ram_device_ptr, on every host, and only WHPX maps a piece
ahead (whpx_map_ahead); TCG on Windows takes the same path as on Linux. The
comment now names the call the code makes and where it is.
2026-12-04 16:29:49 -08:00
Anees Iqbal 4728372edb 🐎 Keep Core Image's shadow libraries by file on every release
Pull request 226 keeps a process's shadow libraries (Metal's own library over
the bytes of a library loaded from a file) by the file's identity, at most 64,
so Core Image's many contexts, each loading its kernel libraries again from
the same files, get the shadow made the first time instead of making and
hashing a new one: on macOS 26 and later alone, every older release making
one shadow per library as before.

Nothing about the shadow differs before macOS 26: it is only read (its
functions, extern functions, reflection and what it serializes), and the
file's identity is the one the library itself is kept by on every release.
So one form serves every release, and the release check goes. What a guest
app sees of its libraries is unchanged; older releases make fewer shadows.
The comment's stale name for the cache is fixed too.
2026-12-04 16:29:49 -08:00
Anees Iqbal 4607314fe1 🐛 Keep RgfxGate's Graft state where the GPU-time look-up misses
Pull request 226 has RgfxGate look ml_gpu_stat_update up through Graft's
graft_kernel_symbol on x86-64 macOS 26 and later, to charge a thread the GPU
time ReimsGraphics hands it. A miss sets the client's published state
(GraftClient.ai.aneesiqbal.RgfxGate on the registry root) to "refused",
naming the symbol, though RgfxGate's hooks were installed before the look-up
and stay: a kernel without the function would show the guest's gate refused.

The look-up now runs only where the state Graft published before it can be
read and put back, and a miss puts it back with graft_client_state, Graft's
own call: such a kernel charges no thread, the callPlatformFunction answers
kIOReturnUnsupported as before, and the client reads as it did. Graft's log
says which way it went. Graft is not touched. rgfx_gpu_stat.h holds the
decision with no kernel header, and tests/gpu_stat_test.cpp (make test) runs
it against stand-ins of Graft's two calls: a miss keeps the state, a hit
leaves it alone, no state or one too long to keep whole means no look-up.

The kext's two comments that said it charges no thread's GPU counter now say
what it does: it imports no ml_gpu_stat_update, and asks RgfxGate to charge.
2026-12-04 16:29:49 -08:00
Anees Iqbal 74c9226d35 ✅ Hold a prepared writer's readers to one GPU wait first
Pull request 226 lets a buffer that names a buffer of another queue the host
has not walked begin once that buffer is prepared (its begin returned, with no
video op of its queue up to it uncommitted), where it waited for its commit.
Two tests lost their assertion that the reader was not committed before the
writer, which no longer holds, and said less of what still does.

They now hold what is promised: the reader's one GPU wait is for the value
the named buffer signals, it is encoded on the reader's own command buffer
ahead of its work (a_reader_in_another_process_waits_on_the_gpu_for_an_
answered_writer) or before its commit (a_buffer_named_while_its_queue_s_
later_buffer_is_walked_first_is_waited_for), and that command buffer is the
one committed. So the GPU runs the write first wherever the two commits fall.

surface_order's module doc said a begin held for a decode waits for the named
buffer's commit; it waits for its prepared mark, which a buffer holding a
video op, or behind one, reaches only at its commit. Three doc lines the pull
request left past the width are wrapped.
2026-12-04 16:29:49 -08:00
Anees Iqbal a81a441930 🔥 Drop the variable that picks a window's present mode
Pull request 226 let REIMS_VGPU_PRESENT_MODE (fifo, mailbox or immediate)
choose a window's swapchain present mode where the surface offers it, for
comparing a host's latency and pacing. A tuning variable is not a product,
and the library picks the mode itself: MAILBOX where the surface offers it,
else FIFO. The variable and its row in docs/api.md go; a window presents as it
did before the pull request, and nothing changes where the variable was unset.
2026-12-04 16:29:49 -08:00
Anees Iqbal 3735ae96e1 🔥 Offer a guest its screen's rate again, with no 164 Hz cap
Pull request 226 capped the refresh rate a titled window's display offers the
guest at 164 Hz, or at REIMS_VGPU_MAX_REFRESH_HZ (24 to 1000 Hz), a screen up
to 1 Hz past the cap keeping its own. The owner's rule stands: the guest is
offered the host's rates, and the VM's refresh-rate option
(REIMS_VGPU_WINDOW_REFRESH_RATE) is the one knob. So the cap and its variable
go, with a_display_runs_at_its_screens_rate_up_to_the_cap and the variable's
row in docs/api.md.

What changes for the guest: on a host screen faster than about 165 Hz, a
titled window's display offers each size at the screen's rate again, as
before the pull request; on a slower screen nothing changes. If the cap hid a
real cost on a fast screen, that is a finding to bring with numbers, not a
default.
2026-12-04 16:29:49 -08:00
Anees Iqbal 2ea42b0581 🔥 Start Windows VMs without prealloc and its switch again
Pull request 226 started QEMU on Windows with the RAM backend's
prealloc=on,prealloc-threads=<vCPUs>, so every page of the guest's section is
touched as QEMU starts, and let REIMS_CTL_WIN_PREALLOC=off turn it off. A
tuning switch is not a product, so the variable goes. The prealloc itself is
taken out too until the Windows leg has measured it: a guest's start and its
time to the desktop with and without it, and what a guest larger than the
host's free RAM does to that host, since a prealloc makes every page resident
and dirty, pages the guest may never touch among them. A Windows VM starts as
before the pull request: memory-backend-ram,share=on, its pages left to the
guest's first touches. q35_on_windows_runs_on_whpx_in_shared_ram holds that
line again, and docs/qemu.md says the first touches run on the vCPUs.
2026-12-04 16:29:49 -08:00
Anees Iqbal 568dd09f5b 🔥 Drop the switch that runs WHPX without its security domain
Pull request 226 let REIMS_CTL_WHPX_SSD=off in reims-ctl's environment start
QEMU with -accel whpx,ssd=off: the partition then runs without Hyper-V's
separate security domain, QEMU clears IBRS, STIBP, IBPB, SSBD, IBRS_ALL and
PSFD from the guest's CPUID, and VM exits skip those speculative-execution
mitigations. A switch that drops the guest's isolation from the host's other
work is not one reims-ctl offers, and a tuning switch is not a product
(contributors' knobs go in the fix-forward): it is removed whole, with its
docs, and the x86-64 VM's -accel is Profile::accel's again, as before the
pull request. Nothing changes for a VM started without the variable.
2026-12-04 16:29:49 -08:00
Anees Iqbal 2bba471260 🐎 Move vendor/qemu to its threaded Windows prealloc
vendor/qemu f073adfb -> c352e26f: the fork's pull request 26, merged on
steelbrain/reims-vgpu-rebase-2 as 1a03ea2d with its commit replayed as
c352e26f, has QEMU's Windows prealloc touch a memory backend's pages in up to
prealloc-threads threads, each over a contiguous share, where it touched them
on one thread. Each touch still writes a zero to a page's first byte, and an
asynchronous prealloc is still done before the call returns.

Only a backend with prealloc=on reaches it, and virtio-mem's calls ask one
thread as before. reims-ctl's Windows command line asks for prealloc since
pull request 226's first commit; the fix-forward that follows takes that out
until the Windows leg has measured it. docs/qemu.md's fork table has the
commit.
2026-12-04 16:29:49 -08:00
sitxovski 4786fa1915 🆕 Charge GPU time on macOS 26 and keep Core Image shadows
Activity Monitor's and powermetrics' per-process GPU time stayed at zero
in a guest: nothing charged it. From macOS 26 (Darwin 25) on, earlier
releases unchanged:
- The bundle sums each command buffer's GPU time from its completion and
  hands it to the kext with WaitCompletions, a second scalar the kext
  offers with kRgfxKextFeatureGpuTime.
- The kext publishes AppUsage per process and the accelerator's
  PerformanceStatistics each second (RgfxGpuTime.hpp, gpu_time_test).
- RgfxGate looks ml_gpu_stat_update up through Graft once, on x86-64
  alone and with no weak import, and charges the calling thread on
  callPlatformFunction("rgfx-gpu-stat-update").

The bundle also keeps up to 64 shadow libraries by file identity, so Core
Image does not compile one again for each icon, and RgfxSdkCompat.h lets
it build against SDK 26.x.

guest/prebuilt and guest/prebuilt-arm64e are not rebuilt here.
2026-12-04 16:29:49 -08:00
sitxovski 112bcb8308 🐎 Cut cross-queue waits, copies and refresh overshoot
A buffer of one queue that names a buffer of another queue still being
walked waited on its queue's thread until that buffer was committed. On a
macOS 26 desktop on Windows with an RTX 4060, 436 begins waited so, up to
53.6 ms. The wait is there so a buffer cannot wait on the GPU for itself
through a cache fill the named buffer's begin adds; that holds once the
named buffer is prepared (its begin returned, every use and fill it adds
fixed), so the begin now waits for a new Until::Prepared mark. A buffer
holding a video op, or begun behind an uncommitted one of its queue, is
prepared only by its commit. The begins that waited fell to 1.

This changes when such a buffer is committed: it may now be committed
before the buffer it names. The GPU order is unchanged: it still waits on
the GPU, exactly once, for the named buffer's surface timeline signal.
a_reader_in_another_process_waits_on_the_gpu_for_an_answered_writer and
a_buffer_named_while_its_queue_s_later_buffer_is_walked_first_is_waited_for
held the old commit order; they now check the wait and the signal alone.

Also:
- A surface cache REFILL is checked again where it is carried out: a cache
  a command buffer wrote since is filled into its shapes alone, so the fill
  never writes over that write.
- replaceRegion reads guest bytes in place, but for tiled textures and
  textures over another resource.
- A display's refresh is capped at 164 Hz by default and never above its
  screen's own rate (REIMS_VGPU_MAX_REFRESH_HZ, 24 to 1000).
- reims-ctl preallocates a Windows guest's RAM with a thread per vCPU
  (REIMS_CTL_WIN_PREALLOC=off opts out); REIMS_CTL_WHPX_SSD=off passes
  ssd=off to WHPX.
- REIMS_VGPU_PRESENT_MODE and the Windows page size are read once.
2026-12-04 16:29:49 -08:00
sitxovski e8ab986eba Merge pull request #226 from sitxovski/tahoe-gpu-time-and-queue-waits 2026-12-04 16:29:49 -08:00
kilbertert bb62d102de reims-vgpu: offer the Shared pool to arm64 guests on Windows TCG 2026-12-04 16:29:49 -08:00
kilbertert 2bd70a0ed0 Merge pull request #224 from kilbertert/win32-arm64-shared-pool 2026-12-04 16:29:48 -08:00
Anees Iqbal 6c43e73eac 🐛 Let go of a pages block's view and import before its answer
At a pages block's BLOCK_RELEASE its view went, with its import, into the
cache of views, and a later pages block over the same runs took it. On
metal2vulkan-runtime's device the import stayed a block the device knows
until the cache let the view go, so after the release's answer, once the kext
had unwired the pages and macOS could give them to anyone, a buffer the guest
pinned at an address in the import resolved into it and lay over those pages,
and a pinned buffer made zeroed from a byte had rt zero its range there on
the CPU.

A pages block's view is now never cached. It goes at the release with its
import, which the platform forgets as the import's buffer goes, and the
release's answer waits for that let-go on the surface worker, besides the
command buffers it waited for before. After the answer no pin resolves in the
import and no buffer the host makes lies over the pages; the platform frees
the import, and the view's mapping with it, at its own last use of them.
IOSurface views are cached as before.

What changes for the guest: a pages block made again over the runs of a
released one makes a view and an import of its own at its first need, where
it took the cached view before, so where the guest took IMPORT_ADDRESSES the
block's address, and the gpuAddress of the no-copy buffers over it, are the
new import's rather than the released block's. A pages block's release is
answered once its view is let go of. The views' summary line counts no pages
views taken from the cache. What remaking the imports costs is measured
apart: a view's import took 1.8 ms to make and 11.4 ms to free on an RTX 3090
(surface_pages.rs's module doc).

Tests: on_vulkan_a_pin_in_a_released_pages_block_s_view_lies_outside_its_pages
(red before: the released view's import was still known);
a_pages_block_s_address_is_its_view_s_known_import_s_where_the_platform_knows_one
now checks that the import is forgotten before the release's hold goes, and
a_pages_block_made_again_over_the_same_runs_makes_a_view_of_its_own,
an_unchanging_pages_block_s_view_is_asked_unchanging_each_block_its_own,
a_read_only_pages_block_s_view_holds_no_import,
the_views_debug_lines_name_a_view_s_runs_by_one_hash,
a_pages_view_made_anew_logs_its_make_s_steps and
a_cached_view_unheld_past_the_age_goes_and_one_taken_within_it_stays (now
over surface views) replace the tests that held the cached pages views.
2026-12-04 16:24:10 -08:00
Anees Iqbal ace29e7471 📝 Point the video blocks' doc at the release's keeping variant [ci skip]
The pages blocks' release now lets go of the block through
GraphicsDecoder::block_released_keeping, and block_released is the tests' form
of it, so rustdoc found no block_released to link to from RegionMemory's doc.
2026-12-04 16:24:10 -08:00
Anees Iqbal 4b52b54e12 🐛 Answer a pages block's release after the buffers posted before it
A pages block's BLOCK_RELEASE was answered once the command buffers the host
had begun for its context had finished, but not after a buffer the context's
queues had published and the host had not begun yet. The kext unwires the
block's pages at the answer and gives them back to macOS, while such a buffer
could still be begun after it and reach the pages through an object its
process destroyed before the release, through the object's GPU address: the
host keeps that object for the buffer (tables.rs, "After the buffers posted
before it"), and the release's refusal, which looks at live objects, does not
see it.

A pages block's release now also waits for every command buffer the
context's queues' rings published before it, taken or not, to be committed,
stood in for or failed, or for its queue to end (its destroy, or its
context's close), and then for those buffers to finish, as for a buffer begun
before the release. The wait blocks no thread and holds nothing on ring 0:
whichever thread ends it begins the release's drain, the commit of the last
such buffer or its queue's end, and the device's reset drops it.

What changes for the guest: a pages block's release answer can come later
than before, by as long as the command buffers its process had published and
not yet begun take to be committed and to finish, at most its queues' depth
of buffers not yet begun. No guest thread waits on that answer: the process's
free returns at once, and the kext's release worker posts and retires
releases as their answers come. Other blocks' releases are answered as
before.

Tests: a_pages_block_s_release_is_answered_after_a_buffer_published_before_it
(red before: the answer came before the buffer's fill and completion),
a_pages_block_s_release_is_answered_once_the_queue_of_a_buffer_it_waits_for_is_gone,
a_pages_block_s_release_waits_for_a_buffer_published_before_it and
a_pages_block_s_release_waits_no_more_for_a_queue_that_ended_or_a_reset.
2026-12-04 16:24:10 -08:00
Anees Iqbal a46ac31c87 🐛 Tell a start's window not opened yet both of its readings
A display's window not opened yet opens once a screen is on, and a start does
not ask whether one is: reims-ctl now says that first, then the GPU to pick
where a screen is on and the window does not open, the desktop's GPU by its
number where the library names its DRM node, else how to list the GPUs. Its
naming of the desktop's GPU also lost its sentence's line breaks to runs of
spaces in the middle of the text (make check-ctl, m3-max-87182); the strings
are whole again. The tests' sample reasons are the library's text again, now
that the X window's bound is reverted.

For the user: "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, <name>,
which can show the window: `reims-ctl set NAME --gpu 2` gives the VM that GPU",
or, with no GPU named, "`reims-ctl gpus` lists the GPUs, and `reims-ctl set
NAME --gpu NUMBER` gives the VM the one your screen is plugged into".
2026-12-04 15:46:45 -08:00
Anees Iqbal fe8f2da6f0 📝 Say a two-GPU laptop's window may still stay empty [ci skip]
The window now opens through the window system its GPU draws to, and the X11
route showed on an RTX 2080 beside the Radeon 780M KWin composites on, with the
screen on (m3-max-87214). The reported two-GPU split itself was not made in the
lab, so the page says it closes on the reporter's run, and that an X11 window
waits for a screen to be on.
2026-12-04 15:46:45 -08:00
Anees Iqbal d6e3b4f1ee 📝 Record that X windows stayed unmapped with every screen off again [ci skip]
um870's and msi-laptop's X11 runs on 2026-12-04 never mapped a window while
their one screen was off, which docs/lessons.md had recorded on 12-02 and the
runs missed; with um870's screen on, the RTX 2080's X11 window showed and
presented. The lesson now says so, that a bound on the X window's showing
would have refused blanked screens, and where to read the screens' state.
2026-12-04 15:46:45 -08:00
Anees Iqbal 81070720ed 📝 Register a window not opened yet and drop the X window's bound [ci skip]
The window's lines' entry now quotes the not-opened line with both readings,
says the UI thread waits until a screen comes on, and says reims-ctl tells a
window not opened yet that it opens once a screen is on before the GPU to
pick. The window system's entry drops the reverted 3 s bound and its test, and
says why the question's X window is not mapped.
2026-12-04 15:46:45 -08:00
Anees Iqbal ff23921e19 🐛 Say a window not opened yet opens once a screen is on
KWin maps no X window while every screen is off, and SDL's opening returns once
one comes on (docs/lessons.md); on um870 and msi-laptop, each with its one
screen off, no X window was mapped (m3-max-87158, m3-max-87192). The 10 s line
said only that the window system had not shown the window, and reims-ctl would
have read it as a GPU to move from, wrong advice for a blanked screen. The
library asks nothing of the screens, so the line now gives both readings.

For the host: "reims-vgpu: no window: display <n>'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", with the desktop's DRM node after it where
it is known.
2026-12-04 15:46:23 -08:00
Anees Iqbal 32d5010711 ⏪ Revert "Give up on an X window its window manager does not show"
This reverts commit 9c2add75bd. The bound refused the X route whenever every
screen is off, a normal desktop state (a blanked screen, a closed lid): KWin
does not map an X window while every screen is off (docs/lessons.md), so the
question's 1 x 1 window stayed unshown there, on um870 (m3-max-87158) and on
msi-laptop (m3-max-87192) alike, each with its one screen off, while an
override-redirect window was shown in 10 ms. A window that SDL opens once a
screen wakes would have become no window at all. The 10 s line that a window
has not opened stays, and tells the host meanwhile.

For the host: the no-window line where the GPU presents to neither window
system reads as before this branch, and no X window is mapped for the question.
2026-12-04 15:46:22 -08:00
Anees Iqbal 6a2da3de71 📝 Register the X window's bound and the desktop GPU's naming [ci skip]
The window system's entry now says the X server counts only where its window
manager shows the question's window within 3 s, with the bound's test. The
window's lines' entry adds the line for an opening not shown in 10 s, what a
parked UI thread holds, and the desktop GPU's DRM node that reims-ctl's start
names as a GPU number of `reims-ctl gpus`, with both naming tests.
2026-12-04 15:46:22 -08:00
Anees Iqbal 1a9e68df7e 🆕 Name the GPU the desktop is drawn on where a VM's window cannot show
Where the library's no-window line names the GPU the desktop is drawn on by its
DRM node, a start now finds that GPU's number among `reims-ctl gpus`' list,
through /sys/dev/char (its PCI address, else IDs one GPU alone has), and says
so with the command that gives it to the VM, since it can show a window on that
desktop. Where none of the list is it, the start says how to list the GPUs and
give the VM the one the screen is plugged into.

For the user: `reims-ctl start` and the TUI now say, for example, "Your desktop
is drawn by GPU 2, <name>, which can show the window: `reims-ctl set NAME --gpu
2` gives the VM that GPU" after the library's reason, in place of its DRM node.
2026-12-04 15:46:22 -08:00
Anees Iqbal d6564da330 🆕 Tell the host of a window not shown in 10 s, and the desktop's GPU
SDL's opening of a window waits for the window system to show it with no bound,
and a start that waited on it said nothing. A window's render thread now tells
the host, 10 s after the opening began, that its window has not opened, so
reims-ctl's start says so while the VM keeps running.

Where the GPU does not present to the Wayland compositor's window, the question
now also reads the GPU the compositor composites on from that window's dma-buf
feedback, and every no-window line ends with "; the desktop is drawn on DRM
node <major>:<minor>", which reims-ctl can name as the GPU that shows a window
there.

For the host: a new line, "reims-vgpu: no window: display <n>'s window has not
opened: the window system has not shown it in 10 s", and the DRM node suffix
on the no-window lines where the compositor's GPU is known.
2026-12-04 15:46:22 -08:00
Anees Iqbal 70035c50f4 🐛 Give up on an X window its window manager does not show
The window-system question now maps its 1 x 1 X window once the GPU says it
presents to it, and counts the X server as a route only where its window
manager shows the window within 3 s. SDL's opening of an X window
(X11_ShowWindow) waits for the window manager with no bound: on um870's KWin
session no X client's window was shown, and SDL's UI thread stayed there for
good (potluck jobs m3-max-87109, 87121, 87122 and 87130, the session locked and
unlocked). A 1 x 1 window made the same way stayed unshown there too, while an
override-redirect one was shown in 10 ms (m3-max-87158).

For the host: where the GPU presents to no window the session's window systems
show, the no-window line now says "neither its Wayland compositor nor its X
server shows a window it presents to", and on X11 a 1 x 1 window is mapped for
the question before the first window opens.
2026-12-04 15:46:22 -08:00
Anees Iqbal eda0eef5d7 📝 Record that a per-platform yes did not mean a window's surface [ci skip]
The lesson of 12-02 ended with the window system chosen by Vulkan's
per-platform answers. The same laptop's next report showed that question
answering yes for Wayland while the window's own surface was refused, the
window empty again. The entry now says so, that um870's 2080 answered yes to
both (job m3-max-87068), so the lab did not make the split, gives the
report's missing DRM node and vfio-pci binding as a lead only, and adds the
window-system log line to how to spot the next one.
2026-12-04 15:46:22 -08:00
Anees Iqbal 28544a53c2 📝 Register the window system's question as asked of a window [ci skip]
The window system's entry said the GPU was asked with no window, Vulkan's
per-platform question. Since 417a81d8a3 it is asked once of a window made
for the question and never shown, the way the swapchain asks of a window's
surface, and the surface, window and connection are destroyed whatever the
answer. The entry says so, says why the per-platform question is not asked
(a user's laptop answered it yes for Wayland, its window then stayed empty),
says the one log line names each answer and the route, and names the new
fake-driver test as a guard.
2026-12-04 15:46:22 -08:00
Anees Iqbal 006a674c86 🐛 Ask a window's own surface which window system the GPU presents to
09f166332e chose the window system from Vulkan's per-platform questions
(vkGetPhysicalDeviceWaylandPresentationSupportKHR and its Xlib twin), which
name no window. A user's laptop, its NVIDIA RTX 4060 Laptop GPU (620.73.04)
picked beside the Intel GPU KWin composites on, answered that question yes
for Wayland, so its window opened through Wayland, and then answered no for
the window's own surface (vkGetPhysicalDeviceSurfaceSupportKHR), where the
swapchain asks: no swapchain, and the window stayed empty. Its vulkaninfo's
per-surface lists showed the same: the GPU presents to XCB and Xlib
surfaces, and to no Wayland surface.

The question is now asked of a window, once, before SDL's video starts: the
window crate makes one over a connection of its own, a wl_surface given no
role on Wayland and an unmapped window on X11, never shown; the sink makes a
Vulkan surface of it and asks what the swapchain asks of a window's surface
(one function the two share: surface support for the queue family, and
B8G8R8A8_UNORM in SRGB_NONLINEAR), then destroys the surface, and the window
crate destroys the window and the connection, whatever the answer. Wayland
is still asked first, and the X server only where the GPU does not present
to the compositor's window.

What changes for the host: on such a laptop the windows open through X11,
XWayland's under KWin, where the GPU presents, instead of an empty Wayland
window. Where a GPU presents to Wayland windows nothing changes. The log's
line names each answer and why each no, and the route taken:
"the windows' GPU presents to a window of the Wayland compositor: no (queue
family 0 does not present to the window's surface); of the X server: yes;
the windows open through X11".

The new test asks a fake driver answering as the report's GPU did (yes per
platform, no for a Wayland surface, yes for an Xlib surface): no for the
Wayland window, yes for the X11 one, and every surface made destroyed.
2026-12-04 15:46:22 -08:00
Anees Iqbal a49ff86f61 ✅ Keep the headless timing test's display from refreshing
a_headless_device_logs_each_present_s_timing_at_its_show reads exactly one
line on the presents' timing target. A refresh of its display between its
present's take and its show also logs the present late, a second line there,
which is the race of the commit before. Its device's 60 Hz refresh thread can
bring one, though only the device's own path from the take to the show lies
between them. Its device now refreshes once in 1000 s (headless_unrefreshed),
and its line names refresh 0, which the test's comparison reads as it read any
other. No comparison changed.
2026-12-04 15:21:19 -08:00
Anees Iqbal 74ba7a3a1e ✅ Refresh a late present's test display once in 1000 s
a_present_shown_late_logs_its_last_writer_to_finish failed on the macOS CI
runner (run 47441893139), and needed a rerun in three Windows legs on the
mini (12-03): its line said "a refresh of its display came between its take
and its show (1 in all)" where the test reads none.

The line names only a refresh that ran: the device counts a display's
refreshes as its refresh thread calls the host at each tick. The test's
headless device refreshes at 60 Hz on that thread, and the test's own polls
(1 ms sleeps) for the device's take of the present and the host's commits lie
between the present's take and its show, so under load a tick falls between
them: 9 of 400 runs on a Linux node beside a CPU hog (job m3-max-87142).

A device of the tests can now be given its headless displays' refresh rate
(GraphicsConfig::headless_refresh_mhz, behind cfg(test)), and the test's
display refreshes once in 1000 s, as the graphics crate's rigs' displays do
(NEVER_MHZ): its refresh thread paces its refreshes by that rate from its
start, so it runs none during the test. A new test pins that such a device
runs no refresh of its own. No comparison changed, and neither the host nor
the guest sees anything new.
2026-12-04 15:20:06 -08:00
Anees Iqbal 0531e6a7f7 🆕 Trace VideoToolbox's frame takes and hand-backs on the host
The M3's HEVC playback missed eight pictures right after play began, with
every frame decoded and every recorded frame emitted, and nothing the host
logs tells a player skip from a late hand-back or a missed capture: no line
times a decoder's frames or the recorder's.

The paravirtual sessions now write three events into the host's profiling
trace (REIMS_VGPU_TRACE, off unless set): a decoder's frame taken, with its
sample's presentation time (vtdfrm), its Demt about to go out, with how it
landed (vtdemt), and an encoder's frame taken, with its presentation time
(vtefrm). With ring 0's takes, which already time each PRESENT_SURFACE, a
traced run lines up the decoder's hand-backs and the guest's presents with
the recording's own timestamps. Nothing changes for the guest or the host
with the trace off.
2026-12-04 14:56:34 -08:00
Anees Iqbal f7f8aca583 📝 Name the paravirtual sessions' trace events in the video docs [ci skip]
A VideoToolbox playback question starts in docs/video, and nothing there said
that the host's trace times the paravirtual sessions. The paravirtual path's
section now names vtdfrm, vtdemt and vtefrm, points at Link::trace for their
fields, and says how, with ring 0's PRESENT_SURFACE takes, they line up the
hand-backs and presents against a guest's recording.
2026-12-04 14:56:34 -08:00
Anees Iqbal e37ae81bcd ✅ Park a test rig's refresh threads before a test sets a rate
a_screen_s_new_rates_are_told_with_display_changed failed once on the macOS CI
runner: after the DISPLAY_CHANGED of the rates going away, the GET_DISPLAYS
that followed was answered behind a second DISPLAY_CHANGED, 24 bytes where the
test read a DISPLAYS.

The tests run each refresh themselves, and the rig's screens run at NEVER_MHZ,
a period of 1000 s, so the device's own refresh thread sleeps through a test.
But that thread reads its screen's mode for its next refresh's time once, when
it starts, and rig_of_rates sets the screen to 120 Hz right after the device
is made: in 1999 of 2000 rates rigs on a Linux node the thread started after
that, and refreshed display 0 at 120 Hz beside the test's own refreshes. Two
refreshes of one display at once can each tell one change: both find the
change owed before either posts it, or one whose modes were read before the
test cleared the rates tells the old modes again after the test's refresh
told the new. The device itself refreshes each display from its one thread,
so the guest never meets this.

The rig now hands a device over only once each display's refresh thread has
read its screen's mode (TestScreen marks a read on a refresh thread), so a
rate a test sets after never paces the thread. A new test pins that a rig's
refresh threads run no refresh at a rate a test sets. No comparison changed.
2026-12-04 14:36:42 -08:00
Anees Iqbal c16328ee3d 🚨 Keep the self-check chroma levels for their test alone
d6ab1eaed7 left CHROMA_LEVELS read only by the test that keeps CELL_COLOURS
equal to the combinations inside RGB, so the library's build called it dead
code and clippy failed under -D warnings on every target. It stays where the
cell list's doc names it, expected dead outside tests. Also lays out the RGB
round-trip test's matrix pairs as rustfmt asks.
2026-12-04 14:04:08 -08:00
Anees Iqbal d6ab1eaed7 🐛 Draw the self-check stream's cells in colours RGB keeps
A guest shows a decoded picture in 8-bit RGB, and a screen recording takes it
back to 4:2:0 from RGB, as does a QMP screendump read as video. Fifteen of the
36 combinations of the flat cells' levels lie outside RGB (Y 40 with Cb or Cr
at 80 or 176, Y 190 with Cb 176): such a cell comes back clipped, up to 32
code values off. On the 780M a QuickTime playback judged from its recording
called WRONG in nearly every frame (1169 of 1241), each off cell an
out-of-gamut one, every in-gamut cell within 12 of its levels.

content_cell now draws each cell from CELL_COLOURS, the 18 combinations of
the same levels whose colour lies 8 or more inside 8-bit RGB under both the
BT.709 and the BT.601 matrix, so a player that takes either matrix leaves a
cell within the judge's slack: a matrix the other way round moves a cell at
most 15.5 luma and 6.4 chroma code values. The slacks and every other
threshold are unchanged. The streams are tagged BT.709 at limited range, so
the guest's player converts by the stated matrix.

Tests: the colours are exactly the combinations inside RGB; each comes back
from 8-bit RGB within the slack, by either matrix either way; pictures shown
in RGB and taken back pass; a stale row of cells is still WRONG after that
round trip. selfcheck.sh selftest adds the same through ffmpeg: the H.264
decode to rgb24 by BT.709 and by BT.601, back to 4:2:0 by BT.709 and
re-encoded, judged clean, and with frame 60's row 2 cells frame 68's, judged
WRONG.
2026-12-04 13:47:05 -08:00
Anees Iqbal cc1f47b30b 🆕 Add a self-checking video stream and its frame-by-frame judge
A screen recording of a guest's playback, or a decoded file of a stream we
did not make, could be judged only for green frames (the vtacc judge). A
wrong, repeated, dropped or reordered picture passed unseen, as there was no
reference decode to set beside it.

The conformance crate's selfcheck module draws pictures that each carry their
own frame number: three bands of 14 bits and their complement. The rest of
the picture says what it should look like: flat cells whose levels change
every eight frames at staggered phases, so a stale reference shows, and
moving stripes. It judges a frame from its pixels alone: repeated, out of
order, torn (its bands disagree), wrong (cells not its number's picture's),
green or partly green (rec-judge.py's measure), unreadable, and the runs of
numbers no frame showed (dropped). A recording is judged in a given crop
region, where a held picture, frames outside the stream, and a loop are no
fault.

tools/selfcheck.sh makes the streams with the host's ffmpeg (H.264, HEVC
Main and Main 10, VP9, AV1, each whose encoder the host has). It judges files
as ffmpeg decodes them in software. Its selftest, which needs no GPU, judges
each codec's decode clean, then calls each fault class from a decode an
ffmpeg filter faulted, and judges a simulated recording clean. Nothing the
encoders write is committed.

The tests are selfcheck::tests: each class made by hand on drawn pictures, a
lossy decode's noise, and a recording scaled into a screen, held, looped and
wrapped past 2^14.
2026-12-04 12:59:49 -08:00
Anees Iqbal 76524528d8 🆕 Count each arm64 video session's frames by way and cause
An arm64 guest's VideoToolbox decoder session ended with three totals (landed,
dropped, failed), and an encoder session with no line at all. A user's report
could not say how each picture went: which way it reached the surface the
guest lent, or why a frame failed.

Each session now logs one line at info as it ends, from what the session and
the arm already know, with no query of the hardware: totals, statuses and
causes alone, nothing of the guest's content.
- A decoder session counts frames landed by what wrote the picture (the
  hardware, the device's GPU, the CPU's copy), dropped, failed by cause (no
  buffer lent in time, the guest's buffer refused, a sample that does not
  read, no decoder opened, the decoder's failure) with their statuses, and
  answered with no decoder. It also counts emits the guest did not answer, a
  refused start, tiles, unread messages, and the time of the arm's decodes.
- An encoder session counts frames emitted with a sample, dropped, failed
  by the encoder or at the format description, refused at their take,
  answered with no encoder, lost at a flush, replaced while waiting, and held
  at its end. It also counts unanswered emits, a refused start, refused
  property sets, unread messages, and the time of the arm's encodes.

The way comes from the arm's own answer. `GuestDecoder::decode` and
`paravirt::BackendDecoder` return `Decoded::Landed(LandedBy)` in place of a
bool, each arm stating at each return what wrote the picture. Nothing
changes for the guest.

The tests are paravirt::decoder::tests and paravirt::encoder::tests. Each
has a counts-to-line test, and a whole-session test whose end line must
equal what the guest was told for every class. The harness fake leg's
the_session_s_end_line_counts_what_the_guest_was_told ties the line to the
guest's own tally of its Demt messages. The arms' tests now assert the way:
the Mac arm's GPU and CPU copies, and the NVIDIA arm's gather and CPU
copies.
2026-12-04 12:59:48 -08:00
Anees Iqbal a9efa5821d 📝 Wrap the VM display settings' doc at the line width [ci skip]
The sentence the refresh-rate option added ran to 156 columns; rewrapped at
100 like the rest of the comment. Comment only (planner's note on #113).
2026-12-04 12:59:48 -08:00
Anees Iqbal c745eecfd0 ⬆️ Build on metal2vulkan development a71ba816e3
Pin Z, from 865592b96b (W): 129 commits, the last a runtime README commit.
SEMANTICS_VERSION 2386, ARTIFACT_FORMAT_VERSION 615, RUNTIME_VERSION 2579 (from
2370, 609 and 2571).

The move alone. It carries the growth fix's straight-line XR decode, under
which a Mac host's KosmicKrisp makes every pipeline an arm64 guest's
WindowServer asks for (pin X's family that failed pipeline creation now
compiles), and issue 181's plane fixes: a Direct3D 11 plane's image takes the
usage its bind flags give and never the attachment feedback loop usage, a draw
reading its own attachment on one goes by the runtime's counted copy, and an
import now needs D3D11_TEXTURE among the driver's compatible handle types,
else the plane takes the copy form. The 16 public items the range removes are
named nowhere in this tree, so no call site changes.
2026-12-04 12:35:53 -08:00
Anees Iqbal e08ab5d787 🎨 Lay out the refresh rate's code as rustfmt asks
rustfmt's check, which the legs run, wants the refresh rate's new code laid
out its way: a struct literal in a returned tuple and two lists in tests
broken over lines. Nothing else changes.
2026-12-04 12:17:54 -08:00
Anees Iqbal 39a1e4c591 📝 Say a 120 Hz-only guest may start at a smaller size [ci skip]
On msi's 3840x2400 120 Hz panel, with the refresh rate set to 120, a fresh guest
disk started at 1680x1050 HiDPI in all three boots (m3-max-86624, and the two B
arms of m3-max-86730), and CoreGraphics listed 13 modes with no 3840x2400 1:1
mode. The #110 tree, before the per-monitor rates, did the same in both of its
arms in that job, so this is macOS's pick on a single-rate list and not a
regression. The known issue now says so and where to change the size.
2026-12-04 12:17:54 -08:00
Anees Iqbal 75f4bbf724 🆕 Set a VM's refresh rate from reims-ctl
A VM can now be given one refresh rate that its displays offer the guest
every size at: reims-ctl create and set take --refresh-rate HZ|auto, and the
interface's create and edit forms a Refresh rate field, as they take the
resolution. It is kept in the VM's settings as [display] refresh_rate, not
saved while unset, and reaches the library as REIMS_VGPU_WINDOW_REFRESH_RATE.
A rate above the screen's is lowered to the screen's, which the help says and
logs/qemu.log logs. 0, negative rates, rates above 1000 Hz and what is no
number are refused when set, with a plain message.

The key is a new one: the refresh apple-gfx's settings saved is still read
past and dropped at the next save, and never sets the rate. Unset, a VM
starts as before. The known issue of a borderless Intel Mac guest's 60 Hz
first start now says how to have it start at the screen's rate.
2026-12-04 11:28:41 -08:00
Anees Iqbal c750d9a60d 🆕 Offer one refresh rate where the host sets one
A display whose host sets REIMS_VGPU_WINDOW_REFRESH_RATE now offers a guest
that takes DISPLAY_RATE every size at that one rate alone, titled or
borderless, and runs its refreshes at it once the guest sets it, through the
same rate machinery as a borderless window's other rates. A rate above the
screen's is lowered to the screen's, with one warning in the log for each
screen rate it is lowered to.

For the guest: with the variable set, its Displays settings list that one
rate. Unset, nothing changes: a titled window offers its screen's rate, a
borderless one its screen's rates, and a headless display 60 Hz. A kext
built before DISPLAY_RATE is offered the screen's rate, as before. The host
only narrows the list it already sends: the kexts, the option ROM and the
wire are unchanged.
2026-12-04 11:28:41 -08:00
Anees Iqbal 01e5bb39e8 🆕 Carry the driver's plane import answers in the diagnostic lines
A video plane on Windows is an image rt makes over a Direct3D 11 texture as
the driver's import query answers it, and the one Windows GPU the tests run on
answers for its own driver alone. A report from a machine whose driver loses
the device while work uses those planes cannot tell which form rt chose there,
nor whether that driver would import a Direct3D 12 resource instead.

At each device's make on Windows the platform now asks the driver the import
queries rt asks of each plane format (the usage the planes' bind flags give,
with the feedback loop's where rt asks it, and over the sRGB sibling's list),
for the Direct3D 11 texture and the Direct3D 12 resource handle types, and the
rt-diag lines carry the answers, a line a plane format, at each write of the
counts, which a report's ask makes. A diagnostic: nothing rt makes changes.
2026-12-04 10:52:42 -08:00
Anees Iqbal 9889a815bb 📝 Name the Linux-only connector read in plain code, not a link
filled_screen's doc linked with_connector_rates, which is built on Linux
alone, so rustdoc for the Windows target could not resolve the link and
failed (lint leg m3-max-86523). The doc now names it in code with where it
exists.
2026-12-04 10:45:33 -08:00
Anees Iqbal 5003565a11 🎨 Lay out the connectors' tests as rustfmt asks
The connectors' read landed with three assertions laid out past rustfmt's call
width, which cargo fmt --check refuses; this is rustfmt's own layout of them.
2026-12-04 10:29:40 -08:00
Anees Iqbal a226538169 📝 Say an x86 guest's first borderless start is at 60 Hz [ci skip]
On a 120 Hz screen a borderless x86-64 guest whose disk has not seen the
display starts at 60 Hz: CoreGraphics moves the default flag from the kext's
120 Hz mode to the same size at 60 Hz, and neither listing the 60 Hz modes
first nor taking the safe flag off them brings it to 120 Hz. The known issue
says so, with the judder of rates that do not divide the screen's, and
design.md and lessons.md record the measured rule. A titled window's display
still lists its screen's rate alone, so the 0 Hz paragraph now says which
window it holds for.
2026-12-04 10:29:36 -08:00
sitxovski 339efbb8cd 🆕 Charge GPU time on macOS 26 and keep Core Image shadows
Activity Monitor's and powermetrics' per-process GPU time stayed at zero
in a guest: nothing charged it. From macOS 26 (Darwin 25) on, earlier
releases unchanged:
- The bundle sums each command buffer's GPU time from its completion and
  hands it to the kext with WaitCompletions, a second scalar the kext
  offers with kRgfxKextFeatureGpuTime.
- The kext publishes AppUsage per process and the accelerator's
  PerformanceStatistics each second (RgfxGpuTime.hpp, gpu_time_test).
- RgfxGate looks ml_gpu_stat_update up through Graft once, on x86-64
  alone and with no weak import, and charges the calling thread on
  callPlatformFunction("rgfx-gpu-stat-update").

The bundle also keeps up to 64 shadow libraries by file identity, so Core
Image does not compile one again for each icon, and RgfxSdkCompat.h lets
it build against SDK 26.x.

guest/prebuilt and guest/prebuilt-arm64e are not rebuilt here.
2026-12-04 17:27:30 +03:00
sitxovski b5adda6039 🐎 Cut cross-queue waits, copies and refresh overshoot
A buffer of one queue that names a buffer of another queue still being
walked waited on its queue's thread until that buffer was committed. On a
macOS 26 desktop on Windows with an RTX 4060, 436 begins waited so, up to
53.6 ms. The wait is there so a buffer cannot wait on the GPU for itself
through a cache fill the named buffer's begin adds; that holds once the
named buffer is prepared (its begin returned, every use and fill it adds
fixed), so the begin now waits for a new Until::Prepared mark. A buffer
holding a video op, or begun behind an uncommitted one of its queue, is
prepared only by its commit. The begins that waited fell to 1.

This changes when such a buffer is committed: it may now be committed
before the buffer it names. The GPU order is unchanged: it still waits on
the GPU, exactly once, for the named buffer's surface timeline signal.
a_reader_in_another_process_waits_on_the_gpu_for_an_answered_writer and
a_buffer_named_while_its_queue_s_later_buffer_is_walked_first_is_waited_for
held the old commit order; they now check the wait and the signal alone.

Also:
- A surface cache REFILL is checked again where it is carried out: a cache
  a command buffer wrote since is filled into its shapes alone, so the fill
  never writes over that write.
- replaceRegion reads guest bytes in place, but for tiled textures and
  textures over another resource.
- A display's refresh is capped at 164 Hz by default and never above its
  screen's own rate (REIMS_VGPU_MAX_REFRESH_HZ, 24 to 1000).
- reims-ctl preallocates a Windows guest's RAM with a thread per vCPU
  (REIMS_CTL_WIN_PREALLOC=off opts out); REIMS_CTL_WHPX_SSD=off passes
  ssd=off to WHPX.
- REIMS_VGPU_PRESENT_MODE and the Windows page size are read once.
2026-12-04 17:27:29 +03:00
kilbertert c2d46d1e0e reims-vgpu: offer the Shared pool to arm64 guests on Windows TCG 2026-12-04 15:04:04 +08:00
Anees Iqbal a910c287cf 🐛 Build the bundle's tests for an x86-64 Mac
On an x86-64 Mac the shell tests compile for x86_64, where BOOL is a signed
char: the two raises lambdas returned a BOOL and a bool, which clang refuses,
and raisesInsertingNil was unused, its callers being only where the device
makes residency sets, which -Werror refuses. The lambdas now return bool, and
the helper is built where its callers are. The tests are unchanged on arm64.
2026-12-03 19:04:09 -08:00
Anees Iqbal c518e049e9 🆕 Tell the host each mode's rate from the guest's kexts
Where the host offers DISPLAY_RATE (FEATURES_EXT bit 3), the x86-64 and
arm64e kexts take it, and each mode set (setScanout, which setDisplayMode,
enableController and the arm64e setMobileMode share) follows SET_SCANOUT
with SET_DISPLAY_RATE carrying the mode's rate. The host then lists each
size again at its screen's other rates and runs the display's refreshes at
the one the guest picked. A host from before it offers no bit 3: this kext
takes nothing there and sends no rate, and the host lists one rate, as
before. A failed set is logged and the refreshes keep the rate before.

The prebuilt sets carry the new ReimsGraphics, and both records and the
option ROM's take the new wire header; the ROM's bytes are unchanged
(m3-max-86348).
2026-12-03 19:04:09 -08:00
Anees Iqbal 537a923466 🆕 Read a Wayland screen's rates from its DRM connector
On Wayland SDL lists a screen's current rate alone (SDL 3.4.18 keeps only
the current wl_output mode), so a borderless window there offered its guest
one rate. Where SDL lists no other rate, the screen it fills now takes the
rates its DRM connector lists at its size.

The read is a plain one (planner's Q1 A): each card's primary node, opened
read-only, GETRESOURCES and then GETCONNECTOR with room for 256 modes, which
reads the list the compositor's last probe left and probes nothing. The
screen's connector is the one connected connector that lists its size within
0.5 Hz of its rate. Where none does, two do (two screens of one model at one
mode, as on ms01) or a card cannot be read, the screen keeps its one rate:
no screen is offered another's. The tests run on connector data captured on
msi and ms01, the ambiguous pair among them.
2026-12-03 19:04:09 -08:00
Anees Iqbal 6e2be76fa6 🆕 Offer a borderless window's guest the rates of its screen
A borderless window fills one host screen, and the display now offers its
guest that screen's rates (owner's 221: borderless and per monitor). The
window's side finds the screen it fills at its opening, when it moves to
another screen and when the screens change (Window::filled_screen), with the
rates that screen lists at its size (HostScreen::rates_hz, from SDL's
full-screen modes or CoreGraphics' modes). WindowScreen takes that screen's
rate as the first mode's and its other rates as Screen::rates, which the
device's SharedScreen passes on.

A titled window keeps today's behaviour exactly: it offers the rate of the
screen it opened on, alone. On Wayland SDL lists a screen's current rate
alone, so there a borderless window offers one rate until the next commit
reads the connector's.
2026-12-03 19:04:09 -08:00
Anees Iqbal aa40f0514e 🆕 Run a display's refreshes at the rate the guest set
A guest that picked a lower rate than its screen's still got VBLANKs, present
answers and window draws at the screen's rate: the refresh thread paced every
display at its screen's mode, and SET_SCANOUT carries no rate, so the host never
learned the guest's pick.

FEATURES_EXT bit 3, DISPLAY_RATE, is taken in DRIVER_FEATURES_EXT. For a guest
that took it, a display offers its screen's other rates (the previous commit)
and ring 0 carries SET_DISPLAY_RATE (13) with the rate of the mode the guest
set. The refresh thread runs at that rate while the display offers a mode at it,
and at the screen's rate otherwise: once a refresh finds the rate gone from the
modes offered, and after a reset. Every library host offers the bit.

For the guest, the change is the offer and the take. A kext built before the
bit takes nothing and is offered each size at the screen's rate alone, as
before. A kext that takes it on an older host takes nothing either. The tests
pin both pairings, the pacing, its fallbacks and the gate. This commit also
regenerates the wire header and its size table, and the design doc describes
the bit, the command and the pacing.
2026-12-03 19:04:09 -08:00
Anees Iqbal f8abde33a7 🆕 Offer each display size again at the screen's other rates
The owner asked for the host screen's refresh rates in the guest, as a Mac
lists a screen's rates for each of its sizes, for a borderless window and the
screen it fills. This is the device's half: a Screen may now list the other
rates its host screen has at its size (Screen::rates, none by default, so every
screen today offers what it did), and offered_modes lists the display's sizes
at the screen's rate first, in today's order, then the same sizes again at
each lower rate, highest first.

Only rates below the screen's own are offered, since the host screen keeps its
mode. Rates within 0.5 Hz of the screen's or of each other are offered once,
keeping the one nearer the screen's rate, because the kexts take a listed rate
within 500 mHz of another for the same mode (RgfxDisplayModes' near). Every size
takes the same rates, and MODES_MAX rises from 8 to 24 (the kexts take 64):
seven sizes get three rates each.

The guest was told only of changes to the first mode, so a borderless window
moving to a screen of its size with other rates would have gone untold. The
device now keeps the whole list it told and sends DISPLAY_CHANGED when any of it
changes, the same path a resize takes.
2026-12-03 19:04:09 -08:00
191 changed files with 13229 additions and 1586 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 (homelab-um870, 2026-12-03, potluck job m3-max-85816).
# Vulkan driver (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 (homelab-um870, 2026-12-03, at 5cb932953e): 218 of the
# Measured on Linux with no Vulkan driver (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.
+10 -2
View File
@@ -262,7 +262,9 @@ 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.
# 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.
- name: Add cc and git to the image
env:
IMAGE: ${{ steps.image.outputs.dir }}
@@ -278,7 +280,13 @@ jobs:
-v "$cache/pacman.conf:/etc/pacman.conf:ro" "$image" bash -euc '
owner=$1
shift
pacman -S --noconfirm --needed "$@"
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
yes | pacman -Sc >/dev/null
chown -R "$owner" /var/cache/pacman/pkg /var/lib/pacman/sync
' bash "$(id -u):$(id -g)" "${extras[@]}"
+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 = "865592b96b791840b26dddb310f33561bfc7d564" }
metal2vulkan = { git = "https://github.com/steelbrain/metal2vulkan", rev = "08848fd8a579d6de1ccdb584f105a61ba2b2f57d" }
# 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 = "865592b96b791840b26dddb310f33561bfc7d564" }
metal2vulkan-runtime = { git = "https://github.com/steelbrain/metal2vulkan", rev = "08848fd8a579d6de1ccdb584f105a61ba2b2f57d" }
# 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
+61 -1
View File
@@ -768,6 +768,13 @@ 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>,
@@ -822,6 +829,13 @@ 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>,
@@ -1234,6 +1248,9 @@ 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)?;
@@ -1483,7 +1500,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 and borderless reach them.
// windows' first sizes, borderless and the refresh rate reach them.
if graphics == vm::Graphics::ReimsVgpu {
let n = c.display.count;
let at = window_sizes_named(&c.display);
@@ -1502,6 +1519,12 @@ 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(
@@ -1721,6 +1744,9 @@ 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)?;
}
@@ -2846,6 +2872,40 @@ 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 the mini, 2026-11-15; job 32290 of the same code got the range).
/// there (job m3-max-32291 on Windows 11, 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)] }
+15 -1
View File
@@ -81,7 +81,9 @@
//! 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`.
//! `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`]).
//! - 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,
@@ -251,6 +253,9 @@ 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()? {
@@ -2295,6 +2300,15 @@ 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");
+190 -1
View File
@@ -1487,6 +1487,15 @@ 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 {
@@ -2035,7 +2044,19 @@ 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 window;
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,
};
}
if Instant::now() >= until || pid(vm).is_none() {
return StartWindow::NotShown;
@@ -2048,6 +2069,98 @@ 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
@@ -2181,6 +2294,82 @@ 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
+67 -7
View File
@@ -2353,6 +2353,8 @@ 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",
@@ -2398,7 +2400,8 @@ impl App {
self.overlay = Some(Overlay::Form(FormKind::Edit(c.name.clone()), form));
return;
}
// The displays', the resolution's, borderless's and the GPU's fields are reims-vgpu's.
// The displays', the resolution's, borderless's, the refresh rate'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),
@@ -2416,6 +2419,13 @@ 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));
@@ -2726,6 +2736,9 @@ 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") {
@@ -3231,6 +3244,17 @@ 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)
@@ -3359,7 +3383,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, and borderless stay as they were.
// first size, borderless and the refresh rate stay as they were.
if f.is_shown("displays") {
c.display.count = f.choice("displays").parse().context("displays: a number")?;
}
@@ -3370,6 +3394,9 @@ 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) {
@@ -3577,15 +3604,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, 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, 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
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 and GPU are reims-vgpu's
borderless, refresh rate 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
@@ -5077,6 +5104,36 @@ 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]
@@ -5089,9 +5146,12 @@ 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;
+97 -7
View File
@@ -247,13 +247,14 @@ impl DiskController {
/// 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. 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, 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.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct Display {
@@ -269,8 +270,22 @@ 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;
@@ -294,6 +309,7 @@ impl Default for Display {
count: 1,
resolution: "1920x1080".into(),
borderless: false,
refresh_rate: None,
}
}
}
@@ -363,10 +379,36 @@ 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'])
@@ -1635,6 +1677,7 @@ 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 {
@@ -1648,6 +1691,53 @@ 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,
+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 ms01's Iris Xe with jemalloc
/// arena for each such block on the allocating thread (measured on an 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.
+1
View File
@@ -328,6 +328,7 @@ include = [
"RgfxScrollDevices",
"RgfxSetCursor",
"RgfxSetDisplayPower",
"RgfxSetDisplayRate",
"RgfxSetScanout",
"RgfxSetVblank",
"RgfxSharedEventCreate",
@@ -1031,6 +1031,18 @@
// 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
@@ -1847,11 +1859,12 @@
#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`]): 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
// 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
// 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
@@ -1859,7 +1872,8 @@
#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`]). A write takes the
// `FEATURES_EXT` offers that are taken ([`RGFX_FEATURE_EXT_SURFACE_HOLD`],
// [`RGFX_FEATURE_EXT_DISPLAY_RATE`]). 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
@@ -1922,6 +1936,24 @@
// 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
@@ -2182,6 +2214,10 @@
// [`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
@@ -3656,6 +3692,10 @@
// 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
@@ -8348,6 +8388,20 @@ 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 {
@@ -8935,8 +8989,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`]. Zero from a host older
// than these.
// `RGFX_VIDEO_ENCODE_CAP_*`: [`RGFX_VIDEO_ENCODE_CAP_IN_PLACE`],
// [`RGFX_VIDEO_ENCODE_CAP_REORDERED`]. Zero from a host older than these.
uint32_t flags;
// Zero.
uint32_t reserved_0c;
@@ -9004,9 +9058,10 @@ 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 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.
// 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.
typedef struct {
// The coded picture's width, the sources' size: even.
uint32_t width;
@@ -9053,7 +9108,8 @@ 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_*` settings bits: [`RGFX_VIDEO_ENCODE_HARD_LIMIT`],
// [`RGFX_VIDEO_ENCODE_REORDERED`].
uint32_t flags;
// The VUI's `colour_primaries` (ITU-T H.273), in the SPS the host packs.
uint8_t color_primaries;
@@ -320,6 +320,7 @@ 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 homelab-um870-1 (Ryzen 7 8745H, CachyOS, Linux 7.3.3, the vDSO's
//! **Measured** 2026-11-18 on a 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 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).
//! `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).
//!
//! 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 homelab-um790-xtx-1's 45 ppm as a transport that climbed to 230 us between
//! wrote, showed the first host'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.
+22 -8
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, offered_modes, straight_rgba};
use crate::display::{CursorImage, Scanout, straight_rgba};
use crate::ring::{Message, set_size, sized};
use crate::wire::*;
@@ -73,6 +73,10 @@ 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,
};
@@ -392,11 +396,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 ([`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.
/// 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).
fn displays(shared: &Shared, seqno: u64) -> Vec<u8> {
let seen = shared.displays_seen();
let mut bytes = RgfxMsgHeader {
@@ -408,9 +412,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 = offered_modes(display.screen.mode(), shared.display_count());
let modes = shared.offered_modes(display);
let first = modes[0];
display.state.lock().told = Some(first);
display.state.lock().told = Some(modes.clone());
let mut records = Vec::new();
let mut mode_count = 0;
for mode in &modes {
@@ -726,6 +730,16 @@ 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 {
+97 -15
View File
@@ -27,12 +27,15 @@
//! 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 ([`Screen::mode`]): at each
//! `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
//! 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 mode is not the one the guest was last told, and then
//! `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
//! 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`
@@ -247,7 +250,8 @@ 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, offered_in_room, scanout_room, scanout_room_at,
CursorImage, Mode, Scanout, Screen, fixed_rate_mode, offered_modes, scanout_room,
scanout_room_at,
};
use crate::ops::RgfxCommandBuffer;
use crate::region::Region;
@@ -359,7 +363,8 @@ 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;
pub(crate) const TAKEN_EXT_FEATURES: u32 =
RGFX_FEATURE_EXT_SURFACE_HOLD | RGFX_FEATURE_EXT_DISPLAY_RATE;
/// 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.
@@ -1897,6 +1902,9 @@ 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.
@@ -1910,8 +1918,12 @@ pub(crate) struct DisplayState {
pub(crate) asleep: bool,
/// Refreshes since the last reset.
refreshes: u64,
/// The mode the guest was last told, in a `DISPLAYS` or a `DISPLAY_CHANGED`'s wake.
pub(crate) told: Option<Mode>,
/// 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>,
/// A `DISPLAY_CHANGED` is owed.
changed: bool,
/// The cursor's image as the guest's last `SET_CURSOR` set it, straight RGBA, before its
@@ -1921,6 +1933,16 @@ 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
@@ -1966,6 +1988,7 @@ impl Device {
.map(|screen| Display {
screen,
state: Mutex::new(DisplayState::default()),
lowered_mhz: AtomicU32::new(0),
})
.collect();
let mut consumer = Consumer::new(SUBMIT);
@@ -2958,6 +2981,12 @@ 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)
@@ -3501,10 +3530,63 @@ impl Shared {
}
}
/// 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())
/// 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(),
}
}
/// Whether `len` bytes at `offset` lie in display `id`'s scanout room
@@ -5430,14 +5512,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(screen) = self.displays.get(display as usize).map(|d| &d.screen) else {
let Some(shown) = self.displays.get(display as usize) 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(screen.mode().period_ns(), now);
let tick = grid.next(self.refresh_period_ns(shown), now);
let mut left = tick.saturating_sub(now);
while left > part {
std::thread::sleep(REFRESH_SLEEP_PART);
@@ -5467,13 +5549,13 @@ impl Shared {
self.watch_version_leave(now);
}
let epoch = self.epoch.load(Ordering::Acquire);
let mode = self.offered_mode(display);
let modes = self.offered_modes(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.is_some_and(|told| told != mode) {
display.told = Some(mode);
if display.told.as_ref().is_some_and(|told| *told != modes) {
display.told = Some(modes);
display.changed = true;
}
(
@@ -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, msi RTX 5080 host; measured). A thread is never refused to a
//! lane with a job, so the waits still end.
//! 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.
//!
//! **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
+341 -10
View File
@@ -34,9 +34,17 @@ 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`]).
/// 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.
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 {
@@ -47,15 +55,29 @@ enum Told {
Power(bool),
}
/// A screen with a mode the test sets, recording what it is told.
/// A screen with a mode, other rates and a set rate 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 {
*self.mode.lock()
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()
}
fn scanout(&self, scanout: Option<Scanout>) {
self.told.lock().push(Told::Scanout(scanout));
@@ -162,6 +184,10 @@ 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.
@@ -231,28 +257,52 @@ impl Rig {
Rig::with_displays(host, lanes, 1)
}
/// [`Self::with_lanes`], for a device of `count` displays, each screen's mode [`MODE`].
/// [`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`]).
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 boxed = (screens.iter())
.map(|(mode, told)| {
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 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,
@@ -455,6 +505,47 @@ 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 {
@@ -837,7 +928,8 @@ 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; one that did not gets the answer without it (`get_displays_answers_the_screen_s_mode`)
/// 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`)
#[test]
fn a_guest_that_took_display_scale_is_told_the_screen_s_scale() {
struct Scales;
@@ -858,9 +950,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, 96, seqno)
(RGFX_EVT_DISPLAYS, 104, seqno)
);
let words: Vec<u32> = bytes[16..92]
let words: Vec<u32> = bytes[16..104]
.chunks(4)
.map(|c| u32::from_le_bytes(c.try_into().unwrap()))
.collect();
@@ -868,7 +960,8 @@ fn a_guest_that_took_display_scale_is_told_the_screen_s_scale() {
assert_eq!(
words,
[
1, 0, 1, 0, 4, 240, 0, 1280, 800, n, 1120, 700, n, 992, 620, n, 960, 600, n
1, 0, 1, 0, 5, 240, 0, 1280, 800, n, 1120, 700, n, 992, 620, n, 960, 600, n, 1696,
1060, n
]
);
}
@@ -1186,6 +1279,244 @@ 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);
let offered = crate::display::offered_modes(screens[i], &[], count as u32, scaled);
assert_eq!(id, i as u32);
assert_eq!(scale, if scaled { screens[i].scale_120ths } else { 0 });
let want: Vec<[u32; 3]> = (offered.iter())
+450 -51
View File
@@ -5,11 +5,17 @@
//! ([`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: 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.
//! ([`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.
//!
//! **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,
@@ -36,7 +42,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 is offered only where its scanout fits the room.
//! Each smaller mode, and the larger one, is offered only where its scanout fits the room.
pub(crate) mod cursor_color;
@@ -125,24 +131,64 @@ 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 most modes a display offers, its first among them.
// 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.
/// cbindgen:ignore
pub const MODES_MAX: usize = 8;
pub const MODES_MAX: usize = 24;
// The first mode and one for each step fit.
const _: () = assert!(SMALLER_MODE_STEPS.len() < MODES_MAX);
// 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 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> {
/// 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> {
let first = offered_in_room(mode, count);
let mut modes = vec![first];
let (w, h) = (u64::from(first.width), u64::from(first.height));
@@ -170,9 +216,96 @@ pub fn offered_modes(mode: Mode, count: u32) -> Vec<Mode> {
..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)]
@@ -246,6 +379,23 @@ 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.
@@ -403,8 +553,8 @@ mod tests {
}
}
/// The modes a display offers for a screen of `width` x `height` on a device of `count`
/// displays, as sizes.
/// 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.
fn sizes(width: u32, height: u32, count: u32) -> Vec<(u32, u32)> {
let mode = Mode {
width,
@@ -412,15 +562,16 @@ mod tests {
refresh_mhz: 59_940,
scale_120ths: 240,
};
offered_modes(mode, count)
offered_modes(mode, &[], count, true)
.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; 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
/// 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
#[test]
fn a_display_offers_its_screen_s_ratio_at_a_mac_s_steps() {
assert_eq!(
@@ -432,7 +583,8 @@ mod tests {
(2880, 1620),
(2560, 1440),
(1920, 1080),
(1440, 810)
(1440, 810),
(5120, 2880)
]
);
assert_eq!(
@@ -444,7 +596,8 @@ mod tests {
(2304, 1440),
(2048, 1280),
(1536, 960),
(1152, 720)
(1152, 720),
(4096, 2560)
]
);
assert_eq!(
@@ -455,15 +608,17 @@ mod tests {
(2000, 1124),
(1920, 1080),
(1696, 954),
(1280, 720)
(1280, 720),
(3408, 1916)
]
);
}
/// 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`
/// 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`
#[test]
fn every_mode_has_the_screen_s_rate_and_steps() {
for (w, h) in [
@@ -483,14 +638,20 @@ mod tests {
refresh_mhz: 143_912,
scale_120ths: 180,
};
let modes = offered_modes(mode, count);
let modes = offered_modes(mode, &[], count, true);
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 m in &modes[1..] {
for (i, m) in modes.iter().enumerate().skip(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}");
assert!(m.width < modes[0].width && m.height < modes[0].height);
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!(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;
@@ -500,12 +661,237 @@ 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
/// 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
#[test]
fn odd_and_portrait_screens_offer_their_own_ratio() {
assert_eq!(sizes(1366, 768, 1), [(1366, 768), (1184, 664)]);
assert_eq!(sizes(1001, 777, 1), [(1001, 777), (864, 670)]);
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(1080, 1920, 1),
[
@@ -513,7 +899,8 @@ mod tests {
(944, 1678),
(832, 1478),
(800, 1422),
(720, 1280)
(720, 1280),
(1440, 2560)
]
);
assert_eq!(
@@ -524,19 +911,26 @@ mod tests {
(1120, 1990),
(1072, 1904),
(960, 1706),
(720, 1280)
(720, 1280),
(1920, 3412)
]
);
}
/// 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, and alone where no step
/// reaches the floor
/// 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
#[test]
fn no_smaller_mode_is_below_the_floor() {
assert_eq!(
sizes(1280, 800, 1),
[(1280, 800), (1120, 700), (992, 620), (960, 600)]
[
(1280, 800),
(1120, 700),
(992, 620),
(960, 600),
(1696, 1060)
]
);
assert_eq!(
sizes(1920, 1080, 1),
@@ -545,18 +939,22 @@ mod tests {
(1680, 944),
(1504, 846),
(1440, 810),
(1280, 720)
(1280, 720),
(2560, 1440)
]
);
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(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(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 only those whose scanout the room holds
/// and of its smaller modes, and its larger one, 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));
@@ -572,7 +970,8 @@ mod tests {
(2032, 1142)
]
);
// 7168 x 7168, 6416 x 6416 and 6144 x 6144 miss the room's 128 MiB.
// 7168 x 7168, 6416 x 6416 and 6144 x 6144 miss the room's 128 MiB, and so does the
// larger 10912 x 10912.
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 (msi RTX 5080 host;
//! measured).
//! threads was in `munmap` of 0x201000 bytes, inside an 81 ms guest frame (an RTX 5080 Laptop
//! host; measured).
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};
+17 -4
View File
@@ -202,6 +202,17 @@ 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;
@@ -209,9 +220,10 @@ 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 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.
/// 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.
#[repr(C)]
#[derive(
Clone, Copy, Debug, Default, PartialEq, Eq, FromBytes, IntoBytes, Immutable, KnownLayout,
@@ -262,7 +274,8 @@ 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_*` settings bits: [`RGFX_VIDEO_ENCODE_HARD_LIMIT`],
/// [`RGFX_VIDEO_ENCODE_REORDERED`].
pub flags: u32,
/// The VUI's `colour_primaries` (ITU-T H.273), in the SPS the host packs.
pub color_primaries: u8,
+53 -8
View File
@@ -723,18 +723,20 @@ 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`]): 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
/// 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
/// 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`]). A write takes the
/// `FEATURES_EXT` offers that are taken ([`RGFX_FEATURE_EXT_SURFACE_HOLD`],
/// [`RGFX_FEATURE_EXT_DISPLAY_RATE`]). 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
@@ -791,6 +793,23 @@ 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;
@@ -1056,6 +1075,9 @@ 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`.
@@ -1950,6 +1972,24 @@ 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
@@ -2511,6 +2551,7 @@ 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);
@@ -5445,8 +5486,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`]. Zero from a host older
/// than these.
/// `RGFX_VIDEO_ENCODE_CAP_*`: [`RGFX_VIDEO_ENCODE_CAP_IN_PLACE`],
/// [`RGFX_VIDEO_ENCODE_CAP_REORDERED`]. Zero from a host older than these.
pub flags: u32,
/// Zero.
pub reserved_0c: u32,
@@ -5457,6 +5498,10 @@ 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,6 +56,9 @@ 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);
@@ -0,0 +1,35 @@
//! 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
}
@@ -0,0 +1,98 @@
//! 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,8 +7,12 @@
//! - [`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;
@@ -0,0 +1,861 @@
//! 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;
@@ -0,0 +1,537 @@
//! 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,6 +119,7 @@ mod linux {
buffer_milliseconds: 1000,
gop_length: None,
b_frames: 0,
coding_order: false,
level: None,
cabac: None,
full_range: false,
@@ -329,6 +329,13 @@ 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>,
@@ -364,6 +371,7 @@ impl EncoderSettings {
allow_frame_reordering: true,
max_frame_delay: None,
b_frames: None,
coding_order: false,
level: None,
entropy: None,
quality_level: None,
@@ -6,6 +6,11 @@
//! 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
@@ -16,7 +21,9 @@
use std::collections::VecDeque;
use std::sync::Arc;
use super::gop::{DecodeTimes, GopConfig, GopPlanner, Planned};
use super::gop::{
CODING_ORDER_REFERENCES, CodingOrder, DecodeTimes, GopConfig, GopPlanner, Planned,
};
use super::limit_rate::LimitRate;
use super::record::Record;
use super::{
@@ -260,6 +267,8 @@ 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,
@@ -280,7 +289,13 @@ 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`.
@@ -311,6 +326,8 @@ 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,
}
@@ -508,10 +525,9 @@ impl<A: Accelerator> Encoder<A> {
)
},
)?;
let reorder = s.allow_frame_reordering
&& s.profile.has_b_slices()
&& limits.max_l1 >= 1
&& limits.max_l0 >= 1;
// 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 b_frames = if reorder {
s.b_frames
.unwrap_or(DEFAULT_B_FRAMES)
@@ -520,9 +536,17 @@ 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.
let (max_references, dpb_pictures): (u32, u32) = if b_frames > 0 { (2, 3) } else { (1, 2) };
// 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)
};
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);
@@ -571,7 +595,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(b_frames > 0),
max_num_reorder_frames: u32::from(reordered),
max_dec_frame_buffering: max_references,
},
};
@@ -623,7 +647,7 @@ impl<A: Accelerator> Encoder<A> {
crop_right,
crop_bottom,
max_dec_pic_buffering_minus1: max_references,
max_num_reorder_pics: u32::from(b_frames > 0),
max_num_reorder_pics: u32::from(reordered),
tools,
vui: hevc::Vui {
sample_aspect_ratio: s.sample_aspect_ratio,
@@ -647,7 +671,9 @@ impl<A: Accelerator> Encoder<A> {
settings: &settings,
coded_width: coded_size.0,
coded_height: coded_size.1,
b_frames,
// 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 },
max_references,
intra_period,
picture_qp: limit_rate.is_some(),
@@ -657,6 +683,13 @@ 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,
@@ -667,7 +700,9 @@ 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,
@@ -696,7 +731,8 @@ impl<A: Accelerator> Encoder<A> {
self.coded_size
}
/// B pictures in a run; 0 when frames keep their order.
/// B pictures in a run of ours, which hold frames back; 0 when each
/// frame's sample comes out as it goes in.
pub fn b_frames(&self) -> u32 {
self.b_frames
}
@@ -722,11 +758,12 @@ 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 that does not upload.
/// time stamp does not follow the last, or in coding order gives no
/// place ([`Self::takes`]), or that does not upload.
pub fn encode(&mut self, frame: &InputFrame<'_>) -> Result<Vec<Coded<A::Error>>, A::Error> {
self.follows(frame.pts)?;
let place = self.takes(frame)?;
let input = self.accelerator.upload(frame)?;
Ok(self.push(input, frame))
Ok(self.push(input, frame, place))
}
/// [`Self::encode`] of a frame another device already wrote into `input`, an input of the
@@ -737,8 +774,8 @@ impl<A: Accelerator> Encoder<A> {
input: A::Input,
frame: &InputFrame<'_>,
) -> Result<Vec<Coded<A::Error>>, A::Error> {
self.follows(frame.pts)?;
Ok(self.push(input, frame))
let place = self.takes(frame)?;
Ok(self.push(input, frame, place))
}
/// [`Self::encode`] of `frame` in place of the last picture coded, whose
@@ -823,6 +860,7 @@ impl<A: Accelerator> Encoder<A> {
forward,
backward,
pts,
dts,
before,
picture: _,
} = held;
@@ -834,9 +872,8 @@ 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;
// Without B pictures a sample's DTS is its PTS, which the last try's
// took.
self.times.push(pts);
// The last try's DTS.
self.times.push(dts);
let planned = Planned {
frame: Pending {
input,
@@ -883,29 +920,67 @@ impl<A: Accelerator> Encoder<A> {
});
}
/// `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}"))?;
/// 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);
}
Ok(())
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)
}
/// Takes `frame`, in `input`, and encodes what its plan gives.
fn push(&mut self, input: A::Input, frame: &InputFrame<'_>) -> Vec<Coded<A::Error>> {
/// 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>> {
self.keep_held();
self.last_pts = Some(frame.pts);
self.times.push(frame.pts);
let dts = match place {
Some(_) => self.coded_dts(frame),
None => frame.pts,
};
self.times.push(dts);
let pending = Pending {
input,
pts: frame.pts,
duration: frame.duration,
id: frame.id,
};
let restart = core::mem::take(&mut self.restart);
let planned = self
.planner
.push(pending, frame.pts, frame.force_key_frame || restart);
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),
};
self.encode_all(planned)
}
@@ -994,6 +1069,9 @@ 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> {
@@ -1063,6 +1141,7 @@ impl<A: Accelerator> Encoder<A> {
> {
let SliceAt {
frame_type,
reference,
order,
frame_num,
idr_pic_id,
@@ -1090,10 +1169,12 @@ impl<A: Accelerator> Encoder<A> {
FrameType::B => h264::SliceType::B,
},
idr: frame_type == FrameType::Idr,
nal_ref_idc: match frame_type {
FrameType::Idr => 3,
FrameType::P => 2,
FrameType::B => 0,
// 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,
},
frame_num,
idr_pic_id,
@@ -1181,6 +1262,7 @@ 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,
@@ -1257,6 +1339,7 @@ impl<A: Accelerator> Encoder<A> {
forward,
backward,
pts: frame.pts,
dts,
before,
picture: Unkept {
frame_type,
@@ -1365,6 +1448,9 @@ 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,
}
@@ -1422,6 +1508,9 @@ pub mod tests {
_ => 0,
};
self.lsbs.push(lsb);
if let Some(slice) = p.h264_slice {
self.ref_idcs.push(slice.nal_ref_idc);
}
}
}
@@ -1774,6 +1863,157 @@ 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,6 +12,9 @@
//! 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;
@@ -264,6 +267,158 @@ 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
@@ -419,6 +574,80 @@ 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 {
+173 -7
View File
@@ -380,11 +380,121 @@ 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.
@@ -395,6 +505,8 @@ 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 {
@@ -403,6 +515,27 @@ 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 {
@@ -422,6 +555,7 @@ 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);
}
@@ -470,20 +604,26 @@ mod tests {
/// A ring from another thread ends the wait with the waiter's answer.
#[test]
fn a_ring_wakes_a_wait() {
let rt = StdRuntime::shared();
let rt = Arc::new(Counted::new(StdRuntime));
let bell = Arc::new(Bell::new());
let flag = Arc::new(Mutex::new(false));
let waiter = std::thread::current().id();
let ringer = {
let (bell, flag) = (Arc::clone(&bell), Arc::clone(&flag));
let (rt, bell, flag) = (Arc::clone(&rt), Arc::clone(&bell), Arc::clone(&flag));
StdRuntime::thread("ringer", move || {
std::thread::sleep(Duration::from_millis(5));
// Once the waiter waits, its question asked and unanswered.
let waits = rt.wait_for_looks(waiter, 1, LONG, || false);
*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()));
assert!(
ringer.is_ok_and(|t| t.join().is_ok_and(|waits| waits)),
"rung before the wait"
);
}
/// A wait with no answer ends at its deadline, on the runtime's clock: on virtual time only
@@ -499,8 +639,10 @@ mod tests {
let got = bell.wait_until(&*rt, rt.deadline_in(LONG), || None::<()>);
done.give(got);
})
};
std::thread::sleep(Duration::from_millis(20));
}
.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()));
let real = StdRuntime;
assert_eq!(
finished.wait_until(&real, real.deadline_in(Duration::from_millis(1))),
@@ -509,7 +651,31 @@ mod tests {
);
rt.advance(LONG);
assert_eq!(finished.wait_until(&real, real.deadline_in(LONG)), Ok(None));
assert!(waiter.is_ok_and(|t| t.join().is_ok()));
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));
}
/// An answer given before the deadline is taken, however late; one is taken once; and an
@@ -147,6 +147,7 @@ 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");
@@ -240,6 +241,7 @@ 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");
@@ -319,6 +321,7 @@ 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");
@@ -378,6 +381,7 @@ 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");
@@ -464,6 +468,7 @@ 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");
@@ -587,6 +592,7 @@ 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);
@@ -778,6 +784,7 @@ 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,6 +595,26 @@ 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,
+20 -1
View File
@@ -226,7 +226,8 @@ 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`]).
/// ([`Session::restore_state`]). `planned` is its plan in a session
/// without picture type decision.
Frame {
input: Buffer,
output: Buffer,
@@ -235,11 +236,24 @@ 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
@@ -780,6 +794,7 @@ impl Session {
timestamp,
idr,
unadvanced,
planned,
} => {
let output = self.output(output, &[BufferKind::Bitstream])?;
self.submitted.borrow().check_free(output)?;
@@ -805,6 +820,10 @@ 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,6 +11,13 @@
//! 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
@@ -23,7 +30,9 @@ use std::collections::VecDeque;
use std::sync::Arc;
use super::ffi::{self, GUID, Zeroed};
use super::{Buffer, Session, Submission};
use super::{Buffer, PicturePlan, Session, Submission};
use crate::codec::encode::FrameType;
use crate::codec::encode::gop::CodingOrder;
use crate::nvidia::cuda::Gpu;
use crate::nvidia::error::Error;
use crate::nvidia::external::ImportedBuffer;
@@ -143,6 +152,12 @@ 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
@@ -225,7 +240,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.
/// later than the last, or in coding order its place in display order.
pub index: u64,
/// Whether it must be an IDR picture.
pub force_idr: bool,
@@ -242,7 +257,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.
/// later than the last, or in coding order its place in display order.
pub index: u64,
/// Whether it must be an IDR picture.
pub force_idr: bool,
@@ -292,6 +307,8 @@ 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
@@ -311,6 +328,31 @@ 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
@@ -345,7 +387,18 @@ impl NvencEncoder {
Tuning::LowLatency => ffi::NV_ENC_TUNING_INFO_LOW_LATENCY,
};
let mut config = session.preset_config(codec, preset, tuning)?.presetCfg;
configure(&mut config, params);
// 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()
},
);
let mut init = ffi::NV_ENC_INITIALIZE_PARAMS::zeroed();
init.version = ffi::NV_ENC_INITIALIZE_PARAMS_VER;
init.encodeGUID = codec;
@@ -360,7 +413,7 @@ impl NvencEncoder {
init.frameRateNum = params.frame_rate.0.max(1);
init.frameRateDen = params.frame_rate.1.max(1);
init.enableEncodeAsync = 0;
init.enablePTD = 1;
init.enablePTD = u32::from(!params.coding_order);
init.maxEncodeWidth = params.width;
init.maxEncodeHeight = params.height;
init.tuningInfo = tuning;
@@ -378,6 +431,9 @@ impl NvencEncoder {
holds,
unkept: None,
restart: false,
coding: params
.coding_order
.then(|| CodingOrder::new(params.gop_length, None, bidirectional)),
session,
device_inputs: Vec::new(),
};
@@ -461,7 +517,7 @@ impl NvencEncoder {
pitch,
frame.index,
unkept.idr || frame.force_idr,
unkept.frame_idx,
(unkept.frame_idx, unkept.planned),
)
}
@@ -479,7 +535,7 @@ impl NvencEncoder {
frame.pitch,
frame.index,
unkept.idr || frame.force_idr,
unkept.frame_idx,
(unkept.frame_idx, unkept.planned),
)
}
@@ -662,19 +718,21 @@ impl NvencEncoder {
) -> Result<Vec<Bitstream>, Error> {
self.keep_going();
let frame_idx = self.submitted;
self.code(
slot_index,
input,
pitch,
index,
force_idr || self.restart,
frame_idx,
)
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())
}
/// Codes the frame in `input` at `pitch` into `slot_index`'s bitstream
/// buffer as `frame_idx`, and reads what comes out; in a session that
/// codes frames in place, without advancing NVENC's state (module doc).
/// 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).
fn code(
&mut self,
slot_index: usize,
@@ -682,7 +740,7 @@ impl NvencEncoder {
pitch: u32,
index: u64,
idr: bool,
frame_idx: u32,
(frame_idx, planned): (u32, Option<PicturePlan>),
) -> Result<Vec<Bitstream>, Error> {
let status = self.session.encode_picture(Submission::Frame {
input,
@@ -692,6 +750,7 @@ impl NvencEncoder {
timestamp: index,
idr,
unadvanced: self.holds,
planned,
});
let status = match status {
Ok(status) => status,
@@ -718,6 +777,7 @@ impl NvencEncoder {
frame_idx,
idr,
picture_type: packet.picture_type,
planned,
});
}
Ok(bitstreams)
@@ -917,6 +977,7 @@ pub fn codes_in_place(
buffer_milliseconds: 1000,
gop_length: None,
b_frames: 0,
coding_order: false,
level: None,
cabac: None,
full_range: false,
@@ -1191,6 +1252,7 @@ pub(crate) mod tests {
buffer_milliseconds: 1000,
gop_length: Some(30),
b_frames: 2,
coding_order: false,
level: None,
cabac: None,
full_range: true,
@@ -1259,6 +1321,237 @@ 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
@@ -1277,6 +1570,7 @@ 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)?;
@@ -1301,6 +1595,7 @@ 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])?;
@@ -1378,6 +1673,7 @@ 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,14 +681,46 @@ pub(crate) struct NV_ENC_PRESET_CONFIG {
pub(crate) reserved2: [*mut c_void; 64],
}
/// `NV_ENC_CODEC_PIC_PARAMS`: the codecs' per-picture parameters, which a
/// session with picture type decision leaves zero.
/// `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`]).
#[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)]
+29 -9
View File
@@ -301,16 +301,31 @@ pub(crate) mod tests {
ready()
}
/// 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) {
/// 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,
) {
let (release, released) = mpsc::channel::<()>();
(release, move || {
let (begun, inside) = mpsc::channel::<()>();
(release, inside, move || {
let _ = begun.send(());
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))
}
@@ -318,12 +333,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, call) = held(7);
let (release, inside, 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");
@@ -335,12 +350,14 @@ 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, call) = held(1);
let (release, inside, 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),
@@ -355,8 +372,9 @@ 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, call) = held(());
let (release, inside, 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);
@@ -369,10 +387,12 @@ 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, call) = held(());
let (release, inside, 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");
+2 -1
View File
@@ -30,6 +30,7 @@
)]
pub mod atom;
mod counts;
pub mod decoder;
pub mod encoder;
mod host;
@@ -49,7 +50,7 @@ mod session;
pub mod status;
pub use decoder::{
Backend, BackendDecoder, Decoded, DecoderConfig, OutputAlignment, Stream, TileLimits,
Backend, BackendDecoder, Decoded, DecoderConfig, LandedBy, OutputAlignment, Stream, TileLimits,
TileRegion,
};
pub use encoder::{BackendEncoder, Encoder, EncoderBackend, EncoderConfig, SourceFrame};
@@ -0,0 +1,102 @@
//! 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"
);
}
}
+321 -91
View File
@@ -76,11 +76,24 @@
//! 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 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.
//! **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.
use std::sync::Arc;
use std::sync::mpsc::Receiver;
@@ -96,6 +109,7 @@ 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,
@@ -268,12 +282,49 @@ 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.
Landed,
/// The picture is in the output surface, written there as it says.
Landed(LandedBy),
/// 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 {
@@ -421,7 +472,7 @@ pub(crate) fn start(
fragments: Vec::new(),
discarding: false,
tiles: None,
emitted: Emitted::default(),
counts: Counts::default(),
unmade: false,
fragment_surfaces: Vec::new(),
}
@@ -479,8 +530,8 @@ struct Worker {
discarding: bool,
/// The tile session a `dsts` started.
tiles: Option<TileSession>,
/// What its frames handed the guest, logged at its end.
emitted: Emitted,
/// What its frames and tiles came to, logged at its end.
counts: Counts,
/// 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,
@@ -488,41 +539,174 @@ struct Worker {
fragment_surfaces: Vec<Arc<dyn LentSurface>>,
}
/// 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 emitted with a failure status, with no buffer.
failed: u64,
/// 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 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,
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,
}
}
/// 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"
)
})
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.
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,
}
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);
}
}
}
}
/// 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"),
))
}
}
@@ -538,6 +722,7 @@ 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;
@@ -550,8 +735,10 @@ impl Worker {
}
self.shared
.let_go(&std::mem::take(&mut self.fragment_surfaces));
if let Some(line) = self.emitted.line() {
if let Some(line) = self.counts.line(self.codec) {
log::info!("{line}");
#[cfg(test)]
self.shared.said_at_end(line);
}
}
@@ -624,6 +811,9 @@ impl Worker {
},
None => status::VIDEO_DECODER_UNSUPPORTED_DATA_FORMAT,
};
if status != NO_ERROR {
self.counts.start_refused = Some(status);
}
self.reply_status(message, status)
}
@@ -704,6 +894,17 @@ 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
@@ -722,7 +923,9 @@ 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(());
@@ -777,6 +980,9 @@ impl Worker {
},
None => status::VIDEO_DECODER_UNSUPPORTED_DATA_FORMAT,
};
if status != NO_ERROR {
self.counts.start_refused = Some(status);
}
self.reply_status(message, status)
}
@@ -920,11 +1126,12 @@ impl Worker {
.sample_buffer(names::SAMPLE_BUFFER)?
.ok_or(WireError::Malformed("no sample buffer"))?;
let sample = SampleBuffer::parse(&serialization)?;
let status = match tile_region(origin, size, at) {
let landed = match tile_region(origin, size, at) {
Some(region) => self.land_tile(&sample, region, surfaces.first()),
None => status::PARAMETER,
None => Err(status::PARAMETER),
};
self.emit_tile(tile, status, buffer);
self.counts.note_tile(landed);
self.emit_tile(tile, landed.err().unwrap_or(NO_ERROR), 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);
@@ -932,34 +1139,41 @@ impl Worker {
Ok(())
}
/// Decodes `sample`, a tile, and lands `region` of it in `output`: the status its `TDem`
/// carries.
/// Decodes `sample`, a tile, and lands `region` of it in `output`: what wrote it there, or the
/// status its `TDem` carries.
fn land_tile(
&mut self,
sample: &SampleBuffer,
region: TileRegion,
output: Option<&Arc<dyn LentSurface>>,
) -> OsStatus {
) -> Result<LandedBy, OsStatus> {
let Some(tiles) = self.tiles.as_mut() else {
return NO_DECODER;
return Err(NO_DECODER);
};
let Some(output) = output else {
return status::PARAMETER;
return Err(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 = access_unit
.and_then(|au| (tiles.decoder).decode_tile(&parameter_sets, &au, &**output, region));
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),
};
match decoded {
Ok(Decoded::Landed) => NO_ERROR,
Ok(Decoded::Landed(by)) => Ok(by),
// A tile is a picture of its own: one its decode skips landed nothing.
Ok(Decoded::Skipped) => status::VIDEO_DECODER_BAD_DATA,
Ok(Decoded::Skipped) => Err(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;
status
Err(status)
}
}
}
@@ -976,8 +1190,9 @@ impl Worker {
message.uuid(names::TILE_BUFFER_UUID, uuid);
}
});
if let Ok(reply) = sent {
self.shared.let_go(&reply.surfaces);
match sent {
Ok(reply) => self.shared.let_go(&reply.surfaces),
Err(_) => self.counts.unanswered += 1,
}
}
@@ -993,18 +1208,19 @@ impl Worker {
Some(Err(status)) => {
self.decoder = None;
self.unmade = true;
Err(status)
Err((Failure::Unopened, status))
}
_ => sample
.data
.as_deref()
.ok_or(status::VIDEO_DECODER_BAD_DATA)
.and_then(|data| annex_b(data, self.length_size)),
.and_then(|data| annex_b(data, self.length_size))
.map_err(|status| (Failure::Sample, status)),
};
let buffer = match self.create_pixel_buffer(frame) {
Ok(buffer) => buffer,
Err(status) => {
self.emit(frame, status, reply.info, None);
Err((failure, status)) => {
self.emit(frame, Outcome::Failed(failure, status), reply.info);
return;
}
};
@@ -1012,30 +1228,31 @@ impl Worker {
self.send_frame_reply(reply, status::NO_ERROR);
}
let parameter_sets = std::mem::take(&mut self.parameter_sets);
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),
});
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))
}
};
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) => {
self.emit(frame, status::NO_ERROR, reply.info, Some(buffer.uuid))
Ok(Decoded::Landed(by)) => {
self.emit(frame, Outcome::Landed(by, buffer.uuid), reply.info);
}
Ok(Decoded::Skipped) => {
self.emit(
frame,
status::NO_ERROR,
reply.info | INFO_FRAME_DROPPED,
None,
);
self.emit(frame, Outcome::Dropped, reply.info | INFO_FRAME_DROPPED);
self.free_unused(buffer.uuid);
}
Err(status) => {
self.emit(frame, status, reply.info, None);
Err((failure, status)) => {
self.emit(frame, Outcome::Failed(failure, status), reply.info);
self.free_unused(buffer.uuid);
}
}
@@ -1077,16 +1294,19 @@ impl Worker {
(self.shared).request_then(&*self.runtime, id, &[], &last, wait, then)
}
/// `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)),
)?;
/// `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))?;
let mut surfaces = reply.surfaces.into_iter();
let surface = surfaces.next();
// A buffer has one surface; more go back.
@@ -1111,16 +1331,25 @@ impl Worker {
self.shared.let_go(&[surface]);
}
// A buffer is made of its surface, and fails without one.
Err(lent.err().unwrap_or(status::PARAMETER))
Err((
Failure::BufferRefused,
lent.err().unwrap_or(status::PARAMETER),
))
}
}
}
/// `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>) {
/// `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) {
video_delay::at(Point::Answer).wait();
self.emitted.note(status, buffer);
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]);
let sent = self.request(names::EMIT_DECODED_FRAME, EMIT_REPLY_WAIT, |message| {
message.s64(names::FRAME, frame);
message.s32(names::ERROR, status);
@@ -1129,8 +1358,9 @@ impl Worker {
message.uuid(names::PIXEL_BUFFER_UUID, uuid);
}
});
if let Ok(reply) = sent {
self.shared.let_go(&reply.surfaces);
match sent {
Ok(reply) => self.shared.let_go(&reply.surfaces),
Err(_) => self.counts.unanswered += 1,
}
}
@@ -71,6 +71,9 @@ 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,
@@ -84,6 +87,8 @@ 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
@@ -127,6 +132,7 @@ struct FakeDecoder {
first_fails: Option<OsStatus>,
gate: Option<Gate>,
dropped: Arc<AtomicUsize>,
script: Script,
}
impl FakeDecoder {
@@ -151,12 +157,13 @@ impl FakeBackend {
Self {
calls: Calls::default(),
regions: Regions::default(),
result: Ok(Decoded::Landed),
result: Ok(Decoded::Landed(LandedBy::Hardware)),
tiles: None,
first_fails: None,
fail_opens: Arc::default(),
gate: None,
dropped: Arc::default(),
script: Script::default(),
}
}
}
@@ -176,6 +183,7 @@ impl Backend for FakeBackend {
first_fails: self.first_fails,
gate: self.gate.clone(),
dropped: Arc::clone(&self.dropped),
script: Arc::clone(&self.script),
}))
}
}
@@ -224,6 +232,9 @@ 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,
@@ -265,6 +276,8 @@ 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 {
@@ -314,7 +327,14 @@ 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), tiles, arm, None, None)
Self::built(
Codec::H264,
Ok(Decoded::Landed(LandedBy::Hardware)),
tiles,
arm,
None,
None,
)
}
/// An H.264 session whose decoders land every picture and decode `tiles`, each decode held
@@ -323,7 +343,7 @@ impl Guest {
let (gate, held) = gate();
let guest = Self::built(
Codec::H264,
Ok(Decoded::Landed),
Ok(Decoded::Landed(LandedBy::Hardware)),
tiles,
|fake| Arc::new(fake),
None,
@@ -346,6 +366,7 @@ 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),
@@ -355,6 +376,7 @@ 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 {
@@ -381,6 +403,7 @@ impl Guest {
dropped,
codec: fourcc,
counted,
script,
};
let answer = guest.send(
b"+dec",
@@ -631,7 +654,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));
let guest = Guest::new(Ok(Decoded::Landed(LandedBy::Hardware)));
guest.start(&avcc(&SPS, 4));
let (_, dpba) = guest.next_of(b"Dpba");
let attributes = plist_of(&dpba, names::PIXEL_BUFFER_ATTRIBUTES);
@@ -672,7 +695,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));
let guest = Guest::new(Ok(Decoded::Landed(LandedBy::Hardware)));
for _ in 0..2 {
let flags = MessageFlags::GUEST_EXPECTS_REPLY;
guest.send(b"dsta", flags, 2, Vec::new(), |_| {});
@@ -691,7 +714,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));
let guest = Guest::new(Ok(Decoded::Landed(LandedBy::Hardware)));
guest.start(&record);
let (_, reply) = guest.next_of(b"dsta");
assert_eq!(status_of(&reply), Some(refused));
@@ -708,7 +731,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));
let guest = Guest::new(Ok(Decoded::Landed(LandedBy::Hardware)));
guest.start(&avcc(&SPS, 4));
guest.next_of(b"Dpba");
guest.next_of(b"dsta");
@@ -754,7 +777,13 @@ 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), None, false, Some(failed));
let guest = Guest::failing_first(
Codec::H264,
Ok(Decoded::Landed(LandedBy::Hardware)),
None,
false,
Some(failed),
);
guest.start(&avcc(&SPS, 4));
guest.next_of(b"Dpba");
guest.next_of(b"dsta");
@@ -786,7 +815,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));
let guest = Guest::new(Ok(Decoded::Landed(LandedBy::Hardware)));
guest.start(&avcc(&SPS, 4));
guest.next_of(b"Dpba");
guest.next_of(b"dsta");
@@ -847,7 +876,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));
let guest = Guest::new(Ok(Decoded::Landed(LandedBy::Hardware)));
guest.start(&avcc(&SPS, 4));
guest.next_of(b"Dpba");
guest.next_of(b"dsta");
@@ -896,31 +925,167 @@ fn a_skipped_picture_is_emitted_dropped_and_its_buffer_unused() {
guest.next_of(b"dfrm");
}
/// 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.
/// 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.
#[test]
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";
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";
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));
let guest = Guest::new(Ok(Decoded::Landed(LandedBy::Hardware)));
guest.start(&avcc(&SPS, 4));
guest.next_of(b"Dpba");
guest.next_of(b"dsta");
@@ -937,7 +1102,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));
let guest = Guest::new(Ok(Decoded::Landed(LandedBy::Hardware)));
guest.start(&avcc(&SPS, 4));
guest.next_of(b"Dpba");
guest.next_of(b"dsta");
@@ -962,7 +1127,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));
let guest = Guest::new(Ok(Decoded::Landed(LandedBy::Hardware)));
guest.start(&avcc(&SPS, 4));
guest.next_of(b"Dpba");
guest.next_of(b"dsta");
@@ -1017,7 +1182,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));
let guest = Guest::new(Ok(Decoded::Landed(LandedBy::Hardware)));
let key = |m: &mut MessageWriter, key: &str| {
m.property_list(names::PROPERTY_KEY, Some(&Value::string(key)));
};
@@ -1105,7 +1270,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));
let guest = Guest::new(Ok(Decoded::Landed(LandedBy::Hardware)));
let can = |record: &[u8], width: u16| {
let description = hand_written(b"avc1", width, 48, record);
guest.send(
@@ -1144,7 +1309,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));
let guest = Guest::new(Ok(Decoded::Landed(LandedBy::Hardware)));
guest.start(&avcc(&SPS, 4));
guest.next_of(b"Dpba");
guest.next_of(b"dsta");
@@ -1178,7 +1343,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));
let guest = Guest::new(Ok(Decoded::Landed(LandedBy::Hardware)));
guest.start(&avcc(&SPS, 4));
guest.next_of(b"Dpba");
guest.next_of(b"dsta");
@@ -1210,7 +1375,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));
let guest = Guest::new(Ok(Decoded::Landed(LandedBy::Hardware)));
let late = MessageHeader {
message_type: FourCc::new(*b"Dbuf"),
flags: MessageFlags::NONE,
@@ -1252,7 +1417,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));
let guest = Guest::new(Ok(Decoded::Landed(LandedBy::Hardware)));
let mut message = MessageWriter::new(
FourCc::new(*b"+dec"),
MessageFlags::GUEST_EXPECTS_REPLY,
@@ -1280,7 +1445,7 @@ const TILES: TileLimits = TileLimits {
#[test]
fn a_tile_session_sends_its_requirements_then_its_reply() {
let guest = Guest::with_tiles(Ok(Decoded::Landed), Some(TILES));
let guest = Guest::with_tiles(Ok(Decoded::Landed(LandedBy::Hardware)), Some(TILES));
guest.start_tiles(&avcc(&SPS, 4));
let (tdrs, requirements) = guest.next_of(b"TDrs");
assert!(!tdrs.flags.contains(MessageFlags::HOST_EXPECTS_REPLY));
@@ -1358,7 +1523,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));
let guest = Guest::new(Ok(Decoded::Landed(LandedBy::Hardware)));
guest.start_tiles(&avcc(&SPS, 4));
let (_, reply) = guest.next_of(b"dsts");
assert_eq!(
@@ -1422,7 +1587,12 @@ 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), Some(TILES), range_extensions);
let guest = Guest::on(
codec,
Ok(Decoded::Landed(LandedBy::Hardware)),
Some(TILES),
range_extensions,
);
guest.start(record);
if let Some(named) = &named {
let (_, dpba) = guest.next_of(b"Dpba");
@@ -1443,7 +1613,12 @@ fn starts_in(
}
assert!(guest.quiet(), "{what}");
let guest = Guest::on(codec, Ok(Decoded::Landed), Some(TILES), range_extensions);
let guest = Guest::on(
codec,
Ok(Decoded::Landed(LandedBy::Hardware)),
Some(TILES),
range_extensions,
);
guest.start_tiles(record);
if let Some(named) = &named {
let (_, tdrs) = guest.next_of(b"TDrs");
@@ -1659,7 +1834,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), Some(TILES));
let guest = Guest::with_tiles(Ok(Decoded::Landed(LandedBy::Hardware)), Some(TILES));
guest.start_tiles(&avcc(&SPS, 4));
guest.next_of(b"TDrs");
guest.next_of(b"dsts");
@@ -1731,7 +1906,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));
let guest = Guest::new(Ok(Decoded::Landed(LandedBy::Hardware)));
guest.start(&avcc(&SPS, 4));
guest.next_of(b"Dpba");
guest.next_of(b"dsta");
@@ -1775,7 +1950,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));
let guest = Guest::new(Ok(Decoded::Landed(LandedBy::Hardware)));
guest.start(&avcc(&SPS, 4));
guest.next_of(b"Dpba");
guest.next_of(b"dsta");
@@ -1820,7 +1995,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));
let guest = Guest::new(Ok(Decoded::Landed(LandedBy::Hardware)));
guest.start(&avcc(&SPS, 4));
guest.next_of(b"Dpba");
guest.next_of(b"dsta");
@@ -1911,7 +2086,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), Some(TILES));
let guest = Guest::with_tiles(Ok(Decoded::Landed(LandedBy::Hardware)), Some(TILES));
guest.start_tiles(&avcc(&SPS, 4));
guest.next_of(b"TDrs");
guest.next_of(b"dsts");
@@ -1957,7 +2132,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), Some(TILES));
let guest = Guest::with_tiles(Ok(Decoded::Landed(LandedBy::Hardware)), Some(TILES));
guest.start_tiles(&avcc(&SPS, 4));
guest.next_of(b"TDrs");
guest.next_of(b"dsts");
@@ -2050,7 +2225,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), None);
let guest = Guest::of(Codec::Vp9, Ok(Decoded::Landed(LandedBy::Hardware)), 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), None);
let guest = Guest::of(Codec::Av1, Ok(Decoded::Landed(LandedBy::Hardware)), None);
let (unit, _) = sequence_obu("svt-main8");
guest.start(&record_of("svt-main8"));
guest.next_of(b"Dpba");
+147 -8
View File
@@ -52,6 +52,18 @@
//! 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")]
@@ -67,6 +79,7 @@ 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,
@@ -210,6 +223,7 @@ pub(crate) fn start(
times: VecDeque::new(),
last_pts: None,
format: None,
counts: Counts::default(),
}
.run();
})
@@ -258,6 +272,87 @@ 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 {
@@ -272,6 +367,7 @@ 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;
@@ -282,7 +378,16 @@ 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]) {
@@ -425,6 +530,7 @@ 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;
@@ -465,6 +571,9 @@ impl Worker {
},
}
};
if status != status::NO_ERROR {
self.counts.start_refused = Some(status);
}
self.reply_status(message, status)
}
@@ -557,6 +666,14 @@ 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)?;
@@ -570,7 +687,9 @@ 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);
@@ -598,7 +717,12 @@ 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) => encoder.encode(&*surface, &source),
Some(encoder) => {
let began = self.runtime.now();
let encoded = encoder.encode(&*surface, &source);
self.counts.encodes.note(self.runtime.elapsed_since(began));
encoded
}
None => Err(status::INVALID_SESSION),
};
let replaced = self.pending.insert(
@@ -615,6 +739,7 @@ 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 {
@@ -624,7 +749,10 @@ impl Worker {
}
status::NO_ERROR
}
Err(status) => status,
Err(status) => {
self.counts.refused.note(status);
status
}
};
let mut reply = self.reply(message);
reply.s32(names::ERROR, status);
@@ -691,6 +819,7 @@ 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);
@@ -705,10 +834,12 @@ 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);
}
};
@@ -716,8 +847,14 @@ impl Worker {
let serialization = self.sample_buffer(&sample).map(|buffer| buffer.serialize());
let (uuid, taken) = self.frame_emitted(frame);
match serialization {
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),
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);
}
}
self.shared.let_go(
&taken
@@ -851,9 +988,10 @@ 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.
/// it is long (the module doc); the guest's answer is waited for and not read, and counted
/// where it does not come.
fn emit_encoded_frame(
&self,
&mut self,
frame: i64,
status: OsStatus,
info: u32,
@@ -898,8 +1036,9 @@ impl Worker {
&message.finish(),
EMIT_REPLY_WAIT,
);
if let Ok(reply) = sent {
self.shared.let_go(&reply.surfaces);
match sent {
Ok(reply) => self.shared.let_go(&reply.surfaces),
Err(_) => self.counts.unanswered += 1,
}
}
}
@@ -61,6 +61,24 @@ 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 {
@@ -80,6 +98,8 @@ 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
@@ -120,6 +140,7 @@ struct FakeEncoder {
configured: bool,
gate: Option<Gate>,
dropped: Arc<AtomicUsize>,
script: Script,
}
impl Drop for FakeEncoder {
@@ -139,6 +160,7 @@ impl EncoderBackend for FakeBackend {
configured: false,
gate: self.gate.clone(),
dropped: Arc::clone(&self.dropped),
script: Arc::clone(&self.script),
}))
}
}
@@ -180,6 +202,29 @@ 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 => {
@@ -232,6 +277,8 @@ 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 {
@@ -270,12 +317,14 @@ 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();
@@ -288,6 +337,7 @@ impl Guest {
dropped,
codec,
counted,
script,
};
assert_eq!(guest.create(Some(listed)), 0, "the create is taken");
guest
@@ -483,6 +533,130 @@ 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,6 +42,16 @@ 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]
@@ -191,6 +201,15 @@ 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,6 +57,14 @@ 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
@@ -106,6 +114,10 @@ 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`).
@@ -124,9 +136,23 @@ 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 {
@@ -145,6 +171,15 @@ 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
@@ -361,6 +396,12 @@ 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.
+54 -7
View File
@@ -442,6 +442,7 @@ 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};
@@ -462,13 +463,50 @@ 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::<()>();
(release, move |_| {
let (begun, inside) = mpsc::channel::<()>();
(release, inside, move |_| {
let _ = begun.send(());
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() {
@@ -600,13 +638,15 @@ mod tests {
#[test]
fn a_release_behind_a_call_in_hand_is_made_after_it_and_in_order() {
let calls = calls();
let rt = Arc::new(VirtualRuntime::default());
let calls = Calls::new(std::ptr::null_mut(), Arc::clone(&rt) as Arc<dyn Runtime>);
let order = Arc::new(Mutex::new(Vec::new()));
let (release, call) = held(());
let (release, inside, call) = held_saying(());
let first = Arc::clone(&order);
let in_hand = past_the_deadline_in_the_call(&rt, inside);
assert_eq!(
calls.wait_call(
soon(),
rt.deadline_in(SOON),
move |raw| {
call(raw);
first.lock().push("call");
@@ -615,16 +655,19 @@ 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.
@@ -675,14 +718,18 @@ mod tests {
#[test]
fn the_thread_ends_once_its_calls_drop_and_its_orders_are_made() {
let calls = calls();
let rt = Arc::new(VirtualRuntime::default());
let calls = Calls::new(std::ptr::null_mut(), Arc::clone(&rt) as Arc<dyn Runtime>);
let shared = Arc::downgrade(&calls.shared);
let (release, call) = held(());
let (release, inside, call) = held_saying(());
let in_hand = past_the_deadline_in_the_call(&rt, inside);
assert_eq!(
calls.wait_call(soon(), call, |_, ()| {}),
calls.wait_call(rt.deadline_in(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,6 +25,8 @@ 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> {
@@ -108,10 +110,12 @@ 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.
/// 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`]).
#[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));
@@ -0,0 +1,395 @@
//! 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");
}
+2 -1
View File
@@ -391,7 +391,8 @@ 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();
std::thread::sleep(Duration::from_millis(20));
// 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()));
assert!(!waited.is_finished(), "ended before its delay");
clock.advance(Duration::from_secs(6));
waited.join().unwrap();
+264
View File
@@ -0,0 +1,264 @@
#!/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"
@@ -560,6 +560,15 @@ 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,10 +17,18 @@
//! 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;
@@ -84,6 +92,9 @@ 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);
@@ -177,6 +188,14 @@ 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)
@@ -234,6 +253,40 @@ 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(),
@@ -279,6 +332,7 @@ impl Clock for VirtualClock {
deadline,
expired: false,
});
self.parks();
id
};
// Registered while holding the mutex, so `advance` cannot deliver before this parks.
@@ -295,6 +349,7 @@ 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);
}
@@ -302,6 +357,7 @@ 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);
}
}
@@ -504,6 +560,67 @@ 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() {
+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 on homelab-um870-1 (2026-11-15), with the file on a workspace disk
//! stalls. In a traced boot (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
//! um870's RTX 3090, the loader's first device was the layer's default, its Radeon 780M
//! an RTX 3090, the loader's first device was the layer's default, the Radeon 780M beside it
//! (**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 {
}
}
/// 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] {
/// 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] {
[
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 = um870();
let list = a_780m_a_3090_and_lavapipe();
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 = um870();
let list = a_780m_a_3090_and_lavapipe();
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,6 +41,34 @@ 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 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
//! 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
//! 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 homelab-ms01-1 (Core i9-13900H, Linux 7.3.1),
//! with each run resolved and recorded on its own. On a 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 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
//! 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
//! 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 (homelab-gem10, Linux 7.2.9,
/// loop waited for QEMU's lock, which that vCPU held, up to 0.89 s (a Ryzen 7 7840HS, 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;
+11 -8
View File
@@ -111,15 +111,18 @@ 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.
/// The host's page size, asked of the system once: it does not change while the process runs.
pub(crate) fn page_size() -> u64 {
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),
}
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),
}
})
}
/// The whole pages `len` bytes at `addr` lie in: the first byte of the first, and their length;
@@ -910,17 +910,18 @@ fn encode(
Ok(())
}
/// 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>) {
/// 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) {
match stopped {
None => {}
Some(Stop::Metal(what)) => refused_as(sel, RtRefusal::Refused, &what),
Some(Stop::Unbuilt(piece)) => refuse(piece, sel),
Some(Stop::Rt(error)) => {
Stop::Metal(what) => refused_as(sel, RtRefusal::Refused, &what),
Stop::Unbuilt(piece) => refuse(piece, sel),
Stop::Rt(error) => {
rt_refused_texture(sel, &error);
}
Some(Stop::Counted) => {}
Stop::Counted => {}
}
}
@@ -949,12 +950,11 @@ impl BlitEncoder<RtPlatform> for RtObj<RtBlitEncoder> {
open.naming.end();
}
drop(open);
let encoded = match stopped {
None => Encoded::RECORDED,
Some(_) => Encoded::REFUSED,
let Some(stop) = stopped else {
return Ok(Encoded::RECORDED);
};
report(sel, stopped);
Ok(encoded)
report(sel, stop);
Ok(Encoded::REFUSED)
});
crate::recorder::rec_done!(recorded_call, recorded_answer);
recorded_answer
@@ -588,12 +588,11 @@ impl RtObj<RtComputeEncoder> {
open.naming.end();
}
drop(open);
let encoded = match stopped {
None => Encoded::RECORDED,
Some(_) => Encoded::REFUSED,
let Some(stop) = stopped else {
return Encoded::RECORDED;
};
naming_functions(functions, || report(sel, stopped));
encoded
naming_functions(functions, || report(sel, stop));
Encoded::REFUSED
}
}
@@ -56,13 +56,32 @@
//! 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;
@@ -188,6 +207,221 @@ 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;
@@ -289,4 +523,65 @@ 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,6 +1507,10 @@ 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()) };
@@ -134,6 +134,10 @@
//! 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:
@@ -1341,23 +1345,33 @@ pub struct Target {
pub made: Arc<Made>,
}
/// The textures a render encoder bound, by stage (vertex, fragment) and slot.
/// 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.
#[derive(Default)]
pub struct Bound([Vec<Option<Arc<Made>>>; 2]);
impl Bound {
/// Slot `slot` of stage `stage` (0 vertex, 1 fragment) holds `texture`.
pub fn set(&mut self, stage: usize, slot: u32, texture: Option<&RtObj<RtTexture>>) {
/// 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));
let (Some(slots), Ok(slot)) = (self.0.get_mut(stage), usize::try_from(slot)) else {
return;
};
if slot >= 256 {
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 slots.len() <= slot {
slots.resize(slot + 1, None);
}
slots[slot] = texture.map(|t| Arc::clone(t.made()));
}
}
@@ -2707,6 +2721,8 @@ 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);
}
@@ -3366,6 +3382,51 @@ 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,6 +3216,8 @@ 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 {
@@ -3259,27 +3261,30 @@ 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"
);
let settler = {
let flights = Arc::clone(&flights);
// 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));
std::thread::Builder::new()
.spawn(move || {
std::thread::sleep(Duration::from_millis(20));
flights.settled(third);
let bound = within(Duration::from_secs(10));
(flights.settle(through, bound, &mut |_| {}, &*waits)).map(|s| s.waited)
})
.expect("a thread")
};
assert_eq!(
flights
.settle(
through,
within(Duration::from_secs(10)),
&mut |_| {},
&clock
)
.map(|s| s.waited),
Ok(1)
const REAL: Duration = Duration::from_secs(10);
assert!(
waits.wait_for_timed_waits(1, REAL, || settle.is_finished()),
"the settle neither waited nor ended"
);
settler.join().expect("the settler ends");
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));
// The clear, and the one committed after, are not waited for.
let at_once = |through| {
(flights.settle(through, within(Duration::ZERO), &mut |_| {}, &clock))
@@ -239,7 +239,8 @@ 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>>) {
seen.bound.set(stage, slot, texture);
let made = texture.map(|t| t.made());
seen.bound.set(stage, slot, made, &self.targets);
if let Some(t) = texture {
self.kept.used(t, Use::Sampled);
}
@@ -306,6 +307,33 @@ 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 {
@@ -1254,7 +1282,7 @@ impl RtObj<RtRenderEncoder> {
if let Err(stop) = bound {
drop(open);
drop(held);
report(draw.vertex_buffer().selector(), Some(stop));
report(draw.vertex_buffer().selector(), stop);
if let Err(raise) = self.encode(on, draw.primitives()) {
return Some(Err(raise));
}
@@ -1272,7 +1300,7 @@ impl RtObj<RtRenderEncoder> {
self.refusal_functions(seen, sel, &stop, true, Some(draw.primitive_type), None);
drop(open);
drop(held);
naming_functions(functions, || report(sel, Some(stop)));
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));
}
@@ -1289,33 +1317,15 @@ 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 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));
}
let refused = (self.command(&mut open, cmd).err())
.map(|stop| (self.refusal(&open.seen, &cmd, &stop), stop));
if ending && let Some(e) = open.rt.take() {
e.end_encoding();
self.mark.end();
@@ -1323,12 +1333,11 @@ impl RenderEncoder<RtPlatform> for RtObj<RtRenderEncoder> {
}
drop(open);
drop(held);
let encoded = match stopped {
None => Encoded::RECORDED,
Some(_) => Encoded::REFUSED,
let Some(((sel, functions), stop)) = refused else {
return Ok(Encoded::RECORDED);
};
naming_functions(functions, || report(sel, stopped));
Ok(encoded)
naming_functions(functions, || report(sel, stop));
Ok(Encoded::REFUSED)
});
crate::recorder::rec_done!(recorded_call, recorded_answer);
recorded_answer
@@ -10,6 +10,12 @@
//! 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;
@@ -179,6 +185,15 @@ 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),* $(,)?) => {
@@ -232,7 +247,8 @@ 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; \
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}\
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}, \
@@ -252,6 +268,9 @@ 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),
@@ -311,6 +330,17 @@ 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;
@@ -381,11 +411,14 @@ 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; submits 60 \
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 \
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, \
@@ -412,6 +445,13 @@ 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, \
@@ -431,6 +471,51 @@ 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,10 +14,12 @@
//! 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 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.
//! **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.
//!
//! **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
@@ -86,8 +88,6 @@
//! 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,6 +138,87 @@ 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.
@@ -300,25 +381,7 @@ impl RtSwapchain {
reason
};
// SAFETY: `surface` and `physical` are live, of one instance.
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(),
)));
}
unsafe { presents(&surface_api, physical, family, surface) }.map_err(destroy)?;
// SAFETY: as above.
let modes =
unsafe { surface_api.get_physical_device_surface_present_modes(physical, surface) }
@@ -376,73 +439,47 @@ impl RtSwapchain {
}
/// Whether `device`'s queue family, the one a swapchain presents on ([`RtSwapchain::new`]),
/// 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.
/// 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.
///
/// # Safety
///
/// `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",
),
/// `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,
};
if !(device.instance().extensions().iter()).any(|e| e.as_c_str() == extension) {
return false;
return Err(Refused(format!(
"the runtime's instance has no {}",
extension.to_string_lossy()
)));
}
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: 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
// 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,
)
}
}
/// Whether the swapchain presents with MAILBOX (else FIFO).
@@ -1885,4 +1922,163 @@ 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,11 +98,13 @@
//! (`rt-refused-metal`), where Metal aborts. A `replaceRegion:` rt refuses changes nothing, counted
//! likewise.
//!
//! **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.
//! **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.
use std::collections::VecDeque;
use std::ops::Range;
@@ -1811,8 +1813,9 @@ impl Texture<RtPlatform> for RtObj<RtTexture> {
self.protection_options
}
/// 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
/// 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
/// 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`).
@@ -1845,11 +1848,12 @@ 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)
{
@@ -1857,14 +1861,21 @@ impl Texture<RtPlatform> for RtObj<RtTexture> {
}
return Ok(());
}
if let Err(error) = self.rt().replace_region(
r,
level,
slice,
rt::HostBytes::from(bytes.as_slice()),
bytes_per_row,
bytes_per_image,
) {
// 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)
{
rt_refused(REPLACE, &error);
}
Ok(())
@@ -2567,7 +2578,8 @@ 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(()));
assert_eq!(counted(COPY_CODE), copies + 1);
// A texture over no buffer: rt reads the bytes in place, with no copy counted.
assert_eq!(counted(COPY_CODE), copies);
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.
+11 -7
View File
@@ -279,22 +279,26 @@ impl Presents {
}
}
/// 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.
/// 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.
#[derive(Clone, Copy, Debug)]
pub enum WindowSystem {
/// A Wayland compositor: its `wl_display`.
/// A Wayland compositor: its `wl_display`, and a `wl_surface` of it.
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 the visual a window takes there.
/// An X server, through Xlib: its `Display`, and a window of it.
Xlib {
/// The server's Xlib `Display`.
display: *mut std::ffi::c_void,
/// The visual's ID, Xlib's `VisualID`.
visual: std::ffi::c_ulong,
/// An unmapped window of the connection's, Xlib's `Window`.
window: std::ffi::c_ulong,
},
}
+130 -24
View File
@@ -23,6 +23,7 @@ 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) |
@@ -47,10 +48,27 @@ 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). 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), 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.
`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::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)
- 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
@@ -136,7 +154,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 homelab-ms01's Iris Xe the
desktop surfaces are the mode's width (on an 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
@@ -169,6 +187,27 @@ 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
@@ -200,9 +239,26 @@ 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.
window system to reach), 60 Hz. A titled window offers that rate alone.
`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
@@ -214,6 +270,27 @@ 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
@@ -498,9 +575,14 @@ 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.
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.
`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`,
@@ -543,24 +625,34 @@ 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: 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.
- 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.
`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)
@@ -589,6 +681,17 @@ 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
@@ -846,7 +949,8 @@ 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.
and hides the host's over the image, as on macOS, its changes alone at most
once a refresh of the window's screen.
`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`,
@@ -854,6 +958,8 @@ 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
@@ -933,7 +1039,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: the Windows mini's UHD 630)
`manual` (a boot whose rt device is lost: a UHD 630 under Windows)
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
+43
View File
@@ -6,6 +6,10 @@
//! - `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
@@ -19,6 +23,10 @@ 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;
/// What the variables say.
#[derive(Clone, Debug, PartialEq)]
pub struct Settings {
@@ -28,6 +36,8 @@ 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>,
}
impl Default for Settings {
@@ -36,6 +46,7 @@ impl Default for Settings {
borderless: false,
screens: Vec::new(),
window_impl: WindowImpl::AppKit,
refresh_mhz: None,
}
}
}
@@ -68,6 +79,21 @@ 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();
@@ -93,6 +119,7 @@ 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()),
..parse(borderless.as_deref(), screens.as_deref())
}
})
@@ -136,6 +163,22 @@ 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() {
+59 -3
View File
@@ -7,8 +7,9 @@
//!
//! 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, `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, 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
//! [`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`]).
@@ -18,7 +19,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 homelab-ms01's Iris Xe
//! 16 pixels are 64 bytes. Measured by metal2vulkan's lane on an 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
@@ -657,6 +658,61 @@ 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() {
+43 -5
View File
@@ -37,7 +37,8 @@
//! 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 move drawing again, and the host's cursor is invisible over the image. The
//! 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
//! 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.
@@ -53,6 +54,8 @@ 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);
@@ -245,6 +248,9 @@ 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.
@@ -298,6 +304,7 @@ 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),
@@ -400,7 +407,7 @@ impl Window {
};
self.post_cursor_refresh();
if drawn {
self.surface.request_draw();
self.surface.request_cursor_draw();
}
}
@@ -420,14 +427,15 @@ impl Window {
};
self.post_cursor_refresh();
if drawn {
self.surface.request_draw();
self.surface.request_cursor_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.
/// 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`).
pub fn cursor_at(&self, at: (u16, u16)) {
let (changed, drawn) = {
let mut guest = self.guest.lock();
@@ -444,7 +452,7 @@ impl Window {
self.post_cursor_refresh();
}
if drawn {
self.surface.request_draw();
self.surface.request_cursor_draw();
}
}
@@ -529,6 +537,36 @@ 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.
+1
View File
@@ -59,6 +59,7 @@ pub mod handle;
pub mod keymap;
pub mod keys;
mod native;
mod pace;
mod present;
pub mod screens;
pub mod scroll;
+3 -2
View File
@@ -23,9 +23,10 @@ mod sdl_thread;
mod windows;
// What the OS adds under the SDL thread's windows: the window system they open through, the GPU
// its compositor composites on, and its names for the release chord's keys in the title.
// its compositor composites on, its names for the release chord's keys in the title, and on Linux
// the rates a screen's DRM connector lists.
#[cfg(target_os = "linux")]
use linux::{HOST_OS, compositor_device, window_system};
use linux::{HOST_OS, compositor_device, connector_rates, window_system};
#[cfg(target_os = "windows")]
use windows::{HOST_OS, compositor_device, window_system};
+5 -2
View File
@@ -2,12 +2,15 @@
//! (`super::sdl_thread`), and what only Linux has: the window system the windows open through,
//! one the GPU presents to (`winsys`), which the UI thread asks for as SDL's video starts
//! (`window_system`), the GPU a Wayland compositor composites on (`feedback`), which a window's
//! render thread asks for (`compositor_device`), and Linux's names for the release chord's keys in
//! the title ([`HOST_OS`]).
//! render thread asks for (`compositor_device`), the rates a screen's DRM connector lists, which a
//! borderless window's screen takes where SDL lists its own rate alone (`connectors`), and Linux's
//! names for the release chord's keys in the title ([`HOST_OS`]).
mod connectors;
mod feedback;
mod winsys;
pub(super) use connectors::connector_rates;
pub(super) use feedback::main_device_of as compositor_device;
pub(super) use winsys::window_system;
@@ -0,0 +1,338 @@
//! The refresh rates a screen's DRM connector lists at the screen's size, for a screen SDL lists
//! no rate of but its own: on Wayland (and X11 through XWayland) SDL gives a screen's current rate
//! alone (`super::super::sdl_thread`'s `ui::host_screen`), and the rates of the screen a
//! borderless window fills are those its display offers its guest (`crate::screens`).
//!
//! **A plain read.** Each DRM card's primary node (`/dev/dri/card*`) is opened read-only, and read
//! with two ioctls: `DRM_IOCTL_MODE_GETRESOURCES` for its connectors' ids, and
//! `DRM_IOCTL_MODE_GETCONNECTOR` for each connector's status and modes, asked with room for
//! [`MODES_ROOM`] modes. The kernel probes the display again only for a `GETCONNECTOR` that asks
//! for no modes (`drm_mode_getconnector`); this one always asks for room, so it reads the list the
//! compositor's last probe left. A connector that lists more modes than the room is read as
//! listing none. Opening a card no compositor holds makes this read its DRM master while the card
//! is open, as any opener of a primary node is; each card is closed once read.
//!
//! **The match** ([`rates_of`]): the screen's connector is the one connected connector, of every
//! card, that lists a mode of the screen's pixels within [`RATE_SLACK_HZ`] of its rate, and its
//! rates are those of its modes of that size, interlaced ones left out. Where none does, more
//! than one does (two screens of one model at one mode), or a card cannot be opened or read, there
//! is no answer, and the screen lists its own rate alone: a screen is never offered another's.
use std::fs::File;
use std::os::fd::AsRawFd;
use std::path::Path;
use crate::screens::screen_rates;
/// The most modes a connector's read takes.
const MODES_ROOM: usize = 256;
/// How far, in Hz, a connector's mode's rate may be from the screen's for the mode to be the
/// screen's: the guest's kexts' tolerance, within which two rates are one mode to them.
const RATE_SLACK_HZ: f64 = 0.5;
/// `DRM_IOCTL_MODE_GETRESOURCES`: `_IOWR('d', 0xA0, struct drm_mode_card_res)`.
const GET_RESOURCES: u32 = iowr(0xA0, size_of::<CardRes>());
/// `DRM_IOCTL_MODE_GETCONNECTOR`: `_IOWR('d', 0xA7, struct drm_mode_get_connector)`.
const GET_CONNECTOR: u32 = iowr(0xA7, size_of::<GetConnector>());
/// `DRM_MODE_CONNECTED`.
const CONNECTED: u32 = 1;
/// `DRM_MODE_FLAG_INTERLACE` and `DRM_MODE_FLAG_DBLSCAN`.
const INTERLACE: u32 = 1 << 4;
const DBLSCAN: u32 = 1 << 5;
// The kernel's sizes of the three records (`include/uapi/drm/drm_mode.h`).
const _: () = assert!(
size_of::<CardRes>() == 64 && size_of::<GetConnector>() == 80 && size_of::<ModeInfo>() == 68
);
/// `_IOWR('d', nr, size)`.
const fn iowr(nr: u32, size: usize) -> u32 {
// An ioctl argument's size, below 2^14.
(3 << 30) | ((size as u32) << 16) | ((b'd' as u32) << 8) | nr
}
/// `struct drm_mode_card_res`.
#[repr(C)]
#[derive(Default)]
struct CardRes {
fb_id_ptr: u64,
crtc_id_ptr: u64,
connector_id_ptr: u64,
encoder_id_ptr: u64,
count_fbs: u32,
count_crtcs: u32,
count_connectors: u32,
count_encoders: u32,
min_width: u32,
max_width: u32,
min_height: u32,
max_height: u32,
}
/// `struct drm_mode_get_connector`.
#[repr(C)]
#[derive(Default)]
struct GetConnector {
encoders_ptr: u64,
modes_ptr: u64,
props_ptr: u64,
prop_values_ptr: u64,
count_modes: u32,
count_props: u32,
count_encoders: u32,
encoder_id: u32,
connector_id: u32,
connector_type: u32,
connector_type_id: u32,
connection: u32,
mm_width: u32,
mm_height: u32,
subpixel: u32,
pad: u32,
}
/// `struct drm_mode_modeinfo`.
#[repr(C)]
#[derive(Clone, Copy, Default)]
struct ModeInfo {
clock: u32,
hdisplay: u16,
hsync_start: u16,
hsync_end: u16,
htotal: u16,
hskew: u16,
vdisplay: u16,
vsync_start: u16,
vsync_end: u16,
vtotal: u16,
vscan: u16,
vrefresh: u32,
flags: u32,
kind: u32,
name: [u8; 32],
}
/// A connector's mode: its pixels, its rate in Hz, and whether it is interlaced.
#[derive(Clone, Copy, Debug, PartialEq)]
struct Mode {
pixels: (u32, u32),
hz: f64,
interlaced: bool,
}
impl Mode {
/// The mode `info` is: its rate its pixel clock over its frame's pixels, a double-scanned or
/// multi-scanned mode's frame counted at its lines' scans; `None` for a frame of no pixels.
fn of(info: &ModeInfo) -> Option<Mode> {
let mut frame = f64::from(info.htotal) * f64::from(info.vtotal);
if info.flags & DBLSCAN != 0 {
frame *= 2.0;
}
if info.vscan > 1 {
frame *= f64::from(info.vscan);
}
(frame > 0.0).then(|| Mode {
pixels: (u32::from(info.hdisplay), u32::from(info.vdisplay)),
hz: f64::from(info.clock) * 1000.0 / frame,
interlaced: info.flags & INTERLACE != 0,
})
}
}
/// The rates, in Hz, the screen's connector lists at `pixels`, for a screen of `pixels` at `hz`
/// (the module doc): `None` where no connector, or more than one, is the screen's, or a card cannot
/// be read.
pub(crate) fn connector_rates(pixels: (u32, u32), hz: f64) -> Option<Vec<f64>> {
rates_of(&connected()?, pixels, hz)
}
/// The rates of the one connector of `connectors` that lists a mode of `pixels` within
/// [`RATE_SLACK_HZ`] of `hz`, at `pixels`; `None` where none or more than one does.
fn rates_of(connectors: &[Vec<Mode>], pixels: (u32, u32), hz: f64) -> Option<Vec<f64>> {
let at_size = |modes: &[Mode]| -> Vec<Mode> {
let at = modes.iter().filter(|m| m.pixels == pixels && !m.interlaced);
at.copied().collect()
};
let mut theirs = (connectors.iter().map(|modes| at_size(modes)))
.filter(|modes| modes.iter().any(|m| (m.hz - hz).abs() <= RATE_SLACK_HZ));
let only = theirs.next()?;
if theirs.next().is_some() {
return None;
}
Some(screen_rates(pixels, only.iter().map(|m| (m.pixels, m.hz))))
}
/// The modes of every connected connector of every DRM card; `None` where a card cannot be
/// opened or read.
fn connected() -> Option<Vec<Vec<Mode>>> {
let dri = Path::new("/dev/dri");
let mut connectors = Vec::new();
for entry in std::fs::read_dir(dri).ok()? {
let name = entry.ok()?.file_name();
if name.to_string_lossy().starts_with("card") {
connectors.extend(card_connectors(&File::open(dri.join(name)).ok()?)?);
}
}
Some(connectors)
}
/// The modes of each connected connector of `card`, a primary node opened read-only.
fn card_connectors(card: &File) -> Option<Vec<Vec<Mode>>> {
let fd = card.as_raw_fd();
let mut res = CardRes::default();
ioctl(fd, GET_RESOURCES, &mut res)?;
let mut ids = vec![0u32; usize::try_from(res.count_connectors).ok()?];
let mut res = CardRes {
connector_id_ptr: address(ids.as_mut_ptr())?,
count_connectors: u32::try_from(ids.len()).ok()?,
..CardRes::default()
};
ioctl(fd, GET_RESOURCES, &mut res)?;
// Connectors that came between the two reads are left out.
ids.truncate(usize::try_from(res.count_connectors).ok()?);
let mut connectors = Vec::new();
for id in ids {
let mut infos = vec![ModeInfo::default(); MODES_ROOM];
let mut connector = GetConnector {
modes_ptr: address(infos.as_mut_ptr())?,
count_modes: u32::try_from(MODES_ROOM).ok()?,
connector_id: id,
..GetConnector::default()
};
ioctl(fd, GET_CONNECTOR, &mut connector)?;
let count = usize::try_from(connector.count_modes).ok()?;
if connector.connection == CONNECTED && count <= MODES_ROOM {
connectors.push(infos[..count].iter().filter_map(Mode::of).collect());
}
}
Some(connectors)
}
/// `pointer`'s address, as the kernel's `__u64` takes it.
fn address<T>(pointer: *mut T) -> Option<u64> {
u64::try_from(pointer.addr()).ok()
}
/// `ioctl(fd, request, arg)`, again where a signal or the driver interrupted it, as libdrm's
/// `drmIoctl` does; `None` where it failed.
fn ioctl<T>(fd: std::ffi::c_int, request: u32, arg: &mut T) -> Option<()> {
loop {
// SAFETY: `request` is a DRM read whose argument is a `T` (its size is in `request`), and
// the pointers `arg` carries are to buffers of the room it names, alive for the call.
let r = unsafe { libc::ioctl(fd, libc::Ioctl::from(request), std::ptr::from_mut(arg)) };
if r == 0 {
return Some(());
}
let error = std::io::Error::last_os_error().raw_os_error();
if error != Some(libc::EINTR) && error != Some(libc::EAGAIN) {
return None;
}
}
}
#[cfg(test)]
mod tests {
use super::*;
/// Modes as `drm_mode_modeinfo` gives them: pixels, htotal, vtotal, clock in kHz and flags.
fn modes(read: &[(u16, u16, u16, u16, u32, u32)]) -> Vec<Mode> {
let info = |&(hdisplay, vdisplay, htotal, vtotal, clock, flags)| ModeInfo {
hdisplay,
vdisplay,
htotal,
vtotal,
clock,
flags,
..ModeInfo::default()
};
read.iter().map(info).filter_map(|i| Mode::of(&i)).collect()
}
/// An RTX 5080 Laptop's eDP-1 panel (card1, NVIDIA 615.71.09), read 2026-12-03.
fn laptop_edp() -> Vec<Mode> {
modes(&[
(3840, 2400, 4000, 2560, 614400, 9),
(3840, 2400, 4000, 2560, 1228800, 10),
])
}
/// An Iris Xe host's two HDMI connectors (card0 HDMI-A-2, card1 HDMI-A-1, i915), their modes
/// at 3840 × 2160 and 2880 × 1800, and card0's at 2560 × 1440, read 2026-12-03: two screens
/// of one model, each listing those sizes.
fn two_hdmi_screens() -> [Vec<Mode>; 2] {
let card0 = modes(&[
(3840, 2160, 4120, 2205, 545010, 9),
(3840, 2160, 4400, 2250, 594000, 5),
(3840, 2160, 4400, 2250, 593410, 5),
(3840, 2160, 5280, 2250, 594000, 5),
(3840, 2160, 4400, 2250, 297000, 9),
(3840, 2160, 4400, 2250, 296700, 5),
(3840, 2160, 5280, 2250, 297000, 5),
(3840, 2160, 5500, 2250, 296700, 5),
(2880, 1800, 3040, 1846, 336720, 9),
(2560, 1440, 2656, 1491, 570250, 9),
]);
let card1 = modes(&[
(3840, 2160, 4120, 2205, 545010, 9),
(3840, 2160, 4400, 2250, 594000, 5),
(3840, 2160, 4400, 2250, 593407, 5),
(3840, 2160, 5280, 2250, 594000, 5),
(3840, 2160, 4400, 2250, 297000, 5),
(3840, 2160, 5500, 2250, 296703, 5),
(2880, 1800, 3040, 1846, 336720, 9),
]);
[card0, card1]
}
/// The rates rounded to the millihertz.
fn mhz(rates: Option<Vec<f64>>) -> Option<Vec<u32>> {
rates.map(|r| r.iter().map(|hz| (hz * 1000.0).round() as u32).collect())
}
/// A screen whose mode one connector lists takes that connector's rates at its size, highest
/// first: the laptop's panel at 120 Hz lists 120 and 60, and so it does at 60
#[test]
fn a_screen_takes_the_rates_of_the_one_connector_listing_its_mode() {
let panel = [laptop_edp()];
assert_eq!(
mhz(rates_of(&panel, (3840, 2400), 120.0)),
Some(vec![120_000, 60_000])
);
assert_eq!(
mhz(rates_of(&panel, (3840, 2400), 60.0)),
Some(vec![120_000, 60_000])
);
let [card0, _] = two_hdmi_screens();
assert_eq!(
mhz(rates_of(&[card0], (3840, 2160), 60.0)),
Some(vec![
60_000, 59_993, 59_940, 50_000, 30_000, 29_970, 25_000, 23_976
])
);
}
/// Two connectors that list the screen's mode, as two screens of one model do, give no
/// answer, nor does a mode no connector lists, at that size or that rate, or an interlaced
/// one: the screen then lists its own rate alone
#[test]
fn two_connectors_listing_the_mode_or_none_give_no_rates() {
let screens = two_hdmi_screens();
assert_eq!(rates_of(&screens, (3840, 2160), 60.0), None);
assert_eq!(rates_of(&screens, (2880, 1800), 60.0), None);
// A size only card0's read here lists.
assert_eq!(
mhz(rates_of(&screens, (2560, 1440), 144.0)),
Some(vec![143_999])
);
assert_eq!(rates_of(&screens, (1920, 1080), 60.0), None);
// A size the panel does not list, at a rate it lists at another.
assert_eq!(rates_of(&[laptop_edp()], (1920, 1200), 60.0), None);
assert_eq!(rates_of(&[laptop_edp()], (3840, 2400), 144.0), None);
// A 1080i mode, as CEA-861 times it, asked at the rate its read gives it.
let interlaced = modes(&[(1920, 1080, 2200, 1125, 74250, INTERLACE | 5)]);
let hz = interlaced[0].hz;
assert_eq!(rates_of(&[interlaced], (1920, 1080), hz), None);
assert_eq!(rates_of(&[], (3840, 2400), 120.0), None);
}
}
@@ -59,10 +59,10 @@ struct Array {
/// `union wl_argument`.
#[repr(C)]
#[derive(Clone, Copy)]
union Argument {
u: u32,
s: *const c_char,
o: *mut c_void,
pub(super) union Argument {
pub(super) u: u32,
pub(super) s: *const c_char,
pub(super) o: *mut c_void,
}
/// A table of the protocol's own, which libwayland-client reads only: shared between threads as
@@ -312,9 +312,9 @@ struct Gathered {
/// `wl_registry_listener`.
#[repr(C)]
struct RegistryListener {
global: unsafe extern "C" fn(*mut c_void, *mut c_void, u32, *const c_char, u32),
global_remove: unsafe extern "C" fn(*mut c_void, *mut c_void, u32),
pub(super) struct RegistryListener {
pub(super) global: unsafe extern "C" fn(*mut c_void, *mut c_void, u32, *const c_char, u32),
pub(super) global_remove: unsafe extern "C" fn(*mut c_void, *mut c_void, u32),
}
/// `zwp_linux_dmabuf_feedback_v1_listener`.
@@ -347,7 +347,12 @@ unsafe extern "C" fn global(
}
/// A global gone: nothing to do.
unsafe extern "C" fn global_remove(_data: *mut c_void, _registry: *mut c_void, _name: u32) {}
pub(super) unsafe extern "C" fn global_remove(
_data: *mut c_void,
_registry: *mut c_void,
_name: u32,
) {
}
/// The feedback is complete.
unsafe extern "C" fn feedback_done(data: *mut c_void, _feedback: *mut c_void) {
@@ -435,8 +440,40 @@ pub(crate) unsafe fn main_device_of(window: *mut SDL_Window) -> Option<(u32, u32
if display.is_null() || surface.is_null() {
return None;
}
// SAFETY: SDL's live display and surface, with an event queue and proxies of this call's own,
// each destroyed before it returns; the listeners' data outlives every dispatch of the queue.
// SAFETY: SDL's live display and its window's surface.
unsafe { read_main_device(client, display, surface) }
}
/// The main device of the dma-buf feedback of `surface`, a `wl_surface` of `display`, as its DRM
/// node's major and minor numbers (the module doc); `None` where there is none to read. Read
/// through an event queue and proxies of this call's own, so a connection SDL or another user
/// reads from sees none of its events.
///
/// # Safety
///
/// `display` is a live connection, and `surface` a live `wl_surface` of it.
pub(super) unsafe fn main_device_of_surface(
display: *mut c_void,
surface: *mut c_void,
) -> Option<(u32, u32)> {
let client = client()?;
// SAFETY: the caller's.
unsafe { read_main_device(client, display, surface) }
}
/// [`main_device_of_surface`] with libwayland-client's calls looked up.
///
/// # Safety
///
/// As [`main_device_of_surface`]'s.
unsafe fn read_main_device(
client: &Client,
display: *mut c_void,
surface: *mut c_void,
) -> Option<(u32, u32)> {
// SAFETY: the caller's live display and surface, with an event queue and proxies of this
// call's own, each destroyed before it returns; the listeners' data outlives every dispatch
// of the queue.
unsafe {
let queue = (client.create_queue)(display);
if queue.is_null() {
@@ -1,45 +1,54 @@
//! The window system SDL's windows open through on Linux ([`window_system`], the choice of
//! `crate::winsys`): before SDL's video starts, the GPU of the first window's sink is asked whether
//! it presents to the session's Wayland compositor, and where it does not, to its X server, over
//! connections of this module's own, each made for the question and closed after it
//! ([`answers`]). libwayland-client
//! and libX11 are the libraries SDL opens, opened here by their names and their calls looked up
//! by name, so nothing is linked; a library or a call missing, or a connection refused, is a window
//! system the session does not have. The X server is asked about its default screen's default
//! visual, the one SDL's window takes.
//! it presents to a window of the session's Wayland compositor, and where it does not, to one of
//! its X server ([`answers`]), once, as SDL's video starts. Each question is asked of a window
//! made for it, over a connection of this module's own, and both are destroyed after it, whatever
//! the answer: on Wayland a `wl_surface` given no role, which the compositor never shows, and on
//! X11 an unmapped window on the default screen's root, of its default visual, the one SDL's
//! window takes. The sink makes a Vulkan surface of the window and asks what its swapchain asks of
//! a window's surface ([`FrameSink::presents_to`]). Where it does not present to the Wayland
//! window, the GPU the compositor composites on is read from that window's dma-buf feedback
//! (`feedback.rs`) for the host's no-window lines (`crate::told`), which name it as the GPU the
//! desktop is drawn on. libwayland-client and libX11 are the libraries SDL opens, opened here by
//! their names and their calls and interface tables looked up by name, so nothing is linked; a
//! library or a call missing, a connection refused, or a compositor that lists no `wl_compositor`
//! is a window system the session does not have.
//!
//! Where the session hands its Wayland connection over in `WAYLAND_SOCKET`, which a client can
//! take once, nothing is asked and SDL picks: a connection of this module's would take it from
//! SDL.
use std::ffi::{CStr, c_char, c_int, c_ulong, c_void};
use std::ffi::{CStr, c_char, c_int, c_uint, c_ulong, c_void};
use std::sync::OnceLock;
use reims_vgpu_vulkan::swapchain::WindowSystem;
use super::feedback::{Argument, RegistryListener, global_remove, main_device_of_surface};
use crate::present::FrameSink;
use crate::told;
use crate::winsys::{Answers, Choice, asks_x11, choose};
/// The window system SDL's windows open through, from what the GPU of `sink`, the first window's,
/// answers ([`answers`], `crate::winsys`), logged at info with the answers; SDL's own pick where
/// there is no sink, its GPU cannot be asked, or the session's Wayland connection is handed over.
/// answers ([`answers`], `crate::winsys`), logged at info with the answers and why each no; SDL's
/// own pick where there is no sink, its GPU cannot be asked, or the session's Wayland connection
/// is handed over.
pub(crate) fn window_system(sink: Option<&dyn FrameSink>) -> Choice {
if std::env::var_os("WAYLAND_SOCKET").is_some() {
return Choice::Sdls;
}
let Some(answers) = sink.and_then(answers) else {
let Some(asked) = sink.and_then(answers) else {
return Choice::Sdls;
};
let choice = choose(Some(answers));
let choice = choose(Some(asked.answers()));
log::info!(
target: "reims_vgpu_window",
"the windows' GPU presents to the Wayland compositor: {}; to the X server: {}; the windows \
open through {}",
said(answers.wayland, "no compositor"),
if asks_x11(answers.wayland) {
said(answers.x11, "no X server")
"the windows' GPU presents to a window of the Wayland compositor: {}; of the X server: \
{}; the windows open through {}",
said(asked.wayland.as_ref(), "no compositor"),
if asks_x11(asked.answers().wayland) {
said(asked.x11.as_ref(), "no X server")
} else {
"not asked"
"not asked".to_owned()
},
match choice {
Choice::Sdls => "SDL's own pick",
@@ -50,34 +59,64 @@ pub(crate) fn window_system(sink: Option<&dyn FrameSink>) -> Choice {
choice
}
/// An answer as the log says it: `yes`, `no`, or `absent` where the session has no such window
/// system.
fn said(answer: Option<bool>, absent: &'static str) -> &'static str {
/// An answer as the log says it: `yes`, `no (why)`, or `absent` where the session has no such
/// window system.
fn said(answer: Option<&Result<(), String>>, absent: &str) -> String {
match answer {
Some(true) => "yes",
Some(false) => "no",
None => absent,
Some(Ok(())) => "yes".to_owned(),
Some(Err(why)) => format!("no ({why})"),
None => absent.to_owned(),
}
}
/// Whether the GPU of `sink` presents to the session's Wayland compositor, and where it does not,
/// to its X server (`crate::winsys`), `None` for one the session does not have; `None` where the
/// sink has no GPU to ask.
fn answers(sink: &dyn FrameSink) -> Option<Answers> {
/// What the GPU answered of each window system's window: why not where it does not present to
/// it; `None` for one the session does not have, or was not asked about.
struct Asked {
/// The Wayland compositor's window.
wayland: Option<Result<(), String>>,
/// The X server's window, asked only where the GPU does not present to the compositor's.
x11: Option<Result<(), String>>,
}
impl Asked {
/// The answers, as the choice takes them.
fn answers(&self) -> Answers {
Answers {
wayland: self.wayland.as_ref().map(Result::is_ok),
x11: self.x11.as_ref().map(Result::is_ok),
}
}
}
/// Whether the GPU of `sink` presents to a window of the session's Wayland compositor, and where
/// it does not, to one of its X server (`crate::winsys`, the module doc); `None` where the sink
/// has no GPU to ask.
fn answers(sink: &dyn FrameSink) -> Option<Asked> {
let mut asked = true;
let mut ask = |system| {
let answer = sink.presents_to(system);
asked &= answer.is_some();
answer.unwrap_or(false)
answer.unwrap_or(Ok(()))
};
// Each connection is live, and this thread's own, during its question.
let wayland = with_wayland(|display| ask(WindowSystem::Wayland { display }));
let x11 = if asks_x11(wayland) {
with_xlib(|display, visual| ask(WindowSystem::Xlib { display, visual }))
// Each connection and window is live, and this thread's own, during its question.
let wayland = with_wayland(|display, surface| {
let answer = ask(WindowSystem::Wayland { display, surface });
if answer.is_err() {
// The GPU the compositor composites on, which can show a window there, for the
// host's no-window lines (`crate::told`).
// SAFETY: the live connection and surface made for the question.
if let Some(node) = unsafe { main_device_of_surface(display, surface) } {
told::desktop_is_on(node);
}
}
answer
});
let x11 = if asks_x11(wayland.as_ref().map(Result::is_ok)) {
with_xlib(|display, window| ask(WindowSystem::Xlib { display, window }))
} else {
None
};
asked.then_some(Answers { wayland, x11 })
asked.then_some(Asked { wayland, x11 })
}
/// Opens `name`, a library SDL opens too, for the process: `None` where it is not installed.
@@ -103,28 +142,85 @@ impl Library {
// SAFETY: the caller's: `T` is the symbol's type, a pointer's size.
(!p.is_null()).then(|| unsafe { std::mem::transmute_copy::<*mut c_void, T>(&p) })
}
/// The address of the library's data `name`.
fn data(&self, name: &CStr) -> Option<*const c_void> {
// SAFETY: a live handle and a symbol name.
let p = unsafe { libc::dlsym(self.0, name.as_ptr()) };
(!p.is_null()).then_some(p.cast_const())
}
}
/// `wl_display_connect`.
type Connect = unsafe extern "C" fn(*const c_char) -> *mut c_void;
/// `wl_display_disconnect`.
type Disconnect = unsafe extern "C" fn(*mut c_void);
/// `wl_display_disconnect` and `wl_proxy_destroy`.
type OfProxy = unsafe extern "C" fn(*mut c_void);
/// `wl_display_roundtrip`.
type Roundtrip = unsafe extern "C" fn(*mut c_void) -> c_int;
/// `wl_proxy_marshal_array_flags`, the interface being one of the library's `wl_interface`s.
type Marshal =
unsafe extern "C" fn(*mut c_void, u32, *const c_void, u32, u32, *mut Argument) -> *mut c_void;
/// `wl_proxy_add_listener`.
type AddListener = unsafe extern "C" fn(*mut c_void, *const c_void, *mut c_void) -> c_int;
/// `wl_proxy_get_version`.
type ProxyVersion = unsafe extern "C" fn(*mut c_void) -> u32;
/// libwayland-client's calls this module makes.
/// libwayland-client's calls and interface tables this module uses.
#[derive(Clone, Copy)]
struct Wayland {
connect: Connect,
disconnect: Disconnect,
disconnect: OfProxy,
roundtrip: Roundtrip,
marshal: Marshal,
add_listener: AddListener,
proxy_destroy: OfProxy,
proxy_version: ProxyVersion,
/// `wl_registry_interface`.
registry: *const c_void,
/// `wl_compositor_interface`.
compositor: *const c_void,
/// `wl_surface_interface`.
surface: *const c_void,
}
// SAFETY: function pointers and the library's own interface tables, never written.
unsafe impl Send for Wayland {}
// SAFETY: as above.
unsafe impl Sync for Wayland {}
/// `wl_display.get_registry`'s opcode.
const GET_REGISTRY: u32 = 1;
/// `wl_registry.bind`'s opcode.
const BIND: u32 = 0;
/// `wl_compositor.create_surface`'s opcode.
const CREATE_SURFACE: u32 = 0;
/// `wl_surface.destroy`'s opcode.
const DESTROY: u32 = 0;
/// `WL_MARSHAL_FLAG_DESTROY`.
const MARSHAL_DESTROY: u32 = 1;
/// The newest `wl_compositor` bound: version 4, which every libwayland-client since 1.4 knows.
const COMPOSITOR_VERSION: u32 = 4;
/// `XOpenDisplay`.
type OpenDisplay = unsafe extern "C" fn(*const c_char) -> *mut c_void;
/// `XDefaultScreen`.
type DefaultScreen = unsafe extern "C" fn(*mut c_void) -> c_int;
/// `XDefaultVisual`.
type DefaultVisual = unsafe extern "C" fn(*mut c_void, c_int) -> *mut c_void;
/// `XVisualIDFromVisual`.
type VisualId = unsafe extern "C" fn(*mut c_void) -> c_ulong;
/// `XRootWindow`.
type RootWindow = unsafe extern "C" fn(*mut c_void, c_int) -> c_ulong;
/// `XCreateSimpleWindow`.
type CreateSimpleWindow = unsafe extern "C" fn(
*mut c_void,
c_ulong,
c_int,
c_int,
c_uint,
c_uint,
c_uint,
c_ulong,
c_ulong,
) -> c_ulong;
/// `XDestroyWindow`.
type DestroyWindow = unsafe extern "C" fn(*mut c_void, c_ulong) -> c_int;
/// `XCloseDisplay`.
type CloseDisplay = unsafe extern "C" fn(*mut c_void) -> c_int;
@@ -133,12 +229,14 @@ type CloseDisplay = unsafe extern "C" fn(*mut c_void) -> c_int;
struct Xlib {
open_display: OpenDisplay,
default_screen: DefaultScreen,
default_visual: DefaultVisual,
visual_id: VisualId,
root_window: RootWindow,
create_simple_window: CreateSimpleWindow,
destroy_window: DestroyWindow,
close_display: CloseDisplay,
}
/// libwayland-client's calls, looked up once: `None` where the library or a call is missing.
/// libwayland-client's calls and tables, looked up once: `None` where the library or one of them
/// is missing.
fn wayland_calls() -> Option<Wayland> {
static CALLS: OnceLock<Option<Wayland>> = OnceLock::new();
*CALLS.get_or_init(|| {
@@ -149,6 +247,14 @@ fn wayland_calls() -> Option<Wayland> {
Some(Wayland {
connect: lib.call(c"wl_display_connect")?,
disconnect: lib.call(c"wl_display_disconnect")?,
roundtrip: lib.call(c"wl_display_roundtrip")?,
marshal: lib.call(c"wl_proxy_marshal_array_flags")?,
add_listener: lib.call(c"wl_proxy_add_listener")?,
proxy_destroy: lib.call(c"wl_proxy_destroy")?,
proxy_version: lib.call(c"wl_proxy_get_version")?,
registry: lib.data(c"wl_registry_interface")?,
compositor: lib.data(c"wl_compositor_interface")?,
surface: lib.data(c"wl_surface_interface")?,
})
}
})
@@ -164,45 +270,213 @@ fn xlib_calls() -> Option<Xlib> {
Some(Xlib {
open_display: lib.call(c"XOpenDisplay")?,
default_screen: lib.call(c"XDefaultScreen")?,
default_visual: lib.call(c"XDefaultVisual")?,
visual_id: lib.call(c"XVisualIDFromVisual")?,
root_window: lib.call(c"XRootWindow")?,
create_simple_window: lib.call(c"XCreateSimpleWindow")?,
destroy_window: lib.call(c"XDestroyWindow")?,
close_display: lib.call(c"XCloseDisplay")?,
})
}
})
}
/// `ask` with a connection to the session's Wayland compositor (`WAYLAND_DISPLAY`'s), made for it
/// and closed after: `None` where there is none to connect to.
fn with_wayland(ask: impl FnOnce(*mut c_void) -> bool) -> Option<bool> {
/// `ask` with a connection to the session's Wayland compositor (`WAYLAND_DISPLAY`'s) and a
/// `wl_surface` of it ([`with_surface`]), made for it and destroyed after, whatever it answers:
/// `None` where there is no compositor to connect to, or no surface is made.
fn with_wayland<T>(ask: impl FnOnce(*mut c_void, *mut c_void) -> T) -> Option<T> {
let calls = wayland_calls()?;
// SAFETY: libwayland-client's call; NULL connects to the session's compositor.
let display = unsafe { (calls.connect)(std::ptr::null()) };
if display.is_null() {
return None;
}
let answer = ask(display);
// SAFETY: the connection made above, used by no one else.
// SAFETY: the connection made above, this thread's alone.
let answer = unsafe { with_surface(&calls, display, ask) };
// SAFETY: the connection made above, every proxy of it this module made destroyed.
unsafe { (calls.disconnect)(display) };
Some(answer)
answer
}
/// `ask` with a connection to the session's X server (`DISPLAY`'s), made for it and closed after,
/// and its default screen's default visual: `None` where there is none to connect to.
fn with_xlib(ask: impl FnOnce(*mut c_void, c_ulong) -> bool) -> Option<bool> {
/// A global listed: `wl_compositor`'s name and version kept.
unsafe extern "C" fn global(
data: *mut c_void,
_registry: *mut c_void,
name: u32,
interface: *const c_char,
version: u32,
) {
// SAFETY: `data` is the `Option<(u32, u32)>` the listener was added with, which outlives the
// registry; `interface` is the event's string.
let (listed, interface) = unsafe {
(
&mut *data.cast::<Option<(u32, u32)>>(),
CStr::from_ptr(interface),
)
};
if interface == c"wl_compositor" {
*listed = Some((name, version));
}
}
static REGISTRY_LISTENER: RegistryListener = RegistryListener {
global,
global_remove,
};
/// `ask` with `display` and a `wl_surface` of it, given no role: the registry, `wl_compositor`
/// bound, the surface made, and each destroyed after the question, whatever it answers, and on
/// every path that made it. `None` where the round trip fails, the compositor lists no
/// `wl_compositor`, or a request makes no proxy.
///
/// # Safety
///
/// `display` is a live connection of the caller's own, which no other thread uses during the call.
unsafe fn with_surface<T>(
calls: &Wayland,
display: *mut c_void,
ask: impl FnOnce(*mut c_void, *mut c_void) -> T,
) -> Option<T> {
// The registry listener's data: it outlives the registry, destroyed before this returns.
let mut listed: Option<(u32, u32)> = None;
let mut args = [Argument {
o: std::ptr::null_mut(),
}];
// SAFETY: the caller's live connection; the request's one argument is its new registry.
let registry = unsafe {
(calls.marshal)(
display,
GET_REGISTRY,
calls.registry,
(calls.proxy_version)(display),
0,
args.as_mut_ptr(),
)
};
if registry.is_null() {
return None;
}
// SAFETY: the registry made above, and `listed`, which outlives it.
let found = unsafe {
(calls.add_listener)(
registry,
(&raw const REGISTRY_LISTENER).cast(),
(&raw mut listed).cast(),
);
((calls.roundtrip)(display) >= 0)
.then_some(listed)
.flatten()
};
let mut answer = None;
if let Some((name, version)) = found {
let version = version.min(COMPOSITOR_VERSION);
// SAFETY: the caller's connection, and the registry made above, which lists
// `wl_compositor` as `name` at `version` or later.
answer = unsafe { with_compositor(calls, display, registry, name, version, ask) };
}
// SAFETY: the registry made above, nothing made of it left: the compositor's proxy is
// destroyed.
unsafe { (calls.proxy_destroy)(registry) };
answer
}
/// `ask` with `display` and a `wl_surface` of it: `wl_compositor`, the global `name` of
/// `registry`, bound at `version`, the surface made, and both destroyed after the question.
///
/// # Safety
///
/// `display` is a live connection of the caller's own, and `registry` a live registry of it, which
/// lists `wl_compositor` as `name` at `version` or later.
unsafe fn with_compositor<T>(
calls: &Wayland,
display: *mut c_void,
registry: *mut c_void,
name: u32,
version: u32,
ask: impl FnOnce(*mut c_void, *mut c_void) -> T,
) -> Option<T> {
let mut bind = [
Argument { u: name },
Argument {
s: c"wl_compositor".as_ptr(),
},
Argument { u: version },
Argument {
o: std::ptr::null_mut(),
},
];
// SAFETY: the caller's registry; `wl_registry.bind`'s arguments, the last its new proxy.
let compositor = unsafe {
(calls.marshal)(
registry,
BIND,
calls.compositor,
version,
0,
bind.as_mut_ptr(),
)
};
if compositor.is_null() {
return None;
}
let mut made = [Argument {
o: std::ptr::null_mut(),
}];
// SAFETY: the compositor bound above; the request's one argument is its new surface.
let surface = unsafe {
(calls.marshal)(
compositor,
CREATE_SURFACE,
calls.surface,
version,
0,
made.as_mut_ptr(),
)
};
let answer = (!surface.is_null()).then(|| {
let answer = ask(display, surface);
// SAFETY: the surface made above, destroyed by its `destroy` request, nothing made of
// it left: the question destroyed the Vulkan surface it made of it.
unsafe {
(calls.marshal)(
surface,
DESTROY,
std::ptr::null(),
version,
MARSHAL_DESTROY,
std::ptr::null_mut(),
)
};
answer
});
// SAFETY: the compositor bound above, which has no destroy request, its surface destroyed.
unsafe { (calls.proxy_destroy)(compositor) };
answer
}
/// `ask` with a connection to the session's X server (`DISPLAY`'s) and an unmapped window of it,
/// on its default screen's root, of the root's visual, its default one: each made for it and
/// destroyed after, whatever it answers; `None` where there is no server to connect to.
fn with_xlib<T>(ask: impl FnOnce(*mut c_void, c_ulong) -> T) -> Option<T> {
let calls = xlib_calls()?;
// SAFETY: libX11's call; NULL connects to the session's server.
let display = unsafe { (calls.open_display)(std::ptr::null()) };
if display.is_null() {
return None;
}
// SAFETY: the live connection made above, and the screen and visual it names.
let visual = unsafe {
// SAFETY: the live connection made above, and the screen and root window it names; the
// window is 1 x 1 pixels, with no border, never mapped.
let window = unsafe {
let screen = (calls.default_screen)(display);
(calls.visual_id)((calls.default_visual)(display, screen))
let root = (calls.root_window)(display, screen);
(calls.create_simple_window)(display, root, 0, 0, 1, 1, 0, 0, 0)
};
let answer = ask(display, visual);
let answer = (window != 0).then(|| {
let answer = ask(display, window);
// SAFETY: the window made above, nothing made of it left: the question destroyed the
// Vulkan surface it made of it.
unsafe { (calls.destroy_window)(display, window) };
answer
});
// SAFETY: the connection made above, used by no one else.
unsafe { (calls.close_display)(display) };
Some(answer)
answer
}
@@ -6,7 +6,8 @@
//! there is something to draw: a new guest frame, a new layout (the view resized or moved to a
//! screen of another scale, or the guest set a mode), the window showing again, or a change of
//! the guest's cursor where the window draws it ([`Window::drawn_cursor`], which each draw hands
//! the sink). It draws only while the window is at least partly visible, once its layer and
//! the sink), whose changes alone are drawn at most once a refresh of the window's screen, where
//! they last put it (`crate::pace`). It draws only while the window is at least partly visible, once its layer and
//! layout exist.
//!
//! Each draw goes through the sink's presenter over a Vulkan surface of the layer
@@ -31,6 +32,7 @@
//! as the view's is ([`LayerRef`]).
use std::sync::Arc;
use std::time::Duration;
use objc2::Message;
use objc2::rc::Retained;
@@ -47,6 +49,7 @@ use super::main_thread::post_main;
use super::metal_surface::LayerTarget;
use crate::geometry::Layout;
use crate::handle::Window;
use crate::pace::{CursorPace, DEFAULT_REFRESH};
use crate::present::{Presenting, RETRY};
/// The render thread's stack.
@@ -109,7 +112,6 @@ pub(crate) struct Surface {
}
/// The surface's state.
#[derive(Default)]
struct SurfaceState {
/// The view's layer, once the window has opened on the main thread.
layer: Option<LayerRef>,
@@ -119,10 +121,29 @@ struct SurfaceState {
visible: bool,
/// Something new to show: a frame, a layout, the window showing again.
dirty: bool,
/// A change of the guest's cursor where the window draws it, drawn at most once a
/// [`SurfaceState::refresh`] (`crate::pace`).
cursor: CursorPace,
/// A refresh of the window's screen ([`Surface::set_refresh`]).
refresh: Duration,
/// The window has ended: the render thread ends.
closed: bool,
}
impl Default for SurfaceState {
fn default() -> SurfaceState {
SurfaceState {
layer: None,
layout: None,
visible: false,
dirty: false,
cursor: CursorPace::default(),
refresh: DEFAULT_REFRESH,
closed: false,
}
}
}
impl std::fmt::Debug for SurfaceState {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("SurfaceState")
@@ -130,6 +151,8 @@ impl std::fmt::Debug for SurfaceState {
.field("layout", &self.layout)
.field("visible", &self.visible)
.field("dirty", &self.dirty)
.field("cursor", &self.cursor)
.field("refresh", &self.refresh)
.field("closed", &self.closed)
.finish()
}
@@ -142,22 +165,34 @@ struct Work {
}
impl SurfaceState {
/// The draw to make now, if any: something new, the window visible, its layer and layout
/// there. `want_layer` asks for a reference to the layer.
/// The draw to make now, if any: something new, or a change of the cursor's that is due
/// (`crate::pace`), the window visible, its layer and layout there. `want_layer` asks for a
/// reference to the layer.
fn take(&mut self, want_layer: bool) -> Option<Work> {
if !(self.dirty && self.visible) {
let now = super::now();
if !((self.dirty || self.cursor.is_due(now, self.refresh)) && self.visible) {
return None;
}
let (Some(layer), Some(layout)) = (&self.layer, self.layout) else {
return None;
};
self.dirty = false;
self.cursor.drawn(now);
Some(Work {
layer: want_layer.then(|| layer.retain()),
layout,
})
}
/// How long to wait for a change of the cursor's to be due, where one waits and would be
/// drawn then; else none, and only a request wakes the render thread.
fn cursor_wait(&self) -> Option<Duration> {
if !(self.visible && self.layer.is_some() && self.layout.is_some()) {
return None;
}
self.cursor.wait(super::now(), self.refresh)
}
/// The draw to make again after a presenter's that had no image in time (`layout`): the
/// newest, else the same, while the window is visible. None while it is not: the draw waits
/// for it to show, which asks for one ([`Surface::set_visible`]).
@@ -224,6 +259,18 @@ impl Surface {
self.update(|s| s.dirty = true);
}
/// The guest's cursor changed where the window draws it: drawn at most once a refresh of
/// the window's screen (`crate::pace`).
pub(crate) fn request_cursor_draw(&self) {
self.update(|s| s.cursor.ask());
}
/// The window's screen refreshes every `refresh`: the cursor's changes are drawn at most
/// that often.
pub(crate) fn set_refresh(&self, refresh: Duration) {
self.update(|s| s.refresh = refresh);
}
/// The window's end: the render thread ends.
pub(crate) fn close(&self) {
self.update(|s| s.closed = true);
@@ -251,7 +298,12 @@ impl Surface {
if let Some(work) = state.take(want_layer) {
return Some(work);
}
self.wake.wait(&mut state);
match state.cursor_wait() {
Some(left) => {
self.wake.wait_for(&mut state, left);
}
None => self.wake.wait(&mut state),
}
}
}
}
@@ -292,7 +344,7 @@ fn run(window: &Window) {
};
let cursor = window.drawn_cursor();
if presenting.needs_presenter() {
presenting.make(|| sink.presenter(&LayerTarget(layer)));
presenting.make(|| sink.presenter(&LayerTarget(layer)), || None);
}
if presenting.draw(
work.layout.drawable,
@@ -382,6 +434,61 @@ mod tests {
drop(surface.take_layer());
}
/// The guest's cursor moved on its own several times inside one refresh of the window's
/// screen (60 Hz, where the window is told no other rate), where the window draws it: one
/// draw, at the last place, not one a move. A run whose moves took more than half a
/// refresh (a loaded host) is tried again
#[test]
fn guest_cursor_moves_inside_one_refresh_are_drawn_once() {
const MOVES: u16 = 8;
for _ in 0..5 {
let window = Window::new(
crate::config::WindowConfig::default(),
0,
crate::handle::title(0),
);
window.cursor_glyph(1, 1, (0, 0), &[255; 4]);
window.guest_mode(64, 32);
window.cursor_show(true);
window.cursor_at((1, 1));
window.cursor_at((2, 1));
assert!(
window.drawn_cursor().is_some(),
"the guest leads its cursor"
);
let surface = window.surface();
surface.set_layer(a_layer());
surface.set_layout(a_layout());
surface.set_visible(true);
assert!(surface.state.lock().take(false).is_some(), "the first draw");
let start = super::super::now();
let mut draws = 0;
for x in 0..MOVES {
window.cursor_at((10 + x, 1));
draws += usize::from(surface.state.lock().take(false).is_some());
}
let took = super::super::now().saturating_duration_since(start);
std::thread::sleep(std::time::Duration::from_millis(40));
draws += usize::from(surface.state.lock().take(false).is_some());
if took > std::time::Duration::from_millis(8) {
window.close();
drop(surface.take_layer());
continue;
}
assert_eq!(draws, 1, "{MOVES} moves inside one refresh");
assert_eq!(
window.drawn_cursor().map(|c| c.at),
Some((10 + MOVES - 1, 1)),
"drawn at the last place"
);
assert!(surface.state.lock().take(false).is_none(), "nothing more");
window.close();
drop(surface.take_layer());
return;
}
panic!("every run's moves took more than half a refresh");
}
/// A presenter's draw with no image in time comes again, the newest layout first, while the
/// window is visible; hidden, it waits for the window to show
#[test]
@@ -33,7 +33,7 @@ use objc2_core_graphics::{
kCGNullDirectDisplay,
};
use crate::screens::{HostScreen, screen_refresh};
use crate::screens::{HostScreen, screen_rates, screen_refresh};
/// The most displays asked for.
const MAX_DISPLAYS: usize = 32;
@@ -86,7 +86,7 @@ fn all_modes(display: CGDirectDisplayID) -> Vec<CFRetained<CGDisplayMode>> {
}
/// The screen `display` is, or `None` where it has no current mode.
fn screen(display: CGDirectDisplayID) -> Option<HostScreen> {
pub(crate) fn screen(display: CGDirectDisplayID) -> Option<HostScreen> {
let mode = CGDisplayCopyDisplayMode(display)?;
let mode = Some(&*mode);
let pixels = mode_pixels(mode);
@@ -96,15 +96,22 @@ fn screen(display: CGDirectDisplayID) -> Option<HostScreen> {
} else {
1.0
};
let modes = all_modes(display).into_iter().map(|other| {
let other = Some(&*other);
(mode_pixels(other), CGDisplayMode::refresh_rate(other))
});
let modes: Vec<((u32, u32), f64)> = (all_modes(display).into_iter())
.map(|other| {
let other = Some(&*other);
(mode_pixels(other), CGDisplayMode::refresh_rate(other))
})
.collect();
Some(HostScreen {
id: display,
pixels,
scale,
refresh_hz: screen_refresh(pixels, CGDisplayMode::refresh_rate(mode), modes),
refresh_hz: screen_refresh(
pixels,
CGDisplayMode::refresh_rate(mode),
modes.iter().copied(),
),
rates_hz: screen_rates(pixels, modes),
})
}
@@ -273,6 +273,12 @@ pub(crate) fn insets(shell: &Shell) -> Insets {
.unwrap_or_default()
}
/// The host screen `shell`'s window is on: its `NSWindow`'s screen, as CoreGraphics lists it.
pub(crate) fn filled_screen(shell: &Shell) -> Option<crate::screens::HostScreen> {
let screen = msg::get("screen", || shell.os.ns_window.screen())?;
appkit::display_id(&screen).and_then(super::screens::screen)
}
/// The screens changed: a borderless window fills its screen again, or the main screen while its
/// own is gone.
pub(crate) fn screens_changed(shell: &mut Shell) {
@@ -386,6 +386,11 @@ pub(crate) fn screen_with_id(id: u32, mtm: MainThreadMarker) -> Option<Retained<
.find(|screen| display_id(screen) == Some(id))
}
/// The host screen `screen` is, as CoreGraphics lists it (`crate::screens`).
fn host_screen(screen: Option<&NSScreen>) -> Option<crate::screens::HostScreen> {
screen.and_then(display_id).and_then(super::screens::screen)
}
/// `NSScreen.mainScreen`.
pub(crate) fn main_screen(mtm: MainThreadMarker) -> Option<Retained<NSScreen>> {
msg::get("mainScreen", || NSScreen::mainScreen(mtm))
@@ -864,6 +869,7 @@ pub(crate) fn open(window: &Arc<Window>, mtm: MainThreadMarker) {
window.surface().set_layer(view.layer_ref());
view.refresh_title();
if borderless {
view.fills(host_screen(screen.as_deref()));
hide_dock_and_menu_bar(mtm);
}
msg::get("makeKeyAndOrderFront:", || {
@@ -961,9 +967,10 @@ pub(crate) fn screens_changed(mtm: MainThreadMarker) {
let screen = screen
.and_then(|id| screen_with_id(id, mtm))
.or_else(|| main_screen(mtm));
if let Some(screen) = screen {
fill(&window, &screen);
if let Some(screen) = &screen {
fill(&window, screen);
}
view.fills(host_screen(screen.as_deref()));
}
view.relayout();
}
@@ -563,6 +563,12 @@ impl DisplayView {
self.apply_hold();
}
/// Tells the window the host screen it fills now, where it is borderless
/// ([`Window::filled_screen`]).
pub(crate) fn fills(&self, screen: Option<crate::screens::HostScreen>) {
self.ivars().window.fills(screen);
}
/// The window is closing, or about to: every key held goes up, and a game's lock lets the
/// pointer go.
pub(crate) fn window_closing(&self) {
@@ -6,7 +6,8 @@
//! there is something to draw: a new guest frame, a new layout (the window resized, or moved to a
//! screen of another scale, or the guest set a mode), the window showing again, or a change of
//! the guest's cursor where the window draws it ([`Window::drawn_cursor`], which each draw hands
//! the presenter). It draws only
//! the presenter), whose changes alone are drawn at most once a refresh of the window's screen,
//! where they last put it (`crate::pace`). It draws only
//! while the window is shown, once SDL's window and the layout exist, through a presenter the sink
//! makes over the window ([`FrameSink::presenter`](crate::FrameSink::presenter)), which makes the
//! window's Vulkan surface ([`VulkanTarget`]), as `crate::present` says: made at the first draw,
@@ -25,8 +26,21 @@
//! swapchain and the Vulkan surface, and only then posts to the UI thread that SDL's window may go
//! ([`crate::sdl::shell::released`]), so the surface always goes before the window under it.
//! Nothing joins it, and the window's end waits for nothing.
//!
//! **An opening that does not return.** SDL's opening of the window on the UI thread waits for
//! the window system to show it, with no bound of its own: on X11, `X11_ShowWindow` waits for the
//! window manager's `MapNotify` (SDL 3.4.18's `SDL_x11window.c`). KWin on Wayland maps no X window
//! while every screen is off (docs/lessons.md): with a host's one screen off, its
//! session locked and unlocked, XWayland's window was never mapped and the opening never returned
//! (**measured** 2026-12-04, on an RTX 2080 and on the Radeon 780M KWin composites on, potluck
//! m3-max-87109, m3-max-87121 and m3-max-87130), so the UI thread waited to the process's end and
//! the start said nothing. The render thread, which starts before the opening is posted, waits for
//! SDL's window up to `told::OPEN_WAIT` first; where it has not come, it logs so and tells the host
//! (`crate::told`), with both readings, a screen off or a GPU the window system does not show, then
//! waits on as before.
use std::sync::Arc;
use std::time::Duration;
use ash::vk;
use reims_vgpu_vulkan::core::rt::spawn_named;
@@ -37,7 +51,9 @@ use sdl3_sys::everything::{SDL_Vulkan_CreateSurface, SDL_Window};
use crate::geometry::Layout;
use crate::handle::{DrawnCursor, DrawnOverlay, Window};
use crate::pace::{CursorPace, DEFAULT_REFRESH};
use crate::present::{Presenting, RETRY, VulkanTarget};
use crate::told;
/// The render thread's stack: 8 MiB, as the process's main thread has. The render thread's
/// presenter can be the first to ask for the process's device, which the runtime then makes on
@@ -97,7 +113,7 @@ pub(crate) struct Surface {
}
/// The surface's state.
#[derive(Debug, Default)]
#[derive(Debug)]
struct SurfaceState {
/// SDL's window, once it has opened on the UI thread.
target: Option<Target>,
@@ -107,6 +123,11 @@ struct SurfaceState {
visible: bool,
/// Something new to show: a frame, a layout, the window showing again, the overlay.
dirty: bool,
/// A change of the guest's cursor where the window draws it, drawn at most once a
/// [`SurfaceState::refresh`] (`crate::pace`).
cursor: CursorPace,
/// A refresh of the window's screen ([`Surface::set_refresh`]).
refresh: Duration,
/// The window has ended: the render thread ends.
closed: bool,
/// What the window draws over the frame, while it shows one.
@@ -115,6 +136,22 @@ struct SurfaceState {
unshown_told: bool,
}
impl Default for SurfaceState {
fn default() -> SurfaceState {
SurfaceState {
target: None,
layout: None,
visible: false,
dirty: false,
cursor: CursorPace::default(),
refresh: DEFAULT_REFRESH,
closed: false,
overlay: None,
unshown_told: false,
}
}
}
/// A draw the render thread takes: SDL's window and the layout.
struct Work {
target: Target,
@@ -122,19 +159,30 @@ struct Work {
}
impl SurfaceState {
/// The draw to make now, if any: something new, the window shown, its window and layout
/// there.
/// The draw to make now, if any: something new, or a change of the cursor's that is due
/// (`crate::pace`), the window shown, its window and layout there.
fn take(&mut self) -> Option<Work> {
if !(self.dirty && self.visible) {
let now = super::now();
if !((self.dirty || self.cursor.is_due(now, self.refresh)) && self.visible) {
return None;
}
let (Some(target), Some(layout)) = (self.target, self.layout) else {
return None;
};
self.dirty = false;
self.cursor.drawn(now);
Some(Work { target, layout })
}
/// How long to wait for a change of the cursor's to be due, where one waits and would be
/// drawn then; else none, and only a request wakes the render thread.
fn cursor_wait(&self) -> Option<Duration> {
if !(self.visible && self.target.is_some() && self.layout.is_some()) {
return None;
}
self.cursor.wait(super::now(), self.refresh)
}
/// The draw to make again after one that had no image in time: the newest, else the same,
/// while the window is shown. None while it is hidden: the draw waits for it to show, which
/// asks for one ([`Surface::set_visible`]).
@@ -223,11 +271,40 @@ impl Surface {
self.update(|s| s.dirty = true);
}
/// The guest's cursor changed where the window draws it: drawn at most once a refresh of
/// the window's screen (`crate::pace`).
pub(crate) fn request_cursor_draw(&self) {
self.update(|s| s.cursor.ask());
}
/// The window's screen refreshes every `refresh`: the cursor's changes are drawn at most
/// that often.
pub(crate) fn set_refresh(&self, refresh: Duration) {
self.update(|s| s.refresh = refresh);
}
/// The window's end: the render thread ends.
pub(crate) fn close(&self) {
self.update(|s| s.closed = true);
}
/// Waits up to `wait` for SDL's window, which the UI thread hands over once the window has
/// opened ([`Surface::set_target`]), or for the window's end: whether either came.
fn opened_within(&self, wait: Duration) -> bool {
let until = super::now().saturating_add(wait);
let mut state = self.state.lock();
loop {
if state.target.is_some() || state.closed {
return true;
}
let left = until.saturating_duration_since(super::now());
if left.is_zero() {
return false;
}
self.wake.wait_for(&mut state, left);
}
}
/// Waits for the next draw; `None` at the window's end. `retry` asks for the last draw
/// again after [`RETRY`], where nothing newer comes first.
fn next(&self, retry: Option<Work>) -> Option<Work> {
@@ -250,7 +327,12 @@ impl Surface {
if let Some(work) = state.take() {
return Some(work);
}
self.wake.wait(&mut state);
match state.cursor_wait() {
Some(left) => {
self.wake.wait_for(&mut state, left);
}
None => self.wake.wait(&mut state),
}
}
}
}
@@ -270,6 +352,19 @@ pub(crate) fn start(window: Arc<Window>) {
/// the window's release to the UI thread.
fn run(window: &Window) {
let surface = window.surface();
if !surface.opened_within(told::OPEN_WAIT) {
// SDL's opening waits, with no bound of its own, for the window system to show the window
// (on X11, `X11_ShowWindow` for the window manager to map it): the host is told, rather
// than a start that says nothing (the module doc, "An opening that does not return").
log::warn!(
target: "reims_vgpu_window",
"window {:?} has not opened in {} s: the window system has not shown it (on X11 under \
KWin, not while every screen is off), and SDL's opening still waits for it",
window.title(),
told::OPEN_WAIT.as_secs()
);
told::not_opened(window.port());
}
let mut presenting = Presenting::new(window.port());
let mut retry = None;
while let Some(work) = surface.next(retry.take()) {
@@ -283,7 +378,10 @@ fn run(window: &Window) {
let Some(sink) = window.sink() else {
continue;
};
presenting.make(|| sink.presenter(&work.target));
presenting.make(
|| sink.presenter(&work.target),
|| work.target.compositor_device(),
);
}
let cursor = window.drawn_cursor();
let overlay = surface.overlay();
@@ -466,7 +564,7 @@ mod tests {
let work = surface.next(None).unwrap();
let scales = Arc::new(Mutex::new(Vec::new()));
let mut presenting = Presenting::default();
presenting.make(|| Some(Box::new(Told(Arc::clone(&scales)))));
presenting.make(|| Some(Box::new(Told(Arc::clone(&scales)))), || None);
draw(&mut presenting, &work.layout, None, None);
assert_eq!(*scales.lock(), [told], "{density} pixels a unit");
}
@@ -499,6 +597,59 @@ mod tests {
assert!(surface.overlay().is_none() && !surface.tell_unshown());
}
/// The guest's cursor moved on its own several times inside one refresh of the window's
/// screen (60 Hz, where the window is told no other rate), where the window draws it: one
/// draw, at the last place, not one a move. A run whose moves took more than half a
/// refresh (a loaded host) is tried again
#[test]
fn guest_cursor_moves_inside_one_refresh_are_drawn_once() {
const MOVES: u16 = 8;
for _ in 0..5 {
let window = Window::new(
crate::config::WindowConfig::default(),
0,
crate::handle::title(0),
);
window.cursor_glyph(1, 1, (0, 0), &[255; 4]);
window.guest_mode(64, 32);
window.cursor_show(true);
window.cursor_at((1, 1));
window.cursor_at((2, 1));
assert!(
window.drawn_cursor().is_some(),
"the guest leads its cursor"
);
let surface = window.surface();
surface.set_target(a_target());
surface.set_layout(a_layout());
surface.set_visible(true);
assert!(surface.state.lock().take().is_some(), "the first draw");
let start = super::super::now();
let mut draws = 0;
for x in 0..MOVES {
window.cursor_at((10 + x, 1));
draws += usize::from(surface.state.lock().take().is_some());
}
let took = super::super::now().saturating_duration_since(start);
std::thread::sleep(Duration::from_millis(40));
draws += usize::from(surface.state.lock().take().is_some());
if took > Duration::from_millis(8) {
window.close();
continue;
}
assert_eq!(draws, 1, "{MOVES} moves inside one refresh");
assert_eq!(
window.drawn_cursor().map(|c| c.at),
Some((10 + MOVES - 1, 1)),
"drawn at the last place"
);
assert!(surface.state.lock().take().is_none(), "nothing more");
window.close();
return;
}
panic!("every run's moves took more than half a refresh");
}
/// A draw that had no image in time is not made again while the window is hidden: it is
/// made once the window shows
#[test]
@@ -322,6 +322,35 @@ pub(crate) fn resized(shell: &mut Shell, size: (i32, i32)) -> bool {
!shell.follows_guest && fit_offered(shell, size, was)
}
/// The host screen `shell`'s window is on, as SDL places it (`SDL_GetDisplayForWindow`): for a
/// borderless window, the screen the compositor shows it full screen on, with its DRM connector's
/// rates on Linux (`with_connector_rates`, Linux only). `None` where SDL names none or gives it no
/// current mode.
pub(crate) fn filled_screen(shell: &Shell) -> Option<screens::HostScreen> {
// SAFETY: the window is SDL's, on this thread.
let display = unsafe { SDL_GetDisplayForWindow(shell.sdl) };
if display.0 == 0 {
return None;
}
let screen = super::ui::host_screen(display)?;
#[cfg(target_os = "linux")]
let screen = with_connector_rates(screen);
Some(screen)
}
/// `screen`, where SDL lists no rate of it but its own, as on Wayland, with the rates its DRM
/// connector lists at its size, where one connector is plainly its
/// (`super::super::linux::connector_rates`); else `screen` as SDL lists it.
#[cfg(target_os = "linux")]
fn with_connector_rates(mut screen: screens::HostScreen) -> screens::HostScreen {
if screen.rates_hz.len() <= 1
&& let Some(rates) = super::super::connector_rates(screen.pixels, screen.refresh_hz)
{
screen.rates_hz = rates;
}
screen
}
/// After the person's resize to `size` from position `was` (SDL's sizes), makes the window the
/// next smaller size whose pixels the guest is offered whole (`units::offered_size`): the image
/// then fills the window, where a size between two leaves up to 15 columns and a row of black
@@ -480,9 +480,13 @@ fn list_screens() -> Vec<HostScreen> {
screens.into_iter().map(|(_, _, s)| s).collect()
}
/// Screen `id`'s size in pixels, scale and refresh rate (its current mode's,
/// `crate::screens::screen_refresh`), or `None` where SDL gives no current mode.
fn host_screen(id: SDL_DisplayID) -> Option<HostScreen> {
/// Screen `id`'s size in pixels, scale, refresh rate (its current mode's,
/// `crate::screens::screen_refresh`) and the rates of its modes of that size
/// (`crate::screens::screen_rates`), or `None` where SDL gives no current mode. On Wayland SDL
/// lists its modes at the current rate alone (SDL 3.4.18's `handle_wl_output_mode` keeps only the
/// current mode's rate, and its full-screen modes are sizes at the desktop's rate; read from its
/// code), so a screen there lists no rate but its own.
pub(crate) fn host_screen(id: SDL_DisplayID) -> Option<HostScreen> {
// SAFETY: SDL's video runs on this thread; the mode is SDL's, valid until the display
// changes, and read at once.
let mode = unsafe { SDL_GetCurrentDisplayMode(id).as_ref() }?;
@@ -516,8 +520,9 @@ fn host_screen(id: SDL_DisplayID) -> Option<HostScreen> {
refresh_hz: crate::screens::screen_refresh(
pixels,
f64::from(mode.refresh_rate),
fullscreen,
fullscreen.iter().copied(),
),
rates_hz: crate::screens::screen_rates(pixels, fullscreen),
})
}
+136
View File
@@ -0,0 +1,136 @@
//! The pace of a window's draws for the guest's cursor alone ([`CursorPace`]).
//!
//! Where the window draws the guest's cursor (`handle`'s module doc, "Who moves the guest's
//! cursor"), each change of it (a move, a glyph, a show or a hide) asks the render thread for a
//! draw of the whole image. Such a draw comes at most once a refresh of the window's screen: one
//! asked within a refresh of the last draw, of any kind, waits for the refresh to pass, and every
//! change asked meanwhile folds into it, which draws the cursor where the guest last put it
//! (`Window::drawn_cursor`, read at the draw). A draw of anything else (a frame, a layout, the
//! window showing again) is made at once, as before, and draws the cursor where it is then, so a
//! change asked before it needs no draw of its own. The trade: the guest's cursor shows at most
//! a refresh later than the guest put it, against a whole draw a move, which the swapchain does
//! not pace where it presents MAILBOX (`reims_vgpu_vulkan::swapchain`), and no screen shows more
//! than one of a refresh. Measured on Linux with an x86-64 macOS 26.7.2 guest, a scripted drag of
//! 1620 moves at 125 a second, before this pace: 1620 draws more than the guest presented, 78 to
//! 145 ms of GPU a second on a Radeon 780M (RADV) and an Iris Xe (ANV).
//!
//! The refresh is the window's screen's ([`Window::screen_refresh`](crate::handle::Window)): the
//! screen a borderless window fills, else the one the display was told at its make, else 60 Hz.
//! The window's own pointer moves draw nothing of the cursor: over the image the host's cursor
//! shows the guest's glyph, and the guest follows it.
use std::time::Duration;
use reims_vgpu_vulkan::core::platform::os::MonoTime;
/// A refresh of a screen whose rate the window was not told: 60 Hz.
pub(crate) const DEFAULT_REFRESH: Duration = Duration::from_nanos(16_666_667);
/// A refresh of a screen running at `hz`: [`DEFAULT_REFRESH`] for a rate that is not a number
/// from 1 to 1000 Hz.
pub(crate) fn refresh_of(hz: f64) -> Duration {
if hz.is_finite() && (1.0..=1000.0).contains(&hz) {
Duration::from_secs_f64(1.0 / hz)
} else {
DEFAULT_REFRESH
}
}
/// The cursor's draws a render thread owes: whether one is asked, and when the window last drew.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(crate) struct CursorPace {
/// A change of the guest's cursor asked for a draw, which no draw made since.
asked: bool,
/// When the window last drew, of any kind.
drawn: Option<MonoTime>,
}
impl CursorPace {
/// A change of the guest's cursor asks for a draw.
pub(crate) fn ask(&mut self) {
self.asked = true;
}
/// The window drew at `at`, the cursor where the guest last put it: no draw is owed.
pub(crate) fn drawn(&mut self, at: MonoTime) {
self.asked = false;
self.drawn = Some(at);
}
/// When the draw asked for is due, a `refresh` after the last draw (at once where the
/// window has not drawn); `None` where none is asked.
pub(crate) fn due(&self, refresh: Duration) -> Option<MonoTime> {
self.asked.then(|| {
self.drawn
.map_or(MonoTime::from_nanos(0), |at| at.saturating_add(refresh))
})
}
/// Whether the draw asked for is due at `now`.
pub(crate) fn is_due(&self, now: MonoTime, refresh: Duration) -> bool {
self.due(refresh).is_some_and(|due| due <= now)
}
/// How long from `now` until the draw asked for is due, where one is asked and is not due
/// yet.
pub(crate) fn wait(&self, now: MonoTime, refresh: Duration) -> Option<Duration> {
let due = self.due(refresh)?;
(due > now).then(|| due.saturating_duration_since(now))
}
}
#[cfg(test)]
mod tests {
use super::*;
fn ms(n: u64) -> MonoTime {
MonoTime::from_nanos(n * 1_000_000)
}
/// Changes asked inside a refresh of the last draw wait for it to pass and are drawn once;
/// one asked a refresh or more after is due at once; a draw of any kind takes what was asked
#[test]
fn the_cursor_is_drawn_at_most_once_a_refresh() {
let refresh = Duration::from_millis(16);
let mut pace = CursorPace::default();
assert_eq!(pace.due(refresh), None, "nothing asked");
pace.ask();
assert!(pace.is_due(ms(5), refresh), "never drawn: at once");
pace.drawn(ms(100));
for at in [101, 105, 115] {
pace.ask();
assert!(!pace.is_due(ms(at), refresh), "inside the refresh");
assert_eq!(
pace.wait(ms(at), refresh),
Some(Duration::from_millis(116 - at))
);
}
assert!(pace.is_due(ms(116), refresh), "the refresh passed");
assert_eq!(pace.wait(ms(116), refresh), None);
pace.drawn(ms(116));
assert_eq!(pace.due(refresh), None, "one draw for every change");
pace.drawn(ms(140));
pace.ask();
assert!(
!pace.is_due(ms(150), refresh),
"a frame's draw starts a refresh"
);
pace.drawn(ms(151));
assert_eq!(pace.due(refresh), None, "and takes the change with it");
pace.ask();
assert!(
pace.is_due(ms(400), refresh),
"long after the last draw: at once"
);
}
/// A screen's rate gives its refresh; a rate that is no number from 1 to 1000 Hz gives 60 Hz
#[test]
fn a_screen_s_rate_gives_its_refresh() {
assert_eq!(refresh_of(120.0), Duration::from_secs_f64(1.0 / 120.0));
assert_eq!(refresh_of(59.94), Duration::from_secs_f64(1.0 / 59.94));
for hz in [0.0, -60.0, 0.5, 2000.0, f64::NAN, f64::INFINITY] {
assert_eq!(refresh_of(hz), DEFAULT_REFRESH, "{hz}");
}
}
}
+31 -15
View File
@@ -91,10 +91,12 @@ pub trait FrameSink: Send + Sync {
/// or this host has no swapchain): the window then stays empty.
fn presenter(&self, target: &dyn VulkanTarget) -> Option<Box<dyn Presenter>>;
/// Whether the GPU the sink presents from presents to windows of `system`, a window system of
/// the host's session, asked before any window opens (on Linux, which window system a window
/// opens through: `crate::winsys`). `None` where the sink has no GPU to ask.
fn presents_to(&self, system: WindowSystem) -> Option<bool> {
/// Whether the GPU the sink presents from presents to `system`'s window, a window of a window
/// system of the host's session made for the question, asked before any display's window
/// opens (on Linux, which window system a window opens through: `crate::winsys`): what the
/// sink's swapchain asks of a window's surface, asked of a surface of that window. Why not
/// where it does not; `None` where the sink has no GPU to ask.
fn presents_to(&self, system: WindowSystem) -> Option<Result<(), String>> {
let _ = system;
None
}
@@ -163,10 +165,18 @@ impl Presenting {
}
/// Makes the presenter with `make`, the sink's: where it makes none, the window stays as it
/// is.
pub(crate) fn make(&mut self, make: impl FnOnce() -> Option<Box<dyn Presenter>>) {
/// is, and the host is told so with the GPU the desktop is drawn on where `desktop`, the
/// window's target's, names it ([`VulkanTarget::compositor_device`], `crate::told`).
pub(crate) fn make(
&mut self,
make: impl FnOnce() -> Option<Box<dyn Presenter>>,
desktop: impl FnOnce() -> Option<(u32, u32)>,
) {
self.presenter = make();
if self.presenter.is_none() {
if let Some(node) = desktop() {
told::desktop_is_on(node);
}
self.end("the GPU makes no swapchain for it");
}
}
@@ -344,13 +354,16 @@ mod tests {
fn presenting_makes_keeps_and_renews_the_presenter() {
let mut p = Presenting::default();
assert!(p.needs_presenter());
p.make(|| scripted(&[Drawn::Retry, Drawn::Presented, Drawn::Ended]));
p.make(
|| scripted(&[Drawn::Retry, Drawn::Presented, Drawn::Ended]),
|| None,
);
assert!(!p.needs_presenter());
assert!(p.draw((4, 4), 1.0, REGION, None, None), "no image: a retry");
assert!(!p.draw((4, 4), 1.0, REGION, None, None));
assert!(!p.draw((4, 4), 1.0, REGION, None, None));
assert!(p.needs_presenter(), "an ended presenter is made again");
p.make(|| None);
p.make(|| None, || None);
assert!(
!p.needs_presenter(),
"no presenter: the window stays as it is"
@@ -371,7 +384,7 @@ mod tests {
draws: Arc::clone(&draws),
dropped: Arc::clone(&dropped),
};
p.make(|| Some(Box::new(losing)));
p.make(|| Some(Box::new(losing)), || None);
assert!(!p.draw((4, 4), 1.0, REGION, None, None), "no retry");
for _ in 0..100 {
assert!(!p.needs_presenter(), "none made again");
@@ -393,7 +406,10 @@ mod tests {
#[test]
fn the_host_is_told_once_whether_the_window_shows() {
let mut p = Presenting::new(1);
p.make(|| scripted(&[Drawn::Retry, Drawn::Nothing, Drawn::Presented]));
p.make(
|| scripted(&[Drawn::Retry, Drawn::Nothing, Drawn::Presented]),
|| None,
);
p.draw((4, 4), 1.0, REGION, None, None);
p.draw((4, 4), 1.0, REGION, None, None);
assert_eq!(p.told, None, "nothing presented yet");
@@ -401,7 +417,7 @@ mod tests {
assert_eq!(p.told, Some(Told::Shown));
assert!(p.shown());
for _ in 0..=RENEWALS {
p.make(|| scripted(&[Drawn::Ended]));
p.make(|| scripted(&[Drawn::Ended]), || None);
p.draw((4, 4), 1.0, REGION, None, None);
}
assert!(p.ended);
@@ -412,18 +428,18 @@ mod tests {
);
let mut p = Presenting::new(0);
p.make(|| None);
p.make(|| None, || None);
assert_eq!(p.told, Some(Told::Empty), "no swapchain");
let mut p = Presenting::new(0);
for _ in 0..=RENEWALS {
p.make(|| scripted(&[Drawn::Ended]));
p.make(|| scripted(&[Drawn::Ended]), || None);
p.draw((4, 4), 1.0, REGION, None, None);
}
assert_eq!(p.told, Some(Told::Empty), "presenters that end in a row");
let mut p = Presenting::new(0);
p.make(|| scripted(&[Drawn::Lost]));
p.make(|| scripted(&[Drawn::Lost]), || None);
p.draw((4, 4), 1.0, REGION, None, None);
assert_eq!(p.told, Some(Told::Empty), "a lost device");
}
@@ -434,7 +450,7 @@ mod tests {
let mut p = Presenting::default();
for _ in 0..=RENEWALS {
assert!(p.needs_presenter());
p.make(|| scripted(&[Drawn::Ended]));
p.make(|| scripted(&[Drawn::Ended]), || None);
p.draw((4, 4), 1.0, REGION, None, None);
}
assert!(!p.needs_presenter());
+59 -3
View File
@@ -7,7 +7,10 @@
//!
//! A screen's refresh rate is the one it runs at ([`screen_refresh`]): its current mode's, so a
//! screen the person set below its highest rate gives the guest the rate it was set to, as the
//! guest's modes run at the host screen's rate, never raised or lowered for frames.
//! guest's modes run at the host screen's rate, never raised or lowered for frames. A screen also
//! lists the rates its modes of its current size run at ([`screen_rates`]), which the display of a
//! borderless window filling it offers its guest below the screen's own
//! (`crate::handle::Window::filled_screen`).
use crate::env;
use crate::native;
@@ -16,7 +19,7 @@ use crate::native;
const DEFAULT_REFRESH_HZ: f64 = 60.0;
/// A host screen.
#[derive(Clone, Copy, Debug, PartialEq)]
#[derive(Clone, Debug, PartialEq)]
pub struct HostScreen {
/// Its display ID: CoreGraphics' on macOS, SDL's on Linux and Windows.
pub id: u32,
@@ -26,6 +29,9 @@ pub struct HostScreen {
pub scale: f64,
/// The refresh rate it runs at, in Hz ([`screen_refresh`]).
pub refresh_hz: f64,
/// The refresh rates of its modes of its current size, in Hz, its own among them
/// ([`screen_rates`]); empty where the OS lists none.
pub rates_hz: Vec<f64>,
}
/// The host's screens, the main one first. Empty where the OS lists none.
@@ -74,12 +80,30 @@ pub(crate) fn screen_refresh(
}
}
/// The refresh rates, in Hz, of the modes of `pixels` among `modes`, each mode's pixels and rate
/// as the OS lists them: the rates a screen whose current mode is `pixels` runs at that size,
/// each once, highest first. A rate of 0, or one that is not a number, is unknown and left out;
/// so is a mode of other pixels, whose rate the screen does not run at its current size (a 4K
/// screen listing 1920×1080 at 120 Hz runs 4K at 60).
pub(crate) fn screen_rates(
pixels: (u32, u32),
modes: impl IntoIterator<Item = ((u32, u32), f64)>,
) -> Vec<f64> {
let mut rates: Vec<f64> = modes
.into_iter()
.filter_map(|(size, hz)| (size == pixels && hz.is_finite() && hz > 0.0).then_some(hz))
.collect();
rates.sort_by(|a, b| b.total_cmp(a));
rates.dedup();
rates
}
/// The screen the window of the display on `port` opens on: the one `REIMS_VGPU_WINDOW_SCREENS`
/// names for it, else screen `port`, else the main screen. `None` where there is no screen.
pub fn screen_for_port(port: u64) -> Option<HostScreen> {
let screens = host_screens();
let index = pick_screen(port, &env::settings().screens, screens.len());
screens.get(index).copied()
screens.get(index).cloned()
}
#[cfg(test)]
@@ -143,4 +167,36 @@ mod tests {
assert_eq!(screen_refresh(UHD, f64::INFINITY, unknown), 60.0);
assert_eq!(screen_refresh(UHD, 0.0, []), 60.0);
}
/// A screen's rates are those of its modes of its current size, each once, highest first,
/// whatever order the OS lists them in; the rates of other sizes and unknown ones are not
/// among them
#[test]
fn a_screen_s_rates_are_those_of_its_size() {
const UHD: (u32, u32) = (3840, 2160);
const FHD: (u32, u32) = (1920, 1080);
// The M3 Max's ProMotion screen, as CoreGraphics lists its modes (macOS 27.0.1).
let promotion = (3456, 2234);
let modes = [60.0, 120.0, 59.94, 50.0, 48.0, 47.95].map(|hz| (promotion, hz));
assert_eq!(
screen_rates(promotion, modes),
[120.0, 60.0, 59.94, 50.0, 48.0, 47.95]
);
// A laptop panel lists 3840×2400 at 60 and 120 Hz; a mode listed twice counts once.
let panel = (3840, 2400);
assert_eq!(
screen_rates(panel, [(panel, 60.0), (panel, 120.0), (panel, 120.0)]),
[120.0, 60.0]
);
// Other sizes' rates and unknown rates are left out.
let modes = [
(UHD, 60.0),
(UHD, 0.0),
(UHD, f64::NAN),
(FHD, 144.0),
(UHD, 30.0),
];
assert_eq!(screen_rates(UHD, modes), [60.0, 30.0]);
assert!(screen_rates(UHD, []).is_empty());
}
}
+15
View File
@@ -202,6 +202,7 @@ pub(crate) fn open(window: &Arc<Window>) {
with_shell(window.id(), |shell| {
shell.relayout();
shell.held_changed();
shell.tell_filled();
});
log::info!(
target: "reims_vgpu_window",
@@ -307,6 +308,7 @@ pub(crate) fn screens_changed() {
os::screens_changed(shell);
}
shell.relayout();
shell.tell_filled();
});
}
}
@@ -399,6 +401,9 @@ impl Shell {
|| k == SDL_EVENT_WINDOW_SAFE_AREA_CHANGED.0 =>
{
self.relayout();
if k == SDL_EVENT_WINDOW_DISPLAY_CHANGED.0 {
self.tell_filled();
}
false
}
k if k == SDL_EVENT_WINDOW_MAXIMIZED.0 || k == SDL_EVENT_WINDOW_ENTER_FULLSCREEN.0 => {
@@ -475,6 +480,16 @@ impl Shell {
unsafe { SDL_SetWindowTitle(self.sdl, title.as_ptr()) };
}
/// Tells a borderless window the host screen it fills now ([`Window::filled_screen`]), as its
/// OS places it ([`os::filled_screen`]): at its opening, when it moves to another screen
/// (`SDL_EVENT_WINDOW_DISPLAY_CHANGED`) and when the screens change. A titled window is told
/// nothing, and its display offers the rate of the screen it opened on alone.
fn tell_filled(&self) {
if crate::env::settings().borderless && !self.closed {
self.window.fills(os::filled_screen(self));
}
}
/// Lays the image out again over the window's size and scale (the module doc), and tells the
/// render thread.
pub(crate) fn relayout(&mut self) {
+117 -11
View File
@@ -5,12 +5,21 @@
//! shows. On Wayland it is mapped only from then on, so a window not told so never appeared;
//! - [`NONE`], once a window, where it draws no more and presented no frame: its swapchain was
//! not made, or ended again and again, or its GPU's device was lost: the window stays empty;
//! or where its opening has not returned within [`OPEN_WAIT`] (`crate::native`'s opening
//! watch): the window system has not shown it yet, which it does once a screen is on, or, with
//! a screen on, may not do for this GPU's window ([`NOT_OPENED`]);
//! - [`NONE`], once a process, where no window opens at all because the GPU presents to no
//! window system of the host's session (`crate::winsys`).
//!
//! A line ends with the reason, in words for the person at the host.
//! A line ends with the reason, in words for the person at the host, and, where the window system
//! named the GPU the host's desktop is drawn on ([`desktop_is_on`]: on Linux under Wayland, the
//! compositor's), with [`DESKTOP`] and that GPU's DRM node, `<major>:<minor>`, which what starts
//! the VM can name the GPU by: one that can show a window there.
use std::io::Write as _;
use std::sync::OnceLock;
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::Duration;
/// How a window's line that it shows starts: `reims-vgpu: window shown: display <n>`.
pub(crate) const SHOWN: &str = "reims-vgpu: window shown: ";
@@ -18,6 +27,45 @@ pub(crate) const SHOWN: &str = "reims-vgpu: window shown: ";
/// How a line that a window shows nothing starts: `reims-vgpu: no window: <why>`.
pub(crate) const NONE: &str = "reims-vgpu: no window: ";
/// How a no-window line names the GPU the desktop is drawn on, before its DRM node's
/// `<major>:<minor>`: `...; the desktop is drawn on DRM node 226:128`.
pub(crate) const DESKTOP: &str = "; the desktop is drawn on DRM node ";
/// What a window's line says where its opening has not returned within [`OPEN_WAIT`], after the
/// display: both readings, since the library does not ask whether a screen is on. KWin shows no X
/// window while every screen is off, and SDL's opening returns once one comes on
/// (docs/lessons.md), so a blanked screen is told so as well as a GPU the window system does not
/// show.
#[cfg_attr(
all(not(any(target_os = "linux", target_os = "windows")), not(test)),
expect(dead_code, reason = "only SDL's windows are opened on the UI thread")
)]
pub(crate) const NOT_OPENED: &str = concat!(
"'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"
);
/// How long a window's opening may take before the host is told the window has not opened: SDL's
/// opening waits, with no bound of its own, for the window system to show the window (on X11, for
/// the window manager to map it).
#[cfg_attr(
not(any(target_os = "linux", target_os = "windows")),
expect(dead_code, reason = "only SDL's windows are opened on the UI thread")
)]
pub(crate) const OPEN_WAIT: Duration = Duration::from_secs(10);
/// The GPU the desktop is drawn on, as the window system named it ([`desktop_is_on`]).
static DESKTOP_NODE: OnceLock<(u32, u32)> = OnceLock::new();
/// The host was told that no window opens at all ([`none`]).
static NONE_TOLD: AtomicBool = AtomicBool::new(false);
/// The window system named the GPU the host's desktop is drawn on: DRM node `node`, its major and
/// minor numbers. The first naming is kept: the session's compositor stays on its GPU.
pub(crate) fn desktop_is_on(node: (u32, u32)) {
let _ = DESKTOP_NODE.set(node);
}
/// Display `display`'s window presented its first frame.
pub(crate) fn shown(display: u64) {
write(&shown_line(display));
@@ -25,7 +73,19 @@ pub(crate) fn shown(display: u64) {
/// Display `display`'s window stays empty, for `why`.
pub(crate) fn empty(display: u64, why: &str) {
write(&empty_line(display, why));
write(&empty_line(display, why, DESKTOP_NODE.get().copied()));
}
/// Display `display`'s window has not opened within [`OPEN_WAIT`]; nothing where the host was
/// told already that no window opens at all ([`none`]).
#[cfg_attr(
not(any(target_os = "linux", target_os = "windows")),
expect(dead_code, reason = "only SDL's windows are opened on the UI thread")
)]
pub(crate) fn not_opened(display: u64) {
if !NONE_TOLD.load(Ordering::Acquire) {
write(&not_opened_line(display, DESKTOP_NODE.get().copied()));
}
}
/// No window opens, for `why`.
@@ -34,7 +94,8 @@ pub(crate) fn empty(display: u64, why: &str) {
expect(dead_code, reason = "only SDL's UI thread chooses a window system")
)]
pub(crate) fn none(why: &str) {
write(&none_line(why));
NONE_TOLD.store(true, Ordering::Release);
write(&none_line(why, DESKTOP_NODE.get().copied()));
}
/// [`shown`]'s line.
@@ -42,14 +103,29 @@ fn shown_line(display: u64) -> String {
format!("{SHOWN}display {display}\n")
}
/// [`empty`]'s line.
fn empty_line(display: u64, why: &str) -> String {
none_line(&format!("display {display}'s window stays empty: {why}"))
/// [`empty`]'s line, naming `desktop` where it is known.
fn empty_line(display: u64, why: &str, desktop: Option<(u32, u32)>) -> String {
none_line(
&format!("display {display}'s window stays empty: {why}"),
desktop,
)
}
/// [`none`]'s line.
fn none_line(why: &str) -> String {
format!("{NONE}{why}\n")
/// [`not_opened`]'s line, naming `desktop` where it is known.
#[cfg_attr(
all(not(any(target_os = "linux", target_os = "windows")), not(test)),
expect(dead_code, reason = "only SDL's windows are opened on the UI thread")
)]
fn not_opened_line(display: u64, desktop: Option<(u32, u32)>) -> String {
none_line(&format!("display {display}{NOT_OPENED}"), desktop)
}
/// [`none`]'s line, naming `desktop` where it is known.
fn none_line(why: &str, desktop: Option<(u32, u32)>) -> String {
match desktop {
Some((major, minor)) => format!("{NONE}{why}{DESKTOP}{major}:{minor}\n"),
None => format!("{NONE}{why}\n"),
}
}
/// Writes `line` on stderr in one write, so it never interleaves with another thread's.
@@ -67,10 +143,40 @@ mod tests {
fn the_window_s_lines_start_as_the_host_reads_them() {
assert_eq!(shown_line(0), "reims-vgpu: window shown: display 0\n");
assert_eq!(
empty_line(1, "the GPU makes no swapchain for it"),
empty_line(1, "the GPU makes no swapchain for it", None),
"reims-vgpu: no window: display 1's window stays empty: the GPU makes no swapchain \
for it\n"
);
assert_eq!(none_line("why"), "reims-vgpu: no window: why\n");
assert_eq!(none_line("why", None), "reims-vgpu: no window: why\n");
}
/// Where the window system named the GPU the desktop is drawn on, every no-window line ends
/// with its DRM node, as reims-ctl reads it to name that GPU; a window whose opening has not
/// returned in time says so
#[test]
fn a_no_window_line_names_the_desktop_s_gpu_where_it_is_known() {
let intel = Some((226, 128));
assert_eq!(
none_line("this GPU cannot show a window on this desktop", intel),
"reims-vgpu: no window: this GPU cannot show a window on this desktop; the desktop \
is drawn on DRM node 226:128\n"
);
assert_eq!(
empty_line(0, "the GPU makes no swapchain for it", intel),
"reims-vgpu: no window: display 0's window stays empty: the GPU makes no swapchain \
for it; the desktop is drawn on DRM node 226:128\n"
);
assert_eq!(
not_opened_line(0, intel),
"reims-vgpu: no window: 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; the desktop is drawn on DRM node 226:128\n"
);
assert_eq!(
not_opened_line(2, None),
"reims-vgpu: no window: display 2'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\n"
);
}
}
+15 -12
View File
@@ -5,16 +5,19 @@
//! A host's session can have two window systems: a Wayland compositor and an X server, which
//! under a Wayland compositor is its XWayland. A GPU's Vulkan driver need not present to both: a
//! laptop's discrete GPU beside the integrated GPU its compositor runs on can present to X11 and
//! not to Wayland (an RTX 4060 Laptop GPU under KWin, NVIDIA 620.70.06, a user's report: its
//! Wayland surface was not presented to, while its XCB and Xlib surfaces were). A window opened
//! through a window system its GPU does not present to gets no swapchain, and on Wayland, which
//! maps a window only once a frame is presented to it, never appears, its entry in the task bar
//! alone showing it. So before SDL's video starts, the GPU of the first window's sink is asked,
//! with no window, whether it presents to the session's window systems
//! ([`FrameSink::presents_to`](crate::FrameSink::presents_to): Vulkan's per-platform
//! presentation-support questions), over a connection of the asker's own to each
//! (`native/linux/winsys.rs`): the Wayland compositor first, and the X server only where it does
//! not present to the compositor, as an X server under a Wayland compositor can be started by the
//! not to Wayland (an RTX 4060 Laptop GPU under KWin, NVIDIA 620.70.06 and 620.73.04, a user's
//! reports: its Wayland surface was not presented to, while its XCB and Xlib surfaces were). A
//! window opened through a window system its GPU does not present to gets no swapchain, and on
//! Wayland, which maps a window only once a frame is presented to it, never appears, its entry in
//! the task bar alone showing it. So once, before SDL's video starts, the GPU of the first
//! window's sink is asked whether it presents to a window of each of the session's window
//! systems ([`FrameSink::presents_to`](crate::FrameSink::presents_to)): a window made for the
//! question and never shown, over a connection of the asker's own to each, both destroyed after
//! it (`native/linux/winsys.rs`), of which the sink makes a Vulkan surface and asks what its
//! swapchain asks of a window's surface. Vulkan's per-platform question, which names no window,
//! is not asked: that GPU answered it yes for Wayland, and its window stayed empty. The Wayland
//! compositor is asked first, and the X server only where the GPU does not present to the
//! compositor's window, as an X server under a Wayland compositor can be started by the
//! connection (XWayland on demand). SDL then picks, or is named the window system to open through:
//!
//! | Wayland | X11 | the windows open through |
@@ -36,8 +39,8 @@
use std::ffi::CStr;
/// What the GPU a window presents from answered for each window system of the host's session:
/// whether its queue family presents to its windows, `None` where the session has none to connect
/// to (no Wayland compositor, no X server).
/// whether its queue family presents to a window of it, `None` where the session has none to
/// connect to (no Wayland compositor, no X server).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Answers {
/// The Wayland compositor's answer.
+99 -39
View File
@@ -13,8 +13,9 @@
//! its render thread last drew into it, its width rounded down to a multiple of 16 and its height
//! to even, so each row of a guest surface of the mode's width starts and ends on a 64-byte line of
//! the GPU's memory (`geometry::offered_mode`; a window of other pixels shows the guest's mode
//! unscaled, beside up to 15 columns and a row of black), then the smaller modes of its ratio
//! (`reims-vgpu-graphics`' `display::offered_modes`), which the window shows scaled to fill it,
//! unscaled, beside up to 15 columns and a row of black), then the smaller modes of its ratio and,
//! on a screen above 1x, one larger one (`reims-vgpu-graphics`' `display::offered_modes`), which
//! the window shows scaled to fill it,
//! keeping its size (`sink`, "Sizes"), every one at the refresh rate of the host screen it opened
//! on; when that size changes (the person resized the window) the device tells the guest
//! (`DISPLAY_CHANGED`). The guest's scanout shows in the window at once and then again at each of
@@ -82,7 +83,7 @@ use reims_vgpu_graphics::wire::{
RGFX_EVT_SHARED_TEXTURE, RGFX_FEATURE_BUFFER_ESCAPED, RGFX_FEATURE_CB_SUBMITTED,
RGFX_FEATURE_COMMIT_ORDER, RGFX_FEATURE_CURSOR_COLOR, RGFX_FEATURE_DISPLAY_COLOR,
RGFX_FEATURE_DISPLAY_POWER, RGFX_FEATURE_DISPLAY_SCALE, RGFX_FEATURE_DOORBELL_ASKS,
RGFX_FEATURE_DOORBELL_PAGES, RGFX_FEATURE_DYNAMIC_LIBRARIES,
RGFX_FEATURE_DOORBELL_PAGES, RGFX_FEATURE_DYNAMIC_LIBRARIES, RGFX_FEATURE_EXT_DISPLAY_RATE,
RGFX_FEATURE_EXT_SHARED_TEXTURE_NAMES, RGFX_FEATURE_EXT_SURFACE_HOLD,
RGFX_FEATURE_FUNCTION_POINTERS, RGFX_FEATURE_GUEST_TIMES, RGFX_FEATURE_HEAP_OVER_PAGES,
RGFX_FEATURE_HOST_TIME, RGFX_FEATURE_ICB_SLOTS, RGFX_FEATURE_ICB_SLOTS_IN_PAGES,
@@ -393,6 +394,11 @@ pub struct GraphicsConfig {
/// without one, [`Error::InvalidArgument`] where it holds another count of modes than the
/// device has displays.
pub headless_modes: Option<Vec<(u16, u16)>>,
/// For the tests: the refresh rate of each display where the device has no window, in
/// thousandths of a hertz, in place of the headless modes' 60 Hz; `None` is 60 Hz. Each
/// display's refresh thread paces its refreshes by it from its start.
#[cfg(test)]
pub(crate) headless_refresh_mhz: Option<u32>,
}
/// The architecture of the macOS guest a graphics device serves ([`GraphicsConfig::guest_arch`]).
@@ -610,22 +616,20 @@ fn pool_source<P: ApiPlatform>(
}
/// Why the device offers the guest no Shared pool, of a device whose host gave it addresses for
/// one (`given`, [`GraphicsConfig::pool`]), whose GPU's memory heaps took a range of them
/// (`ranged`, [`pool_range`]) and which offers it (`offered`, `POOL`); `None` where it offers one.
/// The device writes it once, at its start, at warn: without the pool it offers no `POOL`, and
/// so no `SURFACE_CACHE_EVERY` ([`cache_every`]) and no `MANAGED_AT_COPY` ([`managed_at_copy`]).
/// QEMU gives no addresses on a machine that is neither a PC machine (an x86 target whose PCI
/// host answers `pci-hole64-end`) nor vmapple, on a vmapple machine whose room is 0, and on a PC
/// machine where no whole GiB of addresses lies from the end of the PCI host's 64-bit window to
/// the top quarter of the guest's physical addresses (under KVM and WHPX, to the host's at most)
/// (`reims_graphics_pool_room` and `reims_graphics_pool_room_machine` in
/// `hw/display/reims-graphics-pci.c`); a Windows host offers the pool to an x86-64 guest alone.
fn no_pool(given: bool, ranged: bool, offered: bool) -> Option<&'static str> {
match (given, ranged, offered) {
(_, _, true) => None,
(false, _, false) => Some("the host gave the device no guest addresses for one"),
(true, false, false) => Some("the GPU answers no memory heap"),
(true, true, false) => Some("a Windows host offers one to an x86-64 guest alone"),
/// one (`given`, [`GraphicsConfig::pool`]) and whose GPU's memory heaps took a range of them
/// (`ranged`, [`pool_range`]); `None` where it offers one. The device writes it once, at its
/// start, at warn: without the pool it offers no `POOL`, and so no `SURFACE_CACHE_EVERY`
/// ([`cache_every`]) and no `MANAGED_AT_COPY` ([`managed_at_copy`]). QEMU gives no addresses on a
/// machine that is neither a PC machine (an x86 target whose PCI host answers `pci-hole64-end`)
/// nor vmapple, on a vmapple machine whose room is 0, and on a PC machine where no whole GiB of
/// addresses lies from the end of the PCI host's 64-bit window to the top quarter of the guest's
/// physical addresses (under KVM and WHPX, to the host's at most) (`reims_graphics_pool_room` and
/// `reims_graphics_pool_room_machine` in `hw/display/reims-graphics-pci.c`).
fn no_pool(given: bool, ranged: bool) -> Option<&'static str> {
match (given, ranged) {
(_, true) => None,
(false, false) => Some("the host gave the device no guest addresses for one"),
(true, false) => Some("the GPU answers no memory heap"),
}
}
@@ -817,18 +821,12 @@ impl<P: ApiPlatform> GraphicsDevice<P> {
// The guest's processes take blocks of it for their buffers' slabs (`POOL`). An
// arm64 guest's processes use the blocks write-back, as an x86-64 guest's do: arm64
// boots under TCG and HVF ran on them with no fault (docs/graphics-kext/design.md,
// "The Shared pool"). A Windows host offers it to an x86-64 guest alone, whose cost
// under WHP was measured beside the region's (docs/qemu.md, "Windows hosts: the
// Shared pool"): an arm64 guest runs under TCG there, where it was not measured.
let pool_ledger = (shared_pool.as_ref())
.filter(|_| !cfg!(windows) || config.guest_arch == GuestArch::X86_64)
.map(Pool::ledger);
// "The Shared pool"), and on Windows `vmapple` TCG maps each pool block through
// `memory_region_init_ram_device_ptr` and `memory_region_add_subregion` as Linux TCG
// does (`reims_graphics_pool_add` in `hw/display/reims-graphics-pci.c`).
let pool_ledger = shared_pool.as_ref().map(Pool::ledger);
// The one line of a device with no pool, whatever kept it from one.
if let Some(why) = no_pool(
config.pool.is_some(),
shared_pool.is_some(),
pool_ledger.is_some(),
) {
if let Some(why) = no_pool(config.pool.is_some(), shared_pool.is_some()) {
log::warn!(
"pool: the guest has no Shared pool: {why}; the device offers no POOL, \
SURFACE_CACHE_EVERY or MANAGED_AT_COPY"
@@ -1282,8 +1280,11 @@ impl<P: ApiPlatform> GraphicsDevice<P> {
// A host whose GPU's memory is its own may make an image in place over guest pages it
// imports by their pointer by copying the bytes out and back, so it offers the hold
// that orders a guest's CPU writes around such a make (`SURFACE_HOLD`,
// `decode::surface_cache`'s `shapes`, "The hold"), where it maps the pages at all.
// `decode::surface_cache`'s `shapes`, "The hold"), where it maps the pages at all. Every
// host offers a display's other rates and paces it at the one the guest sets
// (`DISPLAY_RATE`).
let features_ext = RGFX_FEATURE_EXT_SHARED_TEXTURE_NAMES
| RGFX_FEATURE_EXT_DISPLAY_RATE
| if unified_memory && decoder.surface_pages_available() {
RGFX_FEATURE_EXT_SURFACE_HOLD
} else {
@@ -1310,6 +1311,16 @@ impl<P: ApiPlatform> GraphicsDevice<P> {
})
})
.collect();
#[cfg(test)]
let headless: Vec<Mode> = match config.headless_refresh_mhz {
Some(refresh_mhz) => (headless.into_iter())
.map(|mode| Mode {
refresh_mhz,
..mode
})
.collect(),
None => headless,
};
let window_configs: Vec<Option<WindowConfig>> = match config.window {
Some(first) => std::iter::once(first)
.chain(config.display_windows)
@@ -2789,8 +2800,14 @@ impl<P: ApiPlatform> GraphicsControl<P> {
/// the decoder has begun has finished, every one it began for another holder's context
/// before its `BLOCK_UNSHARE`, its close, or the release where neither came first, which the
/// device hands on as an unshare ([`Self::unshare_block`]), and once the display no longer
/// shows or draws a surface's texture over the block ([`DisplayHold`]). A command buffer
/// posted on a ring and not yet begun is not waited for.
/// shows or draws a surface's texture over the block ([`DisplayHold`]). Every answer also
/// waits for every command buffer the context's queues' rings published before the release,
/// begun or not, to be committed, stood in for or failed, or its queue to end, and then for it
/// to finish as above ([`GraphicsDecoder::drain_context_after_published`]). Each waits too for
/// the host to let go of what it does not keep of the block's view: a pages block's import,
/// which the platform that knows it as a block forgets before the answer whether the cache
/// keeps the view or not, so no pin resolves in it once the kext gives the pages back
/// ([`GraphicsDecoder::block_released_keeping`]).
fn release_block(&self, release: &RgfxBlockRelease, answer: CompleteAnswer) {
// Its waits' ends, for a slow answer's line (`slow_answers`).
let marks = Arc::new(ReleaseMarks::asked());
@@ -2845,16 +2862,25 @@ impl<P: ApiPlatform> GraphicsControl<P> {
m.drained();
answer();
});
let drain = decoder.drain_context(release.context, false, answer);
// After the command buffers its context's rings published before the release, begun or
// not: one of them may write the block's pages through an object its process destroyed
// before the release, a pages block's buffer by its GPU address or a texture over a
// surface's shape in place over its pages by its resource index, and the kext unwires
// the pages at the answer.
let drain = decoder.drain_context_after_published(release.context, answer);
// No buffer lies over the block's surface view any more: it goes with the block, and its
// device cache once the surface's pages hold what was written of it, which the answer
// waits for. The copy is made once the buffers still walked that may write the cache
// have finished, on the last one's thread: the context's lane goes on.
let held = Arc::clone(&drain);
// And once its view is let go of: a pages block's goes with its import, which the
// platform that knows it as a block forgets, so nothing of the host's names the pages
// the kext unwires at the answer.
let viewed = Box::new(Arc::clone(&drain));
let (flags, offset) = (release.flags, release.offset);
let m = Arc::clone(&marks);
entry::run(|_| {
decoder.block_released(
decoder.block_released_keeping(
&self.device,
offset,
flags,
@@ -2870,6 +2896,7 @@ impl<P: ApiPlatform> GraphicsControl<P> {
write back ({raise:?})"
);
}),
viewed,
);
});
marks.released();
@@ -5352,6 +5379,10 @@ impl paravirt::Link for GuestLink {
fn count(&self, code: &'static str) {
reims_vgpu_vulkan::answer::count_kind(code);
}
fn trace(&self, kind: &'static str, values: &[u64]) {
reims_vgpu_vulkan::core::trace::event(kind, values);
}
}
/// The lends of the guest's surfaces that `VT_MESSAGE`s gave the host, counted in the degradation
@@ -5695,7 +5726,9 @@ pub(crate) struct WindowScreen {
shown: Arc<Shown>,
/// Whether it shows a presented surface in place of the scanout ([`Presented`]).
shows_surface: Box<dyn Fn() -> bool + Send + Sync>,
/// The refresh rate of the host screen it opened on, in thousandths of a hertz.
/// The refresh rate of the host screen it opened on, in thousandths of a hertz: a titled
/// window's rate. A borderless window's is that of the screen it fills
/// (`Window::filled_screen`), once its OS's side has found it.
refresh_mhz: u32,
/// The guest's cursor, as last told.
cursor: Mutex<CursorState>,
@@ -5951,6 +5984,14 @@ impl Screen for SharedScreen {
self.screen.mode()
}
fn rates(&self) -> Vec<u32> {
self.screen.rates()
}
fn fixed_rate(&self) -> Option<u32> {
self.screen.fixed_rate()
}
fn scanout(&self, scanout: Option<Scanout>) {
let (offset, span) = scanout.map(|s| (s.offset, s.span())).unzip();
let (span, at) = (span.unwrap_or(0), trail::Held::at(None, offset));
@@ -6014,6 +6055,8 @@ impl WindowScreen {
reims_vgpu_window::screens::screen_for_port(port)
.map_or(FALLBACK_MODE.refresh_mhz, |s| hz_to_mhz(s.refresh_hz))
};
// The window draws the guest's cursor's changes at most once a refresh of that screen.
window.screen_refresh(refresh_mhz);
let presented = Arc::clone(presented);
let screen = WindowScreen {
window: Arc::clone(&window),
@@ -6107,8 +6150,9 @@ fn hz_to_mhz(hz: f64) -> u32 {
impl Screen for WindowScreen {
/// The window's size in pixels as last drawn into, else the mode it opened for, its width
/// rounded down to a multiple of 16 and its height to even ([`geometry::offered_mode`]), at
/// its host screen's rate, with the backing scale it was last drawn at (none before its first
/// draw): the display's first mode, which its smaller modes follow.
/// its host screen's rate (for a borderless window, the screen it fills now), with the
/// backing scale it was last drawn at (none before its first draw): the display's first
/// mode, which its smaller modes follow.
fn mode(&self) -> Mode {
let drawn = *self.shown.drawable.lock();
let (width, height) = geometry::offered_mode(drawn.map_or_else(
@@ -6119,14 +6163,30 @@ impl Screen for WindowScreen {
|d| d.pixels,
));
let clamp = |v: u64| u32::try_from(v.max(1)).unwrap_or(u32::MAX);
let filled = self.window.filled_screen();
Mode {
width: clamp(width),
height: clamp(height),
refresh_mhz: self.refresh_mhz,
refresh_mhz: filled.map_or(self.refresh_mhz, |s| hz_to_mhz(s.refresh_hz)),
scale_120ths: drawn.map_or(0, |d| scale_in_120ths(d.scale)),
}
}
/// For a borderless window, the rates the screen it fills lists at its size
/// (`HostScreen::rates_hz`), which the display offers below the screen's own; none for a
/// titled window, whose display offers its screen's rate alone.
fn rates(&self) -> Vec<u32> {
self.window.filled_screen().map_or_else(Vec::new, |s| {
s.rates_hz.iter().map(|&hz| hz_to_mhz(hz)).collect()
})
}
/// The VM's refresh rate where one is set (`REIMS_VGPU_WINDOW_REFRESH_RATE`), titled or
/// borderless: the display offers every size at it alone, at most the screen's rate.
fn fixed_rate(&self) -> Option<u32> {
reims_vgpu_window::env::settings().refresh_mhz
}
/// The window takes the scanout's size as the guest's mode, and draws it.
fn scanout(&self, scanout: Option<Scanout>) {
*self.shown.scanout.lock() = scanout;
+98 -14
View File
@@ -1732,7 +1732,11 @@ impl<P: Platform> GraphicsDecoder<P> {
message: &[u8],
drain: Option<Arc<Drain>>,
) -> RaiseResult<Result<(), DecodeError>> {
let begun = match self.begin_command_buffer(device, message, drain)? {
let begun = self.begin_command_buffer(device, message, drain);
// However far its begin got, a buffer that names it waits for it no more than its
// prepared mark ([`super::commit_order::Until::Prepared`]).
self.note_prepared();
let begun = match begun? {
Ok(begun) => begun,
Err(e) => return Ok(Err(e)),
};
@@ -1847,8 +1851,10 @@ impl<P: Platform> GraphicsDecoder<P> {
}
let begun = self.begin_command_buffer(device, message, drain);
// However far its begin got, a buffer that names it waits for it no more before its own
// begin, only before its commit ([`super::commit_order`]).
// begin, only before its commit ([`super::commit_order`]); and one whose `SURFACE_ORDER`
// names it waits no more than its prepared mark ([`Until::Prepared`]).
self.note_begun();
self.note_prepared();
let begun = match begun? {
Ok(begun) => begun,
Err(e) => return Ok(Err(e)),
@@ -1932,8 +1938,8 @@ impl<P: Platform> GraphicsDecoder<P> {
}
/// Waits, with no lock held, until each buffer of another queue that `order`, the
/// `SURFACE_ORDER` of the buffer `m`, names and the host has not walked yet is committed, or
/// its queue or `m`'s ends, or the device resets
/// `SURFACE_ORDER` of the buffer `m`, names and the host has not walked yet is prepared
/// ([`Until::Prepared`]), or its queue or `m`'s ends, or the device resets
/// ([`super::surface_order::SurfaceOrder::unwalked`]; the module doc of `surface_order`, "A
/// buffer named before the host walks it"): counted, with the longest. A wait past
/// [`BEGIN_WAIT_LOGGED`] is named in the log with what it waits for, and again as it ends.
@@ -1956,7 +1962,7 @@ impl<P: Platform> GraphicsDecoder<P> {
}
named = true;
let waits: Vec<String> = (unwalked.iter())
.filter(|(_, marks, s)| !marks.commit.reached(*s, Until::Committed))
.filter(|(_, marks, s)| !marks.commit.reached(*s, Until::Prepared))
.map(|(q, marks, s)| {
let (taken, committed, _) = marks.progress();
format!(
@@ -1969,12 +1975,12 @@ impl<P: Platform> GraphicsDecoder<P> {
target: "reims_vgpu::graphics",
"surface order: queue {queue:#x}'s buffer {seqno} has waited \
{BEGIN_WAIT_LOGGED:?} at its begin for {}, which its SURFACE_ORDER names and \
the host has not committed; it waits on",
the host has not prepared (or, behind video, committed); it waits on",
waits.join(", ")
);
};
let cancel = &self.shared.commit_cancel;
let until = (Until::Committed, "surface-order-begin");
let until = (Until::Prepared, "surface-order-begin");
let waited =
super::commit_order::wait_telling(&after, own.as_deref(), cancel, until, &mut slept);
let took = clock.now_mono().saturating_duration_since(start);
@@ -2000,7 +2006,8 @@ impl<P: Platform> GraphicsDecoder<P> {
/// ahead of their ends whose outputs it uses ([`super::surface_order::SurfaceOrder::after_decodes`];
/// the module doc of `surface_order`, "A buffer named after a decode whose planes are not yet
/// said written"). With no lock held, on its queue's thread: first until each such buffer
/// its ring published is committed, so its walk has kept its decodes
/// its ring published is prepared (`Until::Prepared`), a buffer holding video work, or
/// behind it, only once committed, so its walk has kept its decodes
/// ([`super::surface_order::Marks::landing`]); then until each decode kept of it has its value
/// signalled by its session; or until the queue waited for or `m`'s ends, or the device
/// resets. Nothing times it out. Counted where it waited, with the longest; a hold past
@@ -2056,13 +2063,17 @@ impl<P: Platform> GraphicsDecoder<P> {
waits.join("; ")
);
};
// First, each buffer its ring published that is not yet committed: its walk keeps its
// decodes before its commit raises its queue's mark.
// First, each buffer its ring published that is not yet prepared: its walk keeps its
// decodes before its commit raises its queue's mark, and a buffer up to which its queue
// holds a video op uncommitted is prepared only by its commit
// ([`super::commit_order::CommitMark::prepare`]); one prepared holds no decode to keep.
let uncommitted: Vec<(Arc<Marks>, u64)> = (after.iter())
.filter(|(_, marks, s, published)| *published && !marks.commit.committed_through(*s))
.filter(|(_, marks, s, published)| {
*published && !marks.commit.reached(*s, Until::Prepared)
})
.map(|(_, marks, s, _)| (Arc::clone(marks), *s))
.collect();
let until = (Until::Committed, "surface-order-decode");
let until = (Until::Prepared, "surface-order-decode");
let waited = super::commit_order::wait_telling(
&uncommitted,
own.as_deref(),
@@ -2122,7 +2133,7 @@ impl<P: Platform> GraphicsDecoder<P> {
/// command buffer on the named queue, readies the device caches its `SURFACE_USE` ops use
/// (filling each that holds an older generation), has it wait on the GPU for the buffers of
/// other queues its `SURFACE_ORDER` names that have not finished, once those the host had
/// not walked are committed ([`Self::wait_for_unwalked`]), and makes its
/// not walked are prepared ([`Self::wait_for_unwalked`]), and makes its
/// `CB_SUBMITTED` and, where it waits for an event or a deferred copy of a cache, its hold of
/// its queue ([`Begun`]); where it gets its records at its take, they are posted before its
/// fills, its ticket in the commit order issued first
@@ -2136,6 +2147,9 @@ impl<P: Platform> GraphicsDecoder<P> {
// The op stream follows the message's fixed part; `op_bytes` must count all of it.
let parsed = read::<RgfxCommandBuffer>(message)
.and_then(|m| ops_of(message, &m).map(|ops| (m, ops, take(ops))));
// Whether its queue's prepared mark waits for its commit ([`Self::note_prepared`]).
self.walks_video
.set(parsed.as_ref().is_some_and(|(_, _, take)| take.video));
// Past a recovery of the device, its process's two-copy `Managed` textures have their GPU
// copies filled again first, before anything of the buffer reaches the platform
// ([`GraphicsDecoder::refill_managed`]).
@@ -2143,7 +2157,7 @@ impl<P: Platform> GraphicsDecoder<P> {
self.refill_managed(device, context_of(m.queue_obj_id));
}
// The buffers of other queues its `SURFACE_ORDER` names that the host has not walked yet
// are committed before it begins, before its uses count among a device cache's users and
// are prepared before it begins, before its uses count among a device cache's users and
// before it takes its ticket ([`Self::wait_for_unwalked`]).
if let Some((m, _, take)) = &parsed
&& let Some(order) = take.order.as_deref()
@@ -12756,6 +12770,76 @@ mod tests {
assert!(!holds(&p, buffer), "kept past its queue's end");
}
/// A flag a block's release's answer sets, and the answer.
fn answer_flag() -> (Arc<AtomicBool>, super::super::DrainAnswer) {
let answered = Arc::new(AtomicBool::new(false));
let set = Arc::clone(&answered);
(
answered,
Box::new(move || set.store(true, Ordering::SeqCst)),
)
}
/// A block's release while a command buffer its context's queue published before it is
/// not yet begun waits for that buffer: not answered at the release, nor at the buffer's
/// commit, but once the buffer has completed, as a release waits for a buffer begun before it.
/// A release with every buffer published committed waits only for the buffers in flight.
#[test]
fn a_block_s_release_waits_for_a_buffer_published_before_it() {
let (p, dec) = setup();
let device = p.device();
let published = buffers_published(&dec);
let mut queue = dec.sender(Some(0), super::super::Sinks::default());
published.store(7, Ordering::SeqCst);
let (answered, answer) = answer_flag();
drop(dec.drain_context_after_published(0, answer));
assert!(
!answered.load(Ordering::SeqCst),
"answered before the buffer posted first was begun"
);
let message = command_buffer_message(100, 7, &[]);
assert_eq!(queue.decode(&device, &message).unwrap(), Ok(()));
queue.end_message();
assert!(
!answered.load(Ordering::SeqCst),
"answered before the buffer posted first completed"
);
p.world().complete_all(CompleteOn::Caller);
assert!(answered.load(Ordering::SeqCst), "never answered");
// Every buffer published committed and finished: answered at once.
let (answered, answer) = answer_flag();
drop(dec.drain_context_after_published(0, answer));
assert!(answered.load(Ordering::SeqCst));
}
/// A block's release that waits for a buffer published before it waits no more where
/// the buffer's queue ends (its destroy, or its context's close) or the device is reset, as
/// none of the buffer runs after that: answered with the buffer never begun.
#[test]
fn a_block_s_release_waits_no_more_for_a_queue_that_ended_or_a_reset() {
for reset in [false, true] {
let (p, dec) = setup();
let device = p.device();
let published = buffers_published(&dec);
let mut ring0 = dec.sender(None, super::super::Sinks::default());
published.store(7, Ordering::SeqCst);
let (answered, answer) = answer_flag();
drop(dec.drain_context_after_published(0, answer));
assert!(!answered.load(Ordering::SeqCst));
if reset {
dec.reset(&device);
} else {
assert_eq!(ring0.decode(&device, &destroy(1)).unwrap(), Ok(()));
ring0.end_message();
}
assert!(
answered.load(Ordering::SeqCst),
"the wait outlived {}",
if reset { "the reset" } else { "its queue" }
);
}
}
/// A context's close with a command buffer begun and one published behind it, never begun:
/// the objects go once the begun buffer is done with them (its view closes after its commit),
/// one its process destroyed before the close among them, which waited for the buffer behind;
@@ -57,6 +57,12 @@ pub(crate) struct CommitMark {
begun: AtomicU64,
/// The highest seqno of the queue's ring whose buffer was committed, stood in for or failed.
through: AtomicU64,
/// The highest seqno of the queue's ring whose buffer is prepared ([`Until::Prepared`]): its
/// begin on the queue's service thread returned, with no buffer of the queue up to it holding
/// a video op uncommitted then.
prepared: AtomicU64,
/// The highest seqno of the queue's ring whose buffer, begun, holds a video op.
video: AtomicU64,
/// The queue ended (its destroy, or its context's close): no wait for it waits more.
ended: AtomicBool,
/// How many threads wait on the mark; one that raises it wakes them only where any do.
@@ -74,6 +80,13 @@ pub(crate) enum Until {
Begun,
/// The buffer named was committed, stood in for or failed.
Committed,
/// The buffer named is prepared ([`CommitMark::prepare`]): its begin returned, so every use it
/// counts among a device cache's users is counted and every fill and GPU wait its begin adds
/// is fixed, and no buffer of its queue up to it holds a video op uncommitted; or it was
/// committed. A buffer whose `SURFACE_ORDER` names it may begin then, its own uses counted
/// after the named buffer's, so no fill of the named buffer's waits for it (the module doc of
/// `surface_order`, "A buffer named before the host walks it").
Prepared,
}
impl CommitMark {
@@ -93,6 +106,25 @@ impl CommitMark {
}
}
/// The queue's buffer at `seqno`'s begin on the queue's service thread returned, `video` where
/// it holds a video op. A buffer holding one is never prepared before its commit: its walk's
/// video ops wait on the CPU for fills and keep landings its waiters are held for. Nor is a
/// buffer while one before it on the queue holding one is uncommitted. Begins run one at a
/// time in ring order on the queue's service thread, so the mark only rises; a stale read of
/// `through` only leaves it lower, and its waiters wait for the commit, as before.
pub(crate) fn prepare(&self, seqno: u64, video: bool) {
if video {
self.video.fetch_max(seqno, Ordering::SeqCst);
return;
}
if self.video.load(Ordering::SeqCst) > self.through.load(Ordering::SeqCst) {
return;
}
if self.prepared.fetch_max(seqno, Ordering::SeqCst) < seqno {
self.wake();
}
}
/// Whether a thread waits on the mark: a commit of another of the process's queues that names
/// the queue ([`wait`]).
pub(crate) fn has_waiters(&self) -> bool {
@@ -125,6 +157,7 @@ impl CommitMark {
/// queue ended. A buffer committed was begun.
pub(crate) fn reached(&self, seqno: u64, until: Until) -> bool {
(until == Until::Begun && self.begun.load(Ordering::SeqCst) >= seqno)
|| (until == Until::Prepared && self.prepared.load(Ordering::SeqCst) >= seqno)
|| self.through.load(Ordering::SeqCst) >= seqno
|| self.ended.load(Ordering::SeqCst)
}
@@ -219,6 +252,7 @@ pub(crate) fn wait(
let what = match until {
Until::Begun => "commit-order-begun",
Until::Committed => "commit-order",
Until::Prepared => "commit-order-prepared",
};
wait_telling(after, own, cancel, (until, what), &mut |_| {})
}
@@ -823,4 +857,34 @@ mod tests {
assert!(!cancel.cut_since(cancel.now()), "waits stayed cut short");
assert!(cancel.cut_since(before));
}
/// A buffer's prepared mark rises at its begin's return where its queue holds no video op
/// uncommitted up to it, and waits for the commits otherwise: a video buffer, and a buffer
/// begun behind one not yet committed, are reached at their commits; once the video buffer is
/// committed, later begins rise again. A commit reaches every wait, as before.
#[test]
fn a_buffer_is_prepared_at_its_begin_unless_video_up_to_it_is_uncommitted() {
use super::{CommitMark, Until};
let m = CommitMark::default();
m.prepare(1, false);
assert!(m.reached(1, Until::Prepared));
assert!(!m.reached(1, Until::Committed));
m.prepare(2, true);
assert!(
!m.reached(2, Until::Prepared),
"a video buffer waits for its commit"
);
m.prepare(3, false);
assert!(!m.reached(3, Until::Prepared), "behind uncommitted video");
m.raise(2);
assert!(m.reached(2, Until::Prepared));
assert!(
!m.reached(3, Until::Prepared),
"its begin came while the video was uncommitted"
);
m.prepare(4, false);
assert!(m.reached(3, Until::Prepared) && m.reached(4, Until::Prepared));
m.raise(5);
assert!(m.reached(5, Until::Prepared));
}
}
Loaded 100 of 191 files, more files were not shown because too many files have changed in this diff. Show more