🆕 Encode an x86-64 guest's HEVC on the host's encoder

An x86-64 guest's hardware HEVC encoding never reached our GPU: macOS's HEVC
encoder plug-in drives only an Intel GPU's driver, found by name, so an app that
required hardware failed at its create (-12908) and others encoded in software
(m3-max-77632, development's set on this host). What the guest sees now, where
the host's video arm lists an HEVC encoder of Main and Main 10 with a constant
QP that codes a frame in place of the last (Linux hosts' VA-API, and NVENC where
its driver codes a frame without advancing its state):

- the accelerator publishes an IntelAccelerator child of its own with
  IOGVAHEVCEncode and IOGVAHEVCEncodeCapabilities (Main and Main 10, up to
  the encoder's level), so VideoToolbox lists a hardware HEVC encoder
  (hevc.gva);
- RgfxGate keeps the Intel driver path the plug-in loads from
  /Library/GPUBundles a hard link to the bundle's executable, at every boot;
- the bundle's video driver takes the plug-in's encode commands (function
  0x20, sub-ID 0x1000), codes each frame on the host (ENCODE_H265) at the QP
  the plug-in's rate control chose, an IRAP picture as a keyframe, Main from
  an 8-bit source and Main 10 from a 10-bit one, and hands back the access
  unit with 4-byte start codes, whose VPS, SPS and PPS make the session's
  format description;
- a frame the plug-in codes again over its data rate limit, at a higher QP,
  is sent in place of the last one (RGFX_VIDEO_ENCODE_IN_PLACE): a P
  picture of the last frame's order count and source surface; a keyframe
  coded again is sent as a new IDR picture;
- a session of a size the host does not encode is refused at its create,
  so an app that allows software encodes in software as before.

A host whose encoder has Main alone gets no nub: VideoToolbox hands the
plug-in a Main 10 session whatever profiles the nub lists, and the driver
learns a session's profile only from its first frame. Nor does one that
codes no frame in place, where a retry would predict from the frame it
replaces. H.264 encode and both decodes are as before on either. The
plug-in's per-CTU QP map (its pool 27) is not applied, and its frame
statistics record is not supplied. The route is macOS 26.7.1's plug-in's,
booted on 26.7.2. Windows hosts list no encoder, so encode in software as
before.

Rows (macOS 26.7.2 guest, 1080p, 300 frames at 8 Mbit/s, decoded back by
VideoToolbox; the rate band is vboot's RATE_BAND_PCT, 6%, both codecs), the
same with the frames in place (m3-max-77615, m3-max-77613, m3-max-77614),
byte for byte but for 205 bytes of the Iris Xe's Main stream:
- RX 7900 XTX (m3-max-77475): Main 105.1%, 45.02 dB; Main 10 104.8%, 45.17 dB
- Iris Xe (m3-max-77476): Main 103.5%, 48.04 dB; Main 10 98.1%, 48.86 dB
- RTX 3090 (m3-max-77477): Main 100.7%, 44.81 dB; Main 10 106.1%, 45.06 dB,
  where NVENC's own lands 104.6%: known-issues and video/bugs.md B97
At a data rate limit of 1 Mbyte a second, the plug-in coded 2 to 30 frames
of a session again, each sent in place: no gap in the order counts, all 300
frames decoded back, and the most bytes in a second 1.7% to 3.0% over the
limit (RX 7900 XTX m3-max-77611, RTX 3090 m3-max-77609, Iris Xe
m3-max-77627; video/bugs.md B100, to be read on a user's report). With a
keyframe every frame the stream comes to 4.1 to 5.0 times the asked rate, as
a real Intel Mac's comes to 5.7 times with the same QPs frame for frame
(m3-max-77635; design.md, known-issues); every frame decodes back.
Main 10 from a retained pool and from the app's own 8-bit buffers decodes as
from the pool taken per frame on all three. A real Intel Mac's hevc.gva
(macOS 26.7.1, m3-max-77481) replaces the session's pool at the third Main 10
frame, as ours does. Speed (Iris Xe, m3-max-77497): 94 to 118 fps at 1080p
against software's 3.3; 10.3 to 10.8 at 8K against 0.5 (B98, B99).

Tests: the kext's publish condition and its pairing with a host that codes
no frame in place (video_codecs_test: the caps of both decoders and encoders
without the flag publish no HEVC encode and the rest as before), the link's
update on real files (rgfxgate alias_test), and the driver's listing, create
refusals, settings, keyframes, write-back, failures, refused sources and the
frames it sends in place, and those it does not: never a keyframe, so a
session of keyframes from one reused surface sends none (video_driver_tests;
m3-max-77590). Development's set on this host (m3-max-77632) encodes H.264 to
the same bytes as this one and decodes as before. Docs: design.md and
devices.md, video/bugs.md B97 to B100, and known-issues.md's HEVC encoding
line, which now says which GPUs encode HEVC for an Intel Mac guest, and its
section on HEVC over the bitrate asked.
This commit is contained in:
Anees Iqbal committed 2026-11-27 16:26:01 -08:00
1 parent 80eea13d5d
commit 319f54dabb
16 files changed
+1445 -67

No files matched your search

+164 -4
View File
@@ -1566,10 +1566,10 @@ Stages:
VideoToolbox ranks the encoder by, as an AMD Mac's (`VTRating` 350,
`VTQualityRating` 50 on a Radeon Pro 5300M's, macOS 26.7.1): AppleGVA's
`h264.gva` is listed as hardware, and a session requiring hardware is
made and encodes on the host's encoder. It lists no HEVC encode, on a
host that encodes HEVC too, so VideoToolbox lists no `hevc.gva` and a
session requiring hardware fails −12908, as on a Mac without an HEVC
encoder (**measured**, macOS 26.7.2 guest, Iris Xe host, 2026-11-16).
made and encodes on the host's encoder. It encodes HEVC Main and Main
10 where the caps list an HEVC encoder of both with a constant QP,
through the HEVC encoder plug-in's Intel route ("HEVC encode takes the
plug-in's Intel route", below).
- **Routing:** AppleGVA hands a session to the AMD driver only on the
Macs without an Intel GPU, or where `com.apple.AppleGVA`'s
`gvaForceAMDKE` is set; elsewhere, an iMac20,1 among them, it looks for
@@ -1669,6 +1669,166 @@ Stages:
frame toward the session's average bitrate (**measured**, macOS 26.7.2
guest, Iris Xe host, 2026-11-16). AppleGVA schedules a frame
only once it has the last one's status, so one frame is in flight.
- **HEVC encode takes the plug-in's Intel route.** AppleGVA's HEVC
encoder plug-in (`hevc.gva`) drives no AMD driver. On an x86-64 Mac it
finds its GPU encoder by name: the last service named
`IntelAccelerator` whose `IOGVACodec` names an Intel generation, with
`IOGVAHEVCEncode` and `IOVARendererID` on it; VideoToolbox lists that
encoder with the capabilities its `IOGVAHEVCEncodeCapabilities`
carries. With no such service, a session requiring hardware failed
−12903, one naming our GPU too (**measured**, macOS 26.7.2 guest, RX
7900 XTX host, m3-max-77226). So where the caps list an HEVC encoder
of Main from NV12 and Main 10 from P010 with a constant QP among its
rate controls, which codes a frame in place of the last
(`RGFX_VIDEO_ENCODE_CAP_IN_PLACE`, below; `rgfxHevcEncode`), the
accelerator, once registered,
attaches a plain `IOService` named `IntelAccelerator` as its child
(`publishHevcEncoder`, `guest/kext/src/RgfxAccelerator.cpp`):
`IOGVACodec` "Gen9", `IOGVAHEVCEncode` "2", our `IOVARendererID`, and
Main and Main 10, up to the encoder's level, rated as the H.264
encoder. It carries no `IODVDBundleName`, which AppleGVA's own loader
looks for, and no Metal device or framebuffer hangs off it.
- **Both profiles, or no nub.** The plug-in names two profiles, Main
and Main 10, and reads four source formats, `420v`, `420f`, `x420`
and `xf20` (macOS 26.7.1's plug-in). VideoToolbox
hands it a session of a profile the nub does not list: a Main 10
session on a nub of Main alone was made on `hevc.gva`, and its first
frame came to the driver with a 10-bit source (Iris Xe and Radeon
780M hosts, m3-max-77365 and m3-max-77368). The driver's create sees
only the session's size, so it cannot refuse such a session, and the
nub stands only where the host encodes both profiles. A host of Main
alone gets none, and VideoToolbox encodes HEVC in software, as
before.
- **The driver path is a link to the bundle.** The plug-in loads the
driver the generation names, `AppleIntelSKLGraphicsVADriver.bundle`,
from `/Library/GPUBundles` before `/System/Library/Extensions`, and
macOS ships none in `/Library/GPUBundles`. RgfxGate's install pass
keeps the driver's executable path there a hard link to the
bundle's executable at every boot, made again whenever the
executable is a new file, as each install writes it
(`guest/rgfxgate/src/rgfx_alias.h`, tested on real files by
`tests/alias_test.cpp`; x86-64 only). One inode, so the link
carries the executable's signature and rootless tag, and dyld maps
one image whichever path a process loads it by.
- **The commands.** The plug-in calls the bundle's entry points as its
Intel driver: one encode command a frame (function 0x20, sub-ID
0x1000) whose parameters name the source IOSurface (`+0x10`), the
NAL unit type the plug-in chose for the picture (`+0x33c`) and the
slice QP its rate control chose (`+0x3d8`), beside its own VPS,
SPS, PPS and slice headers, which are for a driver that codes under
them. The driver sends `RGFX_OP_VIDEO_ENCODE_H265` at that QP as a
constant QP, an IRAP type (BLA, IDR, CRA) forcing a keyframe, Main
from a `420v` or `420f` source and Main 10 of P010 from an `x420` or
`xf20` one; the host codes under its own parameter sets. Once the command is done,
the driver writes the access unit at the start of the plug-in's
bitstream buffer (pool 0), each VCL NAL unit, VPS, SPS and PPS after
a 4-byte start code and the other NAL units left out, and its length
as the words at `+0x3a0` (0) and `+0x3a8`; the plug-in makes the
session's format description from that VPS, SPS and PPS, and each
sample from the slice segments. A failed frame publishes a length of
0 and fails the context's next schedule, as H.264's does.
- **A frame coded again is coded in place.** Where a frame's access
unit comes out over the session's data rate limit
(`kVTCompressionPropertyKey_DataRateLimits`), the plug-in codes the
same frame again at a QP 3 higher, twice at most, and drops the
first; nothing of the limit reaches the driver. Sent as a new frame,
the retry was coded on the host after the dropped one and predicted
from it: at a limit of 1 Mbit a second at 1080p, each session's 5
retries, all of P pictures, left gaps in the stream's order counts,
and VideoToolbox decoded 134 and 149 of 300 frames back, failing the
rest −17694 (**measured**, Main and Main 10, RX 7900 XTX host,
m3-max-77530; H.264's encoder made no retry there, and its 300
frames decoded). The command carries no frame counter, so the driver
takes a command of a P picture whose order count (the whole
PicOrderCntVal, `+0x4`, not the slice header's least significant
bits) and source surface are the last frame's as the retry
(`hevcCodesAgain`), and sends it with `RGFX_VIDEO_ENCODE_IN_PLACE`
and the last frame's index; the host codes it from the references
the last one was coded from, with its order count
([video/devices.md](../video/devices.md), "An encode"). A keyframe
is never sent in place: the host codes each as an IDR picture, whose
order count, 0, a new keyframe from the last one's surface shares,
and a keyframe coded again is sent as a new IDR picture, which the
stream decodes as well, the host's rate control counting one
picture more. A frame after one the host failed is never coded in
place. The host's sessions for the plug-in have no
B pictures (the driver sends none), and a host refuses a frame in
place in a session of B pictures, failing it. The nub stands only
where the host codes in place: an NVENC host whose driver refuses
it gets none (`checked_in_place`). Sent in place, at the same limit
the plug-in coded 2 to 30 frames of a session again: no gap in the
order counts, all 300 frames decoded back, and the most bytes in a
second 1.7% to 3.0% over the limit (**measured**, Main and Main 10,
m3-max-77611 RX 7900 XTX, m3-max-77609 RTX 3090, m3-max-77627 Iris
Xe; [video/bugs.md](../video/bugs.md) B100).
- **What the driver does not take.** The plug-in writes a QP for each
32×32 CTU before each frame (pool 27, one 32-bit value a CTU, within
a few steps of the frame's QP); the host codes the frame's QP
alone. The frame statistics record the plug-in hands the driver
(`+0x3b8`) is not supplied: it stays as the plug-in zeroes it. Of
its values, the plug-in's rate control reads one, a measure of the
picture's complexity per 16×16 block, which neither VA-API nor NVENC
reports; with none, it chooses each QP from the bits the frames
before came to, and lands a session's average bit rate within 6% of
the one asked on two of the three GPUs below. The record's per-CTU
statistics steer only the QP map, which the host does not take.
- The route is macOS 26.7.1's plug-in's, booted on 26.7.2. On an Iris
Xe host (m3-max-77329), a session requiring hardware was made on
`hevc.gva`, and its 10 frames at 1080p were coded on iHD, with the
keyframes where the session asked for them.
- **What a session gets** (**measured**, macOS 26.7.2 guest, 1080p,
300 frames at 8 Mbit/s, each decoded back by VideoToolbox and
compared with its source; the host's own encoder, ffmpeg's NVENC at
P4 or its VA-API encoder as it comes, on the same frames at the
guest's bit rate):
| GPU | Main: bit rate, luma | Main 10: bit rate, luma | host's own luma, Main / Main 10 |
|---|---|---|---|
| RX 7900 XTX (m3-max-77475) | 105.1%, 45.02 dB | 104.8%, 45.17 dB | 45.19 / 45.63 dB |
| Iris Xe (m3-max-77476) | 103.5%, 48.04 dB | 98.1%, 48.86 dB | 47.92 / 49.35 dB |
| RTX 3090 (m3-max-77477) | 100.7%, 44.81 dB | 106.1%, 45.06 dB | 45.76 / 46.60 dB |
NVENC's own Main 10 encode of the same frames at 8 Mbit/s came to
104.6% (the 3090's 106.1% is [video/bugs.md](../video/bugs.md)
B97). Main 10 sessions whose frames came from the session's pool
taken once and kept, or from the app's own 8-bit buffers, decoded
back as the pool's did (30 frames, as ffmpeg decodes them: 45.09 dB
of luma on the XTX, 48.97 on the Iris Xe, 45.03 on the 3090). A
session of a size the host does not encode, 64×64 or 128×96, was
made on the guest's software encoder (`hevc.vcp`), as before. With
frames coded in place (m3-max-77615, m3-max-77613, m3-max-77614),
the same sessions' streams came out byte for byte the same on the
XTX and the 3090, and on the Iris Xe but for 205 bytes of one.
- **A keyframe every frame comes to 4 to 5 times the asked rate, as
on a real Intel Mac** (**measured**, `MaxKeyFrameInterval` 1, 1080p,
30 distinct frames from one reused source buffer at 8 Mbit/s). The
plug-in lowers its QP frame after frame, its slices' QPs falling
from 20 to 13, so each frame comes out larger than the one before:
411.5% of the asked on the Iris Xe (m3-max-77627), 427.8% on the RTX
3090 (m3-max-77609) and 496.8% on the RX 7900 XTX (m3-max-77611),
every frame decoding back. A real Intel Mac's `hevc.gva` (a 2019
MacBook Pro, macOS 26.7.1) came to 571.8% in the same test, with the
same QPs frame for frame (m3-max-77635). The host's own encoders,
given the same frames with a keyframe every frame, came to 99.6% to
122.3%.
- **VideoToolbox replaces a session's pixel buffer pool.** On
`hevc.gva`, the pool `VTCompressionSessionGetPixelBufferPool`
answered before the encoder started is replaced when it starts: at
the third frame of a Main 10 session, by another pool of `420v`, on
a real Intel Mac (macOS 26.7.1, m3-max-77481) as on ours
(m3-max-77475), and at the first frame of a Main session on ours.
An app that keeps the first pool without retaining it reads freed
memory from then on; one that takes the pool again for each frame,
or retains it, does not.
- **Speed** (**measured**, Iris Xe, m3-max-77497, the host's whole
machine): at 1080p, 94 to 118 frames a second, where the guest's
software encoder made 3.2 to 3.3; at 8192×4320, 10.3 and 10.8, where
software made 0.5 (B98). Per 8K frame, of 93 to 97 ms, the host's GPU
wrote the encoder's input in 12.4 to 12.7 ms and the app copied into
its buffers in 8.5 to 10.9 ms; the rest is the host's encode and the
guest's round trip. Those 30 8K frames at 60 Mbit/s came to 118% of
the rate asked and 44.87 dB of luma, where software's came to 91%
and 48.12 dB (B99).
- **The HEVC output surface is named in the parameters, not on the
command.** An H.264 decode arrives as a pipeline whose transfer command
carries the output surface; an HEVC decode is a bare decode command with
+32 -3
View File
@@ -68,9 +68,12 @@ or has no player for them at all:
common form: 4:2:0 colour at 8 or 10 bits. Other AV1 videos have no player in the guest. Your
GPU's AV1 decoder doesn't decode 4:4:4 or 4:2:2, its 12-bit pictures would lose two bits on
the way to the guest, and macOS in a virtual machine has no AV1 decoder of its own.
- **HEVC encoding on Intel Mac guests.** macOS 26.7.2 sends hardware HEVC encoding to an Intel
GPU, even when an app asks for ours, so apps encode HEVC in software. On Linux hosts, H.264
encoding uses your GPU.
- **HEVC encoding on Intel Mac guests, on some GPUs.** On a Linux host, an Intel Mac guest
encodes HEVC on your GPU if your GPU encodes HEVC at both 8 and 10 bits, at the sizes your GPU
encodes, and can encode a frame over again in its place. GPUs that encode through VA-API can;
NVIDIA GPUs can where their driver allows it. With any other GPU, the guest encodes HEVC in
software. Encoding doesn't use your GPU on Windows yet, whichever GPU you have, so the guest
encodes video in software there.
- **HEVC at 4:2:2, 4:4:4 or 12 bits on Intel Mac guests.** macOS 26.7.2 would only take these
from a GPU as 4:2:0 at 10 bits, which loses colour detail, so the guest keeps decoding them in
software at full quality.
@@ -103,6 +106,32 @@ from earlier frames, which is most of them. An arm64 guest gets a decode error f
those frames rather than a wrong picture. Other AV1 videos play. We haven't seen this on AMD or
Intel GPUs.
## HEVC from Intel Mac guests can come out over the bitrate asked
When an app in an Intel Mac guest encodes HEVC on your GPU, it asks for a bitrate, and macOS's
encoder picks each frame's quality to land on it. It also looks for a measure of how detailed
each picture is, which the GPUs we support don't report, so it judges from the sizes of the
frames before. In our tests it lands within 6% of the ask at 1080p and 4K, with three
exceptions:
- On an NVIDIA GeForce RTX 3090, 10-bit HEVC at 1080p came out at 106% of the bitrate asked:
8.49 Mbit/s for 8 Mbit/s. NVIDIA's own encoder, given the same frames on the same card, came
out at 105%.
- At 8K (8192×4320) on an Intel Iris Xe, a one-second clip came out at 118% of the bitrate asked,
and further from the original picture than the guest's own software encoder got with fewer
bits (44.9 dB of PSNR against 48.1 dB). The GPU encodes 8K at about 10 frames a second, 20 times
as fast as the software encoder but short of real time.
- When an app asks for every frame to be a keyframe, the video came out at 4.1 to 5.0 times the
bitrate asked on the GPUs we tested, each frame bigger and sharper than the one before. That's
macOS's own encoder: with every frame a keyframe, it keeps raising each frame's quality the
same way on a real Intel Mac, which came out at 5.7 times the bitrate asked in the same test.
The video still plays back correctly.
An app can also set a hard limit on the bytes in any one second. In our tests at 1080p with
such a limit, the busiest second came out 1.7% to 3.0% over it, and every frame still played
back. A real Intel Mac stayed under the same limit, but we ran it with a keyframe every 30
frames and ours with macOS's default spacing, so the two runs don't compare directly.
## Sound comes after video on Windows
On a Windows host, a VM's sound reaches your speakers about 0.1 s after the guest sends it, and
+28
View File
@@ -102,6 +102,34 @@ Everything known to be wrong, untested or put off in the reims-graphics device's
- **Why it waits:** none of our streams resizes, and no run has shown one.
- **Fix:** one decoder at the largest size the stream may reach, each frame decoded at its own size, checked with a stream that resizes on each arm.
### B97. An Intel Mac guest's 10-bit HEVC on an RTX 3090 comes to 106% of the asked bit rate
- **What:** a macOS 26.7.2 guest's Main 10 session on its hardware HEVC encoder (`hevc.gva`, docs/graphics-kext/design.md, "HEVC encode takes the plug-in's Intel route"), 1080p, 300 frames at 8 Mbit/s, came to 8.49 Mbit/s on an RTX 3090: 106.1% of the asked, 0.1 point past the 6% every other row lands in (Main on the 3090 100.7%; Main 10 on an RX 7900 XTX 104.8%, on an Iris Xe 98.1%).
- **Evidence:** **measured**, driver 620.70.06, 2026-11-27, m3-max-77477. NVENC's own Main 10 encode of the same frames (ffmpeg, P4, VBR at 8 Mbit/s) came to 104.6%.
- **Why it waits:** the bit rate is the macOS plug-in's: the host codes each frame at the QP the plug-in's rate control chose, and that rate control reads a measure of each picture's complexity which no host encoder reports (the frame statistics the driver does not supply), so it chooses from the bits the frames before came to. 1.5 points over NVENC's own rate at the same ask.
- **Fix, if one is wanted:** a complexity on the plug-in's scale, which neither VA-API nor NVENC gives.
### B98. An Intel Mac guest's 8K HEVC encodes at about 10 frames a second on an Iris Xe
- **What:** 8192x4320 sessions on the guest's hardware HEVC encoder made 10.3 and 10.8 frames a second on an Iris Xe (RPL-P), where the guest's software encoder made 0.5; at 1080p the hardware made 94 to 118.
- **Evidence:** **measured**, iHD 26.3.5, 2026-11-27, m3-max-77497 (the host's whole machine, hardware and software alternated, 30 frames each). Per frame, of 93 to 97 ms, the host's GPU wrote the encoder's input in 12.4 to 12.7 ms and the app's own copy into its buffers took 8.5 to 10.9 ms; the other 70 to 75 ms are the host's encode and the guest's round trip, which no log line separates.
- **Why it waits:** the hardware is 20 times the software's speed at that size, so it is offered.
- **Fix:** first split those 70 ms between the host's VA-API encode and the round trip.
### B99. An Intel Mac guest's short 8K HEVC sessions come to 118% of the asked rate, under software's quality
- **What:** in the sessions of B98, 30 frames at 60 Mbit/s, the hardware's stream came to 71.0 Mbit/s (118%) and 44.87 dB of luma against its source, its last frame 39.17 dB; the guest's software encoder's came to 54.7 Mbit/s (91%) and 48.12 dB.
- **Evidence:** **measured**, m3-max-77497, as B98.
- **Why it waits:** above 1080p the rate is reported, not held to a band; the bit rate and the QPs are the plug-in's rate control's (B97). A longer session has not been measured at that size.
- **Fix:** a longer 8K session's row first, to see whether the plug-in's rate control settles.
### B100. An Intel Mac guest's HEVC under a hard data rate limit goes up to 3% over it in a second
- **What:** with `kVTCompressionPropertyKey_DataRateLimits` at 1,000,000 bytes in one second, 1080p, 300 frames at 8 Mbit/s and the plug-in's default keyframe interval (6 keyframes in 300 frames, 60 frames apart or closer), the most bytes in one second of the guest's stream came to 1.7% to 3.0% over the limit: Main 1,021,534 and Main 10 1,027,996 on an RX 7900 XTX, 1,017,335 and 1,021,809 on an RTX 3090, 1,029,488 and 1,029,273 on an Iris Xe. The plug-in coded 2 to 30 frames of each session again at a higher QP, each in place of the last, and every frame decodes back.
- **Evidence:** **measured**, 2026-11-27, m3-max-77611, m3-max-77609, m3-max-77627. A real Intel Mac's `hevc.gva` (a 2019 MacBook Pro, macOS 26.7.1) under the same limit kept it at a keyframe interval of 30: none of 271 one-second windows over, the most 957,229 bytes, 86.6% of the asked rate (**measured**, m3-max-77635). The two ran at different keyframe intervals, so they do not compare as equal.
- **Why it waits:** the retries and their QPs are the plug-in's, and no run has yet put the guest and a real Mac at one keyframe interval. It is to be read when a user reports an HEVC stream breaking its hard data rate limit.
- **Fix:** first the guest's and a real Mac's rows at one keyframe interval; then whatever separates them.
## Upstream bugs
Bugs in drivers, libraries and tools that our code or our checks work around.
+33 -5
View File
@@ -3,9 +3,10 @@
The reims-graphics device (PCI 1234:5247) decodes and encodes the guest's H.264 and HEVC on the
host's hardware. The guest's video driver, in our Metal bundle, is AppleGVA's vendor driver
([docs/graphics-kext/design.md](../graphics-kext/design.md), "Decided", 16); it decodes, and
encodes H.264 (`ENCODE_H264`), sending no `ENCODE_H265` yet. This file is the host's side: what
it answers the guest, and what a decode and an encode do. The wire's records and their
fields are documented where they are defined: `crates/reims-vgpu-graphics/src/wire.rs` (the caps and
encodes H.264 (`ENCODE_H264`) and HEVC Main and Main 10 (`ENCODE_H265`, through the HEVC encoder
plug-in's Intel route: design.md, "HEVC encode takes the plug-in's Intel route"). This file is the
host's side: what it answers the guest, and what a decode and an encode do. The wire's records and
their fields are documented where they are defined: `crates/reims-vgpu-graphics/src/wire.rs` (the caps and
the session) and `crates/reims-vgpu-graphics/src/ops/video.rs` (the ops).
## Which hardware
@@ -237,8 +238,18 @@ the device info (`GraphicsDevice::with_platform`, in `graphics.rs`):
`guest/bundle/src/RgfxVideoDriver.cpp`, `PixelRequirement`).
- **What an encode entry takes**: an `RgfxVideoEncodeCaps` per entry (`encode`): the rate
controls (a bit each of CQP, CBR and VBR, as the arm's API lists them for the codec's
profiles) and the most consecutive B pictures, 0 on both arms, whose encoders keep frames in
display order.
profiles), the most consecutive B pictures, 0 on both arms, whose encoders keep frames in
display order, and in `flags`, `RGFX_VIDEO_ENCODE_CAP_IN_PLACE` where the arm codes a frame in
place of the last one ("An encode", below): always on VA-API; on NVENC where NVENC says it
codes a frame without advancing its state (`NV_ENC_CAPS_DISABLE_ENC_STATE_ADVANCE`) for every
profile of the codec, and a session of the codec with a state buffer coded a frame, the frame
again in its place and a frame after it at the device's start (`checked_in_place`,
`graphics/nvidia/encode.rs`). NVENC's interface (13.0) lists no capability for restoring a
state (`nvEncRestoreEncoderState`), only for coding without advancing it, so that session is
the query: it adds a median of 56.9 ms to the device's start on an RTX 3090 and 61.9 ms on an
RTX 2080 (**measured**, five checks each, m3-max-77618, m3-max-77597). A driver that lacks
the capability or refuses that session leaves the flag off, which the guest's kext reads as no
HEVC encoder.
- **What a decode entry bounds**: an `RgfxVideoDecodeCaps` per entry (`decode`): the narrowest
HEVC tile column the arm decodes, in luma samples, 128 on both arms
(`reims_vgpu_video::codec::hevc::MIN_TILE_COLUMN_WIDTH`); zero, no bound, in every other
@@ -411,6 +422,23 @@ buffer of an encode session's process (reims-vgpu's `graphics/video_host/encode.
declines that copy (said once a session), the planes are read as host bytes, in the surface's
pages, or, for a plane in a device cache, in a staging buffer the GPU copies it into first, and
the encoder's upload copies them. The encoder codes the same bytes either way.
- **A frame coded in place** (`RGFX_VIDEO_ENCODE_IN_PLACE`, from a guest that read the caps
flag) replaces the last frame, whose access unit the guest drops: it is coded from the
references the last one was coded from, with its order count, at the QP the settings give
now, so no later picture predicts from the dropped one. The x86-64 guest's HEVC driver sends
one where macOS's encoder plug-in codes a frame again over its data rate limit
([design.md](../graphics-kext/design.md), "HEVC encode takes the plug-in's Intel route"). The
VA crate's encoder holds its last picture back from its stream (`Accelerator::keep`) until the
next frame, and codes the frame again in its place (`Encoder::encode_in_place`,
`crates/reims-vgpu-video/src/codec/encode/encoder.rs`). NVENC codes each frame of such a
session without advancing its state, which a state buffer keeps as it is after the frame, and
takes that state (`nvEncRestoreEncoderState`) as the next frame comes
(`NvencEncoder::new_in_place`). A frame that cannot be coded in place fails
(`RGFX_VIDEO_ENCODE_FAILED`): with none to replace, with B pictures, with a hard limit the VA
crate's own rate control holds, of another `frame_index` than the last one's, or asking a
keyframe in place of a frame that is not one. The frame after it then does not predict from
the dropped one: on VA-API it is an IDR picture, and on NVENC it is coded from the state
before the dropped one.
- **The access unit is written** in Annex-B form into the bitstream buffer, a keyframe's with
its parameter sets first, and the frame's `RgfxVideoEncodeResult` after it. One past the
capacity is not written (`RGFX_VIDEO_ENCODE_OVERFLOW`, with the bytes it needed), and the
+17 -9
View File
@@ -465,15 +465,21 @@ void *rgfx::video::decode(Session *session, const Decode &decode)
namespace {
// The textures over `source`'s two planes an encode of `session`'s reads, made once per surface;
// false where the surface is of no format the host reads or a texture is not made. Over the
// surface's pages where its block is made here: the host reads a source's bytes on the CPU, so a
// device cache would only be one more copy. The caller holds the session's lock.
bool sourceTextures(rgfx::video::Session *session, IOSurfaceRef source, id<MTLTexture> *luma,
// The textures over `source`'s two planes an encode of `session`'s reads at `settings`' format,
// made once per surface: a '420v' or '420f' surface's bytes for NV12, an 'x420' or 'xf20'
// surface's 16-bit samples, the 10 bits high in each as P010 has them, for P010. False where the
// surface is of another format or a texture is not made. Over the surface's pages where its block
// is made here: the host reads a source's bytes on the CPU, so a device cache would only be one
// more copy. The caller holds the session's lock.
bool sourceTextures(rgfx::video::Session *session, IOSurfaceRef source,
const RgfxVideoEncodeSettings &settings, id<MTLTexture> *luma,
id<MTLTexture> *chroma)
{
const OSType format = IOSurfaceGetPixelFormat(source);
if ((format != '420v' && format != '420f') || IOSurfaceGetPlaneCount(source) != 2)
const bool deep = settings.format == RGFX_VIDEO_FORMAT_P010;
const bool taken = deep ? format == 'x420' || format == 'xf20'
: format == '420v' || format == '420f';
if (!taken || IOSurfaceGetPlaneCount(source) != 2)
return false;
const uint64_t key = IOSurfaceGetID(source);
auto it = session->sources.find(key);
@@ -490,7 +496,8 @@ bool sourceTextures(rgfx::video::Session *session, IOSurfaceRef source, id<MTLTe
RgfxAskUncachedScope ask;
for (size_t plane = 0; plane < 2; plane++) {
const MTLPixelFormat format =
plane == 0 ? MTLPixelFormatR8Unorm : MTLPixelFormatRG8Unorm;
deep ? (plane == 0 ? MTLPixelFormatR16Unorm : MTLPixelFormatRG16Unorm)
: (plane == 0 ? MTLPixelFormatR8Unorm : MTLPixelFormatRG8Unorm);
MTLTextureDescriptor *desc = [MTLTextureDescriptor
texture2DDescriptorWithPixelFormat:format
width:IOSurfaceGetWidthOfPlane(source, plane)
@@ -544,7 +551,7 @@ void *rgfx::video::encode(Session *session, const Encode &encode)
bool send;
{
std::lock_guard<std::mutex> hold(session->lock);
if (!sourceTextures(session, encode.source, &luma, &chroma))
if (!sourceTextures(session, encode.source, encode.settings, &luma, &chroma))
return nullptr;
send = !session->settingsSent ||
memcmp(&session->sentSettings, &encode.settings, sizeof encode.settings) != 0;
@@ -563,7 +570,8 @@ void *rgfx::video::encode(Session *session, const Encode &encode)
body.bitstream_capacity = encode.capacity;
body.result_offset = resultOffset;
body.frame_index = encode.frameIndex;
body.flags = encode.forceKeyframe ? RGFX_VIDEO_ENCODE_FORCE_KEYFRAME : 0;
body.flags = (encode.forceKeyframe ? RGFX_VIDEO_ENCODE_FORCE_KEYFRAME : 0) |
(encode.inPlace ? RGFX_VIDEO_ENCODE_IN_PLACE : 0);
[(RgfxCmdBuffer *)cb rgfxEncodeVideoSession:session->objId
codec:session->codec
encode:body
+5 -2
View File
@@ -103,14 +103,17 @@ void *decode(Session *session, const Decode &decode);
/// One frame to encode on its session, of its codec: the two-plane surface `source`, NV12's
/// ('420v', '420f'), its whole planes, the settings' size; the `settings` in force from it on,
/// which the call sends the host where they differ from the last it sent the session (the
/// first's always); its place in display order, `frameIndex`; and whether it must be a keyframe.
/// The access unit takes at most `capacity` bytes.
/// first's always); its place in display order, `frameIndex`; whether it must be a keyframe; and
/// whether it is coded in place of the session's last frame, whose access unit the guest drops
/// (`RGFX_VIDEO_ENCODE_IN_PLACE`, `frameIndex` the last one's). The access unit takes at most
/// `capacity` bytes.
struct Encode {
IOSurfaceRef source;
RgfxVideoEncodeSettings settings;
uint64_t frameIndex;
bool forceKeyframe;
uint64_t capacity;
bool inPlace;
};
/// Commits the encode on `session`'s queue: a token for its completion, null where it was not
+251 -3
View File
@@ -145,6 +145,11 @@ constexpr uint64_t kCodecHevc = 0x800;
// the encode function, 0x800 is H.264 (an HEVC encode is 0x1000), where under the decode function
// it is HEVC.
constexpr uint64_t kEncodeH264 = 0x800;
// An encode's sub-ID for HEVC, which the guest's HEVC encoder plug-in (AppleGVAHEVCEncoder) looks
// up through the accelerator's Intel nub, and the sub-ID of the frame statistics (the process
// function) it looks up beside it, which it makes no context of.
constexpr uint64_t kEncodeHevc = 0x1000;
constexpr uint64_t kProcessFrameStatistics = 0x1000;
Function &addFunction(CapabilityBlock &b, uint32_t function_id, uint64_t sub_id, uint32_t in,
std::initializer_list<uint32_t> outs, uint32_t engine = kVideoEngine)
@@ -174,6 +179,28 @@ void addDecoder(CapabilityBlock &b, uint64_t codec, std::initializer_list<uint32
decode.next = &transfer;
}
// The host's HEVC encoder where the guest's HEVC encoder plug-in can drive it, as the kext
// publishes it (RgfxVideoCodecs.hpp's rgfxHevcEncode): Main from NV12 and Main 10 from P010, with a
// constant QP among its rate controls, since the plug-in's rate control picks each frame's QP, and
// one that codes a frame in place of the last (RGFX_VIDEO_ENCODE_CAP_IN_PLACE), since the plug-in
// codes a frame again where it came out over its data rate limit (encodeHevcFrame). Both
// profiles: a session may be of either, and the driver learns which only from its first frame's
// source, past its create. Null otherwise.
const RgfxVideoCodecCaps *hevcEncoder()
{
const RgfxVideoCodecCaps *caps =
rgfx::video::hostCodec(RGFX_VIDEO_CODEC_HEVC, RGFX_VIDEO_ENCODE);
const uint32_t profiles = RGFX_VIDEO_HEVC_MAIN | RGFX_VIDEO_HEVC_MAIN_10;
const uint32_t formats = RGFX_VIDEO_FORMAT_NV12 | RGFX_VIDEO_FORMAT_P010;
const RgfxVideoEncodeCaps encode = rgfx::video::encodeCaps(RGFX_VIDEO_CODEC_HEVC);
const bool cqp = (encode.rate_controls & (1u << RGFX_VIDEO_RATE_CQP)) != 0;
const bool inPlace = (encode.flags & RGFX_VIDEO_ENCODE_CAP_IN_PLACE) != 0;
return caps && (caps->profiles & profiles) == profiles &&
(caps->formats & formats) == formats && cqp && inPlace
? caps
: nullptr;
}
void fillCapabilities(CapabilityBlock &b)
{
memset(&b, 0, sizeof b);
@@ -209,6 +236,12 @@ void fillCapabilities(CapabilityBlock &b)
if (rgfx::video::hostCodec(RGFX_VIDEO_CODEC_H264, RGFX_VIDEO_ENCODE) &&
rgfx::video::encodeCaps(RGFX_VIDEO_CODEC_H264).rate_controls != 0)
addFunction(b, kFunctionEncode, kEncodeH264, 'NV12', {'rawb'});
// HEVC encode, where the plug-in can drive the host's encoder (hevcEncoder), and the frame
// statistics the plug-in looks up beside it.
if (hevcEncoder()) {
addFunction(b, kFunctionEncode, kEncodeHevc, 'NV12', {'rawb'});
addFunction(b, kFunctionProcess, kProcessFrameStatistics, 'NV12', {'NV12', 'rawb'});
}
// Frame processing on the graphics engine.
addFunction(b, kFunctionProcess, 0x10, 'NV12', {'NV12'}, kGraphicsEngine);
b.functions = b.function_list;
@@ -516,6 +549,26 @@ uint64_t u64At(const uint8_t *base, size_t off)
// host and the parameter sets it last sent there.
struct Driver;
// An HEVC encode context's last frame sent (Context::hevc_last): whether there is one, its
// picture's order count and its source's IOSurface ID.
struct HevcLast {
bool sent;
uint32_t poc;
uint32_t source;
};
// Whether the plug-in's HEVC encode of a picture of order count `poc` from the IOSurface of ID
// `source`, a keyframe where `keyframe`, is sent in place of `last`: the same picture from the same
// source, which the plug-in codes again where a frame's access unit came out over its data rate
// limit, at a higher QP, dropping the first; each new frame has an order count of its own. Never a
// keyframe: the host codes each as an IDR picture, whose order count, 0, a new frame from the
// surface of the last may share, and a keyframe coded again is sent as a new IDR picture, which
// the stream decodes as well, its rate control counting one picture more.
bool hevcCodesAgain(const HevcLast &last, uint32_t poc, uint32_t source, bool keyframe)
{
return !keyframe && last.sent && last.poc == poc && last.source == source;
}
struct Context {
// The driver AppleGVA made the context on, whose bitstream buffers its pictures name.
Driver *driver;
@@ -538,6 +591,9 @@ struct Context {
// since its last schedule, which fails its next (RgfxVideoStatus.hpp).
uint64_t frames = 0;
std::atomic<bool> encode_failed{false};
// An HEVC encode context's last frame sent, which the plug-in may code again in its place
// (hevcCodesAgain); none before its first, and after a frame the host failed.
HevcLast hevc_last{};
// Whether its first output surface's layout was logged (outputSaid).
std::atomic<bool> output_said{false};
};
@@ -1318,6 +1374,172 @@ bool encodeSettings(Context *context, const uint8_t *P, IOSurfaceRef source,
return true;
}
// An HEVC encode command's parameters (Command::parameters, P), as AppleGVAHEVCEncoder's driver
// class for an Intel GPU fills them for the encode function's sub-ID 0x1000 (macOS 26.7.1's
// plug-in, booted on 26.7.2): the picture's order count (its PicOrderCntVal) at +0x4; the source
// frame, an IOSurface, at +0x10; the NAL unit type the plug-in chose for the picture, which its
// sample's sync attachments follow, at +0x33c; and the slice QP its rate control chose, at
// +0x3d8. The order count is the whole PicOrderCntVal, its most significant part kept by the
// plug-in, not the slice header's least significant bits. Where a frame's access unit comes out
// over the session's data rate limit, the plug-in codes the same frame again at a higher QP, twice
// at most, with the same order count, NAL unit type and source, and drops the first
// (hevcCodesAgain). The plug-in reads the access unit
// from the start of its bitstream pool's one buffer (pool 0), as many bytes as the word at +0x3a8
// less the one at +0x3a0, both of which it zeroes before each encode. It takes the access unit as
// Annex-B with 4-byte start codes: its VPS, SPS and PPS make the session's format description,
// and its slice segments, each start code rewritten to a 4-byte length in place, the sample; it
// drops NAL units of other types. Its own parameter sets and slice headers in the command are
// for a driver that codes under them; the host codes under its own, which the format description
// then carries.
constexpr size_t kHevcPoc = 0x004, kHevcSource = 0x010, kHevcNalType = 0x33c, kHevcBegin = 0x3a0,
kHevcEnd = 0x3a8, kHevcQp = 0x3d8;
constexpr uint32_t kHevcBitstreamPool = 0;
// The settings the host encodes the HEVC frame of command parameters `P` with, from its source
// `source`, into `out`: the source's size, format and range, Main from a '420v' or '420f' source
// and Main 10 from an 'x420' or 'xf20' one, and a constant QP, the one the plug-in chose for the
// picture; the plug-in's NAL types make every keyframe. False, logged once a reason, where the
// host does not encode it so.
bool encodeHevcSettings(const uint8_t *P, IOSurfaceRef source, RgfxVideoEncodeSettings *out)
{
const RgfxVideoCodecCaps *caps = hevcEncoder();
const OSType format = IOSurfaceGetPixelFormat(source);
const bool deep = format == 'x420' || format == 'xf20';
const uint32_t profile = deep ? RGFX_VIDEO_HEVC_MAIN_10 : RGFX_VIDEO_HEVC_MAIN;
const uint32_t layout = deep ? RGFX_VIDEO_FORMAT_P010 : RGFX_VIDEO_FORMAT_NV12;
const uint32_t width = (uint32_t)IOSurfaceGetWidth(source),
height = (uint32_t)IOSurfaceGetHeight(source);
if (!caps || !(deep || format == '420v' || format == '420f') || !(caps->profiles & profile) ||
!(caps->formats & layout) || width % 2 || height % 2 ||
!rgfx::video::sizeTaken(caps, width, height)) {
static std::atomic<bool> said;
notSent(said, "its HEVC encode asks a format, profile or size the host does not encode");
return false;
}
RgfxVideoEncodeSettings s = {};
s.width = width;
s.height = height;
s.format = layout;
s.profile = profile;
s.full_range = format == '420f' || format == 'xf20';
s.key_frame_interval = UINT32_MAX;
s.quality = 50;
s.rate_control = RGFX_VIDEO_RATE_CQP;
s.qp_i = s.qp_p = s.qp_b = std::min<uint32_t>(u32At(P, kHevcQp), 51);
*out = s;
return true;
}
// Commits the HEVC encode of parameters `P` on `context`'s session: its work on the host, or null
// where it could not be sent.
void *encodeHevcFrame(Context *context, const uint8_t *P)
{
IOSurfaceRef source = (IOSurfaceRef)u64At(P, kHevcSource);
const uint8_t *buffer;
size_t bytes;
if (!source || CFGetTypeID(source) != IOSurfaceGetTypeID() ||
!bitstreamBuffer(context->driver, kHevcBitstreamPool, 0, &buffer, &bytes) || bytes < 8) {
static std::atomic<bool> said;
notSent(said, "its HEVC encode names no source surface (+0x10), or the driver has no "
"bitstream pool 0");
return nullptr;
}
rgfx::video::Encode e = {};
e.source = source;
if (!encodeHevcSettings(P, source, &e.settings))
return nullptr;
// An IRAP picture (BLA, IDR or CRA) the plug-in asks for is a keyframe; the host makes no other.
const uint32_t nal = u32At(P, kHevcNalType);
e.forceKeyframe = nal >= 16 && nal <= 21;
// The plug-in's frame again, at a higher QP, is coded in place of the last one sent, of its
// place in display order, unless it is a keyframe (hevcCodesAgain).
const uint32_t poc = u32At(P, kHevcPoc), id = IOSurfaceGetID(source);
e.inPlace = hevcCodesAgain(context->hevc_last, poc, id, e.forceKeyframe);
e.frameIndex = e.inPlace ? context->frames - 1 : context->frames;
// The host's access unit is never longer than the wire's bound for its size; the start codes
// made 4 bytes long add one a NAL unit at most, which the pool's buffer has room for.
const uint64_t bound = (uint64_t)e.settings.width * e.settings.height *
(e.settings.format == RGFX_VIDEO_FORMAT_P010 ? 2 : 1) * 3 / 2 +
(1u << 20);
e.capacity = std::min<uint64_t>(bound, bytes / 2);
void *work = rgfx::video::encode(context->session, e);
if (!work) {
static std::atomic<bool> said;
notSent(said, "a source of no format the host reads, or no command buffer");
return nullptr;
}
if (!e.inPlace)
context->frames++;
context->hevc_last = {true, poc, id};
return work;
}
// Writes the Annex-B access unit `in` (`size` bytes, start codes of 3 or 4 bytes) into `out` (of
// `room` bytes) as the HEVC plug-in reads it: each VCL NAL unit, VPS, SPS and PPS after a 4-byte
// start code, its trailing zero bytes left out, and the NAL units of other types (access unit
// delimiters, SEI, filler), which the plug-in drops, left out. The bytes written; 0 where none
// fit or there is no slice segment.
uint64_t hevcAccessUnit(const uint8_t *in, uint64_t size, uint8_t *out, uint64_t room)
{
auto startCode = [&](uint64_t i) {
return i + 3 <= size && in[i] == 0 && in[i + 1] == 0 && in[i + 2] == 1;
};
uint64_t i = 0, written = 0;
bool slices = false;
while (i < size && !startCode(i))
i++;
while (i < size) {
const uint64_t begin = i + 3;
uint64_t end = begin;
while (end < size && !startCode(end))
end++;
i = end;
while (end > begin && in[end - 1] == 0)
end--;
if (end - begin < 2)
continue;
const uint32_t type = (in[begin] >> 1) & 0x3f;
if (type > 34 || (type > 21 && type < 32))
continue;
if (written + 4 + (end - begin) > room)
return 0;
static const uint8_t code[4] = {0, 0, 0, 1};
memcpy(out + written, code, 4);
memcpy(out + written + 4, in + begin, end - begin);
written += 4 + (end - begin);
slices = slices || type <= 21;
}
return slices ? written : 0;
}
// Publishes the done HEVC encode of token `t` to the plug-in: its access unit at the start of the
// bitstream pool's buffer (hevcAccessUnit), and its length as the words at +0x3a0 (0) and +0x3a8.
// A frame the host did not encode, or whose access unit does not fit, publishes a length of 0,
// which the plug-in takes as no sample, and fails the context's next schedule.
void publishHevcEncoded(Token *t)
{
uint8_t *P = t->parameters;
RgfxVideoEncodeResult result = {};
const uint8_t *bytes = nullptr;
const uint8_t *buffer = nullptr;
size_t room = 0;
const bool done = rgfx::video::encodeResult(t->work, &result, &bytes) &&
result.status == RGFX_VIDEO_ENCODE_OK && result.bitstream_size > 0 &&
bitstreamBuffer(t->encode->driver, kHevcBitstreamPool, 0, &buffer, &room);
const uint64_t size =
done ? hevcAccessUnit(bytes, result.bitstream_size, const_cast<uint8_t *>(buffer), room) : 0;
if (size == 0) {
t->encode->encode_failed = true;
static std::atomic<bool> said;
if (!said.exchange(true))
os_log_error(rgfxLog(), "RGFX: video: an HEVC encode not delivered: host status %u, %llu bytes",
result.status, (unsigned long long)result.bitstream_size);
}
const uint64_t begin = 0;
memcpy(P + kHevcBegin, &begin, sizeof begin);
memcpy(P + kHevcEnd, &size, sizeof size);
}
// Commits the encode command `c`'s frame on its context's session: its work on the host, or null
// where it could not be sent.
void *encodeFrame(const Command *c)
@@ -1329,6 +1551,8 @@ void *encodeFrame(const Command *c)
notSent(said, "its encode command names no encode session or no parameters");
return nullptr;
}
if (context->sub_id == kEncodeHevc)
return encodeHevcFrame(context, P);
IOSurfaceRef source = (IOSurfaceRef)u64At(P, kEncodeSource);
const uint8_t *nal = (const uint8_t *)u64At(P, kEncodeNal);
const uint32_t capacity = u32At(P, kEncodeCapacity);
@@ -1372,6 +1596,10 @@ void publishEncoded(Token *t)
if (t->published)
return;
t->published = true;
if (t->encode->sub_id == kEncodeHevc) {
publishHevcEncoded(t);
return;
}
uint8_t *P = t->parameters;
uint8_t *length = (uint8_t *)u64At(P, kEncodeLength);
const uint32_t capacity = u32At(P, kEncodeCapacity), start = u32At(P, kEncodeStart);
@@ -1428,7 +1656,9 @@ uint64_t answer(int entry, uint64_t a0, uint64_t a1, uint64_t a2)
fi->width, fi->height, nullptr, {}}
: nullptr;
const bool encode = context && fi->function_id == kFunctionEncode;
const uint32_t codec = encode ? (fi->sub_id == kEncodeH264 ? RGFX_VIDEO_CODEC_H264 : 0)
const uint32_t codec = encode ? (fi->sub_id == kEncodeH264 ? RGFX_VIDEO_CODEC_H264
: fi->sub_id == kEncodeHevc ? RGFX_VIDEO_CODEC_HEVC
: 0)
: !context || fi->function_id != kFunctionDecode ? 0
: fi->sub_id == kCodecH264 ? RGFX_VIDEO_CODEC_H264
: fi->sub_id == kCodecHevc ? RGFX_VIDEO_CODEC_HEVC
@@ -1436,10 +1666,25 @@ uint64_t answer(int entry, uint64_t a0, uint64_t a1, uint64_t a2)
if (encode) {
// An encode of a coded size the host does not encode is refused here, where
// VideoToolbox hears of it at its session's create.
const RgfxVideoCodecCaps *caps = codec ? hostEncoder(codec) : nullptr;
if (caps && rgfx::video::sizeTaken(caps, fi->width, fi->height))
// An HEVC encode takes the host's encoder only where the plug-in can drive it
// (hevcEncoder).
const RgfxVideoCodecCaps *caps = codec == RGFX_VIDEO_CODEC_HEVC ? hevcEncoder()
: codec ? hostEncoder(codec)
: nullptr;
const bool sized = caps && rgfx::video::sizeTaken(caps, fi->width, fi->height);
if (sized)
context->session = rgfx::video::openSession(codec, RGFX_VIDEO_ENCODE);
if (!context->session) {
static std::atomic<bool> said;
if (!said.exchange(true))
os_log_error(rgfxLog(),
"RGFX: video: an %{public}s encode of %ux%u refused at its "
"create: %{public}s",
codec == RGFX_VIDEO_CODEC_HEVC ? "HEVC" : "H.264", fi->width,
fi->height,
!caps ? "the host has no encoder the driver drives"
: !sized ? "the host encodes no picture of its size"
: "no session opened");
for (uint32_t j = 0; j < i; j++) {
deleteContext((Context *)ci->info->contexts[j]);
ci->info->contexts[j] = nullptr;
@@ -1662,6 +1907,9 @@ uint64_t answer(int entry, uint64_t a0, uint64_t a1, uint64_t a2)
// (publishEncoded).
const bool failed = encode && context && context->encode_failed.exchange(false);
hostFailed = hostFailed || failed;
// The host holds no frame of this context's to code again in place.
if (failed)
context->hevc_last = {};
void *work = !decode || failed ? nullptr
: encode ? encodeFrame(decode)
: decodePicture(decode);
+387 -34
View File
@@ -255,6 +255,12 @@ std::vector<FakeSession *> g_sentOn;
// the host lists without one, which the driver reads as none).
bool g_hostEncodes = true;
uint32_t g_encodeRates = 1u << RGFX_VIDEO_RATE_CQP | 1u << RGFX_VIDEO_RATE_VBR;
// The profiles the stand-in host's HEVC encoder takes, each from its format (Main from NV12, Main
// 10 from P010): both, as the hosts' arms have them, where a check does not change them.
uint32_t g_hevcEncodeProfiles = RGFX_VIDEO_HEVC_MAIN | RGFX_VIDEO_HEVC_MAIN_10;
// The stand-in host's encoders' flags (RgfxVideoEncodeCaps::flags): frames coded in place, as the
// hosts' arms code them, where a check does not change them.
uint32_t g_encodeFlags = RGFX_VIDEO_ENCODE_CAP_IN_PLACE;
// Each encode the driver sends, as it sent it.
struct SentEncode {
FakeSession *session;
@@ -263,6 +269,7 @@ struct SentEncode {
uint64_t frameIndex;
bool forceKeyframe;
uint64_t capacity;
bool inPlace;
};
std::vector<SentEncode> g_encodes;
// Each encode's work, done at once: what the host answers of it, the status and access unit the
@@ -300,14 +307,14 @@ const RgfxVideoCodecCaps *hostCodec(uint32_t codec, uint32_t direction)
h264.formats = RGFX_VIDEO_FORMAT_NV12;
hevc.formats = RGFX_VIDEO_FORMAT_NV12 | RGFX_VIDEO_FORMAT_P010;
hevc.max_references = g_hevcMaxReferences;
// And, where a check has them, H.264 encode of every profile and HEVC encode of Main, of
// 144x144 to 4096x4096.
// And, where a check has them, H.264 encode of every profile and HEVC encode of the profiles
// g_hevcEncodeProfiles names, of 144x144 to 4096x4096.
static RgfxVideoCodecCaps h264Encode = {}, hevcEncode = {};
h264Encode.codec = RGFX_VIDEO_CODEC_H264;
h264Encode.profiles = RGFX_VIDEO_H264_BASELINE | RGFX_VIDEO_H264_MAIN | RGFX_VIDEO_H264_HIGH;
h264Encode.max_level = 52;
hevcEncode.codec = RGFX_VIDEO_CODEC_HEVC;
hevcEncode.profiles = RGFX_VIDEO_HEVC_MAIN;
hevcEncode.profiles = g_hevcEncodeProfiles;
hevcEncode.max_level = 186;
for (RgfxVideoCodecCaps *c : {&h264Encode, &hevcEncode}) {
c->direction = RGFX_VIDEO_ENCODE;
@@ -315,6 +322,8 @@ const RgfxVideoCodecCaps *hostCodec(uint32_t codec, uint32_t direction)
c->min_size[0] = c->min_size[1] = 144;
c->max_size[0] = c->max_size[1] = 4096;
}
hevcEncode.formats = (g_hevcEncodeProfiles & RGFX_VIDEO_HEVC_MAIN ? RGFX_VIDEO_FORMAT_NV12 : 0) |
(g_hevcEncodeProfiles & RGFX_VIDEO_HEVC_MAIN_10 ? RGFX_VIDEO_FORMAT_P010 : 0);
if (direction == RGFX_VIDEO_ENCODE)
return !g_hostEncodes ? nullptr
: codec == RGFX_VIDEO_CODEC_H264 ? &h264Encode
@@ -333,8 +342,10 @@ RgfxVideoDecodeCaps decodeCaps(uint32_t codec)
RgfxVideoEncodeCaps encodeCaps(uint32_t codec)
{
RgfxVideoEncodeCaps c = {};
if (g_hostEncodes && (codec == RGFX_VIDEO_CODEC_H264 || codec == RGFX_VIDEO_CODEC_HEVC))
if (g_hostEncodes && (codec == RGFX_VIDEO_CODEC_H264 || codec == RGFX_VIDEO_CODEC_HEVC)) {
c.rate_controls = g_encodeRates;
c.flags = g_encodeFlags;
}
return c;
}
@@ -396,7 +407,7 @@ void *decode(Session *session, const Decode &d)
void *encode(Session *session, const Encode &e)
{
g_encodes.push_back({session, e.source ? IOSurfaceGetID(e.source) : 0, e.settings, e.frameIndex,
e.forceKeyframe, e.capacity});
e.forceKeyframe, e.capacity, e.inPlace});
EncodeWork &work = g_encodeWork.emplace_back();
work.result.status = g_encodeStatus;
work.result.bitstream_size = g_accessUnit.size();
@@ -807,14 +818,16 @@ std::vector<uint8_t> setsOf(const rgfx::video::h265::Sps &sps, const rgfx::video
return sets;
}
// A surface of `width` by `height` samples of a byte each.
IOSurfaceRef canvas(uint32_t width, uint32_t height)
// A surface of `width` by `height` samples of a byte each, of pixel format `format` where it is
// not 0.
IOSurfaceRef canvas(uint32_t width, uint32_t height, OSType format = 0)
{
CFMutableDictionaryRef props = CFDictionaryCreateMutable(
nullptr, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
const int32_t values[3] = {(int32_t)width, (int32_t)height, 1};
const CFStringRef keys[3] = {kIOSurfaceWidth, kIOSurfaceHeight, kIOSurfaceBytesPerElement};
for (int i = 0; i < 3; i++) {
const int32_t values[4] = {(int32_t)width, (int32_t)height, 1, (int32_t)format};
const CFStringRef keys[4] = {kIOSurfaceWidth, kIOSurfaceHeight, kIOSurfaceBytesPerElement,
kIOSurfacePixelFormat};
for (int i = 0; i < (format ? 4 : 3); i++) {
CFNumberRef n = CFNumberCreate(nullptr, kCFNumberSInt32Type, &values[i]);
CFDictionarySetValue(props, keys[i], n);
CFRelease(n);
@@ -1590,6 +1603,8 @@ void checkH264SpsLayouts()
constexpr uint32_t kFunctionEncode = 0x20;
constexpr uint64_t kEncodeH264 = 0x800, kEncodeHevc = 0x1000;
constexpr uint32_t kFunctionProcess = 2;
constexpr uint64_t kProcessFrameStatistics = 0x1000;
constexpr uint64_t kBadArgument = 5;
enum { kAllocatePixelBufferPool = 8, kQueryCommandStatus = 11 };
constexpr uint32_t kQueryDone = 1;
@@ -1635,16 +1650,23 @@ int listed(uint32_t id, uint64_t sub)
const char *g_self;
// In a process of its own, as the driver fills its capability block once a process (the test
// binary run again, `listed ENCODES RATES`, which exits 0 where the block lists H.264 encode
// `want` times): a host that `encodes` H.264 with rate controls `rates`.
void checkListedOn(bool encodes, uint32_t rates, int want, const char *what)
// binary run again, `listed ENCODES RATES WANT WANT_HEVC HEVC_PROFILES`, which exits 0 where the
// block lists H.264 encode `want` times and HEVC encode, with the frame statistics beside it,
// `wantHevc` times): a host that `encodes` H.264 and HEVC with rate controls `rates`, its HEVC
// encoder of `hevcProfiles`.
void checkListedOn(bool encodes, uint32_t rates, int want, int wantHevc, const char *what,
uint32_t hevcProfiles = RGFX_VIDEO_HEVC_MAIN | RGFX_VIDEO_HEVC_MAIN_10,
uint32_t flags = RGFX_VIDEO_ENCODE_CAP_IN_PLACE)
{
char encodesArg[4], ratesArg[16], wantArg[4];
char encodesArg[4], ratesArg[16], wantArg[4], wantHevcArg[4], profilesArg[16], flagsArg[16];
std::snprintf(encodesArg, sizeof encodesArg, "%d", encodes ? 1 : 0);
std::snprintf(ratesArg, sizeof ratesArg, "%u", rates);
std::snprintf(wantArg, sizeof wantArg, "%d", want);
std::snprintf(wantHevcArg, sizeof wantHevcArg, "%d", wantHevc);
std::snprintf(profilesArg, sizeof profilesArg, "%u", hevcProfiles);
std::snprintf(flagsArg, sizeof flagsArg, "%u", flags);
char *const argv[] = {const_cast<char *>(g_self), const_cast<char *>("listed"), encodesArg,
ratesArg, wantArg, nullptr};
ratesArg, wantArg, wantHevcArg, profilesArg, flagsArg, nullptr};
pid_t pid = 0;
CHECK(posix_spawn(&pid, g_self, nullptr, nullptr, argv, environ) == 0, "%s: no child", what);
int status = 0;
@@ -1653,40 +1675,58 @@ void checkListedOn(bool encodes, uint32_t rates, int want, const char *what)
}
// The child of checkListedOn: whether the block of its host lists H.264 encode `want` times, and
// HEVC encode never.
// HEVC encode and the frame statistics `wantHevc` times each.
int listedChild(char **argv)
{
g_hostEncodes = std::atoi(argv[2]) != 0;
g_encodeRates = (uint32_t)std::strtoul(argv[3], nullptr, 10);
g_hevcEncodeProfiles = (uint32_t)std::strtoul(argv[6], nullptr, 10);
g_encodeFlags = (uint32_t)std::strtoul(argv[7], nullptr, 10);
void *table = nullptr;
uint8_t params[64] = {}, identity[64] = {};
if (AVD_CreateAVDAccelerator(&table, params, identity) != 0 || !table)
return 2;
g_table = (DriverTable *)table;
g_driver = createDriver();
if (listed(kFunctionEncode, kEncodeHevc) != 0)
const int wantHevc = std::atoi(argv[5]);
if (listed(kFunctionEncode, kEncodeHevc) != wantHevc ||
listed(kFunctionProcess, kProcessFrameStatistics) != wantHevc)
return 3;
return listed(kFunctionEncode, kEncodeH264) == std::atoi(argv[4]) ? 0 : 1;
}
// The capability block lists H.264 encode (function 0x20, sub-ID 0x800, NV12 in and a bitstream
// out) where the host has an H.264 encoder with a rate control, and no HEVC encode, though the host
// has an HEVC encoder: the driver encodes no HEVC, so it answers as a Mac without an HEVC encoder
// does (VideoToolbox lists no hevc.gva, and a create that requires hardware fails -12908, measured
// on macOS 26.7.2); a host with no encoder, or one it lists with no rate control, lists none. The rest of the checks run on a host
// that encodes, so every answer of the block with the encoder listed is one AppleGVA may divide by
// (checkNoZeroAnswers).
// out) where the host has an H.264 encoder with a rate control, and HEVC encode (sub-ID 0x1000),
// with the frame statistics the HEVC encoder plug-in looks up beside it (function 2, sub-ID
// 0x1000), where the host has an HEVC encoder of Main from NV12 and Main 10 from P010 with a
// constant QP, at which the driver codes the plug-in's frames, that codes a frame in place of the
// last; a host with no encoder, or one it lists with no rate control, lists neither, and one with
// no constant QP, of one of the two profiles alone, or that codes no frame in place, lists no HEVC
// encode, and H.264 encode as before. The rest of the checks run on a host
// that encodes, so every answer of the block with the encoders listed is one AppleGVA may divide
// by (checkNoZeroAnswers).
void checkEncodeListedApart()
{
checkListedOn(false, 1u << RGFX_VIDEO_RATE_CQP, 0, "H.264 encode listed with no host encoder");
checkListedOn(true, 0, 0, "H.264 encode listed with no rate control");
checkListedOn(true, 1u << RGFX_VIDEO_RATE_CQP, 1, "H.264 encode not listed once");
checkListedOn(false, 1u << RGFX_VIDEO_RATE_CQP, 0, 0, "encode listed with no host encoder");
checkListedOn(true, 0, 0, 0, "encode listed with no rate control");
checkListedOn(true, 1u << RGFX_VIDEO_RATE_VBR, 1, 0,
"H.264 encode not listed once, or HEVC encode listed, with no constant QP");
checkListedOn(true, 1u << RGFX_VIDEO_RATE_CQP, 1, 1, "H.264 or HEVC encode not listed once");
checkListedOn(true, 1u << RGFX_VIDEO_RATE_CQP, 1, 0, "HEVC encode listed of Main alone",
RGFX_VIDEO_HEVC_MAIN);
checkListedOn(true, 1u << RGFX_VIDEO_RATE_CQP, 1, 0, "HEVC encode listed of Main 10 alone",
RGFX_VIDEO_HEVC_MAIN_10);
checkListedOn(true, 1u << RGFX_VIDEO_RATE_CQP, 1, 0,
"HEVC encode listed, or H.264 encode not, on a host that codes no frame in place",
RGFX_VIDEO_HEVC_MAIN | RGFX_VIDEO_HEVC_MAIN_10, 0);
}
void checkEncodeListed()
{
CHECK(listed(kFunctionEncode, kEncodeH264) == 1, "H.264 encode not listed once");
CHECK(listed(kFunctionEncode, kEncodeHevc) == 0, "HEVC encode listed");
CHECK(listed(kFunctionEncode, kEncodeHevc) == 1, "HEVC encode not listed once");
CHECK(listed(kFunctionProcess, kProcessFrameStatistics) == 1,
"the frame statistics not listed once");
const CapabilityBlock *b = capabilities();
for (uint32_t f = 0; f < b->function_count; f++) {
const Function &fn = *b->functions[f];
@@ -1698,6 +1738,9 @@ void checkEncodeListed()
}
}
// The stand-in host's rate controls where a check does not change them.
constexpr uint32_t kCqpVbr = 1u << RGFX_VIDEO_RATE_CQP | 1u << RGFX_VIDEO_RATE_VBR;
// Makes one encode context of `sub` of `width` x `height`: CreateContexts' answer, the context in
// `context`.
uint64_t makeEncode(void **context, uint32_t width, uint32_t height, uint64_t sub = kEncodeH264)
@@ -1716,9 +1759,11 @@ uint64_t makeEncode(void **context, uint32_t width, uint32_t height, uint64_t su
return call(kCreateContexts, &init);
}
// An H.264 encode context opens an encode session on the host where the host encodes its size;
// one of a size past the host's, one on a host with no encoder, and an HEVC encode on a host that
// encodes HEVC are refused at their create, with no session left open.
// An H.264 or HEVC encode context opens an encode session on the host where the host encodes its
// size; one of a size past the host's, one on a host with no encoder, and an HEVC encode on a host
// whose encoder has no constant QP, encodes Main alone, or codes no frame in place, are refused at
// their create, with no session left open, so VideoToolbox takes its software encoder where the
// app allows it; an H.264 encode on that last host opens as before.
void checkEncodeCreate()
{
g_hostEncodes = true;
@@ -1726,14 +1771,23 @@ void checkEncodeCreate()
uint32_t width, height;
uint64_t sub;
bool encodes;
uint32_t rates;
uint64_t want;
} cases[] = {
{640, 480, kEncodeH264, true, kOk}, {4096, 4096, kEncodeH264, true, kOk},
{4097, 480, kEncodeH264, true, kUnsupported}, {128, 480, kEncodeH264, true, kUnsupported},
{640, 480, kEncodeH264, false, kUnsupported}, {640, 480, kEncodeHevc, true, kUnsupported},
{640, 480, kEncodeH264, true, kCqpVbr, kOk},
{4096, 4096, kEncodeH264, true, kCqpVbr, kOk},
{4097, 480, kEncodeH264, true, kCqpVbr, kUnsupported},
{128, 480, kEncodeH264, true, kCqpVbr, kUnsupported},
{640, 480, kEncodeH264, false, kCqpVbr, kUnsupported},
{640, 480, kEncodeHevc, true, kCqpVbr, kOk},
{1920, 1088, kEncodeHevc, true, kCqpVbr, kOk},
{4097, 480, kEncodeHevc, true, kCqpVbr, kUnsupported},
{640, 480, kEncodeHevc, false, kCqpVbr, kUnsupported},
{640, 480, kEncodeHevc, true, 1u << RGFX_VIDEO_RATE_VBR, kUnsupported},
};
for (const auto &c : cases) {
g_hostEncodes = c.encodes;
g_encodeRates = c.rates;
g_opened.clear();
void *context = nullptr;
CHECK(makeEncode(&context, c.width, c.height, c.sub) == c.want,
@@ -1748,6 +1802,25 @@ void checkEncodeCreate()
}
}
g_hostEncodes = true;
g_encodeRates = kCqpVbr;
g_hevcEncodeProfiles = RGFX_VIDEO_HEVC_MAIN;
g_opened.clear();
void *mainOnly = nullptr;
CHECK(makeEncode(&mainOnly, 640, 480, kEncodeHevc) == kUnsupported && !mainOnly &&
g_opened.empty(),
"an HEVC encode on a host of Main alone not refused");
g_hevcEncodeProfiles = RGFX_VIDEO_HEVC_MAIN | RGFX_VIDEO_HEVC_MAIN_10;
g_encodeFlags = 0;
void *notInPlace = nullptr;
CHECK(makeEncode(&notInPlace, 640, 480, kEncodeHevc) == kUnsupported && !notInPlace &&
g_opened.empty(),
"an HEVC encode on a host that codes no frame in place not refused");
void *h264 = nullptr;
CHECK(makeEncode(&h264, 640, 480, kEncodeH264) == kOk && h264 && g_opened.size() == 1,
"an H.264 encode on a host that codes no frame in place refused");
ContextDelete del = {1, 0, &h264};
CHECK(call(kDeleteContexts, &del) == kOk, "DeleteContexts");
g_encodeFlags = RGFX_VIDEO_ENCODE_CAP_IN_PLACE;
}
// AllocatePixelBufferPool gives an encoder's pools of kinds 0xe and 0x1b: a buffer of the product
@@ -2003,6 +2076,284 @@ void checkEncodeFrames()
g_encodeRates = 1u << RGFX_VIDEO_RATE_CQP | 1u << RGFX_VIDEO_RATE_VBR;
}
// An HEVC encode command's parameters as the HEVC encoder plug-in's Intel driver class fills
// them, as far as the driver reads and writes them: the source surface (P+0x10), the NAL unit type
// the plug-in chose (P+0x33c), its slice QP (P+0x3d8), and the words the access unit's length is
// published as (P+0x3a0, P+0x3a8), which the plug-in zeroes before each encode.
struct HevcEncode {
uint8_t parameters[0x800] = {};
HevcEncode(IOSurfaceRef source, uint32_t nalType, uint32_t qp, uint32_t poc)
{
std::memcpy(parameters + 0x4, &poc, 4);
std::memcpy(parameters + 0x10, &source, 8);
std::memcpy(parameters + 0x33c, &nalType, 4);
std::memcpy(parameters + 0x3d8, &qp, 4);
}
uint64_t begin() const { return u64(parameters + 0x3a0); }
uint64_t size() const { return u64(parameters + 0x3a8) - begin(); }
static uint64_t u64(const uint8_t *at)
{
uint64_t v;
std::memcpy(&v, at, 8);
return v;
}
};
// Schedules `e` on `context`: Schedule's answer, its token in `token`.
uint64_t scheduleHevcEncode(void *context, const HevcEncode &e, void **token)
{
Command c = {};
c.function_id = kFunctionEncode;
c.sub_id = kEncodeHevc;
c.context = context;
c.parameters = e.parameters;
const Command *list[1] = {&c};
void *tokens[1] = {};
CommandList cl = {1, 0, list};
TokenList tl = {1, 0, tokens};
const uint64_t answer = call(kSchedule, &cl, &tl);
*token = tokens[0];
return answer;
}
// An HEVC encode is sent with the settings the source and the plug-in's choices give, and
// published where the plug-in reads it as it is queried done:
// - the settings: the source's size, Main of NV12 for a '420v' or '420f' source, its range, the
// plug-in's slice QP as a constant QP, no keyframes of the host's own; an IRAP NAL unit type
// (BLA, IDR, CRA) forces a keyframe, another does not; the frames count up; the access unit
// takes at most half the bitstream pool's buffer;
// - the access unit lands at the start of the buffer, each NAL unit after a 4-byte start code: a
// 3-byte start code made 4, trailing zero bytes left out, and the NAL units the plug-in drops
// (an access unit delimiter, SEI) left out; its length is published as the words at +0x3a0 (0)
// and +0x3a8;
// - a frame the host failed, an access unit of no slice segment, or one past the buffer, publishes
// a length of 0 and fails the context's next schedule, sending nothing; the schedule after it
// goes on;
// - an 'x420' source is sent as Main 10 of P010 and an 'xf20' one as Main 10 at full range; a
// source of another format (BGRA) is not sent.
void checkHevcEncodeFrames()
{
g_hostEncodes = true;
g_encodeRates = 1u << RGFX_VIDEO_RATE_CQP;
g_encodes.clear();
g_encodeWork.clear();
constexpr uint32_t kBuffer = 0x1000;
const uint64_t bufferAt = allocate(g_driver, 0, kBuffer);
CHECK(bufferAt != 0, "the bitstream buffer refused");
const uint8_t *buffer = (const uint8_t *)bufferAt;
IOSurfaceRef source = canvas(640, 480, '420v');
void *context = nullptr;
CHECK(makeEncode(&context, 640, 480, kEncodeHevc) == kOk, "a create of one HEVC encode");
// An IDR access unit as a host writes one: an access unit delimiter, then VPS, SPS and PPS,
// an SEI and the IDR slice; the SPS after a 3-byte start code, trailing zero bytes at the end.
const std::vector<uint8_t> aud = {0x46, 0x01, 0x10}, vps = {0x40, 0x01, 0x0c, 0x01, 0xff},
sps = {0x42, 0x01, 0x01, 0x01, 0x60, 0x03},
pps = {0x44, 0x01, 0xc1, 0x72}, sei = {0x4e, 0x01, 0x05, 0x02, 0x80},
idr = {0x28, 0x01, 0xaf, 0x13, 0x77, 0x03, 0x11},
trail = {0x02, 0x01, 0xd0, 0x2a, 0x05};
auto unit = [](std::vector<uint8_t> &au, const std::vector<uint8_t> &nal, bool four) {
const uint8_t code[4] = {0, 0, 0, 1};
au.insert(au.end(), four ? code : code + 1, code + 4);
au.insert(au.end(), nal.begin(), nal.end());
};
g_accessUnit.clear();
unit(g_accessUnit, aud, true);
unit(g_accessUnit, vps, true);
unit(g_accessUnit, sps, false);
unit(g_accessUnit, pps, true);
unit(g_accessUnit, sei, true);
unit(g_accessUnit, idr, true);
g_accessUnit.insert(g_accessUnit.end(), {0, 0});
std::vector<uint8_t> want;
for (const auto *nal : {&vps, &sps, &pps, &idr})
unit(want, *nal, true);
void *token = nullptr;
HevcEncode first(source, 20, 24, 0);
CHECK(scheduleHevcEncode(context, first, &token) == kOk && token, "an IDR frame not scheduled");
CHECK(g_encodes.size() == 1, "%zu encodes sent", g_encodes.size());
const SentEncode &sent = g_encodes[0];
const RgfxVideoEncodeSettings &st = sent.settings;
CHECK(sent.surface == IOSurfaceGetID(source) && sent.frameIndex == 0 && sent.forceKeyframe &&
sent.capacity == kBuffer / 2,
"the IDR frame's encode: surface %u, frame %llu, keyframe %d, capacity %llu", sent.surface,
(unsigned long long)sent.frameIndex, sent.forceKeyframe,
(unsigned long long)sent.capacity);
CHECK(st.width == 640 && st.height == 480 && st.format == RGFX_VIDEO_FORMAT_NV12 &&
st.profile == RGFX_VIDEO_HEVC_MAIN && st.level == 0 &&
st.rate_control == RGFX_VIDEO_RATE_CQP && st.qp_i == 24 && st.qp_p == 24 &&
st.qp_b == 24 && st.key_frame_interval == UINT32_MAX && st.full_range == 0,
"the IDR frame's settings: profile %#x level %u rate %u qp %u keys %u range %u",
st.profile, st.level, st.rate_control, st.qp_i, st.key_frame_interval, st.full_range);
CHECK(queryEncode(token) == kQueryDone, "the IDR frame not done");
CHECK(first.begin() == 0 && first.size() == want.size() &&
std::memcmp(buffer, want.data(), want.size()) == 0,
"the IDR frame's access unit: %llu bytes from %llu", (unsigned long long)first.size(),
(unsigned long long)first.begin());
// A TRAIL_R frame of another QP, after a 3-byte start code.
g_accessUnit.clear();
unit(g_accessUnit, trail, false);
HevcEncode p(source, 1, 31, 1);
CHECK(scheduleHevcEncode(context, p, &token) == kOk, "a P frame not scheduled");
CHECK(g_encodes.size() == 2 && g_encodes[1].frameIndex == 1 && !g_encodes[1].forceKeyframe &&
g_encodes[1].settings.qp_p == 31,
"the P frame's encode");
CHECK(queryEncode(token) == kQueryDone && p.size() == trail.size() + 4 && buffer[3] == 1 &&
std::memcmp(buffer + 4, trail.data(), trail.size()) == 0,
"the P frame's access unit: %llu bytes", (unsigned long long)p.size());
// A CRA picture is a keyframe; a QP past 51 is sent as 51.
HevcEncode cra(source, 21, 60, 2);
CHECK(scheduleHevcEncode(context, cra, &token) == kOk && g_encodes.back().forceKeyframe &&
g_encodes.back().settings.qp_i == 51,
"a CRA frame's encode");
CHECK(queryEncode(token) == kQueryDone, "the CRA frame not done");
// A frame the host failed publishes no access unit, and fails the next schedule.
g_encodeStatus = RGFX_VIDEO_ENCODE_FAILED;
HevcEncode failed(source, 1, 31, 3);
CHECK(scheduleHevcEncode(context, failed, &token) == kOk, "the failing frame not scheduled");
g_encodeStatus = RGFX_VIDEO_ENCODE_OK;
CHECK(queryEncode(token) == kQueryDone && failed.size() == 0, "the failed frame published");
const size_t before = g_encodes.size();
HevcEncode after(source, 1, 31, 4);
CHECK(scheduleHevcEncode(context, after, &token) == kNotSent && g_encodes.size() == before,
"the frame after a failed one sent");
CHECK(scheduleHevcEncode(context, after, &token) == kOk, "the next frame not scheduled");
CHECK(queryEncode(token) == kQueryDone && after.size() == trail.size() + 4,
"the next frame not published");
// An access unit of no slice segment, and one past the buffer, publish none.
g_accessUnit.clear();
unit(g_accessUnit, sei, true);
HevcEncode noSlice(source, 1, 31, 5);
CHECK(scheduleHevcEncode(context, noSlice, &token) == kOk, "the frame of no slice not scheduled");
CHECK(queryEncode(token) == kQueryDone && noSlice.size() == 0,
"an access unit of no slice published");
CHECK(scheduleHevcEncode(context, after, &token) == kNotSent,
"the frame after one of no slice sent");
g_accessUnit.clear();
unit(g_accessUnit, std::vector<uint8_t>(kBuffer, 0x26), true);
HevcEncode past(source, 1, 31, 6);
CHECK(scheduleHevcEncode(context, past, &token) == kOk, "the frame past the buffer not scheduled");
CHECK(queryEncode(token) == kQueryDone && past.size() == 0,
"an access unit past the buffer published");
CHECK(scheduleHevcEncode(context, after, &token) == kNotSent,
"the frame after one past the buffer sent");
// A full-range source is sent of its range, a 10-bit one as Main 10 of P010; a BGRA one is
// not sent.
g_accessUnit.clear();
unit(g_accessUnit, trail, true);
IOSurfaceRef full = canvas(640, 480, '420f'), deep = canvas(640, 480, 'x420'),
deepFull = canvas(640, 480, 'xf20'), bgra = canvas(640, 480, 'BGRA');
const struct {
IOSurfaceRef source;
uint32_t profile, format, fullRange;
} sources[] = {
{full, RGFX_VIDEO_HEVC_MAIN, RGFX_VIDEO_FORMAT_NV12, 1},
{deep, RGFX_VIDEO_HEVC_MAIN_10, RGFX_VIDEO_FORMAT_P010, 0},
{deepFull, RGFX_VIDEO_HEVC_MAIN_10, RGFX_VIDEO_FORMAT_P010, 1},
};
for (const auto &c : sources) {
HevcEncode frame(c.source, 1, 31, 7);
CHECK(scheduleHevcEncode(context, frame, &token) == kOk, "a frame of format %#x not sent",
(unsigned)IOSurfaceGetPixelFormat(c.source));
const RgfxVideoEncodeSettings &fs = g_encodes.back().settings;
CHECK(fs.profile == c.profile && fs.format == c.format && fs.full_range == c.fullRange &&
fs.qp_p == 31,
"a frame of format %#x: profile %#x format %u range %u",
(unsigned)IOSurfaceGetPixelFormat(c.source), fs.profile, fs.format, fs.full_range);
CHECK(queryEncode(token) == kQueryDone, "a frame of format %#x not done",
(unsigned)IOSurfaceGetPixelFormat(c.source));
}
const size_t sentBefore = g_encodes.size();
HevcEncode refused(bgra, 1, 31, 8);
CHECK(scheduleHevcEncode(context, refused, &token) == kNotSent &&
g_encodes.size() == sentBefore,
"a BGRA frame sent");
ContextDelete del = {1, 0, &context};
CHECK(call(kDeleteContexts, &del) == kOk, "DeleteContexts");
CHECK(callOn(g_driver, kFreeBitstreamBufferPool, (const void *)0) == kOk,
"FreeBitstreamBufferPool");
for (IOSurfaceRef s : {source, full, deep, deepFull, bgra})
CFRelease(s);
g_accessUnit.clear();
g_encodeRates = kCqpVbr;
}
// The plug-in's frame coded again (hevcCodesAgain): a command of the last frame's order count and
// source, of a P picture, is sent in place of it (RGFX_VIDEO_ENCODE_IN_PLACE), with its frame
// index, at its own QP. Not in place: a new order count from the same surface, the same order
// count from another surface, and a keyframe, which is sent as a new frame: an IDR picture coded
// again right after itself, and each of keyframes from one reused surface, of order count 0 each.
// Both of two retries in a row are in place, and so is the retry of the P picture right after an
// IDR picture. After a frame the host failed, the next frame sent is a new one, whatever its order
// count and surface.
void checkHevcCodesAgain()
{
g_hostEncodes = true;
g_encodeRates = 1u << RGFX_VIDEO_RATE_CQP;
g_encodes.clear();
g_encodeWork.clear();
CHECK(allocate(g_driver, 0, 0x1000) != 0, "the bitstream buffer refused");
IOSurfaceRef a = canvas(640, 480, '420v'), b = canvas(640, 480, '420v');
void *context = nullptr;
CHECK(makeEncode(&context, 640, 480, kEncodeHevc) == kOk, "a create of one HEVC encode");
const uint8_t trail[] = {0, 0, 0, 1, 0x02, 0x01, 0xd0, 0x2a, 0x05};
g_accessUnit.assign(trail, trail + sizeof trail);
constexpr uint32_t kIdr = 19, kTrail = 1;
// Sends a frame and has it done: the encode sent for it.
auto send = [&](IOSurfaceRef source, uint32_t nal, uint32_t qp, uint32_t poc) {
HevcEncode e(source, nal, qp, poc);
void *token = nullptr;
CHECK(scheduleHevcEncode(context, e, &token) == kOk && token,
"a frame of order count %u not scheduled", poc);
CHECK(queryEncode(token) == kQueryDone && e.size() == sizeof trail,
"a frame of order count %u not published", poc);
return g_encodes.back();
};
auto is = [&](const SentEncode &e, bool inPlace, uint64_t index, bool key, uint32_t qp,
const char *what) {
CHECK(e.inPlace == inPlace && e.frameIndex == index && e.forceKeyframe == key &&
e.settings.qp_i == qp,
"%s: in place %d, frame %llu, keyframe %d, QP %u", what, e.inPlace,
(unsigned long long)e.frameIndex, e.forceKeyframe, e.settings.qp_i);
};
// An IDR picture, and the same again at a higher QP right after it: a new IDR picture.
is(send(a, kIdr, 30, 0), false, 0, true, 30, "the IDR picture");
is(send(a, kIdr, 33, 0), false, 1, true, 33, "the IDR picture again");
// The P picture after it, and that again: in place, of its index.
is(send(a, kTrail, 30, 1), false, 2, false, 30, "the P picture after the IDR picture");
is(send(a, kTrail, 33, 1), true, 2, false, 33, "the P picture after the IDR picture again");
// A new order count from the same surface: a new frame.
is(send(a, kTrail, 30, 2), false, 3, false, 30, "a new order count from the same surface");
// That frame again twice: in place both times, of its index.
is(send(a, kTrail, 33, 2), true, 3, false, 33, "a P picture again");
is(send(a, kTrail, 36, 2), true, 3, false, 36, "a P picture again, twice");
// The same order count from another surface: a new frame.
is(send(b, kTrail, 30, 2), false, 4, false, 30, "the same order count from another surface");
is(send(b, kTrail, 30, 3), false, 5, false, 30, "the next P picture");
// Keyframes from one reused surface, each of order count 0: each a new frame.
for (uint64_t n = 6; n < 9; n++)
is(send(a, kIdr, 30, 0), false, n, true, 30, "a keyframe from one surface");
// A frame the host fails, then the same frame: its schedule fails, and the one after it is a
// new frame.
g_encodeStatus = RGFX_VIDEO_ENCODE_FAILED;
HevcEncode failed(a, kTrail, 30, 1);
void *token = nullptr;
CHECK(scheduleHevcEncode(context, failed, &token) == kOk, "the failing frame not scheduled");
g_encodeStatus = RGFX_VIDEO_ENCODE_OK;
CHECK(queryEncode(token) == kQueryDone && failed.size() == 0, "the failed frame published");
HevcEncode again(a, kTrail, 33, 1);
CHECK(scheduleHevcEncode(context, again, &token) == kNotSent, "the frame after a failed one sent");
is(send(a, kTrail, 33, 1), false, 10, false, 33, "the frame after a failed one's refusal");
ContextDelete del = {1, 0, &context};
CHECK(call(kDeleteContexts, &del) == kOk, "DeleteContexts");
CHECK(callOn(g_driver, kFreeBitstreamBufferPool, (const void *)0) == kOk,
"FreeBitstreamBufferPool");
CFRelease(a);
CFRelease(b);
g_accessUnit.clear();
g_encodeRates = kCqpVbr;
}
// Runs a check, naming it first where VIDEO_TESTS_TRACE is set, so a crash names its check.
#define RUN(check) \
do { \
@@ -2013,7 +2364,7 @@ void checkEncodeFrames()
int main(int argc, char **argv)
{
if (argc == 5 && std::strcmp(argv[1], "listed") == 0)
if (argc == 8 && std::strcmp(argv[1], "listed") == 0)
return listedChild(argv);
g_self = argv[0];
RUN(checkEncodeListedApart);
@@ -2042,6 +2393,8 @@ int main(int argc, char **argv)
RUN(checkEncodeCreate);
RUN(checkPixelPools);
RUN(checkEncodeFrames);
RUN(checkHevcEncodeFrames);
RUN(checkHevcCodesAgain);
std::printf("video_driver_tests: %d checks passed\n", g_checks);
return 0;
}
+67
View File
@@ -225,6 +225,7 @@ void registerAccelerator(RgfxAccelerator *accelerator, const char *when)
{
IOLog("RgfxAccelerator: the bundle is at %s%s: registered\n", bundle.paths.executable, when);
accelerator->registerService(kIOServiceSynchronous);
accelerator->publishHevcEncoder();
IOLockLock(bundle.lock);
bundle.state = kBundleRegistered;
IOLockUnlock(bundle.lock);
@@ -1007,6 +1008,9 @@ void RgfxAccelerator::publishVideoCodecs()
OSSafeReleaseNULL(rating);
OSSafeReleaseNULL(h264);
}
RgfxHevcEncode hevcEncode;
if (rgfxHevcEncode(caps, &hevcEncode))
hevcEncodeLevel = hevcEncode.maxLevel;
RgfxHevcDecode hevc;
if (!rgfxHevcDecode(caps, &hevc))
return;
@@ -1037,6 +1041,69 @@ void RgfxAccelerator::publishVideoCodecs()
OSSafeReleaseNULL(profiles);
}
// The guest's HEVC encoder plug-in (AppleGVAHEVCEncoder) finds a GPU encoder on an x86-64 Mac by
// name alone: the last service named IntelAccelerator whose IOGVACodec names an Intel generation
// ("Gen9" picks the driver at AppleIntelSKLGraphicsVADriver.bundle, which RgfxGate links to the
// bundle), with IOGVAHEVCEncode and IOVARendererID on it, and VideoToolbox lists that encoder
// with the capabilities IOGVAHEVCEncodeCapabilities carries. The nub is a plain IOService, a
// child of the accelerator, with no IODVDBundleName, which AppleGVA's own loader skips: no Metal
// device, no framebuffer, and none of AppleGVA's other routes moves to it (their Intel route
// looks only under IGPU@2 or GFX0@2). Main and Main 10, up to the host encoder's level: the two
// profiles the plug-in names, both of which the host encodes where the nub is published
// (rgfxHevcEncode).
void RgfxAccelerator::publishHevcEncoder()
{
const uint32_t level = hevcEncodeLevel;
if (level == 0)
return;
IOService *nub = OSTypeAlloc(IOService);
if (!nub || !nub->init()) {
OSSafeReleaseNULL(nub);
IOLog("RgfxAccelerator: no HEVC encoder: no memory\n");
return;
}
nub->setName("IntelAccelerator");
nub->setProperty("IOGVACodec", "Gen9");
nub->setProperty("IOGVAHEVCEncode", "2");
nub->setProperty("IOVARendererID", kVideoRendererID, kDriverKeyNumberBits);
OSArray *profiles = OSArray::withCapacity(2);
OSDictionary *details = OSDictionary::withCapacity(2);
OSDictionary *capabilities = OSDictionary::withCapacity(4);
OSNumber *maxLevel = OSNumber::withNumber(level, 32);
OSNumber *rating = OSNumber::withNumber(kRgfxHevcEncodeRating, 32);
OSNumber *quality = OSNumber::withNumber(kRgfxHevcEncodeQualityRating, 32);
OSNumber *mainProfile = OSNumber::withNumber(1, 32);
OSNumber *main10Profile = OSNumber::withNumber(2, 32);
OSDictionary *profileDetail = OSDictionary::withCapacity(1);
const bool made = profiles && details && capabilities && maxLevel && rating && quality &&
mainProfile && main10Profile && profileDetail &&
profileDetail->setObject("VTMaxEncodeLevel", maxLevel) &&
profiles->setObject(mainProfile) && profiles->setObject(main10Profile) &&
details->setObject("1", profileDetail) &&
details->setObject("2", profileDetail) &&
capabilities->setObject("VTSupportedProfileArray", profiles) &&
capabilities->setObject("VTPerProfileDetails", details) &&
capabilities->setObject("VTRating", rating) &&
capabilities->setObject("VTQualityRating", quality) &&
nub->setProperty("IOGVAHEVCEncodeCapabilities", capabilities);
OSSafeReleaseNULL(profileDetail);
OSSafeReleaseNULL(main10Profile);
OSSafeReleaseNULL(mainProfile);
OSSafeReleaseNULL(quality);
OSSafeReleaseNULL(rating);
OSSafeReleaseNULL(maxLevel);
OSSafeReleaseNULL(capabilities);
OSSafeReleaseNULL(details);
OSSafeReleaseNULL(profiles);
if (made && nub->attach(this)) {
nub->registerService();
IOLog("RgfxAccelerator: HEVC encode, Main and Main 10, level %u\n", level);
} else {
IOLog("RgfxAccelerator: no HEVC encoder: its nub not made\n");
}
nub->release();
}
// A queue's doorbell exits to the host, which may offer the ring's next command buffer to its
// decoder before the write returns: the write holds no lock and leaves interrupts as they are, so
// the CPU takes its IPIs (a TLB shootdown's among them) however long the host takes, and the
+10 -1
View File
@@ -455,6 +455,11 @@ public:
// Whether that framebuffer has started (ReimsGraphics::hasStarted): before, and once its stop
// has begun, the device holds nothing of any context, and no message of one reaches it.
bool framebufferStarted();
// Publishes the nub the guest's HEVC encoder plug-in finds a GPU encoder by
// (RgfxAccelerator.cpp, publishHevcEncoder), where publishVideoCodecs found the host encodes
// HEVC; once the accelerator has registered, so the plug-in finds it only with the bundle,
// and RgfxGate's link to it, in place.
void publishHevcEncoder();
// The bundle (RgfxAccelerator.cpp, "The bundle"): the accelerator registers only once the
// bundle MetalPluginName names is on disk and the framebuffer has started, and opens no user
@@ -758,7 +763,8 @@ private:
void nameProviderForVideo();
// Publishes the host's hardware video that AppleGVA reads from the accelerator, from the
// video caps the host wrote (RgfxVideoCodecs.hpp): its video driver, H.264 encode and HEVC
// decode, each where the host has it.
// decode, each where the host has it, and the level of its HEVC encode, which
// publishHevcEncoder publishes.
void publishVideoCodecs();
// Has IOSurface align the bytes per row it works out for a surface as the host's GPU takes
// such rows in place (RgfxSurfaceRows.hpp; IOSurface's own where the host asks no more), and
@@ -826,6 +832,9 @@ private:
bool reviveSurfaceBlock(RgfxSurfaceEntry &e, OSObject *surface, uint32_t surfaceId);
IOPCIDevice *pci;
// The level of the host's HEVC encoder, which publishVideoCodecs read from its caps, and 0
// where it encodes no HEVC the guest's plug-in can drive (RgfxVideoCodecs.hpp).
uint32_t hevcEncodeLevel = 0;
IOMemoryMap *registerMap;
volatile UInt8 *registers;
IODeviceMemory *region;
+40
View File
@@ -134,4 +134,44 @@ static inline bool rgfxH264Encode(const RgfxVideoCaps &caps)
return false;
}
// The ratings the accelerator's HEVC encoder publishes (IOGVAHEVCEncodeCapabilities): as for
// H.264 encode, an AMD Mac's.
constexpr uint32_t kRgfxHevcEncodeRating = 350;
constexpr uint32_t kRgfxHevcEncodeQualityRating = 50;
// What the host's HEVC encoder offers the guest: Main and Main 10, up to its level.
struct RgfxHevcEncode {
uint32_t maxLevel;
};
// Whether `caps` lists an HEVC encoder the guest's HEVC encoder plug-in can drive, and its level
// in `out`: an encode entry of Main from NV12 and Main 10 from P010, with a constant QP among its
// rate controls, since the plug-in's rate control picks each frame's QP and the driver codes at
// it (guest/bundle/src/RgfxVideoDriver.cpp), and that codes a frame in place of the last one
// (RGFX_VIDEO_ENCODE_CAP_IN_PLACE), since the plug-in codes a frame again at a higher QP where it
// came out over its data rate limit. Both profiles, as the plug-in's session may be of either
// and the driver learns which only from its first frame's source, past its create. False for an
// older host's caps, for a host with no video arm or no such encoder, and on an arm64 guest.
static inline bool rgfxHevcEncode(const RgfxVideoCaps &caps, RgfxHevcEncode *out)
{
if (!kRgfxGuestVideoDriver || caps.version < RGFX_VIDEO_CAPS_VERSION)
return false;
const uint32_t n = caps.codec_count < RGFX_VIDEO_CAPS_CODECS ? caps.codec_count
: RGFX_VIDEO_CAPS_CODECS;
for (uint32_t i = 0; i < n; i++) {
const RgfxVideoCodecCaps &c = caps.codecs[i];
if (c.codec != RGFX_VIDEO_CODEC_HEVC || c.direction != RGFX_VIDEO_ENCODE)
continue;
const uint32_t profiles = RGFX_VIDEO_HEVC_MAIN | RGFX_VIDEO_HEVC_MAIN_10;
const uint32_t formats = RGFX_VIDEO_FORMAT_NV12 | RGFX_VIDEO_FORMAT_P010;
if ((c.profiles & profiles) != profiles || (c.formats & formats) != formats ||
!(caps.encode[i].rate_controls & (1u << RGFX_VIDEO_RATE_CQP)) ||
!(caps.encode[i].flags & RGFX_VIDEO_ENCODE_CAP_IN_PLACE))
return false;
out->maxLevel = c.max_level;
return true;
}
return false;
}
#endif
+92 -5
View File
@@ -1,9 +1,10 @@
// video_codecs_test: what the accelerator publishes of the host's video: its video driver, HEVC
// decode and H.264 encode (RgfxVideoCodecs.hpp). Built with each architecture's rules (the
// decode, H.264 encode and HEVC encode (RgfxVideoCodecs.hpp). Built with each architecture's rules (the
// Makefile's video_codecs_test, and video_codecs_arm64_test with RGFX_GUEST_ARM64=1): the x86-64
// kext publishes what the host's caps list, the arm64e kext nothing.
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include "RgfxVideoCodecs.hpp"
@@ -121,10 +122,89 @@ static void x86Rules()
RgfxVideoCaps uncounted = alone;
uncounted.codec_count = 0;
CHECK(!rgfxH264Encode(uncounted));
// HEVC encode is published where the caps list an HEVC encoder of Main from NV12 and Main 10
// from P010 with a constant QP among its rate controls, that codes a frame in place of the
// last, up to its level: after the decoders, or alone.
RgfxVideoCaps hevc = caps(RGFX_VIDEO_HEVC_MAIN, 153);
hevc.codec_count = 3;
hevc.codecs[2] = hevc.codecs[1];
hevc.codecs[2].direction = RGFX_VIDEO_ENCODE;
hevc.codecs[2].profiles = RGFX_VIDEO_HEVC_MAIN | RGFX_VIDEO_HEVC_MAIN_10;
hevc.codecs[2].formats = RGFX_VIDEO_FORMAT_NV12 | RGFX_VIDEO_FORMAT_P010;
hevc.codecs[2].max_level = 150;
hevc.encode[2].rate_controls = 1u << RGFX_VIDEO_RATE_CQP | 1u << RGFX_VIDEO_RATE_VBR;
hevc.encode[2].flags = RGFX_VIDEO_ENCODE_CAP_IN_PLACE;
RgfxHevcEncode e = {};
CHECK(rgfxHevcEncode(hevc, &e) && e.maxLevel == 150);
RgfxVideoCaps hevcAlone = {};
hevcAlone.version = RGFX_VIDEO_CAPS_VERSION;
hevcAlone.codec_count = 1;
hevcAlone.codecs[0] = hevc.codecs[2];
hevcAlone.encode[0] = hevc.encode[2];
e = {};
CHECK(rgfxHevcEncode(hevcAlone, &e) && e.maxLevel == 150);
// Not where they list none: decoders alone, an H.264 encoder, an HEVC encoder of Main alone
// or Main 10 alone, of no P010 or no NV12, of no constant QP or of no rate control, one that
// codes no frame in place, an older host's caps, an entry past the count; and the answer is
// left as it was.
e = {};
CHECK(!rgfxHevcEncode(caps(RGFX_VIDEO_HEVC_MAIN, 153), &e));
CHECK(!rgfxHevcEncode(alone, &e));
RgfxVideoCaps mainOnly = hevcAlone;
mainOnly.codecs[0].profiles = RGFX_VIDEO_HEVC_MAIN;
CHECK(!rgfxHevcEncode(mainOnly, &e));
RgfxVideoCaps main10 = hevcAlone;
main10.codecs[0].profiles = RGFX_VIDEO_HEVC_MAIN_10;
CHECK(!rgfxHevcEncode(main10, &e));
RgfxVideoCaps noP010 = hevcAlone;
noP010.codecs[0].formats = RGFX_VIDEO_FORMAT_NV12;
CHECK(!rgfxHevcEncode(noP010, &e));
RgfxVideoCaps noNv12 = hevcAlone;
noNv12.codecs[0].formats = RGFX_VIDEO_FORMAT_P010;
CHECK(!rgfxHevcEncode(noNv12, &e));
RgfxVideoCaps bitrateOnly = hevcAlone;
bitrateOnly.encode[0].rate_controls = 1u << RGFX_VIDEO_RATE_VBR | 1u << RGFX_VIDEO_RATE_CBR;
CHECK(!rgfxHevcEncode(bitrateOnly, &e));
RgfxVideoCaps hevcNoRate = hevcAlone;
hevcNoRate.encode[0].rate_controls = 0;
CHECK(!rgfxHevcEncode(hevcNoRate, &e));
RgfxVideoCaps notInPlace = hevcAlone;
notInPlace.encode[0].flags = 0;
CHECK(!rgfxHevcEncode(notInPlace, &e));
RgfxVideoCaps hevcOld = hevcAlone;
hevcOld.version = 0;
CHECK(!rgfxHevcEncode(hevcOld, &e));
RgfxVideoCaps hevcUncounted = hevcAlone;
hevcUncounted.codec_count = 0;
CHECK(!rgfxHevcEncode(hevcUncounted, &e));
CHECK(e.maxLevel == 0);
// The pairing with a host that codes no frame in place: the caps of both decoders and both
// encoders, the HEVC one without the flag, publish no HEVC encode, and the H.264 encode and
// both decoders as before; with the flag, the HEVC encode too, and the rest the same.
RgfxVideoCaps every = caps(RGFX_VIDEO_HEVC_MAIN | RGFX_VIDEO_HEVC_MAIN_10, 153);
every.codec_count = 4;
every.codecs[2] = encoder.codecs[2];
every.encode[2] = encoder.encode[2];
every.codecs[3] = hevc.codecs[2];
every.encode[3] = hevc.encode[2];
every.encode[3].flags = 0;
RgfxHevcDecode decode = {};
CHECK(!rgfxHevcEncode(every, &e));
CHECK(rgfxH264Encode(every) && rgfxDecodesVideo(every) && rgfxHevcDecode(every, &decode));
const RgfxHevcDecode without = decode;
every.encode[3].flags = RGFX_VIDEO_ENCODE_CAP_IN_PLACE;
decode = {};
CHECK(rgfxHevcEncode(every, &e) && e.maxLevel == 150);
CHECK(rgfxH264Encode(every) && rgfxDecodesVideo(every) && rgfxHevcDecode(every, &decode));
CHECK(memcmp(&decode, &without, sizeof decode) == 0);
// The flag on the H.264 encoder changes nothing of its publish.
RgfxVideoCaps h264InPlace = alone;
h264InPlace.encode[0].flags = RGFX_VIDEO_ENCODE_CAP_IN_PLACE;
CHECK(rgfxH264Encode(h264InPlace));
}
// The arm64e kext's rules: no video driver, no HEVC decode and no H.264 encode, whatever the caps
// list.
// The arm64e kext's rules: no video driver, no HEVC decode, no H.264 encode and no HEVC encode,
// whatever the caps list.
static void arm64Rules()
{
CHECK(!kRgfxGuestVideoDriver);
@@ -155,8 +235,15 @@ static void arm64Rules()
alone.codecs[0] = encoder.codecs[2];
alone.encode[0] = encoder.encode[2];
CHECK(!rgfxH264Encode(alone));
// Nothing written to the answer.
CHECK(d.count == 0 && d.maxLevel == 0);
// An HEVC encoder of Main and Main 10 with a constant QP: no HEVC encode.
RgfxVideoCaps hevc = alone;
hevc.codecs[0].codec = RGFX_VIDEO_CODEC_HEVC;
hevc.codecs[0].profiles = RGFX_VIDEO_HEVC_MAIN | RGFX_VIDEO_HEVC_MAIN_10;
hevc.codecs[0].formats = RGFX_VIDEO_FORMAT_NV12 | RGFX_VIDEO_FORMAT_P010;
RgfxHevcEncode e = {};
CHECK(!rgfxHevcEncode(hevc, &e));
// Nothing written to the answers.
CHECK(d.count == 0 && d.maxLevel == 0 && e.maxLevel == 0);
}
int main()
+4 -1
View File
@@ -6,7 +6,8 @@
#
# make BUNDLE_DIR=<signed reims-graphics.bundle dir> build/RgfxGate.kext
# make test native tests of the matching and preference logic,
# the tree removal, the pass's decisions, the AVX-512
# the tree removal, the HEVC driver link, the pass's
# decisions, the AVX-512
# state copy, and when the payload is made again
# make sigproof build/xstate_sigproof-x86_64, the guest's own proof
# of what a thread keeps across signals and thread
@@ -131,6 +132,8 @@ test: sigproof
$(BUILD)/obj/gva_pref_test
xcrun --sdk macosx clang++ -std=c++17 -Wall -Wextra -Werror -Isrc tests/tree_test.cpp -o $(BUILD)/obj/tree_test
$(BUILD)/obj/tree_test
xcrun --sdk macosx clang++ -std=c++17 -Wall -Wextra -Werror -Isrc tests/alias_test.cpp -o $(BUILD)/obj/alias_test
$(BUILD)/obj/alias_test
xcrun --sdk macosx clang++ -std=c++17 -Wall -Wextra -Werror -Isrc tests/pass_test.cpp -o $(BUILD)/obj/pass_test
$(BUILD)/obj/pass_test
xcrun --sdk macosx clang++ -std=c++17 -Wall -Wextra -Werror -Isrc tests/xstate_test.cpp -o $(BUILD)/obj/xstate_test
+83
View File
@@ -46,6 +46,7 @@
#include "RgfxGateVnop.hpp"
#include "rgfx_match.h"
#include "rgfx_pass.h"
#include "rgfx_alias.h"
#include "rgfx_tree.h"
namespace rgfxgate {
@@ -571,6 +572,77 @@ static bool installBundle(vfs_context_t ctx) {
return ok;
}
#if !defined(__arm64e__)
// The HEVC encoder plug-in's driver path, which RgfxGate links to the bundle's
// executable (rgfx_alias.h): AppleGVAHEVCEncoder loads the driver its Intel
// nub's IOGVACodec names ("Gen9", the accelerator's publishHevcEncoder) from
// /Library/GPUBundles before /System/Library/Extensions, and macOS ships no
// driver in /Library/GPUBundles. x86-64 only: an arm64 guest takes no GPU video
// driver.
extern "C" int VNOP_LINK(vnode_t, vnode_t, struct componentname *, vfs_context_t);
static const char kHevcDriverBundle[] = "/Library/GPUBundles/AppleIntelSKLGraphicsVADriver.bundle";
static const char kHevcDriverContents[] =
"/Library/GPUBundles/AppleIntelSKLGraphicsVADriver.bundle/Contents";
static const char kHevcDriverMacOS[] =
"/Library/GPUBundles/AppleIntelSKLGraphicsVADriver.bundle/Contents/MacOS";
static const char kHevcDriverExec[] =
"/Library/GPUBundles/AppleIntelSKLGraphicsVADriver.bundle/Contents/MacOS/"
"AppleIntelSKLGraphicsVADriver";
// The file system rgfx_alias_update works on: lookups that do not follow a
// final symbolic link, and each write below the MAC layer, as the install's.
struct KernelAlias {
vfs_context_t ctx;
bool file_id(const char *path, uint64_t *id) {
vnode_t vp = nullptr;
if (vnode_lookup(path, VNODE_LOOKUP_NOFOLLOW, &vp, ctx) != 0)
return false;
struct vnode_attr va;
VATTR_INIT(&va);
VATTR_WANTED(&va, va_fileid);
const bool ok = vnode_getattr(vp, &va, ctx) == 0 && VATTR_IS_SUPPORTED(&va, va_fileid);
if (ok)
*id = va.va_fileid;
vnode_put(vp);
return ok;
}
void remove(const char *path) {
clearRootless(path, ctx);
removeFile(path, ctx);
}
bool ensure_dir(const char *path) { return ensureDir(path, ctx); }
bool link(const char *target, const char *path) {
vnode_t vp = nullptr;
if (vnode_lookup(target, VNODE_LOOKUP_NOFOLLOW, &vp, ctx) != 0)
return false;
char leaf[256];
struct componentname cn;
int err = -1;
vnode_t dvp = parentAndLeaf(path, CREATE, &cn, leaf, sizeof(leaf), ctx);
if (dvp != nullptr) {
err = VNOP_LINK(vp, dvp, &cn, ctx);
vnode_put(dvp);
}
vnode_put(vp);
return err == 0;
}
void tag(const char *path) { tagRootless(path, ctx); }
};
// Keeps the HEVC encoder plug-in's driver path a hard link to the installed
// executable (rgfx_alias.h), logging what it did.
static void linkHevcDriver(vfs_context_t ctx) {
char exec[1024];
joinPath(exec, sizeof(exec), kBundlePath, kExecRel);
static const char *const dirs[] = {kHevcDriverBundle, kHevcDriverContents, kHevcDriverMacOS};
KernelAlias fs{ctx};
const RgfxAliasResult r = rgfx_alias_update(fs, exec, dirs, 3, kHevcDriverExec);
static const char *const said[] = {"current", "linked", "no executable", "FAILED"};
graft_client_log(kClientID, "HEVC driver link %s: %s", kHevcDriverExec, said[r]);
}
#endif
// Records the install's outcome as RgfxGate's Graft client state
// (GraftClient.ai.aneesiqbal.RgfxGate, "<state>: <reason>"), so a refusal is
// visible there and never hidden behind the install-done flag, which only says
@@ -670,6 +742,13 @@ static void doInstall() {
bool needWrite = installNeeded(ctx);
bool tagged = bundleTagged(ctx);
if (!needWrite && tagged) {
#if !defined(__arm64e__)
gInstallThread = current_thread();
gInstalling = true;
linkHevcDriver(ctx);
gInstalling = false;
gInstallThread = nullptr;
#endif
graft_client_log(kClientID, "bundle current and tagged; no install");
recordInstallState("present", "bundle already installed and tagged");
vfs_context_rele(ctx);
@@ -693,6 +772,10 @@ static void doInstall() {
tagRootless(kContainerPath, ctx);
ok = true;
}
#if !defined(__arm64e__)
if (ok)
linkHevcDriver(ctx);
#endif
gInstalling = false;
gInstallThread = nullptr;
+59
View File
@@ -0,0 +1,59 @@
// The link the guest's HEVC encoder plug-in loads the bundle's executable by
// (RgfxGateInstall.cpp's linkHevcDriver). AppleGVAHEVCEncoder, finding the
// accelerator's IntelAccelerator nub, dlopens a fixed path under
// /Library/GPUBundles, which must pass its trust check: the link is a hard link
// to the installed executable, one inode, so it carries the executable's
// signature and rootless tag, and dyld maps one image whichever path a process
// loads it by. Each install writes the executable as a new inode, so the link
// is made again whenever it names another file than the executable.
//
// No kernel or Graft dependency: the update takes the file system as a
// parameter, which the kext gives its VNOP calls and the native tests
// (tests/alias_test.cpp) a real directory, so the tests run the exact code the
// kext runs.
#pragma once
#include <stddef.h>
#include <stdint.h>
// What an update did.
enum RgfxAliasResult {
// The link already names the executable's file: nothing changed.
kRgfxAliasCurrent = 0,
// The link was made, after any other file at its path was removed.
kRgfxAliasLinked,
// There is no executable to link to: nothing changed.
kRgfxAliasNoTarget,
// A directory above the link, or the link itself, could not be made.
kRgfxAliasFailed,
};
// Makes `link` a hard link to `target` where it names another file or none:
// the file at `link` (not followed, so a symbolic link is replaced itself) is
// removed, the directories `dirs` (`ndirs` of them, outermost first, each
// holding the next and the last holding `link`) are made where absent, the link
// is made, and then the directories are tagged, deepest first, as the
// bundle's tree is. `Fs` answers file_id(path, &id) (a lookup that does not
// follow a final symbolic link; false where nothing is there), and does
// remove(path), ensure_dir(path) (true where a directory is there after),
// link(target, path) (true where made) and tag(path).
template <typename Fs>
static inline RgfxAliasResult rgfx_alias_update(Fs &fs, const char *target,
const char *const *dirs, size_t ndirs,
const char *link) {
uint64_t want = 0, have = 0;
if (!fs.file_id(target, &want))
return kRgfxAliasNoTarget;
if (fs.file_id(link, &have)) {
if (have == want)
return kRgfxAliasCurrent;
fs.remove(link);
}
for (size_t i = 0; i < ndirs; i++)
if (!fs.ensure_dir(dirs[i]))
return kRgfxAliasFailed;
if (!fs.link(target, link))
return kRgfxAliasFailed;
for (size_t i = ndirs; i-- > 0;)
fs.tag(dirs[i]);
return kRgfxAliasLinked;
}
+173
View File
@@ -0,0 +1,173 @@
// Native tests of the link the boot-time install keeps from the HEVC encoder
// plug-in's driver path to the bundle's executable (src/rgfx_alias.h), over
// real files in a scratch directory, with the file system calls a user process
// has in place of the kext's VNOP calls. Build and run with `make test`.
#include "rgfx_alias.h"
#include <cassert>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <fcntl.h>
#include <string>
#include <sys/stat.h>
#include <unistd.h>
namespace {
// The file system as the update sees it, through lstat, unlink, mkdir and
// link. Counts the removals and tags it is asked for.
struct PosixFs {
unsigned removes = 0;
unsigned tags = 0;
bool file_id(const char *path, uint64_t *id) {
struct stat st;
if (lstat(path, &st) != 0)
return false;
*id = (uint64_t)st.st_ino;
return true;
}
void remove(const char *path) {
removes++;
unlink(path);
}
bool ensure_dir(const char *path) {
struct stat st;
if (mkdir(path, 0755) == 0)
return true;
return lstat(path, &st) == 0 && S_ISDIR(st.st_mode);
}
bool link(const char *target, const char *path) { return ::link(target, path) == 0; }
void tag(const char *) { tags++; }
};
std::string g_root;
std::string at(const char *rel) { return g_root + "/" + rel; }
void writeFile(const std::string &path, const char *bytes) {
const int fd = open(path.c_str(), O_CREAT | O_TRUNC | O_WRONLY, 0644);
assert(fd >= 0);
assert(write(fd, bytes, strlen(bytes)) == (ssize_t)strlen(bytes));
close(fd);
}
// A file written aside and renamed over `path`: a new inode, as each install
// writes the executable.
void replaceFile(const std::string &path, const char *bytes) {
const std::string aside = path + ".new";
writeFile(aside, bytes);
assert(rename(aside.c_str(), path.c_str()) == 0);
}
uint64_t inode(const std::string &path) {
struct stat st;
return lstat(path.c_str(), &st) == 0 ? (uint64_t)st.st_ino : 0;
}
bool isFile(const std::string &path) {
struct stat st;
return lstat(path.c_str(), &st) == 0 && S_ISREG(st.st_mode);
}
struct Paths {
std::string target, bundle, contents, macos, link;
const char *dirs[3];
Paths()
: target(at("reims-graphics")), bundle(at("Driver.bundle")),
contents(at("Driver.bundle/Contents")), macos(at("Driver.bundle/Contents/MacOS")),
link(at("Driver.bundle/Contents/MacOS/Driver")) {
dirs[0] = bundle.c_str();
dirs[1] = contents.c_str();
dirs[2] = macos.c_str();
}
RgfxAliasResult update(PosixFs &fs) const {
return rgfx_alias_update(fs, target.c_str(), dirs, 3, link.c_str());
}
};
// No executable: nothing is made.
void testNoTarget() {
Paths p;
PosixFs fs;
assert(p.update(fs) == kRgfxAliasNoTarget);
assert(inode(p.bundle) == 0 && fs.removes == 0 && fs.tags == 0);
}
// A first update makes the directories and the link, the executable's own
// inode, and tags the directories; a second changes nothing.
void testFirstAndCurrent() {
Paths p;
writeFile(p.target, "v1");
PosixFs fs;
assert(p.update(fs) == kRgfxAliasLinked);
assert(isFile(p.link) && inode(p.link) == inode(p.target));
assert(fs.removes == 0 && fs.tags == 3);
PosixFs again;
assert(p.update(again) == kRgfxAliasCurrent);
assert(again.removes == 0 && again.tags == 0 && inode(p.link) == inode(p.target));
}
// An install writes the executable as a new inode: the link to the old one is
// removed and made again to the new one.
void testNewExecutable() {
Paths p;
const uint64_t old = inode(p.target);
replaceFile(p.target, "v2");
assert(inode(p.target) != old);
PosixFs fs;
assert(p.update(fs) == kRgfxAliasLinked);
assert(fs.removes == 1 && inode(p.link) == inode(p.target));
}
// Another file at the link's path, a copy or a symbolic link to the
// executable, is replaced by the link itself.
void testOtherFiles() {
Paths p;
unlink(p.link.c_str());
writeFile(p.link, "a copy");
PosixFs fs;
assert(p.update(fs) == kRgfxAliasLinked);
assert(fs.removes == 1 && inode(p.link) == inode(p.target));
unlink(p.link.c_str());
assert(symlink(p.target.c_str(), p.link.c_str()) == 0);
PosixFs fs2;
assert(p.update(fs2) == kRgfxAliasLinked);
assert(fs2.removes == 1 && isFile(p.link) && inode(p.link) == inode(p.target));
}
// A file where a directory above the link belongs: no link, no tags.
void testBlockedDirectory() {
Paths p;
unlink(p.link.c_str());
rmdir(p.macos.c_str());
writeFile(p.macos, "not a directory");
PosixFs fs;
assert(p.update(fs) == kRgfxAliasFailed);
assert(fs.tags == 0 && !isFile(p.link));
unlink(p.macos.c_str());
}
} // namespace
int main() {
char tmpl[] = "/tmp/rgfx-alias-test.XXXXXX";
const char *dir = mkdtemp(tmpl);
assert(dir != nullptr);
g_root = dir;
testNoTarget();
testFirstAndCurrent();
testNewExecutable();
testOtherFiles();
testBlockedDirectory();
Paths p;
unlink(p.link.c_str());
rmdir(p.macos.c_str());
rmdir(p.contents.c_str());
rmdir(p.bundle.c_str());
unlink(p.target.c_str());
rmdir(g_root.c_str());
std::printf("alias_test: OK\n");
return 0;
}