diff --git a/CHANGELOG.md b/CHANGELOG.md index 6f8cb830..2fc504a5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,8 +1,37 @@ # Changelog -**GPU power limit, from the optional GPUSensors.kext**: when the kext is loaded and an administrator has allowed GPU changes, Settings › GPU control and the panel can lower the RX 6800 XT's power limit in 10 W steps down to the card's own minimum (225 W on a card that starts at 240 W). The kext checks every request and goes back to the start-up limit on its own when RyzenStatus quits, stops answering or the Mac sleeps; a switch on the page asks for the same limit again after launch and wake, only while changes are allowed and never with a password. Another switch, Allow changes after restart too, asks for an administrator password once and then allows GPU changes again at every startup, so the remembered limit comes back after a restart too; turning it off asks again and removes that step. With GPUSensors.kext 0.8.0, Close Changes closes them again without a password, and on an RX 6900 XT the page shows the readings only. GPUSensors.kext is not public yet; without it, nothing changes. +## [1.90.0] — 2026-11-26 — kexts 3.42.0 (No kext changes) -**AWDL / AirDrop activity in the Network card**: with a Wi-Fi driver that publishes AWDL activity in the I/O Registry (`RTLAwdlPeers` and `RTLAwdlChannel` on the `awdl0` interface, and optionally the `RTLLed` status LED mode), the panel's Network card shows a line with the number of peers exchanging data over AWDL (AirDrop, Sidecar, Continuity) and its current channel. Settings › Monitor › Alerts adds an optional notification when AWDL goes from no peers to some; it is off by default and fires at most once a minute. The line can be hidden like the card's other blocks. With other Wi-Fi hardware nothing changes and nothing extra is read. +**More GPU control (minimum clock, undervolt, overclock and profiles), HDR colour and a fix for decoding after sleep in the GPU decoders, optional MPEG-2, VC-1, MPEG-4 and Motion JPEG decoders, FaceTime and Continuity Camera fixes in the encoding fix, and an AWDL line in the Network card.** The AMD processor kexts stay at 3.42.0, so your EFI's CPU kexts need no change. If you use the RyzenStatus GPU parts, open the RyzenStatus GPU installer in the disk image's "GPU RX 6000" folder to update the decoders to 0.3.7, the encoding fix to 1.3.0 and GPU sensors to 0.9.0. + +### GPU control (needs GPUSensors.kext) + +- **Power limit**: Settings › GPU control and the panel can lower the RX 6800 XT's power limit in 10 W steps down to the card's own minimum. It goes back to the start-up limit by itself when RyzenStatus quits, stops answering or the Mac sleeps. A switch asks for the same limit again after launch and wake, and Allow changes after restart too asks for an administrator password once so the remembered settings also come back after a restart. +- **GFX minimum clock (GPUSensors 0.9.0)**: raises the minimum clock, up to the GFX maximum in force. The card then draws more power and runs warmer at idle, so the kext watches the temperature while it is held. +- **GFX voltage (GPUSensors 0.9.0)**: lowers the voltage in 25 mV steps, down to the card's own minimum (an undervolt). It suggests stock minus 25 mV as a starting point and never applies it by itself. +- **Overclock (GPUSensors 0.9.0)**: off by default. Raises the GFX maximum clock up to the card's own maximum and the power limit up to the card's own percent (never more than +15 %). Every raise is held under the temperature watchdog. +- **Profiles**: save what the card holds (power limit, fan curve with zero RPM, clocks, voltage) under a name and load it again in one click. A value this card does not take is left out, and the page says which one. +- Every GPU change stays inside the limits the card publishes and goes back to stock when RyzenStatus quits, stops answering or the Mac sleeps. Memory clock and fast memory timings are not offered, because the driver cannot apply them on macOS. Only the RX 6800 XT writes; the RX 6900 XT shows readings only. Details in [docs/GPU_CONTROL.md](docs/GPU_CONTROL.md). +- When `gpucontrol hold` from Terminal holds the card, the page now says it is RyzenStatus's own tool instead of "Another program has the control". +- Tested with unit tests only. + +### GPU decoders and encoding fix + +- **HDR colour (decoders 0.3.7)**: AV1 and VP9 pictures now carry their colour and HDR information, so HDR video is no longer shown washed out. Not tested on the GPU yet. +- **After a sleep (decoders 0.3.7)**: a video that was playing before a sleep keeps decoding after the wake and switches to fresh decoder state at its next key frame, without dropping frames. 0.3.6 was never released: in a real sleep test it made those videos fail. +- **MPEG-2, VC-1 and MPEG-4 decoders (optional, macOS 26.7.2 to 26.7.4)**: hardware decoding of these older formats on the RX 6800 XT. Not installed by default: run `install/install.sh --with-legacy-decoders` from the GPU parts. Installed, they replace Apple's decoders for these formats. MPEG-4 streams with B-frames are left to Apple's decoder, and MPEG-2 field pictures are not decoded on the GPU. +- **JPEG and Motion JPEG decoder (optional, macOS 26.7.3 only)**: decodes JPEG and Motion JPEG video on the card's JPEG block. Not installed by default: `install/install.sh --with-jpeg`. It needs a reboot, and the block is powered only while pictures arrive. +- **Encoding fix 1.3.0**: Continuity Camera and FaceTime video are decoded by the GPU instead of the CPU, and with a MacPro7,1 or iMacPro1,1 SMBIOS FaceTime's encoder no longer looks for a T2 chip, so outgoing video works. This part is for macOS 15.8.2, 26.7.2 and 26.7.3 and is turned off with `--no-cc`. Not tried in a real FaceTime call yet. +- **macOS 26.7.4**: the decoders and the encoding fix know 26.7.4's drivers. Checked from the installer only, not run on a card with 26.7.4 yet. + +### Network + +- **AWDL / AirDrop activity**: with a Wi-Fi driver that publishes AWDL activity in the I/O Registry, the Network card shows how many peers are exchanging data over AWDL (AirDrop, Sidecar, Continuity) and on which channel. Settings › Monitor › Alerts adds an optional notification when AWDL starts; off by default, at most once a minute. With other Wi-Fi hardware nothing changes. + +### Fixes + +- **Closed-lid rule**: the passwordless closed-lid rule could not be written, so its setup always failed right after the password. It is now written and checked before it is put in place. +- **Hardware Validation**: a new row says whether GPUSensors.kext is loaded and found a supported card. It is information only and never fails. ## [1.89.0] — 2026-11-23 — kexts 3.42.0 (No kext changes) diff --git a/GPU/CHANGELOG.md b/GPU/CHANGELOG.md index 24a1cfcd..b67c3c51 100644 --- a/GPU/CHANGELOG.md +++ b/GPU/CHANGELOG.md @@ -2,6 +2,177 @@ The encoding fix keeps its own history in `encode/CHANGELOG.md`. +## JPEG decoder 1.0.0 (RyzenStatus 1.90.0) + +- New, optional, macOS 26.7.3 only: `VCNJpeg.kext` (`jpeg/`) and the VideoToolbox plug-in + `JPEGVCNDecoder.bundle` (`decode/jpeg/`) decode JPEG and Motion JPEG (`jpeg`, `dmb1`) on + the JPEG block of the VCN, which Apple's driver carries but never starts. Baseline 4:2:0 + and 4:2:2; anything else goes to Apple's software decoder. +- The kext creates the JPEG queue and a 128 MiB block of buffers (`vcnjpegpool=`, 8 to + 128) when the driver starts its video queues, and powers the block only while pictures + arrive: PowerPlay client 21 and the queue start with the first picture, both are given + back two seconds after the last one. +- Off by default: `install/install.sh --with-jpeg`, or `install/jpeg.sh install` and + `install/decoders.sh install --jpeg`. The package carries them only when built with + `VCNVT_JPEG_DECODER=1`. The loader kext lists the JPEG plug-in too. +- It comes from the test kext that decoded through the same plug-in on an RX 6800 XT + (4:2:0, 4:2:2 and `dmb1` at 1280x720, under 5 ms a frame, within 1 of FFmpeg). The + product kext ran once on an RX 6800 XT with 26.7.3 (2026-11-25, started from a separate + OpenCore config): four VideoToolbox cases decoded on the GPU at 74 to 75 dB against the + reference, 90 frames through `avconvert`, and the block powered off two seconds after the + last picture. +- `install.sh --with-jpeg` takes the kext as installed only when the config.plist it installs + to lists it: a kext started from another config file (one picked in OpenCore for one boot) + was skipped before, though the next normal boot would not load it. + +## GPU sensors 0.9.0 (RyzenStatus 1.90.0; host tests only) + +- A program may now hold a raised GFX minimum clock (OD8 id 1) with the rest of the OD8 + state: `gpucontrol hold gfxmin 1500 -- `, `gpucontrol check gfxmin 1500`. It is + taken only inside the card's own range for it (the 0x9f entry: 500 to 2800 MHz on the test + RX 6800 XT, stock 500) and never above the GFX maximum of the same state (the stock one, or + the lowered one held with it): the driver's own rule (`PhwComm_OD8_SetGfxClockLimits`: both + requested, each in its range, minimum at most the maximum). Anything else is refused with + the new reason `GfxMinRange` (12), never clamped. It goes back to stock in the same cases + as the rest of OD8 (release, close, 30 s of silence, a wake), through the same stock pair. +- It is the first setting that can make the card warmer at idle, so it is taken only while + the fan watchdog has fresh readings, and the watchdog runs while it is held: 95 C, or no + readings for 10 s, puts stock back and turns writing off. The "too hot with the fan under + 90 %" rule stays with a held curve, because the stock fan climbs slowly by design. +- The read-back allows the minimum to read up to 25 MHz lower than sent, never higher, as + for the maximum. Whether the firmware ever rounds it is not known yet. +- The channel stays version 2: `setOd8` takes 14 scalars (the 14th is the minimum) as well as + the 0.7.0 form of 13, `status` sets flag 512 (`kFlagGfxMin`), `OD8WriteState` gains `Held` + bit 16, `GfxMinHeld` and `Takes` (23: what `setOd8` takes). An older kext refuses the + 14-scalar form with a wrong-count error; `gpucontrol` and the app send it only with a + minimum. +- A lower GFX voltage (OD8 id 37, the firmware's `VddGfxOffset`): `gpucontrol hold volt 1050 + -- `. Read end to end in HWLibs 25G342: the driver offers it with + `PP_OD8VoltageSliderSupport` (the Navi 21 default, 1) as a range from swsmu+328 to swsmu+332 + (881 to 1075 mV on the test card, stock 1075), stages value minus the top as the OD table's + `VddGfxOffset` (int16 mV, written whole to the firmware) and reads it back as top plus + offset. So it is a millivolt cap that moves the whole voltage curve down, and it cannot go + above the top. Linux writes the same field and needs SMU firmware 58.41.0 or later (the + test card: 58.76.0). The kext takes it lower only (at or below stock, at or above the card's + minimum) in 25 mV steps from stock, reads it back exactly, and sends the stock value in + every other call so a way back never leaves an offset behind. Refused: `VoltRange` (13); + not offered or not allowed now: `NoFeature`. +- Raises, only when the request asks for them and only inside the card's own OverDrive + range: a GFX maximum above stock up to the 0x9f maximum (2800 MHz here) with `setOd8` flag + 4, `gpucontrol hold gfxmax 2500 overclock -- `; and a power limit above the + start-up one with `set`'s new 3-scalar form (flag 1), `gpucontrol hold power 260 raise -- + `, up to `PowerRange.CeilW` = start-up limit x (100 + the 0x9f power percent) / + 100, the way Linux takes `power1_cap_max`, the percent cut at +15 (261 W on the test card, + +9 %). The driver's 0x6e path has no ceiling of its own (it sends SMU message 0x32 with the + watts as given), so this is the only one. One step past either maximum is refused + (`GfxRange`; the new reply 21 `AboveCeiling`). Each raise is taken only while the watchdog + has fresh readings (new reply 22 `NoReadings` for `set`) and is held under it: 95 C or no + readings for 10 s puts stock back and turns writing off (new `WriteOff` 16 + `PowerWatchdog` for the power limit). +- The channel stays version 2: `setOd8` also takes 15 scalars (the 15th is the voltage), + `set` also takes 3, `status` sets flags 1024 (`kFlagVolt`) and 2048 (`kFlagRaise`), + `OD8WriteState` gains `Held` bits 32 (voltage) and 64 (GFX maximum above stock), `VoltHeld`, + and `Takes` 119; `PowerRange` gains `CeilW`. An older kext refuses the new counts. +- Not added, and why (read in the 25G342 driver, 2026-11-25): the memory maximum (id 8) and + fast memory timings (id 14, AC timing). Both start with `PhwComm_OD8_StartMemoryOverclock` + -> `PECI_StartGPUMemoryOverclock`, an IRI call 0x110018 to the display driver, and on macOS + that interface is `AtiAppleDalServices::dalIriFunction`, which has no case for 0x110018 (nor + 0x110019, the end) and answers status 1, so the start fails. A memory maximum then makes + `PhwComm_OD8_ApplySettings` return before the OD table is written (the whole call fails + and the new clock stays staged), and fast timings are recorded but never programmed + (nothing could be read back). Also not added: the fan minimum speed (id 10) and fan target + temperature (id 12), which the driver does not offer while the fan curve is offered + (feature 0, and `PhwComm_OD8_SetGenericSetting` skips a setting whose feature is 0). +- `gpucontrol status` names a held GFX maximum above stock "GFX max raised" (it said + "lowered" for every held maximum) and shows a held voltage as "GFX voltage lowered". + +## Decoders 0.3.7 (RyzenStatus 1.90.0) + +Everything since 0.3.5, the last release. The sleep part was host-tested only; the rest as +said in each item. + +- Colour and HDR metadata: every AV1 and VP9 picture now carries its colour primaries, + transfer function and matrix, plus the mastering display colour volume and content light + level when the stream or the container has them. Before, BT.2020 PQ video was shown as + untagged video (washed out, no HDR). AV1 takes them from the sequence header first and the + container where the header says nothing, and keeps the `HDR_MDCV` and `HDR_CLL` metadata + OBUs (a cut or unknown one changes nothing); VP9 takes the container first, then the + bitstream's `color_space` (VP9 has no transfer function of its own). Host tests only; not + run on the GPU yet. +- New, optional, macOS 26.7.2 and 26.7.3 (and 26.7.4, same driver code): MPEG-2, VC-1 and + MPEG-4 part 2 decoders (`decode/mpeg2/`, `decode/vc1/`, `decode/mpeg4/`), installed only + with `install/decoders.sh install --legacy` or `install/install.sh --with-legacy-decoders`; + installed, they replace Apple's decoders for these formats. Run on an RX 6800 XT with 26.7.3 + through VideoToolbox: VC-1 bit-exact (advanced profile I/P/B, WMV3 main, 1080i frame and + field interlaced), MPEG-2 frame pictures 58.8 dB or better, MPEG-4 I/P 59 to 67 dB. + Refused before the GPU: MPEG-4 B-VOPs (they stall the firmware, on Linux as well) and MPEG-2 + field pictures (the firmware writes their chroma as zeros; Mesa does not decode them on this + card either). +- MPEG-4: a B-VOP whose TRD is 0 is never sent (direct mode divides by it), the size goes to + the firmware aligned to 16 as Mesa does (1920x1080 as 1920x1088; the pictures keep the real + size), and the quantizer matrices always go in stream order. + +- A system sleep. 0.3.6 made things worse in the first real sleep test on this Mac (RX 6800 XT, Tahoe + 26.7.3): it noticed the sleep (132 s asleep), but every session from before it then + failed all its frames with -12911, and the new sessions after the wake lost their first + frames to the refusal below. The same test with 0.3.5, which knows nothing of sleeps, + kept decoding on the old sessions after the wake with every frame matching its reference. +- So an AV1 or VP9 session from before a sleep now keeps decoding, as 0.3.5 did, and at its + next key frame (AV1: a key frame that refreshes every reference slot; VP9: a key frame, or + an intra-only frame that refreshes every slot and resets every probability context) its + driver objects are replaced inside the same decoder: the old accelerator is closed without + the driver's own teardown and a new accelerator, driver, context and bitstream pool are + opened, and the key frame decodes on them. No frame is dropped and the host sees no error. +- Only when the old session fails after the wake (a driver call, a command that does not + finish, a firmware error) is it replaced at once; that frame and the ones up to the next + key frame are then dropped (no picture, no error), at most 600 of them. A command that did + not finish has its accelerator closed on the background thread. Right after a wake a + command on the old session may take up to 15 s instead of 1 s (in the test one frame of + each decode took about 10 s and then decoded correctly). +- -12911 is left for a replacement that fails, or no key frame within those 600 frames. +- A new session no longer refuses to open while one from before a sleep is still open. +- The MPEG-2, VC-1 and MPEG-4 decoders are unchanged: their sessions from before a sleep + still stop as in 0.3.6. +- Each replacement leaves the old driver handle and its bitstream pool (up to 96 MiB) in the + process, as the quiet close already did. + +## Decoders 0.3.6 (not released; replaced by 0.3.7) + +- A decode session from before a system sleep is no longer used after it. A user reported + that with the AV1 and VP9 decoders a wake from sleep hung the Mac a while later, with + glitches before it, and that a VP9 video came out red and broken in Chrome right after a + wake while Safari played it fine. Apple's kernel driver keeps a decoder's video context + across a sleep but restarts the video engine under it, and nothing tells the program + (see "A system sleep" in `docs/how-it-works.md`). The plug-ins now notice a sleep from the + time the Mac spent asleep or the time of its last wake, with no notification. A session + opened before it writes and sends nothing more: its frames fail as a malfunction + (-12911), so VideoToolbox makes a new session, and the host gets a working decoder again + or falls back to software. Closing such a session leaves out the driver's own teardown, + which would send the restarted engine a command for the lost session and wait for it + with no time limit; only the accelerator's connections are closed, on a background + thread. The MPEG-2, VC-1 and MPEG-4 decoders share the code and get the same. +- While such a session is still open in a process, no new session opens there, in any of + the plug-ins: VideoToolbox decodes the new stream in software until the old sessions are + closed. The reporter's log showed why: a browser's decoder process kept two VP9 sessions + open across a sleep, the AV1 session it opened after the wake never decoded a frame, and + the Mac hung after the next wake. +- `vtvp9test` has `-renew` (a new session for every `-loop` pass, in the same process) and + prints a line per pass with the time; `vtav1test` gets `-loop` and `-renew` too. They are + for the sleep test in `docs/testing.md`. +- Not run across a real sleep yet. + +## macOS 26.7.4 (25G422) (RyzenStatus 1.90.0) + +- Decoders: `AMDRadeonVADriver2` of 26.7.4 has a new UUID, + `F7D8F5849EC139DB857C769697294957`, added to `kValidatedDrivers` in `decode/av1/vcnav1.c`, + `decode/vp9/vcnvp9.c` and `decode/common/vcnlegacy.c` (MPEG-2, VC-1, MPEG-4), and 25G422 to + `install/validated-builds.json` with `av1`, `vp9` and `legacy` set to `"untested-on-gpu"` + and `jpeg` false (the VCNJpeg kext knows only 26.7.3's HWLibs and AMDRadeonX6000). Checked from the installer before updating (its cryptex + rebuilt with `rawpatch`): the driver's 2760 functions are identical to 26.7.3's and every + section is the same except one Apple build path in `__cstring`. Not decoded on a card on + 26.7.4 yet. New plug-ins mean new code directory hashes, so the loader kext must ship with + them. + ## Decoders 0.3.5 (RyzenStatus 1.89.0) - The `stats` line's slow-frame count now uses the stream's own frame time. It used to count diff --git a/GPU/README.md b/GPU/README.md index 11d1d3b9..aec465c7 100644 --- a/GPU/README.md +++ b/GPU/README.md @@ -16,6 +16,7 @@ without replacing any Apple driver: | **Decoders** (`decode/`) | Safari and Chrome play AV1 and VP9 video (YouTube up to 4K60 and 8K) on the GPU instead of the CPU | Two of macOS's VideoToolbox plug-ins that send AV1 and VP9 to the card's video engine through Apple's own driver | | **Encoding fix** (`encode/`, optional) | Hardware HEVC/H.264 encoding at full speed: OBS at 4K60 without repeated frames, sizes wider than 4096 without GPU stalls | A small kernel extension for Lilu (a kext OpenCore loads, 1.7.0 or newer) that keeps the video engine's clocks up while encoding, and a service that corrects two settings in Apple's encoder process | | **GPU sensors** (`sensors/`, optional) | Edge, memory and VR temperatures, voltages, throttling, video and fabric clocks, and PCIe link | A Lilu kernel extension that publishes the readings Apple's AMD driver already takes and hides, and `gpusensors` to print them | +| **JPEG decoder** (`jpeg/`, optional, macOS 26.7.3 only) | Motion JPEG (webcam recordings, camera clips) decoded on the GPU in apps that use VideoToolbox | A Lilu kernel extension that starts the card's JPEG block, which Apple's driver carries but never uses, and a VideoToolbox plug-in for `jpeg` and `dmb1` | | **Installer app** (`installer/`, optional) | Graphical front end for checking, installing, updating and removing each part | A SwiftUI app for the command-line tools in `install/` | ## Before you start @@ -32,12 +33,13 @@ Inc. | Component | Version | Run on a GPU | |---|---|---| -| AV1 decoder (`decode/av1/`) | 0.3.5 | 0.3.3 on RX 6800 XT (Tahoe 26.7.3); 0.1 on RX 6900 XT (Sequoia 15.8.2) | -| VP9 decoder (`decode/vp9/`) | 0.3.5 | 0.3.3 on RX 6800 XT (Tahoe 26.7.3); 0.2 on RX 6900 XT (Sequoia 15.8.2) | +| AV1 decoder (`decode/av1/`) | 0.3.7 | 0.3.3 on RX 6800 XT (Tahoe 26.7.3); 0.1 on RX 6900 XT (Sequoia 15.8.2) | +| VP9 decoder (`decode/vp9/`) | 0.3.7 | 0.3.3 on RX 6800 XT (Tahoe 26.7.3); 0.2 on RX 6900 XT (Sequoia 15.8.2) | | Loader kext (`decode/loader/`) | 1.1.0 | RX 6800 XT (Tahoe 26.7.3) with AMFIPass off; not run on Sequoia | | Encoding fix kext (`encode/kext/`) | 1.3.0 (code as 1.2.6) | RX 6800 XT (Tahoe 26.7.3); 1.2.1 reported on RX 6900 XT (Sequoia 15.8.3); Navi 23 static only | | Encoding fix service (`encode/tool/`) | 1.3.0 | RX 6800 XT (Tahoe 26.7.3; FaceTime encoder part in a test process); 1.2.1 reported on RX 6900 XT (Sequoia 15.8.3); cc decoder part run with an iPhone camera on RX 6900 XT (15.8.2) | -| GPU sensors kext (`sensors/`) | 0.8.1 | 0.8.0 on RX 6800 XT (Tahoe 26.7.3) | +| GPU sensors kext (`sensors/`) | 0.9.0 | 0.8.0 on RX 6800 XT (Tahoe 26.7.3) | +| JPEG decoder kext (`jpeg/`) | 1.0.0 | RX 6800 XT (Tahoe 26.7.3), one product test | Full test results, dates and what has never been tried are in [docs/status.md](docs/status.md). @@ -102,6 +104,7 @@ in [install/README.md](install/README.md#undo-everything). | `decode/` | The two decoder plug-ins: `av1/`, `vp9/`, the code they share in `common/`, the kext that lets them load without AMFIPass in `loader/`, and their tests | | `encode/` | The encoding fix: `kext/`, the service in `tool/`, a test encoder in `vtenc/`, its scripts and tests | | `sensors/` | The GPU sensors: a kext that publishes the readings the driver takes and hides, and `gpusensors` to show them | +| `jpeg/` | The JPEG decoder kext; its VideoToolbox plug-in is in `decode/jpeg/` | | `install/` | Command-line installers and the list of validated macOS builds | | `installer/` | Graphical installer app (SwiftUI front end for `install/`) | | `tools/` | Dependency bootstrap, the repository cleanliness check, formatting, binary comparison, driver validation helpers | diff --git a/GPU/build.sh b/GPU/build.sh index e3e971cc..adbf35a3 100755 --- a/GPU/build.sh +++ b/GPU/build.sh @@ -1,18 +1,20 @@ #!/bin/zsh # build.sh - builds every part of the repository. Installs nothing. # -# ./build.sh the decoders, their loader kext, the GPU sensors and the encoding fix +# ./build.sh the decoders, their loader kext, the GPU sensors, the encoding fix and +# the JPEG decoder kext # ./build.sh decode only the decoders # ./build.sh loader only the loader kext (needs tools/bootstrap.sh once) # ./build.sh sensors only the GPU sensors (the kext needs tools/bootstrap.sh once) # ./build.sh encode only the encoding fix (needs tools/bootstrap.sh once) +# ./build.sh jpeg only the JPEG decoder kext (needs tools/bootstrap.sh once) emulate -L zsh setopt err_exit no_unset pipe_fail cd "${0:A:h}" what=${1:-all} case $what in - all|decode|loader|sensors|encode) ;; - *) print "usage: ./build.sh [decode|loader|sensors|encode]"; exit 2 ;; + all|decode|loader|sensors|encode|jpeg) ;; + *) print "usage: ./build.sh [decode|loader|sensors|encode|jpeg]"; exit 2 ;; esac if [[ $what == (all|decode) ]]; then print "== decoders" @@ -30,3 +32,7 @@ if [[ $what == (all|encode) ]]; then print "== encoding fix" encode/build.sh fi +if [[ $what == (all|jpeg) ]]; then + print "== JPEG decoder kext" + jpeg/build.sh +fi diff --git a/GPU/decode/VERSION b/GPU/decode/VERSION index c2c0004f..0f826853 100644 --- a/GPU/decode/VERSION +++ b/GPU/decode/VERSION @@ -1 +1 @@ -0.3.5 +0.3.7 diff --git a/GPU/decode/av1/vcnav1.c b/GPU/decode/av1/vcnav1.c index 9d97a5d7..36bc19fa 100644 --- a/GPU/decode/av1/vcnav1.c +++ b/GPU/decode/av1/vcnav1.c @@ -23,6 +23,11 @@ int vcnav1_gpu_armed = 0; #define VCN_MODE_VCN0 4 #define NUM_DPB 9 +// A session that failed after a sleep is rebuilt and waits for a key frame, +// dropping the frames before it; at 60 fps this is ten seconds of frames. A +// stream that does not send one by then is stopped the way PR 160 stopped it, +// so the host can hand it to another decoder. +#define REBUILD_MAX_DROPPED 600 #define NUM_BS VCN_NUM_BS #define BS_SIZE VCN_BS_SIZE #define SEQ_BYTES 2048 @@ -62,8 +67,16 @@ struct VcnAV1 { bool poolTen; bool stuck; // a command never finished: the GPU may still hold it bool broken; // stuck, or a driver call failed: nothing more goes out - int failure; // VCNAV1_FAIL_* of the last error - bool shown; // the current decode call output a frame + // The system slept since the driver side opened: frames still go to it, and + // it is rebuilt at the next key frame (on_frame). + bool rebuildAtKey; + unsigned keptAfterWake; // frames decoded on it since the sleep was seen + bool needKey; // rebuilt after a failure: drop frames until a key frame + unsigned dropped; // frames dropped since that rebuild + unsigned rebuilds; // driver objects rebuilt in this session (one per sleep) + uint32_t lastFw; // firmware result of the last command that finished + int failure; // VCNAV1_FAIL_* of the last error + bool shown; // the current decode call output a frame CVPixelBufferRef hidden; // retained: last frame it decoded without showing unsigned fwErrors; // decodes the firmware reported as failed unsigned done; // decode commands that finished @@ -92,6 +105,9 @@ static const char* const kValidatedDrivers[] = { "1181E2CA31B33DF090E23AE70552D753", // macOS 26.7.2 (25G332) and 26.7.3 // (25G342, same binary): compared in // IDA against 26.7.1, same code + "F7D8F5849EC139DB857C769697294957", // macOS 26.7.4 (25G422): same code + // as 26.7.3 (2760/2760 functions + // identical, only a build path) }; static CFNumberRef cfnum(long long v) { @@ -172,6 +188,45 @@ static CVPixelBufferRef new_target(VcnAV1* d, uint32_t w, uint32_t h, if (CVPixelBufferPoolCreatePixelBuffer(NULL, d->pool, &pb)) return NULL; return pb; } +// One AV1 context on the driver handle this session has open: what a create +// and a rebuild after a sleep both need. +static int av1_create_context(VcnAV1* d) { + AVD_ContextList list = {0}; + void* ctxOut[2] = {0}; + AVD_FunctionInfo* fis[1] = {&list.inlineInfo}; + list.count = 1; + list.functions = fis; + list.contextsOut = ctxOut; + // mode 3/5 => VAVcnDecoder::Init(1) => second VCN instance (VCN1Dec), which + // has NO AV1 on Navi21 and hangs the GPU. Mode 4 (what AppleGVA uses for + // H.264) => Init(0) => VCN0Dec. + list.inlineInfo = (AVD_FunctionInfo){.kind = 1, + .function = AVD_FUNC_AV1, + .mode = VCN_MODE_VCN0, + .pixelRate = d->maxW * d->maxH * 60, + .width = d->maxW, + .height = d->maxH, + .inFormat = 0x72617762, + .inFormatCount = 1, + .outFormat = 0x4e563132, + .outFormatCount = 1}; + AVD_DriverContextInit ci = {.list = &list}; + int r = FN(CreateContexts)(d->s.drv, &ci); + if (r || !ctxOut[0]) return r ? r : 1; + d->s.ctx = ctxOut[0]; + return 0; +} + +// The builds the AV1 parameter blocks were validated against, or the override +// a dry run sets (vcndriver.h). +static bool av1_driver_allowed(const VcnDriverLib* lib) { + for (size_t i = 0; i < sizeof(kValidatedDrivers) / sizeof(*kValidatedDrivers); + i++) + if (!strcmp(lib->uuid, kValidatedDrivers[i])) return true; + const char* ov = getenv("VCNAV1_ALLOW_UNVALIDATED_DRIVER"); + return ov && !strcmp(ov, "1"); +} + VcnAV1* vcnav1_create(uint32_t maxWidth, uint32_t maxHeight, char* err, size_t errLen) { VcnAV1* d = calloc(1, sizeof(*d)); @@ -215,33 +270,125 @@ VcnAV1* vcnav1_create(uint32_t maxWidth, uint32_t maxHeight, char* err, // included. if (!vcn_session_open(&d->s, &lib, svc, vlog(), why, sizeof(why))) FAIL("%s", why); - AVD_ContextList list = {0}; - void* ctxOut[2] = {0}; - AVD_FunctionInfo* fis[1] = {&list.inlineInfo}; - list.count = 1; - list.functions = fis; - list.contextsOut = ctxOut; - // mode 3/5 => VAVcnDecoder::Init(1) => second VCN instance (VCN1Dec), which - // has NO AV1 on Navi21 and hangs the GPU. Mode 4 (what AppleGVA uses for - // H.264) => Init(0) => VCN0Dec. - list.inlineInfo = (AVD_FunctionInfo){.kind = 1, - .function = AVD_FUNC_AV1, - .mode = VCN_MODE_VCN0, - .pixelRate = maxWidth * maxHeight * 60, - .width = maxWidth, - .height = maxHeight, - .inFormat = 0x72617762, - .inFormatCount = 1, - .outFormat = 0x4e563132, - .outFormatCount = 1}; - AVD_DriverContextInit ci = {.list = &list}; - int r = FN(CreateContexts)(d->s.drv, &ci); - if (r || !ctxOut[0]) FAIL("CreateContexts(AV1) %d", r); - d->s.ctx = ctxOut[0]; + int r = av1_create_context(d); + if (r) FAIL("CreateContexts(AV1) %d", r); DBG("created: drv=%p ctx=%p bs=%p\n", d->s.drv, d->s.ctx, d->s.bsAddr[0]); return d; } +// Rebuilds the driver side of a session the system slept through: the objects +// from before the sleep are dropped without a word to the driver, and a fresh +// accelerator, driver, context and bitstream pool are opened for the same +// plug-in session, so the host's decoder object lives on. The references live +// in the old driver's DPB, so the DPB pictures and the reference slots go; the +// parser keeps the sequence header (a key frame does not always repeat it) and +// the frame header being decoded. busy: the old session's last command may +// still be on the GPU, so its accelerator is closed on the teardown queue and +// the pictures are let go only after that. False when the rebuild fails: the +// caller then stops the session as PR 160 did. +static bool av1_rebuild(VcnAV1* d, bool busy, char* why, size_t whyLen) { + CVPixelBufferRef old[NUM_DPB + 1]; + int n = 0; + for (int i = 0; i < NUM_DPB; i++) + if (d->dpb[i]) { + old[n++] = d->dpb[i]; + d->dpb[i] = NULL; + } + if (d->hidden) { // its own reference to one of them + old[n++] = d->hidden; + d->hidden = NULL; + } + if (busy) { + // Without memory for the list the pictures are never let go: a command + // still on the GPU may write into them. + CVPixelBufferRef* keep = n ? malloc((size_t)n * sizeof(*keep)) : NULL; + if (keep) memcpy(keep, old, (size_t)n * sizeof(*keep)); + int kept = keep ? n : 0; + vcn_session_drop_later(&d->s, "AV1 session from before the sleep", ^{ + for (int i = 0; i < kept; i++) CVPixelBufferRelease(keep[i]); + free(keep); + }); + } else { + vcn_session_drop(&d->s); + for (int i = 0; i < n; i++) CVPixelBufferRelease(old[i]); + } + vcnav1_flush(d); + d->bsNext = 0; + VcnDriverLib lib; + if (!vcn_driver_load(&lib, why, whyLen)) return false; + if (!av1_driver_allowed(&lib)) { + snprintf(why, whyLen, "AMDRadeonVADriver2 build %s not validated", + lib.uuid); + return false; + } + io_service_t svc = vcn_find_accelerator(); + if (!svc) { + snprintf(why, whyLen, "no AMD accelerator"); + return false; + } + if (!vcn_session_reopen(&d->s, &lib, svc, vlog(), why, whyLen)) return false; + int r = av1_create_context(d); + if (r) { + snprintf(why, whyLen, "CreateContexts(AV1) %d", r); + vcn_session_drop(&d->s); + return false; + } + d->rebuilds++; + return true; +} + +// Rebuilds now (av1_rebuild) and leaves the session decoding on the new driver; +// dropUntilKey: the frames before the next key frame are dropped. False, with +// the session stopped as a device failure, when the rebuild fails. +static bool rebuild_now(VcnAV1* d, bool busy, bool dropUntilKey, + const char* cause) { + char why[200]; + unsigned kept = d->keptAfterWake; + if (!av1_rebuild(d, busy, why, sizeof(why))) { + d->rebuildAtKey = false; + d->broken = true; + d->failure = VCNAV1_FAIL_DEVICE; + snprintf(d->err, sizeof(d->err), + "session stopped: the system slept since it opened and the " + "rebuild failed (%s)", + why); + return false; + } + // What these said was about the old driver objects. + d->rebuildAtKey = false; + d->stuck = d->broken = false; + d->keptAfterWake = 0; + d->needKey = dropUntilKey; + d->dropped = 0; + if (dropUntilKey) + os_log_error( + vlog(), + "the session from before the sleep failed after the wake " + "(%{public}s, %u frames decoded on it before): driver rebuilt, " + "frames are dropped until the next key frame", + cause, kept); + else + os_log_error(vlog(), + "driver rebuilt at the first key frame after the sleep (%u " + "frames decoded on the session from before it), no frame " + "dropped", + kept); + return true; +} + +// The session from before the sleep failed on the frame being decoded: it is +// rebuilt at once and this frame is dropped, like the ones after it until a +// key frame. 0, or -1 when the rebuild fails. +static int failed_after_wake(VcnAV1* d, bool busy) { + char cause[256]; + snprintf(cause, sizeof(cause), "%s", d->err); + if (!rebuild_now(d, busy, true, cause)) return -1; + d->err[0] = 0; + d->failure = VCNAV1_FAIL_STREAM; + d->dropped = 1; + return 0; +} + static void destroy_now(VcnAV1* d) { vcn_session_close(&d->s); // The pictures go after the driver: a stuck command may still write one. @@ -258,7 +405,7 @@ static void destroy_now(VcnAV1* d) { void vcnav1_destroy(VcnAV1* d) { if (!d) return; - vcn_teardown(d->stuck, vlog(), "AV1 session", ^{ + vcn_teardown(d->stuck, vcn_session_lost(&d->s), vlog(), "AV1 session", ^{ destroy_now(d); }); } @@ -530,9 +677,12 @@ static int submit(VcnAV1* d, AV1Params* prm, double* sched, double* wait) { } uint32_t fw = 0; int ds = 0; - VcnWaitResult w = - vcn_wait_command(FN(QueryAVDCommandStatus), d->s.drv, refcons[0], - VCN_COMMAND_TIMEOUT_MS, &fw, &ds); + // Longer on the session from before a sleep: right after a wake the driver + // can take seconds before a command runs (vcndriver.h). + unsigned limit = + d->rebuildAtKey ? vcn_wake_command_timeout_ms : VCN_COMMAND_TIMEOUT_MS; + VcnWaitResult w = vcn_wait_command(FN(QueryAVDCommandStatus), d->s.drv, + refcons[0], limit, &fw, &ds); *sched = t1 - t0; *wait = tnow_ms() - t1; DBG("wait=%d firmware=%u driver=%d\n", (int)w, fw, ds); @@ -541,8 +691,7 @@ static int submit(VcnAV1* d, AV1Params* prm, double* sched, double* wait) { // target, could only make things worse: the session stops here. d->stuck = d->broken = true; snprintf(d->err, sizeof(d->err), - "the GPU did not finish a frame in %d ms; session stopped", - VCN_COMMAND_TIMEOUT_MS); + "the GPU did not finish a frame in %u ms; session stopped", limit); return -1; } if (w != VCN_WAIT_DONE) { @@ -554,6 +703,7 @@ static int submit(VcnAV1* d, AV1Params* prm, double* sched, double* wait) { } d->failure = VCNAV1_FAIL_STREAM; d->done++; + d->lastFw = fw; // Counted, not refused: what each firmware result means for the picture // has not been checked on a GPU yet. The first one of a session is logged // at once, the count goes in the stats line. @@ -574,6 +724,39 @@ static bool seq_supported(const AV1Seq* s) { static int on_frame(void* vctx, AV1Parser* p, AV1ParseResult kind) { VcnAV1* d = vctx; const AV1Frame* h = &p->fh; + // A key frame that refreshes every reference slot (a shown key frame always + // does): nothing decoded before it is used after it, so the driver objects + // can be replaced here without losing a frame. A hidden key frame that keeps + // some slots is not one: the frames after it may still use those. + bool restart = kind == AV1_PARSE_FRAME_READY && + h->frame_type == AV1_KEY_FRAME && + h->refresh_frame_flags == 0xFF; + // The system slept since the driver side opened, and it kept decoding (a + // real sleep on this Mac did not break it): it is replaced at the first such + // key frame, which then decodes on the new one. + if (d->rebuildAtKey && restart && !rebuild_now(d, false, false, NULL)) + return -1; + // After a rebuild that followed a failure nothing from before it can be + // used: every frame but such a key frame is dropped (no picture for this + // sample, which is what a hidden frame looks like to the host, not an + // error), and the key frame starts the decoder again. Bounded: a stream that + // never sends one is stopped as a device failure, PR 160's behaviour. + if (d->needKey) { + if (!restart) { + if (++d->dropped > REBUILD_MAX_DROPPED) { + d->broken = true; + d->failure = VCNAV1_FAIL_DEVICE; + snprintf(d->err, sizeof(d->err), + "no key frame in %u frames after the system sleep", + d->dropped); + return -1; + } + return 0; + } + vcnav1_flush(d); + d->needKey = false; + d->dropped = 0; + } if (kind == AV1_PARSE_SHOW_EXISTING) { AV1RefSlot* r = &p->ref[h->frame_to_show_map_idx]; if (!r->valid || r->dpb_slot < 0 || r->dpb_slot >= NUM_DPB || @@ -689,7 +872,18 @@ static int on_frame(void* vctx, AV1Parser* p, AV1ParseResult kind) { h->TileRows, p->tile_data_size, slot, h->refresh_frame_flags); double tf1 = timing ? tnow_ms() : 0; double tSched, tWait; - if (submit(d, &prm, &tSched, &tWait)) return -1; + if (submit(d, &prm, &tSched, &tWait)) + // On the session from before a sleep, a driver failure is taken for the + // sleep's doing: rebuilt at once, instead of stopping the session. + return d->rebuildAtKey && d->broken ? failed_after_wake(d, d->stuck) : -1; + if (d->rebuildAtKey) { + if (d->lastFw) { + // A firmware error on it after the wake: its picture is not trusted. + snprintf(d->err, sizeof(d->err), "firmware result %u", d->lastFw); + return failed_after_wake(d, false); + } + d->keptAfterWake++; + } if (timing) fprintf(stderr, "timing bytes=%zu prep=%.2f sched=%.2f wait=%.2f\n", p->tile_data_size, tf1 - tf0, tSched, tWait); @@ -743,6 +937,15 @@ int vcnav1_decode(VcnAV1* d, const uint8_t* tu, size_t size, int64_t userTag, CVPixelBufferRelease(d->hidden); d->hidden = NULL; } + // A sleep since the driver side opened: it keeps decoding, and on_frame + // rebuilds it at the next key frame (or at once if it fails). + if (!d->broken && !d->rebuildAtKey && vcn_session_lost(&d->s)) { + d->rebuildAtKey = true; + d->keptAfterWake = 0; + os_log_error(vlog(), + "AV1 session from before the sleep: it keeps decoding and is " + "rebuilt at the next key frame"); + } if (d->broken) { snprintf(d->err, sizeof(d->err), "session stopped: %s", d->stuck ? "the GPU did not finish an earlier frame" diff --git a/GPU/decode/build.sh b/GPU/decode/build.sh index 5812415c..2b3e6416 100755 --- a/GPU/decode/build.sh +++ b/GPU/decode/build.sh @@ -4,6 +4,8 @@ # VP9VCNDecoder.bundle vp09 on the same block # MPEG2VCNDecoder.bundle mp2v, VC1VCNDecoder.bundle vc-1/WVC1/WMV3 and # MPEG4VCNDecoder.bundle mp4v on the same block (common/vcnlegacy.c) +# JPEGVCNDecoder.bundle jpeg and dmb1 on the JPEG block of the VCN, through the VCNJpeg kext +# (jpeg/); installed only on request (install/decoders.sh --jpeg) # lvprobe the installer's helper that asks macOS whether it would accept them # kextentry the installers' helper that edits OpenCore's config.plist for the # loader kext and the sensors kext @@ -57,6 +59,7 @@ LEGACY=(common/vcnlegacy.c common/vcndriver.c common/vcnsession.c) build_bundle MPEG2VCNDecoder mpeg2 mpeg2/MPEG2VCNDecoder.c mpeg2/vcnmpeg2.c mpeg2/mpeg2parse.c $LEGACY build_bundle VC1VCNDecoder vc1 vc1/VC1VCNDecoder.c vc1/vcnvc1.c vc1/vc1parse.c $LEGACY build_bundle MPEG4VCNDecoder mpeg4 mpeg4/MPEG4VCNDecoder.c mpeg4/vcnmpeg4.c mpeg4/mpeg4parse.c $LEGACY +build_bundle JPEGVCNDecoder jpeg jpeg/JPEGVCNDecoder.c jpeg/vcnjpeg.c jpeg/jpegprep.c # lvprobe (install/lvprobe.c) asks macOS whether it would accept a plug-in; the installer # runs it. It must carry the library-validation flag, or the kernel says yes to everything. @@ -84,8 +87,8 @@ if [[ ${1:-} == tests ]]; then xcrun clang $TFLAGS -Iav1 -Ivp9 -Icommon tests/colortest.c av1/av1parse.c vp9/vp9parse.c \ -framework CoreFoundation -framework CoreMedia -framework CoreVideo -o $T/colortest xcrun clang $TFLAGS -Ivp9 tests/vp9state.c vp9/vp9parse.c -o $T/vp9state - for c in AV1 VP9; do - xcrun clang $TFLAGS -DTEST_$c -Icommon tests/plugintest.c -framework CoreFoundation -framework CoreMedia \ + for c in AV1 VP9 JPEG; do + xcrun clang $TFLAGS -DTEST_$c -Icommon -Ijpeg tests/plugintest.c -framework CoreFoundation -framework CoreMedia \ -framework CoreVideo -framework VideoToolbox -o $T/plugintest-${(L)c} done for c in MPEG2 VC1 MPEG4; do @@ -98,10 +101,11 @@ if [[ ${1:-} == tests ]]; then vc1/vc1parse.c vc1/vcnvc1.c mpeg4/mpeg4parse.c mpeg4/vcnmpeg4.c common/vcnlegacy.c common/vcndriver.c \ common/vcnsession.c -framework CoreFoundation -framework CoreVideo -framework IOKit -framework IOSurface \ -o $T/legacyparse - # The MPEG-2 and VC-1 codec layers on a stand-in for the session: what each stream sends to the + # The MPEG-2, VC-1 and MPEG-4 codec layers on a stand-in for the session: what each stream sends to the # firmware and which picture comes back. - xcrun clang $TFLAGS -Icommon -Impeg2 -Ivc1 tests/layertest.c mpeg2/mpeg2parse.c mpeg2/vcnmpeg2.c \ - vc1/vc1parse.c vc1/vcnvc1.c -framework CoreFoundation -framework CoreVideo -o $T/layertest + xcrun clang $TFLAGS -Icommon -Impeg2 -Ivc1 -Impeg4 tests/layertest.c mpeg2/mpeg2parse.c mpeg2/vcnmpeg2.c \ + vc1/vc1parse.c vc1/vcnvc1.c mpeg4/mpeg4parse.c mpeg4/vcnmpeg4.c \ + -framework CoreFoundation -framework CoreVideo -o $T/layertest # Which decoder VideoToolbox gives an MPEG-4 stream, the MPEG-4 plug-in (on a stand-in # session) next to Apple's AppleMP4V. xcrun clang $TFLAGS -Icommon -Impeg4 tests/legacypick.c mpeg4/vcnmpeg4.c mpeg4/mpeg4parse.c \ @@ -109,14 +113,26 @@ if [[ ${1:-} == tests ]]; then -o $T/legacypick 2>&1 | { grep -v -E "pointer not aligned in '_k(Base|Decoder)Class'|disabling chained fixups" || true; } xcrun clang $TFLAGS -Icommon tests/acceltest.c common/vcndriver.c -framework CoreFoundation -framework IOKit \ -o $T/acceltest - xcrun clang $TFLAGS -Icommon tests/waittest.c common/vcnsession.c -framework CoreFoundation -framework IOKit \ + # vcndriver.c for vcn_sleep_mark, which vcnsession.c reads when a session opens or closes + xcrun clang $TFLAGS -Icommon tests/waittest.c common/vcnsession.c common/vcndriver.c -framework CoreFoundation \ + -framework IOKit \ -o $T/waittest + # Two plug-ins in one process, each with its own copy of the session code (stalelib.c built + # twice), and a made-up sleep: the other sees a session from before the sleep and opens anyway. + for l in a b; do + xcrun clang $TFLAGS -dynamiclib -fvisibility=hidden -Icommon tests/stalelib.c common/vcnsession.c \ + -framework CoreFoundation -framework IOKit -install_name @rpath/libstale-$l.dylib -o $T/libstale-$l.dylib + done + xcrun clang $TFLAGS -Icommon tests/staletest.c -o $T/staletest # The decoder sessions against a made-up driver: sessiontest.c stands in for common/vcndriver.c. for c in av1 vp9; do xcrun clang $TFLAGS -DTEST_${(U)c} -Icommon -I$c tests/sessiontest.c $c/vcn$c.c $c/${c}parse.c \ common/vcnsession.c -framework CoreFoundation -framework CoreVideo -framework IOKit \ -framework IOSurface -o $T/sessiontest-$c done + # The JPEG plug-in's preparer and session against a made-up kext (it is tested also when it is not built). + xcrun clang $TFLAGS -Ijpeg tests/jpegtest.c jpeg/vcnjpeg.c jpeg/jpegprep.c -framework CoreFoundation \ + -framework CoreVideo -framework CoreGraphics -framework ImageIO -framework IOKit -o $T/jpegtest xcrun clang++ -std=c++17 $TFLAGS -Iloader tests/loadertest.cpp -o $T/loadertest print "built the test programs in decode/$T" fi diff --git a/GPU/decode/common/vcndriver.c b/GPU/decode/common/vcndriver.c index 19970a78..3f6e6afe 100644 --- a/GPU/decode/common/vcndriver.c +++ b/GPU/decode/common/vcndriver.c @@ -3,8 +3,11 @@ #include #include #include +#include #include #include +#include +#include bool vcn_codec_is_amd(CFTypeRef codec) { return codec && CFGetTypeID(codec) == CFStringGetTypeID() && @@ -75,3 +78,49 @@ bool vcn_driver_load(VcnDriverLib* lib, char* err, size_t errLen) { } return true; } + +void vcn_sleep_mark(VcnSleepMark* m) { + static mach_timebase_info_data_t tb; + if (!tb.denom) mach_timebase_info(&tb); + // mach_continuous_time is mach_absolute_time plus the time spent asleep. The + // two are read apart: a reading whose two absolute times are more than 10 us + // apart (the thread was preempted between them) is taken again. + uint64_t asleep = 0, mono = 0; + for (int i = 0; i < 8; i++) { + uint64_t a = mach_absolute_time(), c = mach_continuous_time(), + b = mach_absolute_time(); + asleep = c > b ? c - b : 0; + mono = b; + if ((b - a) * tb.numer / tb.denom < 10000) break; + } + m->asleepNs = asleep * tb.numer / tb.denom; + m->monoNs = mono * tb.numer / tb.denom; + struct timeval wall; + gettimeofday(&wall, NULL); + m->wallUs = (int64_t)wall.tv_sec * 1000000 + wall.tv_usec; + // kern.waketime changes once per sleep and costs a sysctl; the codecs ask for + // a mark on every frame (60 to 120 times a second at 4K60), so the value is + // read again at most every 100 ms of mach_absolute_time. Time spent asleep + // does not advance that clock, so a waketime read a moment before a sleep can + // be reused for a moment after the wake; the time asleep is read every time + // and is what notices the sleep. Relaxed reads and writes: a value read twice + // by two threads is the same one. + static uint64_t wakeReadAtNs; + static int64_t wakeUs; + static bool wakeKnown; + if (!__atomic_load_n(&wakeReadAtNs, __ATOMIC_RELAXED) || + m->monoNs - __atomic_load_n(&wakeReadAtNs, __ATOMIC_RELAXED) >= + 100000000ull) { + struct timeval wake = {0}; + size_t len = sizeof(wake); + bool failed = sysctlbyname("kern.waketime", &wake, &len, NULL, 0) || + len != sizeof(wake); + __atomic_store_n(&wakeUs, + failed ? 0 : (int64_t)wake.tv_sec * 1000000 + wake.tv_usec, + __ATOMIC_RELAXED); + __atomic_store_n(&wakeKnown, !failed, __ATOMIC_RELAXED); + __atomic_store_n(&wakeReadAtNs, m->monoNs, __ATOMIC_RELAXED); + } + m->wakeUs = __atomic_load_n(&wakeUs, __ATOMIC_RELAXED); + m->wakeKnown = __atomic_load_n(&wakeKnown, __ATOMIC_RELAXED); +} diff --git a/GPU/decode/common/vcndriver.h b/GPU/decode/common/vcndriver.h index d62f4054..e0906ecb 100644 --- a/GPU/decode/common/vcndriver.h +++ b/GPU/decode/common/vcndriver.h @@ -43,6 +43,72 @@ bool vcn_driver_load(VcnDriverLib* lib, char* err, size_t errLen); // frame takes 5-60 ms on Navi 21, even at the video engine's lowest clock. enum { VCN_COMMAND_TIMEOUT_MS = 1000 }; +// The same for a command on a session from before a sleep, until it is +// rebuilt. Around a real wake on this Mac (2026-11-25, 0.3.5) one frame of +// each decode took 10.2 to 10.9 s and then decoded correctly. That time was +// spent in Apple's calls (0.3.5 already gave up on a command after 1 s and +// reported no error), probably while the GPU was being started again; a +// command that waits like that on the engine itself must not be taken for a +// stuck one. A variable, so a test can make it short; the plug-ins never +// change it. +enum { VCN_WAKE_COMMAND_TIMEOUT_MS = 15000 }; +extern unsigned vcn_wake_command_timeout_ms; + +// A system sleep, as a session sees it. Apple's kernel driver keeps a decoder's +// video context across a sleep, but stops the video engine before it and starts +// it again at wake, and saves nothing of the session on the engine +// (AMDRadeonX6000, 26.7.3 KDK, read in IDA: systemWillSleep stops the VCN rings +// once their last command finished, powerUpHW and internalDidWake start them +// again, saveVCNSession is empty). Nothing in the driver, AppleGVA or +// VideoToolbox tells a decoder about it. +// +// On this Mac (RX 6800 XT, 26.7.3, 2026-11-25) a real sleep did not break the +// sessions that were open across it: 0.3.5, which knows nothing of sleeps, kept +// decoding on them after the wake with every frame matching its reference. So +// an AV1 or VP9 session from before a sleep keeps decoding, and is rebuilt +// quietly at its next key frame (vcnav1.c / vcnvp9.c), where nothing from +// before the rebuild is needed any more: no frame is dropped and no error +// reaches the host. (The MPEG-2, VC-1 and MPEG-4 sessions, vcnlegacy.c, still +// stop at the first picture after a sleep, as in 0.3.6.) Only +// when the old session fails after the wake (a driver call, a command that +// does not finish, a firmware error) is it rebuilt at once, and the frames are +// dropped until a key frame. Closing it still skips the driver's own teardown, +// which would send the engine a command for that session and wait for it with +// no time limit (vcn_session_close). +// +// The mark is the time this Mac has spent asleep since it started, as the +// kernel counts it (mach_continuous_time runs on during a sleep, +// mach_absolute_time does not), the time of the last wake (kern.waketime), and +// the wall clock read next to mach_absolute_time. Any of the three changing +// means the system slept. The third is there for a machine whose sleep path +// skips the kernel's wake accounting, where the first signal never moves, and +// whose kern.waketime is refused inside the sandbox, where the second one is +// dead: the RTC counts through a sleep even when the kernel counted none of it, +// so a wall clock that ran ahead of mach_absolute_time is a sleep the other two +// would miss. None of the three needs a notification, which a +// decoder could not get anyway: VideoToolbox's decoder service is sandboxed +// without the root power domain's user client that IORegisterForSystemPower +// opens (VTDecoderSandboxProfile.sb). +typedef struct { + uint64_t asleepNs; // time asleep since boot + int64_t wakeUs; // last wake in microseconds since 1970; 0 when unknown + bool wakeKnown; // kern.waketime could be read (its value may still be 0) + uint64_t monoNs; // mach_absolute_time at the same reading, in ns + int64_t wallUs; // that same moment on the wall clock, us since 1970 +} VcnSleepMark; + +// Reads all of it now (vcndriver.c: it asks the system). kern.waketime is a +// sysctl and the codecs ask for a mark on every frame, so that one value is +// reused for 100 ms of mach_absolute_time; a sleep is still noticed at once +// through the time asleep. +void vcn_sleep_mark(VcnSleepMark* m); + +// True when the system has slept between `then` and `now`: the time asleep +// moved by more than 1 ms (the error of a reading, not a sleep: a real one +// takes seconds), the wake time is two different non-zero values, or the wall +// clock ran more than a second ahead of mach_absolute_time (see above). +bool vcn_slept_between(const VcnSleepMark* then, const VcnSleepMark* now); + typedef enum { VCN_WAIT_DONE = 0, // finished; *hwStatus = firmware result, 0 = no error VCN_WAIT_TIMEOUT = 1, // still running after timeoutMs: the GPU is stuck @@ -65,7 +131,7 @@ enum { VCN_NUM_BS = 4 }; // One accelerator, one driver and its bitstream pool: what a decoder session // holds of the driver. The codec adds its context (ctx) itself. -typedef struct { +typedef struct VcnDriverSession { AVD_DestroyAVDAccelerator_fn destroy; AVD_Accelerator* accel; void* drv; @@ -73,6 +139,10 @@ typedef struct { void* bsAddr[VCN_NUM_BS]; io_service_t svc; // the accelerator service; released by close bool poolAllocated; + VcnSleepMark opened; // taken when open began + bool lost; // the system slept since: see vcn_session_lost + bool listed; // in this plug-in's list of open sessions (vcnsession.c) + struct VcnDriverSession* nextOpen; os_log_t log; } VcnDriverSession; @@ -80,20 +150,81 @@ typedef struct { // taken over: close releases it, and so does a failed open. On failure every // part opened so far is closed again, s is left empty and err says which call // failed. +// +// It counts, once per process, the sessions of this process that opened before +// a system sleep and are still open in any of the plug-ins (they ask each +// other through the process's local notification center), for the log. It +// does not refuse because of them: those sessions rebuild for themselves, and +// refusing turned a paused tab into no hardware decode in the whole process +// (F3 of the review; in the real sleep test of 0.3.6, every new session after +// the wake lost its first frames to it). A decoder session does not fail when +// it finds the system slept either: it keeps decoding and rebuilds its driver +// side (vcn_session_reopen) at the next key frame, so the host's decoder object +// lives on and never sees a malfunction. Only a rebuild that fails stops it. bool vcn_session_open(VcnDriverSession* s, const VcnDriverLib* lib, io_service_t svc, os_log_t log, char* err, size_t errLen); +// Opens the driver side of a session that replaces one the system slept +// through: the same work without the check for other sessions of the process +// from before the sleep (this one is being replaced, not added beside them), +// and it clears `lost`, because what it opens is from after the wake. The +// session stays in this plug-in's list of open ones. +bool vcn_session_reopen(VcnDriverSession* s, const VcnDriverLib* lib, + io_service_t svc, os_log_t log, char* err, + size_t errLen); + +// Drops the driver objects of a lost session without telling the driver +// anything: AVD_DestroyAVDAccelerator (that is what closes the IOKit clients) +// and the service. The driver handle, its context and the bitstream pool are +// left where they are, because only the driver can free them and it may be +// wedged after a wake (F4 of the review); a rebuild leaks that once per sleep +// and starts a new pool. The session stays listed as open. On a session whose +// last command finished this took 0-1 ms after a real wake (0.3.6 test, +// 2026-11-25). +void vcn_session_drop(VcnDriverSession* s); + +// The same, for a session whose last command may still be on the GPU (it did +// not finish in time, or its status could not be read): the accelerator is +// destroyed on the teardown queue (vcn_teardown), because that close can wait +// for the command in the kernel, and then `after` runs there (the codec lets go +// of the pictures the command may still write). The session is empty when this +// returns and can be opened again at once. +void vcn_session_drop_later(VcnDriverSession* s, const char* what, + void (^after)(void)); + +// True once the system has slept since s opened (see VcnSleepMark), and from +// then on; the first time, it says so in the log. The AV1 or VP9 codec that +// finds this keeps decoding on the session and rebuilds its driver side at the +// next key frame (vcnav1.c / vcnvp9.c: vcn_session_drop then +// vcn_session_reopen), or at once if the session fails after the wake; only a +// rebuild that fails stops the session, with kVTVideoDecoderMalfunctionErr +// (-12911). A session with no accelerator is never lost. +bool vcn_session_lost(VcnDriverSession* s); + // Closes what open (and the codec's CreateContexts) made, in the order Apple's // own decoders use: DeleteContexts, FreeBitstreamBufferPool (only when the pool // was allocated), DeleteDriver, AVD_DestroyAVDAccelerator, then the service. // Every step can block in the kernel while a command is still on the GPU. +// +// A lost session (vcn_session_lost) skips the first three. DeleteContexts, and +// DeleteDriver for a context still open, send the engine a destroy command for +// the session and wait for it with no time limit (AMDRadeonVADriver2: +// VADecoder::Terminate -> DestroyDecodeSession -> waitForCurrentEvent), for a +// session the engine lost at wake; the pool's textures may wait for a command +// the wake dropped. Only AVD_DestroyAVDAccelerator runs: it closes the +// accelerator's device, shared and video context connections, and the kernel's +// close of a video context sends the engine nothing (AMDRadeonX6000: +// contextStop -> destroyVCNSession -> submitDestroyCommand, which returns at +// once). What the driver allocated in this process stays allocated: nothing +// touches it again. void vcn_session_close(VcnDriverSession* s); -// Runs close() now, or, when stuck (a command never finished), on a background -// queue, with a log line before and after: the driver's teardown then waits in -// the kernel for that command, and the caller (VideoToolbox's invalidate) must -// not wait with it. what names the session in the log. -void vcn_teardown(bool stuck, os_log_t log, const char* what, +// Runs close() now, or on a background queue when stuck (a command never +// finished) or lost (the system slept since the session opened), with a log +// line before and after: the teardown may then wait in the kernel, and the +// caller (VideoToolbox's invalidate) must not wait with it. what names the +// session in the log. +void vcn_teardown(bool stuck, bool lost, os_log_t log, const char* what, void (^close)(void)); // Waits until every teardown handed to the background queue has finished, at diff --git a/GPU/decode/common/vcnlegacy.c b/GPU/decode/common/vcnlegacy.c index 88c73806..7421bb1f 100644 --- a/GPU/decode/common/vcnlegacy.c +++ b/GPU/decode/common/vcnlegacy.c @@ -94,6 +94,9 @@ static bool mapped(const void* p, size_t n, vm_prot_t prot); static const char* const kValidatedDrivers[] = { "1181E2CA31B33DF090E23AE70552D753", // macOS 26.7.2 (25G332) and 26.7.3 // (25G342, same binary) + "F7D8F5849EC139DB857C769697294957", // macOS 26.7.4 (25G422): same code + // as 26.7.3 (2760/2760 functions + // identical, only a build path) }; // --------------------------------------------------------------------------- @@ -210,8 +213,13 @@ uint32_t vcnlegacy_build_message(uint8_t* msg, size_t cap, uint8_t* d = msg + decodeOff; const uint32_t a = w <= 32 ? 32 : 64; U32(d, 0) = m->codecId; - U32(d, 8) = m->sizeInMacroblocks ? (w + 15) / 16 : w; - U32(d, 12) = m->sizeInMacroblocks ? (h + 15) / 16 : h; + // db_pitch and db_aligned_height below come out the same from either size. + U32(d, 8) = m->sizeInMacroblocks ? (w + 15) / 16 + : m->alignSizeTo16 ? al(w, 16) + : w; + U32(d, 12) = m->sizeInMacroblocks ? (h + 15) / 16 + : m->alignSizeTo16 ? al(h, 16) + : h; U32(d, 16) = m->bitstreamSize; U32(d, 20) = m->dpbSize; U32(d, 24) = (uint32_t)(((uint64_t)3 * pitch * texh) >> 1); @@ -351,6 +359,7 @@ static int hook_set_message(uint8_t* proc, const LegacyParams* prm, .width = DEC_WIDTH(dec), .height = DEC_HEIGHT(dec), .sizeInMacroblocks = d->cfg.sizeInMacroblocks, + .alignSizeTo16 = d->cfg.alignSizeTo16, .pitch = TEX_PITCH(target), .texHeight = TEX_HEIGHT(target), .bytesPerElement = TEX_BPE(target), @@ -660,9 +669,10 @@ static void destroy_now(VcnLegacy* d) { void vcnlegacy_destroy(VcnLegacy* d) { if (!d) return; - vcn_teardown(d->stuck, d->log, "legacy codec session", ^{ - destroy_now(d); - }); + vcn_teardown(d->stuck, vcn_session_lost(&d->s), d->log, + "legacy codec session", ^{ + destroy_now(d); + }); } static bool driver_validated(const VcnDriverLib* lib) { @@ -846,10 +856,14 @@ int vcnlegacy_decode(VcnLegacy* d, const void* block, uint32_t blockSize, d->err[0] = 0; d->failure = VCNLEGACY_FAIL_STREAM; d->haveStatus = false; + // Nothing goes into the pool or to the engine for a session from before a + // system sleep (vcndriver.h). + if (!d->broken && vcn_session_lost(&d->s)) d->broken = true; if (d->broken) { snprintf(d->err, sizeof(d->err), "session stopped: %s", - d->stuck ? "the GPU did not finish an earlier picture" - : "an earlier driver call failed"); + d->stuck ? "the GPU did not finish an earlier picture" + : d->s.lost ? "the system slept since it opened" + : "an earlier driver call failed"); d->failure = VCNLEGACY_FAIL_DEVICE; return -1; } diff --git a/GPU/decode/common/vcnlegacy.h b/GPU/decode/common/vcnlegacy.h index f6b052b8..2016217f 100644 --- a/GPU/decode/common/vcnlegacy.h +++ b/GPU/decode/common/vcnlegacy.h @@ -44,6 +44,10 @@ typedef struct { // VC-1 simple and main profile: the decode block carries the size in // macroblocks (Mesa, ac_vcn_dec.c vcn_build_decode_cmd). bool sizeInMacroblocks; + // MPEG-4: the decode block carries the size aligned to 16 (1920x1080 as + // 1920x1088), as Mesa's radeon_create_decoder aligns dec->base for this + // codec. The pictures keep the real size. + bool alignSizeTo16; const char* logSubsystem; // os_log subsystem of the codec } VcnLegacyConfig; @@ -98,6 +102,7 @@ typedef struct { uint32_t codecId, messageId; uint32_t width, height; bool sizeInMacroblocks; + bool alignSizeTo16; // width/height_in_samples aligned to 16 uint32_t pitch, texHeight, bytesPerElement; // of the target texture uint32_t dpbSize, bitstreamSize; uint32_t streamHandle, feedbackNumber; diff --git a/GPU/decode/common/vcnsession.c b/GPU/decode/common/vcnsession.c index ebf3c9e5..d746a11b 100644 --- a/GPU/decode/common/vcnsession.c +++ b/GPU/decode/common/vcnsession.c @@ -1,9 +1,11 @@ // The part of a decoder session that only talks to the driver through its // function pointers: the wait for a command, opening and closing the -// accelerator, driver and bitstream pool. See vcndriver.h. +// accelerator, driver and bitstream pool, and what a system sleep does to a +// session. See vcndriver.h. #include #include #include +#include #include #include #include @@ -61,16 +63,179 @@ VcnWaitResult vcn_wait_command(AVD_QueryAVDCommandStatus_fn query, void* driver, #define FN(name) ((AVD_##name##_fn)s->accel->fn[AVD_FN_##name]) -bool vcn_session_open(VcnDriverSession* s, const VcnDriverLib* lib, - io_service_t svc, os_log_t log, char* err, - size_t errLen) { +unsigned vcn_wake_command_timeout_ms = VCN_WAKE_COMMAND_TIMEOUT_MS; + +bool vcn_slept_between(const VcnSleepMark* then, const VcnSleepMark* now) { + if (now->asleepNs > then->asleepNs + 1000000) return true; + if (then->wakeUs && now->wakeUs && then->wakeUs != now->wakeUs) return true; + // The wall clock counts through a sleep even when the kernel counted none of + // it, and mach_absolute_time does not: the two running apart by more than a + // second is a sleep neither of the other signals saw. A wall clock set back + // (NTP, a manual change) makes the difference negative and is not a sleep; a + // clock set forward is, which is the safe direction. + if (then->wallUs && now->wallUs) { + int64_t wallUs = now->wallUs - then->wallUs; + int64_t monoUs = (int64_t)(now->monoNs - then->monoNs) / 1000; + if (wallUs - monoUs > 1000000) return true; + } + return false; +} + +bool vcn_session_lost(VcnDriverSession* s) { + if (s->lost) return true; + if (!s->accel) return false; + VcnSleepMark now; + vcn_sleep_mark(&now); + if (!vcn_slept_between(&s->opened, &now)) return false; + s->lost = true; + os_log_error(s->log, + "the system slept since this session opened (%.1f s asleep in " + "between)", + now.asleepNs > s->opened.asleepNs + ? (double)(now.asleepNs - s->opened.asleepNs) / 1e9 + : 0.0); + return true; +} + +// The open sessions of this plug-in, and how the plug-ins of a process count +// each other's sessions from before a sleep. Each plug-in bundle has its own +// copy of this file. They meet in the process's local notification center, +// which calls every observer, in every image, on the posting thread before the +// post returns. +static pthread_mutex_t g_open_lock = PTHREAD_MUTEX_INITIALIZER; +static VcnDriverSession* g_open; + +static void list_open(VcnDriverSession* s) { + pthread_mutex_lock(&g_open_lock); + s->nextOpen = g_open; + g_open = s; + s->listed = true; + pthread_mutex_unlock(&g_open_lock); +} +static void unlist(VcnDriverSession* s) { + if (!s->listed) return; + pthread_mutex_lock(&g_open_lock); + for (VcnDriverSession** p = &g_open; *p; p = &(*p)->nextOpen) + if (*p == s) { + *p = s->nextOpen; + break; + } + s->listed = false; + pthread_mutex_unlock(&g_open_lock); +} + +#define STALE_QUERY CFSTR("com.droga.vcn.sessions-from-before-a-sleep") +typedef struct { + VcnSleepMark now; + int stale; +} StaleQuery; + +// One plug-in's answer: how many of its open sessions opened before a sleep. +static void count_stale(CFNotificationCenterRef center, void* observer, + CFNotificationName name, const void* object, + CFDictionaryRef info) { + (void)center, (void)observer, (void)name, (void)object; + CFNumberRef n = info ? CFDictionaryGetValue(info, CFSTR("query")) : NULL; + int64_t addr = 0; + if (!n || CFGetTypeID(n) != CFNumberGetTypeID() || + !CFNumberGetValue(n, kCFNumberSInt64Type, &addr) || !addr) + return; + StaleQuery* q = (StaleQuery*)(intptr_t)addr; + pthread_mutex_lock(&g_open_lock); + for (VcnDriverSession* s = g_open; s; s = s->nextOpen) + if (vcn_slept_between(&s->opened, &q->now)) q->stale++; + pthread_mutex_unlock(&g_open_lock); +} + +static void pin_this_image(void); + +// Sessions of this process, in every plug-in, opened before a sleep and still +// open; -1 when the question could not be asked. +static int stale_sessions(const VcnSleepMark* now) { + static dispatch_once_t once; + dispatch_once(&once, ^{ + // The observer is called from other plug-ins: this image must stay. + pin_this_image(); + CFNotificationCenterAddObserver( + CFNotificationCenterGetLocalCenter(), (const void*)&g_open, count_stale, + STALE_QUERY, NULL, CFNotificationSuspensionBehaviorDeliverImmediately); + }); + StaleQuery q = {.now = *now}; + int64_t addr = (int64_t)(intptr_t)&q; + CFNumberRef n = CFNumberCreate(NULL, kCFNumberSInt64Type, &addr); + const void* k[] = {CFSTR("query")}; + const void* v[] = {n}; + CFDictionaryRef info = + n ? CFDictionaryCreate(NULL, k, v, 1, &kCFTypeDictionaryKeyCallBacks, + &kCFTypeDictionaryValueCallBacks) + : NULL; + if (n) CFRelease(n); + if (!info) return -1; + CFNotificationCenterPostNotification(CFNotificationCenterGetLocalCenter(), + STALE_QUERY, NULL, info, true); + CFRelease(info); + return q.stale; +} + +// Shared by open and reopen. `rebuild` keeps the session in this plug-in's +// list of open sessions (it is replacing one, not adding one) and skips the +// question asked of the other plug-ins, which was for a new session opened +// beside a stale one; a rebuild is the answer to that case now. +static bool open_session(VcnDriverSession* s, const VcnDriverLib* lib, + io_service_t svc, os_log_t log, bool rebuild, + char* err, size_t errLen) { + bool listed = s->listed; + VcnDriverSession* nextOpen = s->nextOpen; *s = (VcnDriverSession){.destroy = lib->destroy, .svc = svc, .log = log}; + if (rebuild) { + // Already in the list: keep it there (close unlists it if this fails). + s->listed = listed; + s->nextOpen = nextOpen; + } + // Before anything is opened: a sleep during the open loses the session too. + vcn_sleep_mark(&s->opened); + if (!s->opened.wakeKnown) { + // Not fatal: the other two signals still count. Said once, because in a + // sandbox it is the expected case (container.sb lists kern.waketime by + // name, so a profile stricter than that one refuses it) and the value is + // never read later, which used to be invisible. + static bool told; + if (!__atomic_exchange_n(&told, true, __ATOMIC_RELAXED)) + os_log_error(log, + "kern.waketime is not readable in this process: a sleep is " + "noticed through the monotonic and wall clocks only"); + } #define FAIL(...) \ do { \ snprintf(err, errLen, __VA_ARGS__); \ vcn_session_close(s); \ return false; \ } while (0) + // Other sessions of this process from before a sleep are only counted now: a + // new session opens beside them and each one rebuilds for itself, which is + // what stops a paused tab from turning hardware decode off for the process + // (F3 of the review). A rebuild does not ask at all. + int stale = rebuild ? 0 : stale_sessions(&s->opened); + if (stale < 0) { + // The question could not be asked (no memory for the dictionary). Fail + // open, as a decoder must, but say so once: this is the one case where + // the guard is not in force. + static bool toldQuery; + if (!__atomic_exchange_n(&toldQuery, true, __ATOMIC_RELAXED)) + os_log_error(log, + "could not ask the other plug-ins for sessions from before " + "a sleep: this session opens beside them"); + } + if (stale > 0) { + // Once per process: the count is a diagnostic, not a refusal any more. + static bool toldStale; + if (!__atomic_exchange_n(&toldStale, true, __ATOMIC_RELAXED)) + os_log_error(log, + "%d session(s) of this process from before a system sleep " + "are still open: this one opens beside them and rebuilds " + "for itself if it needs to", + stale); + } if (!lib->destroy) { // Said once per process: every session would say the same. static bool told; @@ -119,12 +284,75 @@ bool vcn_session_open(VcnDriverSession* s, const VcnDriverLib* lib, for (int i = 0; i < VCN_NUM_BS; i++) if (!s->bsAddr[i]) FAIL("AllocateBitstreamBufferPool: no buffer %d", i); #undef FAIL + if (!rebuild) list_open(s); return true; } +bool vcn_session_open(VcnDriverSession* s, const VcnDriverLib* lib, + io_service_t svc, os_log_t log, char* err, + size_t errLen) { + return open_session(s, lib, svc, log, false, err, errLen); +} + +bool vcn_session_reopen(VcnDriverSession* s, const VcnDriverLib* lib, + io_service_t svc, os_log_t log, char* err, + size_t errLen) { + return open_session(s, lib, svc, log, true, err, errLen); +} + +// Takes the accelerator and the service out of s and forgets the rest of the +// driver objects (see vcn_session_drop); the session stays listed. +static void detach(VcnDriverSession* s, AVD_Accelerator** accel, + io_service_t* svc) { + *accel = s->accel; + *svc = s->svc; + s->accel = NULL; + s->drv = NULL; + s->ctx = NULL; + s->poolAllocated = false; + memset(s->bsAddr, 0, sizeof(s->bsAddr)); + s->svc = 0; +} + +void vcn_session_drop(VcnDriverSession* s) { + if (!s->accel) return; + // No DeleteContexts, FreeBitstreamBufferPool or DeleteDriver: those send the + // engine a command for a session it has forgotten and wait with no limit. + AVD_Accelerator* accel; + io_service_t svc; + detach(s, &accel, &svc); + if (s->destroy) s->destroy(accel); + if (svc) IOObjectRelease(svc); +} + +void vcn_session_drop_later(VcnDriverSession* s, const char* what, + void (^after)(void)) { + AVD_Accelerator* accel; + io_service_t svc; + detach(s, &accel, &svc); + AVD_DestroyAVDAccelerator_fn destroy = s->destroy; + // vcn_teardown copies the block, and with it `after`. + vcn_teardown(true, false, s->log, what, ^{ + if (accel && destroy) destroy(accel); + // Released only after the driver is gone: it may hold on to the service. + if (svc) IOObjectRelease(svc); + if (after) after(); + }); +} + +// Skipping the driver's own teardown keeps this close from waiting on a command +// for a session the engine has forgotten, but it does not make it a +// non-blocking call: AVD_DestroyAVDAccelerator below still closes three IOKit +// user clients, and on the kernel side a context stop goes through PowerPlay's +// notify (escape 0x34), which can wait after a failed wake. That is why a lost +// or stuck session is closed on the teardown queue (vcn_teardown) and never on +// the caller's thread. void vcn_session_close(VcnDriverSession* s) { + // Asked here too: a session can be closed without having been asked since + // the wake (a paused video that is closed after it). + bool lost = vcn_session_lost(s); if (s->accel) { - if (s->drv) { + if (s->drv && !lost) { if (s->ctx) { void* ctxs[1] = {s->ctx}; AVD_DriverContextDelete del = {.count = 1, .contexts = ctxs}; @@ -134,7 +362,27 @@ void vcn_session_close(VcnDriverSession* s) { FN(DeleteDriver)(s->drv); } if (s->destroy) s->destroy(s->accel); + if (lost) { + // What the skipped teardown leaves behind, and how much of it this + // process has left behind so far: the driver's pool and context go with + // the driver handle, which is never deleted here. Accounting only; the + // fix is a process that does not sleep with sessions open. + static long lostCloses; + long n = __atomic_add_fetch(&lostCloses, 1, __ATOMIC_RELAXED); + os_log_error( + s->log, + "session from before the sleep closed without the driver's own " + "teardown: %ld so far in this process, up to %lld MiB of the " + "driver's bitstream pool and its context not returned%{public}s", + n, (long long)n * VCN_NUM_BS * VCN_BS_SIZE / (1024 * 1024), + s->destroy ? "" + : " (this driver build has no " + "AVD_DestroyAVDAccelerator: it stays open)"); + } } + // Out of the list only now: until the accelerator is closed, the session + // still counts as open for a new one. + unlist(s); // Released only after the driver is gone: it may hold on to the service. if (s->svc) IOObjectRelease(s->svc); os_log_t log = s->log; @@ -156,32 +404,39 @@ static dispatch_queue_t teardown_queue(void) { // A close may still run after the host is done with the plug-in. If the // host unloaded the bundle by then, the queue would run code that is gone: // this image stays loaded for the life of the process. - Dl_info info; - if (dladdr((const void*)vcn_teardown, &info) && info.dli_fname) - dlopen(info.dli_fname, RTLD_NOW | RTLD_NOLOAD | RTLD_NODELETE); + pin_this_image(); }); return q; } -void vcn_teardown(bool stuck, os_log_t log, const char* what, +static void pin_this_image(void) { + Dl_info info; + if (dladdr((const void*)vcn_teardown, &info) && info.dli_fname) + dlopen(info.dli_fname, RTLD_NOW | RTLD_NOLOAD | RTLD_NODELETE); +} + +void vcn_teardown(bool stuck, bool lost, os_log_t log, const char* what, void (^close)(void)) { - if (!stuck) { + if (!stuck && !lost) { close(); return; } // Kept for the line after the close, which runs once the caller is gone. char* name = strdup(what ? what : "session"); - os_log_error(log, - "%{public}s: a command never finished; closing the session on " - "a background thread, the driver may wait for the GPU", - name ? name : "session"); + os_log_error( + log, + "%{public}s: %{public}s; closing the session on a background " + "thread, the close may wait for the GPU", + name ? name : "session", + stuck ? "a command never finished" : "the system slept since it opened"); dispatch_queue_t q = teardown_queue(); // also makes the group // dispatch_group_async copies this block, and with it close. dispatch_group_async(teardown_group, q, ^{ double t0 = wait_now_ms(); close(); - os_log_error(log, "%{public}s: stuck session closed after %.0f ms", - name ? name : "session", wait_now_ms() - t0); + os_log_error(log, "%{public}s: %{public}s session closed after %.0f ms", + name ? name : "session", stuck ? "stuck" : "lost", + wait_now_ms() - t0); free(name); }); } diff --git a/GPU/decode/jpeg/Info.plist b/GPU/decode/jpeg/Info.plist new file mode 100644 index 00000000..29dac93c --- /dev/null +++ b/GPU/decode/jpeg/Info.plist @@ -0,0 +1,81 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + JPEGVCNDecoder + CFBundleIdentifier + com.droga.videodecoder.jpeg.vcn + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + JPEGVCNDecoder + CFBundlePackageType + BNDL + CFBundleShortVersionString + __VERSION__ + CFBundleVersion + __VERSION__ + LSMinimumSystemVersion + 13.0 + CMClassImplementations + + + CMClassID + com.apple.videotoolbox.videodecoder + CMClassImplementationID + com.droga.videodecoder.jpeg.vcn + CMClassImplementationName + AMD VCN JPEG Decoder + CMClassImplementationVersion + 1 + CMExecutableArchitectures + + x86_64 + + CMFactoryFunction + JPEGVCN_VTDecoder_CreateInstance + CMManufacturer + droga + CMMatchingInfo + + VTCodecType + jpeg + VTIsHardwareAccelerated + + VTRating + 400 + + + + CMClassID + com.apple.videotoolbox.videodecoder + CMClassImplementationID + com.droga.videodecoder.dmb1.vcn + CMClassImplementationName + AMD VCN Motion JPEG (OpenDML) Decoder + CMClassImplementationVersion + 1 + CMExecutableArchitectures + + x86_64 + + CMFactoryFunction + JPEGVCN_VTDecoder_CreateInstance + CMManufacturer + droga + CMMatchingInfo + + VTCodecType + dmb1 + VTIsHardwareAccelerated + + VTRating + 400 + + + + + diff --git a/GPU/decode/jpeg/JPEGVCNDecoder.c b/GPU/decode/jpeg/JPEGVCNDecoder.c new file mode 100644 index 00000000..4fe14f84 --- /dev/null +++ b/GPU/decode/jpeg/JPEGVCNDecoder.c @@ -0,0 +1,759 @@ +// VideoToolbox decoder plugin for 'jpeg' (Photo JPEG / Motion JPEG A) and +// 'dmb1' (Open DML Motion JPEG) on the JPEG block of the AMD VCN (macOS +// x86_64), built on vcnjpeg. It is VP9VCNDecoder.c with the VP9 parts taken +// out: the same ABI, the same threading and the same tests (tests/plugintest.c +// with -DTEST_JPEG); see vtav1/AV1VCNDecoder.c for where the private plugin +// interface comes from. +// +// It needs the VCNJpeg kext (GPU/jpeg). Both are installed only on request +// (install/decoders.sh --jpeg, install/jpeg.sh; install.sh --with-jpeg). +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "vcnjpeg.h" + +// ---- private CoreMedia / VideoToolbox plugin SPI +// ------------------------------------------- +typedef const void* CMBaseClassID; +typedef struct OpaqueCMBaseObject* CMBaseObjectRef; +typedef struct OpaqueVTVideoDecoder* VTVideoDecoderRef; +typedef struct OpaqueVTVideoDecoderSession* VTVideoDecoderSession; +typedef struct OpaqueVTVideoDecoderFrame* VTVideoDecoderFrame; + +#pragma pack(push, 4) +typedef struct { + uint32_t version; + size_t derivedStorageSize; + Boolean (*equal)(CMBaseObjectRef, CMBaseObjectRef); + OSStatus (*invalidate)(CMBaseObjectRef); + void (*finalize)(CMBaseObjectRef); + CFStringRef (*copyDebugDescription)(CMBaseObjectRef); + OSStatus (*copyProperty)(CMBaseObjectRef, CFStringRef, CFAllocatorRef, void*); + OSStatus (*setProperty)(CMBaseObjectRef, CFStringRef, CFTypeRef); + OSStatus (*notificationBarrier)(CMBaseObjectRef); + const void* propertyHandlers; +} CMBaseClass; + +typedef struct { + uint32_t version; + OSStatus (*startSession)(VTVideoDecoderRef, VTVideoDecoderSession, + CMVideoFormatDescriptionRef); + OSStatus (*decodeFrame)(VTVideoDecoderRef, VTVideoDecoderFrame, + CMSampleBufferRef, VTDecodeFrameFlags, + VTDecodeInfoFlags*); + OSStatus (*copySupportedPropertyDictionary)(VTVideoDecoderRef, + CFDictionaryRef*); + OSStatus (*setProperties)(VTVideoDecoderRef, CFDictionaryRef); + OSStatus (*copySerializableProperties)(VTVideoDecoderRef, CFAllocatorRef, + CFDictionaryRef*); + Boolean (*canAcceptFormatDescription)(VTVideoDecoderRef, + CMFormatDescriptionRef); + OSStatus (*finishDelayedFrames)(VTVideoDecoderRef); + void* reserved[6]; +} VTVideoDecoderClass; +#pragma pack(pop) + +typedef struct { + void* reserved; + const CMBaseClass* baseClass; + const VTVideoDecoderClass* decoderClass; +} VTVideoDecoderVTable; + +extern OSStatus CMDerivedObjectCreate(CFAllocatorRef, const void* vtable, + CMBaseClassID, CMBaseObjectRef*); +extern void* CMBaseObjectGetDerivedStorage(CMBaseObjectRef); +extern CMBaseClassID VTVideoDecoderGetClassID(void); +extern CMBaseObjectRef VTVideoDecoderGetCMBaseObject(VTVideoDecoderRef); +extern OSStatus VTDecoderSessionSetPixelBufferAttributes(VTVideoDecoderSession, + CFDictionaryRef); +extern OSStatus VTDecoderSessionEmitDecodedFrame(VTVideoDecoderSession, + VTVideoDecoderFrame, OSStatus, + VTDecodeInfoFlags, + CVImageBufferRef); + +// ---- decoder instance +// ---------------------------------------------------------------------- +// What the decode queue and the calls still inside the plug-in use. It lives +// apart from the CoreMedia storage, which CoreMedia frees as soon as finalize +// returns, and it is counted: the storage holds one reference, each queued +// frame one and each call in the plug-in one, and the last to let go frees +// it. finalize can run on the decode queue (a host that lets go of its session +// from inside its output callback), where it may wait for nothing: the frames +// still queued and a call waiting for the queue then find the state alive, +// closed, and emit nothing. +typedef struct { + VTVideoDecoderSession session; + VcnJpeg* vcn; + int32_t width, height; + bool tenBit; // never: kept so the code stays the one of the VP9 plug-in + // Set by invalidate once the queue is drained, and by finalize: nothing is + // emitted any more. + bool invalidated; + CVPixelBufferRef + lastFrame; // retained shown frame of the chunk being decoded + pthread_mutex_t lock; + // What canAcceptFormatDescription reads, under meta. A decode holds lock + // for as long as the GPU takes; meta is never held across a driver call. + pthread_mutex_t meta; + CMVideoFormatDescriptionRef format; // of the running session; NULL: none + bool broken; // the session failed as a device: it decodes nothing more + // Also under meta. closing: invalidate or finalize has begun, frames are + // refused. callers: decodeFrame calls from outside the decode queue that + // are still in the plug-in (waiting for a slot, queuing, or decoding at + // once); idle is signalled when the count drops to 0. + bool closing; + int callers; + pthread_cond_t idle; + dispatch_queue_t + queue; // serial: frames are decoded (and emitted) in submission order + dispatch_semaphore_t slots; // bounds frames queued but not yet decoded + // stats, logged every STATS_EVERY frames: decode = vcnjpeg_decode time, queue + // = enqueue -> start + int st_n, st_over, st_depth_max, depth; + double st_dec_sum, st_dec_max, st_q_sum, st_q_max, st_t0; + // frame time of the stream (ms, 0 until known) and the last sample's time + double st_frame_ms, st_frame_sum; + CMTime st_last_pts; + int refs; // see above; changed with atomics only +} State; + +// The CoreMedia storage of the decoder object. +typedef struct { + State* state; // NULL once finalized +} Storage; + +#define STATS_EVERY 120 + +// Frames that may wait in the queue. The VCN runs one command at a time, the +// queue only lets the caller keep feeding samples while the previous one +// decodes. (The JPEG block, too, runs one picture at a time.) +#define MAX_QUEUED 4 + +// The JPEG block of Navi 21 takes up to 16384 x 16384 (Linux, nv.c). Nothing +// has run on the GPU yet; the kext's buffers set the real limit per picture. +#define MAX_WIDTH 16384 +#define MAX_HEIGHT 16384 + +static os_log_t logger(void) { + static os_log_t l; + static dispatch_once_t once; + dispatch_once(&once, ^{ + l = os_log_create("com.droga.vtjpegvcn", "decoder"); + }); + return l; +} + +// Driver sessions of this plug-in in this process, for the log: a host that +// keeps creating sessions without ending them shows up as a growing "live". +static long g_started, g_ended, g_live; + +// Sets the format canAcceptFormatDescription compares with (NULL: none), for +// a session that starts or ends. Either way the session is not broken. +static void set_format(State* s, CMVideoFormatDescriptionRef fmt) { + pthread_mutex_lock(&s->meta); + CMVideoFormatDescriptionRef old = s->format; + s->format = fmt ? (CMVideoFormatDescriptionRef)CFRetain(fmt) : NULL; + s->broken = false; + pthread_mutex_unlock(&s->meta); + if (old) CFRelease(old); +} + +// Ends the decoder session, if there is one, and logs it with the counts. The +// caller holds s->lock or is the only one left using s. +static void end_session(State* s, const char* why) { + set_format(s, NULL); + if (!s->vcn) return; + vcnjpeg_destroy(s->vcn); + s->vcn = NULL; + long ended = __atomic_add_fetch(&g_ended, 1, __ATOMIC_RELAXED), + live = __atomic_sub_fetch(&g_live, 1, __ATOMIC_RELAXED), + started = __atomic_load_n(&g_started, __ATOMIC_RELAXED); + os_log_info(logger(), + "session %dx%d ended (%{public}s): %ld started, %ld ended, %ld " + "live in this process", + s->width, s->height, why, started, ended, live); +} + +static State* state_retain(State* s) { + __atomic_add_fetch(&s->refs, 1, __ATOMIC_RELAXED); + return s; +} +// The last one frees the state. Nothing is queued and no call is inside the +// plug-in by then: no lock is held, nobody waits on the semaphore and every +// slot has been given back. +static void state_release(State* s) { + if (__atomic_sub_fetch(&s->refs, 1, __ATOMIC_ACQ_REL)) return; + end_session(s, "finalized"); // finalize ended it already: only the format + if (s->lastFrame) CVPixelBufferRelease(s->lastFrame); + if (s->queue) dispatch_release(s->queue); + if (s->slots) dispatch_release(s->slots); + pthread_mutex_destroy(&s->lock); + pthread_mutex_destroy(&s->meta); + pthread_cond_destroy(&s->idle); + free(s); +} + +// The state of a decoder, without a reference: for calls that wait for +// nothing. +static State* state_of(VTVideoDecoderRef dec) { + Storage* st = + CMBaseObjectGetDerivedStorage(VTVideoDecoderGetCMBaseObject(dec)); + return __atomic_load_n(&st->state, __ATOMIC_ACQUIRE); +} +// The same with a reference, for a call that may wait for the decode queue: +// it keeps the state alive until the call lets go, also if the decoder is +// finalized meanwhile. NULL after finalize. +static State* state_enter(VTVideoDecoderRef dec) { + State* s = state_of(dec); + return s ? state_retain(s) : NULL; +} + +// Marks the decode queue. The output callback runs on it, and a call made from +// inside the callback must not wait for the queue, which is busy running it. +static char kQueueKey; +static bool on_queue(State* s) { + return dispatch_get_specific(&kQueueKey) == s; +} +// Waits until every queued frame has been emitted, also those queued from +// inside the callback while it waited. From inside the callback the frames +// queued after the running one cannot be waited for. +static void drain(State* s) { + if (!s->queue || on_queue(s)) return; + do + dispatch_sync(s->queue, ^{ + }); + while (__atomic_load_n(&s->depth, __ATOMIC_RELAXED) > 0); +} + +// A decodeFrame call from outside the decode queue counts itself in callers +// for as long as it runs. Returns false, counting nothing, once invalidate or +// finalize has begun. +static bool enter_call(State* s, bool counted) { + pthread_mutex_lock(&s->meta); + bool open = !s->closing; + if (open && counted) s->callers++; + pthread_mutex_unlock(&s->meta); + return open; +} +static void leave_call(State* s) { + pthread_mutex_lock(&s->meta); + if (--s->callers == 0) pthread_cond_broadcast(&s->idle); + pthread_mutex_unlock(&s->meta); +} +static bool is_closing(State* s) { + pthread_mutex_lock(&s->meta); + bool closing = s->closing; + pthread_mutex_unlock(&s->meta); + return closing; +} +// Refuses frames from now on and waits for the decodeFrame calls still on +// their way in: drain() only sees frames already queued, and a call that +// waits for a slot has not queued its frame yet. From the decode queue (the +// output callback) nothing is waited for: a call waiting for a slot may be +// waiting for the frame whose callback this is. Such a call refuses its frame +// once it gets the slot. Its own reference keeps the state until it has +// left, as each queued frame's own does until the frame has run, also when +// finalize runs on the queue. +static void close_calls(State* s) { + pthread_mutex_lock(&s->meta); + s->closing = true; + if (!on_queue(s)) + while (s->callers > 0) pthread_cond_wait(&s->idle, &s->meta); + pthread_mutex_unlock(&s->meta); +} + +// ---- CMBaseClass +// --------------------------------------------------------------------------- +static OSStatus base_invalidate(CMBaseObjectRef obj) { + Storage* st = CMBaseObjectGetDerivedStorage(obj); + State* s = __atomic_load_n(&st->state, __ATOMIC_ACQUIRE); + if (!s) return noErr; + state_retain(s); + // Frames handed in from now on are refused; the ones already queued are + // still emitted. + close_calls(s); + drain(s); + pthread_mutex_lock(&s->lock); + // None is emitted any more. + __atomic_store_n(&s->invalidated, true, __ATOMIC_RELAXED); + end_session(s, "invalidated"); + pthread_mutex_unlock(&s->lock); + state_release(s); + return noErr; +} + +// Off the decode queue this waits, as invalidate does, for the calls still on +// their way in and for every queued frame. On the queue (the host let go of +// the decoder from inside its output callback) it waits for neither: the +// frames queued behind the running one and a call waiting for the queue on +// another thread still hold the state, run after this returns and emit +// nothing. Either way the session ends here, once, under lock: a decode holds +// lock for as long as the GPU works on its frame, and on the queue the frame +// whose callback this is has finished with the GPU before it emits. +static void base_finalize(CMBaseObjectRef obj) { + Storage* st = CMBaseObjectGetDerivedStorage(obj); + State* s = __atomic_exchange_n(&st->state, NULL, __ATOMIC_ACQ_REL); + if (!s) return; + close_calls(s); + drain(s); + pthread_mutex_lock(&s->lock); + __atomic_store_n(&s->invalidated, true, __ATOMIC_RELAXED); + end_session(s, "finalized"); // releases the format too + pthread_mutex_unlock(&s->lock); + state_release(s); // the storage's reference: the last one frees the state +} + +static CFStringRef base_copy_debug_description(CMBaseObjectRef obj) { + return CFStringCreateWithFormat(NULL, NULL, CFSTR(""), + obj); +} + +static OSStatus base_copy_property(CMBaseObjectRef obj, CFStringRef key, + CFAllocatorRef alloc, void* out) { + if (!key || !out) return kVTParameterErr; + if (CFEqual( + key, + kVTDecompressionPropertyKey_UsingHardwareAcceleratedVideoDecoder)) { + *(CFTypeRef*)out = CFRetain(kCFBooleanTrue); + return noErr; + } + return kVTPropertyNotSupportedErr; +} + +static OSStatus base_set_property(CMBaseObjectRef obj, CFStringRef key, + CFTypeRef value) { + return kVTPropertyNotSupportedErr; +} + +// ---- VTVideoDecoderClass +// ------------------------------------------------------------------- +static OSStatus start_session(State* s, VTVideoDecoderSession session, + CMVideoFormatDescriptionRef fmt) { + if (!fmt) return kVTParameterErr; + CMVideoDimensions dim = CMVideoFormatDescriptionGetDimensions(fmt); + if (dim.width <= 0 || dim.height <= 0) + return kVTVideoDecoderUnsupportedDataFormatErr; + // A second start replaces the decoder of the first one. Ending it drops its + // format too: a start that fails must leave none that + // canAcceptFormatDescription could match. + drain(s); + pthread_mutex_lock(&s->lock); + end_session(s, "replaced by a new start"); + s->session = session; + pthread_mutex_unlock(&s->lock); + int32_t width = dim.width, height = dim.height; + bool tenBit = false; + if (width > MAX_WIDTH || height > MAX_HEIGHT) + return kVTVideoDecoderUnsupportedDataFormatErr; + + // A JPEG format description says nothing about sampling or precision: + // each picture carries its own. 4:2:0 comes out as '420f', 4:2:2 as '422f'; + // vcnjpeg refuses what the block is not given (progressive, 4:4:4, grey). + FourCharCode codec = CMFormatDescriptionGetMediaSubType(fmt); + if (codec != kCMVideoCodecType_JPEG && + codec != kCMVideoCodecType_JPEG_OpenDML) + return kVTVideoDecoderUnsupportedDataFormatErr; + + char err[256] = ""; + __atomic_store_n(&vcnjpeg_gpu_armed, 1, __ATOMIC_RELAXED); + VcnJpeg* vcn = vcnjpeg_create(MAX_WIDTH, MAX_HEIGHT, err, sizeof(err)); + if (!vcn) { + os_log_error(logger(), "vcnjpeg_create: %{public}s", err); + return kVTVideoDecoderNotAvailableNowErr; + } + // A picture the kext's buffers cannot hold goes to Apple's software decoder. + if (!vcnjpeg_fits(vcn, (uint32_t)width, (uint32_t)height)) { + os_log_error(logger(), + "%dx%d does not fit the kext's buffers (vcnjpegpool)", width, + height); + vcnjpeg_destroy(vcn); + return kVTVideoDecoderUnsupportedDataFormatErr; + } + // The new session is set up before anything else can see it: until it is + // published below, neither invalidate nor a decode can reach it. + CFDictionaryRef attrs = + vcnjpeg_copy_pixel_buffer_attributes(width, height, tenBit); + if (!attrs) { // out of memory: no session rather than one with no attributes + vcnjpeg_destroy(vcn); + return kVTAllocationFailedErr; + } + VTDecoderSessionSetPixelBufferAttributes(session, attrs); + CFRelease(attrs); + pthread_mutex_lock(&s->lock); + if (__atomic_load_n(&s->invalidated, __ATOMIC_RELAXED)) { + // Invalidated while the session was being made: nothing may stay open. + pthread_mutex_unlock(&s->lock); + vcnjpeg_destroy(vcn); + return kVTInvalidSessionErr; + } + end_session(s, "replaced by a new start"); // a start that ran alongside + s->vcn = vcn; + s->st_frame_ms = 0; // a new stream: learn its frame time again + s->st_last_pts = kCMTimeInvalid; + s->width = width; + s->height = height; + s->tenBit = tenBit; + long started = __atomic_add_fetch(&g_started, 1, __ATOMIC_RELAXED), + live = __atomic_add_fetch(&g_live, 1, __ATOMIC_RELAXED), + ended = __atomic_load_n(&g_ended, __ATOMIC_RELAXED); + set_format(s, fmt); + pthread_mutex_unlock(&s->lock); + os_log(logger(), + "session %dx%d %{public}s: %ld started, %ld ended, %ld live in this " + "process", + width, height, tenBit ? "10-bit" : "8-bit", started, ended, live); + return noErr; +} +static OSStatus dec_start_session(VTVideoDecoderRef dec, + VTVideoDecoderSession session, + CMVideoFormatDescriptionRef fmt) { + State* s = state_enter(dec); // it waits for the queue + if (!s) return kVTInvalidSessionErr; + OSStatus r = start_session(s, session, fmt); + state_release(s); + return r; +} + +static void on_output(void* ctx, CVPixelBufferRef frame, const void* p, + uint32_t w, uint32_t h, int64_t tag) { + State* s = ctx; + // A chunk has at most one shown frame; keep the last one if a stream breaks + // that rule. + if (s->lastFrame) CVPixelBufferRelease(s->lastFrame); + s->lastFrame = CVPixelBufferRetain(frame); +} + +static double now_ms(void) { + static mach_timebase_info_data_t tb; + if (!tb.denom) mach_timebase_info(&tb); + return (double)mach_absolute_time() * tb.numer / tb.denom / 1e6; +} + +// The stream's frame time: the sample's duration, or the step from the +// previous sample's presentation time when the caller gives none. The last good +// value is kept for samples with no timing; 60 fps is assumed until one is +// known. It is the stream's time, so at 2x playback each frame really has half +// of it. +static double frame_ms(State* s, CMSampleBufferRef sbuf) { + if (!sbuf) return s->st_frame_ms > 0 ? s->st_frame_ms : 1000.0 / 60; + CMTime d = CMSampleBufferGetDuration(sbuf); + CMTime pts = CMSampleBufferGetPresentationTimeStamp(sbuf); + double ms = 0; + if (CMTIME_IS_NUMERIC(d) && d.value > 0) { + ms = CMTimeGetSeconds(d) * 1000; + } else if (CMTIME_IS_NUMERIC(pts) && CMTIME_IS_NUMERIC(s->st_last_pts)) { + // A step longer than 100 ms is a seek, not a frame. + ms = CMTimeGetSeconds(CMTimeSubtract(pts, s->st_last_pts)) * 1000; + if (ms > 100) ms = 0; + } + if (CMTIME_IS_NUMERIC(pts)) s->st_last_pts = pts; + if (ms >= 1 && ms <= 1000) s->st_frame_ms = ms; + return s->st_frame_ms > 0 ? s->st_frame_ms : 1000.0 / 60; +} + +// A frame counts as slow when its decode alone took longer than the stream's +// frame time. Time in the queue is not counted: frames wait there by design, +// up to the queue depth, while the one ahead decodes. +static void stats_add(State* s, double queued, double decode, double frame) { + if (!s->st_n) s->st_t0 = now_ms(); + s->st_n++; + s->st_dec_sum += decode; + if (decode > s->st_dec_max) s->st_dec_max = decode; + s->st_q_sum += queued; + if (queued > s->st_q_max) s->st_q_max = queued; + s->st_frame_sum += frame; + if (decode > frame) s->st_over++; + if (s->st_n >= STATS_EVERY) { + os_log(logger(), + "stats %dx%d: %d frames in %.0f ms, decode avg %.2f max %.2f ms, " + "queue avg %.2f max %.2f ms, " + "decode over frame time (avg %.1f ms) %d, max depth %d, " + "firmware errors %u", + s->width, s->height, s->st_n, now_ms() - s->st_t0, + s->st_dec_sum / s->st_n, s->st_dec_max, s->st_q_sum / s->st_n, + s->st_q_max, s->st_frame_sum / s->st_n, s->st_over, s->st_depth_max, + vcnjpeg_firmware_errors(s->vcn)); + s->st_n = s->st_over = s->st_depth_max = 0; + s->st_dec_sum = s->st_dec_max = s->st_q_sum = s->st_q_max = 0; + s->st_frame_sum = 0; + } +} + +// A sample larger than the JPEG room of the kext's largest block (256 MiB, a +// quarter of it for the JPEG) cannot be decoded: refuse it before copying. +enum { kMaxSampleBytes = 0x4000000 }; + +// What VideoToolbox is told when a sample fails. A broken session (a driver +// call failed, or the GPU did not finish a command) is a malfunction, so that +// the host can fall back to another decoder; bad data is kept for streams +// that cannot be decoded as they are. +static OSStatus decode_status(int failure) { + switch (failure) { + case VCNJPEG_FAIL_DEVICE: + return kVTVideoDecoderMalfunctionErr; + case VCNJPEG_FAIL_MEMORY: + return kVTAllocationFailedErr; + // VideoToolbox's own code for it: FFmpeg goes on with the next frame on + // this one, and makes a new session on any other error. + case VCNJPEG_FAIL_REFERENCE: + return kVTVideoDecoderReferenceMissingErr; + default: + return kVTVideoDecoderBadDataErr; + } +} + +// Decode one chunk and hand its shown frame to VideoToolbox. A chunk with only +// hidden frames is valid: it hands back the last hidden frame's picture (see +// below). +static void decode_and_emit(State* s, VTVideoDecoderFrame frame, + CMSampleBufferRef sbuf, double enqueued) { + double started = now_ms(); + CMBlockBufferRef bb = CMSampleBufferGetDataBuffer(sbuf); + size_t len = bb ? CMBlockBufferGetDataLength(bb) : 0; + OSStatus status = noErr; + uint8_t* copy = NULL; + char* ptr = NULL; + if (!len || len > kMaxSampleBytes) + status = kVTVideoDecoderBadDataErr; + else if (CMBlockBufferIsRangeContiguous(bb, 0, len) && + !CMBlockBufferGetDataPointer(bb, 0, NULL, NULL, &ptr) && ptr) { + } else { + copy = malloc(len); + if (!copy) + status = kVTAllocationFailedErr; + else if (CMBlockBufferCopyDataBytes(bb, 0, len, copy)) + status = kVTVideoDecoderBadDataErr; + ptr = (char*)copy; + } + pthread_mutex_lock(&s->lock); + int depth = __atomic_load_n(&s->depth, __ATOMIC_RELAXED); + if (depth > s->st_depth_max) s->st_depth_max = depth; + bool invalidated = s->invalidated; + if (!status && !s->vcn) status = kVTInvalidSessionErr; + if (!status && + vcnjpeg_decode(s->vcn, (const uint8_t*)ptr, len, 0, on_output, s)) { + os_log_error(logger(), "decode: %{public}s", vcnjpeg_last_error(s->vcn)); + int failure = vcnjpeg_failure(s->vcn); + status = decode_status(failure); + // The session takes no more frames: canAcceptFormatDescription says no + // from now on, so VideoToolbox makes a new decoder. + if (failure == VCNJPEG_FAIL_DEVICE) { + pthread_mutex_lock(&s->meta); + s->broken = true; + pthread_mutex_unlock(&s->meta); + } + } + CVPixelBufferRef out = s->lastFrame; + s->lastFrame = NULL; + // A sample that holds only a hidden frame (a caller that sends frames one by + // one, as FFmpeg does) hands back that frame's picture. FFmpeg makes a new + // session whenever a decode returns no picture, and the new session has + // lost the references. A temporal unit or superframe always shows one frame, + // so Safari and Chrome never get here. + bool shown = out != NULL; + if (!status && !out && s->vcn) { + CVPixelBufferRef hidden = vcnjpeg_hidden_picture(s->vcn); + if (hidden) out = CVPixelBufferRetain(hidden); + } + double decode = now_ms() - started; + // A sample with only a hidden frame carries another frame's time: it is + // measured against the known frame time and does not change it. + stats_add(s, started - enqueued, decode, frame_ms(s, shown ? sbuf : NULL)); + pthread_mutex_unlock(&s->lock); + free(copy); + // A sample that failed hands back no picture, even one it showed before. + if (status && out) { + CVPixelBufferRelease(out); + out = NULL; + } + if (!invalidated) + VTDecoderSessionEmitDecodedFrame(s->session, frame, status, + out ? 0 : kVTDecodeInfo_FrameDropped, out); + if (out) CVPixelBufferRelease(out); +} + +// The caller holds a reference to s for as long as this runs. +static OSStatus decode_frame(State* s, VTVideoDecoderFrame frame, + CMSampleBufferRef sbuf, VTDecodeFrameFlags flags, + VTDecodeInfoFlags* infoOut) { + if (!sbuf) return kVTParameterErr; + // From inside the output callback the queue is already running this code, + // and invalidate run from there waits for no call (see close_calls). + bool counted = !on_queue(s); + if (!enter_call(s, counted)) return kVTInvalidSessionErr; + if (!(flags & kVTDecodeFrame_EnableAsynchronousDecompression)) { + double t = now_ms(); + if (!counted) + decode_and_emit(s, frame, sbuf, t); + else + dispatch_sync(s->queue, ^{ + decode_and_emit(s, frame, sbuf, t); + }); // keeps order with queued work + if (counted) leave_call(s); + return noErr; + } + // From inside the output callback the running frame still holds its slot, + // so waiting for one could wait for ever: queue the frame without one. + if (counted) { + dispatch_semaphore_wait(s->slots, DISPATCH_TIME_FOREVER); + // An invalidate that began during the wait refuses the frame. + if (is_closing(s)) { + dispatch_semaphore_signal(s->slots); + leave_call(s); + return kVTInvalidSessionErr; + } + } + CFRetain(sbuf); + double t = now_ms(); + __atomic_add_fetch(&s->depth, 1, __ATOMIC_RELAXED); + state_retain(s); // the frame's own reference, let go of last + dispatch_async(s->queue, ^{ + decode_and_emit(s, frame, sbuf, t); + __atomic_sub_fetch(&s->depth, 1, __ATOMIC_RELAXED); + CFRelease(sbuf); + if (counted) dispatch_semaphore_signal(s->slots); + state_release(s); + }); + if (infoOut) *infoOut = kVTDecodeInfo_Asynchronous; + // Queued and counted in depth: from here on drain() waits for the frame. + // Until then the call is counted in callers, so an invalidate or finalize + // off the queue, which waits for callers before it drains, cannot miss it. + // On the queue they wait for no frame queued behind the running one. + if (counted) leave_call(s); + return noErr; +} +static OSStatus dec_decode_frame(VTVideoDecoderRef dec, + VTVideoDecoderFrame frame, + CMSampleBufferRef sbuf, + VTDecodeFrameFlags flags, + VTDecodeInfoFlags* infoOut) { + if (infoOut) *infoOut = 0; + State* s = state_enter(dec); + if (!s) return kVTInvalidSessionErr; + OSStatus r = decode_frame(s, frame, sbuf, flags, infoOut); + state_release(s); + return r; +} + +static OSStatus dec_copy_supported_properties(VTVideoDecoderRef dec, + CFDictionaryRef* out) { + if (!out) return kVTParameterErr; + *out = NULL; + const void* k[] = {kVTPropertyTypeKey, kVTPropertyReadWriteStatusKey}; + const void* v[] = {kVTPropertyType_Boolean, + kVTPropertyReadWriteStatus_ReadOnly}; + CFDictionaryRef hw = + CFDictionaryCreate(NULL, k, v, 2, &kCFTypeDictionaryKeyCallBacks, + &kCFTypeDictionaryValueCallBacks); + if (!hw) return kVTAllocationFailedErr; + const void* keys[] = { + kVTDecompressionPropertyKey_UsingHardwareAcceleratedVideoDecoder}; + const void* vals[] = {hw}; + *out = CFDictionaryCreate(NULL, keys, vals, 1, &kCFTypeDictionaryKeyCallBacks, + &kCFTypeDictionaryValueCallBacks); + CFRelease(hw); + return *out ? noErr : kVTAllocationFailedErr; +} + +// A new size or configuration gets a new session. Size changes inside the +// stream don't come through here, the format description stays the same for +// those. +static Boolean dec_can_accept_format(VTVideoDecoderRef dec, + CMFormatDescriptionRef fmt) { + State* s = state_of(dec); + if (!s || !fmt) return false; + // A decoder whose start failed, whose session broke or whose invalidate has + // begun takes no format: VideoToolbox must make a new one. Read under meta, + // not lock: a decode holds lock while the GPU works on its frame. + pthread_mutex_lock(&s->meta); + CMFormatDescriptionRef cur = + s->format && !s->broken && !s->closing ? CFRetain(s->format) : NULL; + pthread_mutex_unlock(&s->meta); + if (!cur) return false; + Boolean same = false; + CMVideoDimensions a = CMVideoFormatDescriptionGetDimensions(cur), + b = CMVideoFormatDescriptionGetDimensions(fmt); + if (CMFormatDescriptionGetMediaSubType(fmt) == + CMFormatDescriptionGetMediaSubType(cur) && + a.width == b.width && a.height == b.height) + same = true; + CFRelease(cur); + return same; +} + +static OSStatus dec_finish_delayed_frames(VTVideoDecoderRef dec) { + State* s = state_enter(dec); + if (!s) return noErr; + drain(s); // every queued frame has been emitted when this returns + state_release(s); + return noErr; +} + +static const CMBaseClass kBaseClass = { + .version = 1, + .derivedStorageSize = sizeof(Storage), + .invalidate = base_invalidate, + .finalize = base_finalize, + .copyDebugDescription = base_copy_debug_description, + .copyProperty = base_copy_property, + .setProperty = base_set_property, +}; + +static const VTVideoDecoderClass kDecoderClass = { + .version = 3, + .startSession = dec_start_session, + .decodeFrame = dec_decode_frame, + .copySupportedPropertyDictionary = dec_copy_supported_properties, + .canAcceptFormatDescription = dec_can_accept_format, + .finishDelayedFrames = dec_finish_delayed_frames, +}; + +static const VTVideoDecoderVTable kVTable = {NULL, &kBaseClass, &kDecoderClass}; + +__attribute__((visibility("default"))) OSStatus +JPEGVCN_VTDecoder_CreateInstance(FourCharCode codec, CFAllocatorRef alloc, + VTVideoDecoderRef* out) { + if (!out) return kVTParameterErr; + *out = NULL; + if (codec != kCMVideoCodecType_JPEG && + codec != kCMVideoCodecType_JPEG_OpenDML) + return kVTCouldNotFindVideoDecoderErr; + CMBaseObjectRef obj = NULL; + OSStatus r = + CMDerivedObjectCreate(alloc, &kVTable, VTVideoDecoderGetClassID(), &obj); + if (r || !obj) return r ? r : kVTAllocationFailedErr; + Storage* st = CMBaseObjectGetDerivedStorage(obj); + memset(st, 0, sizeof(*st)); + State* s = calloc(1, sizeof(*s)); + if (!s) { + CFRelease(obj); + return kVTAllocationFailedErr; + } + s->refs = 1; // the storage's + pthread_mutex_init(&s->lock, NULL); + pthread_mutex_init(&s->meta, NULL); + pthread_cond_init(&s->idle, NULL); + s->queue = dispatch_queue_create( + "com.droga.vtjpegvcn.decode", + dispatch_queue_attr_make_with_qos_class(DISPATCH_QUEUE_SERIAL, + QOS_CLASS_USER_INTERACTIVE, 0)); + s->slots = dispatch_semaphore_create(MAX_QUEUED); + if (!s->queue || !s->slots) { + state_release(s); // the only reference: frees what was made + CFRelease(obj); // finalize finds no state + return kVTAllocationFailedErr; + } + dispatch_queue_set_specific(s->queue, &kQueueKey, s, NULL); + // Published with release once it is set up; from here on finalize frees + // it. + __atomic_store_n(&st->state, s, __ATOMIC_RELEASE); + *out = (VTVideoDecoderRef)obj; + return noErr; +} diff --git a/GPU/decode/jpeg/jpeg_app.h b/GPU/decode/jpeg/jpeg_app.h new file mode 100644 index 00000000..363b7875 --- /dev/null +++ b/GPU/decode/jpeg/jpeg_app.h @@ -0,0 +1,108 @@ +/* + * jpeg_app.h - how a program asks the VCNJpeg kext (GPU/jpeg) to decode a JPEG + * without a user client of its own: through the AMD accelerator's video + * context, the connection every sandboxed process may open. + * + * IOServiceOpen(accelerator, task, 3, &conn) type 3 = video context + * IOConnectCallStructMethod(conn, 258, in, inSize, out, &outSize) + * + * Selector 258 is AMDRadeonX6000_AMDAccelVideoContext::sendPMCommand(in, out, + * inSize, &outSize), declared with variable-size structs both ways and meant + * for PowerPlay escapes. The kext routes that function and takes the requests + * that start with the header below; everything else goes on to the original. + * Without the kext such a request reaches PowerPlay, whose PP_Cwdde refuses it + * (low 16 bits of the code above 0xB0, code below 0xC08001) and changes + * nothing: the caller gets an error and knows there is no decoder. + * + * Plain C: the kext, the tool and the VideoToolbox plug-in share this file. + * Struct data is at most 4096 bytes each way. LOAD and READ move a JPEG and + * the picture in pieces of that size; LOAD_USER and READ_USER instead give the + * address of a buffer in the caller's own memory, which the kext reads or + * fills with copyin/copyout in one go (a 48-megapixel picture is 74 MB: about + * 18000 calls in pieces). + */ +#ifndef JPEG_APP_H +#define JPEG_APP_H +#include + +#define JA_PROTOCOL 1u +#define JA_VIDEO_CONTEXT_TYPE 3u /* IOServiceOpen type */ +#define JA_SELECTOR 258u +#define JA_HEADER_SIZE 16u /* what a PowerPlay escape header says too */ +#define JA_CODE 0x004A5047u /* never a PowerPlay escape, see above */ +#define JA_REPLY_MAGIC 0x4a504741u /* "JPGA" */ +#define JA_MAX_IO 4096u + +enum { + JA_OP_INFO = 1, /* reply v: state bits (JA_STATE_*), JPEG capacity, surface + capacity, jobs */ + JA_OP_LOAD = + 2, /* arg0 offset, arg1 size of the whole JPEG; data: the next piece */ + JA_OP_RUN = 3, /* arg0 flags (jp::Flags); reply data: ja_picture */ + JA_OP_READ = 4, /* arg0 offset into the surface; reply data: the next piece */ + JA_OP_RELEASE = 5, /* gives the decoder back to whoever comes next */ + JA_OP_LOAD_USER = 6, /* arg0 address of the whole JPEG in the caller's memory, + arg1 its size */ + JA_OP_READ_USER = + 7, /* arg0 address of a buffer in the caller's memory, arg1 its size: the + whole surface is copied there; reply v[0] = bytes */ +}; + +/* INFO reply v[0]: the decoder's state (the kext's jp::State) */ +enum { + JA_STATE_POOL = 1 << 0, /* the buffers were taken when the driver started */ + JA_STATE_CREATED = 1 << 1, /* the JPEG queue exists */ + JA_STATE_STARTED = 1 << 2, /* the block is powered and its queue started (only + while decoding) */ + JA_STATE_STUCK = 1 << 3, /* a job failed in a way that stops the decoder until + the next restart */ +}; + +enum { + JA_OK = 0, + JA_MORE = 1, /* LOAD: piece taken, more expected */ + JA_BUSY = 2, /* another client holds the decoder: try again */ + JA_NOT_READY = 3, /* no buffers, queue not started, or stuck */ + JA_BAD_REQUEST = 4, + JA_NOT_OWNER = 5, /* RUN or READ without a LOAD of this client */ + JA_BAD_STREAM = 6, /* detail: jc::Stream */ + JA_FAILED = 7, /* the job did not succeed; detail: jp::Status */ + JA_BAD_ADDRESS = + 8, /* LOAD_USER / READ_USER: the buffer could not be read or written */ +}; + +struct ja_request { + uint32_t size; /* JA_HEADER_SIZE */ + uint32_t code; /* JA_CODE */ + uint32_t protocol; /* JA_PROTOCOL */ + uint32_t op; + uint64_t arg0; + uint64_t arg1; + /* data follows */ +}; + +struct ja_reply { + uint32_t magic; /* JA_REPLY_MAGIC */ + uint32_t status; /* JA_OK ... */ + uint32_t detail; + uint32_t dataBytes; /* bytes of data after this struct */ + uint64_t v[4]; + /* data follows */ +}; + +/* What RUN returns about the picture; the surface is NV12 with this layout. */ +struct ja_picture { + uint32_t width, height; + uint32_t pitch; /* bytes per row, luma and chroma */ + uint32_t alignedHeight; /* luma rows in the surface */ + uint32_t chromaOffset; /* from the start of the surface */ + uint32_t surfaceBytes; + uint32_t elapsedMs; /* submit to completion, in the kernel */ + uint32_t format; /* 0 NV12 (4:2:0: luma, then UV at chromaOffset), 1 YUYV + (4:2:2, one plane) */ +}; + +#define JA_LOAD_PIECE (JA_MAX_IO - (uint32_t)sizeof(struct ja_request)) +#define JA_READ_PIECE (JA_MAX_IO - (uint32_t)sizeof(struct ja_reply)) + +#endif diff --git a/GPU/decode/jpeg/jpeg_app_client.h b/GPU/decode/jpeg/jpeg_app_client.h new file mode 100644 index 00000000..95059855 --- /dev/null +++ b/GPU/decode/jpeg/jpeg_app_client.h @@ -0,0 +1,187 @@ +/* + * jpeg_app_client.h - the caller's side of jpeg_app.h: one picture through the + * VCNJpeg kext. Plain C, header only; the VideoToolbox plug-in and the + * kext's host tests (jpeg/tests/apps_test.cpp) use it. + * + * The transport is a function, so tests can put a fake behind it; the real one + * (ja_iokit_*) calls selector 258 of a video context of the AMD accelerator. + */ +#ifndef JPEG_APP_CLIENT_H +#define JPEG_APP_CLIENT_H +#include +#include +#include +#include + +#include "jpeg_app.h" + +/* One struct call: in -> out, *outSize is the room on entry and the bytes + written on return. 0 = the call went through (kern_return_t KERN_SUCCESS for + the real one). */ +typedef int (*ja_transport)(void* ctx, const void* in, size_t inSize, void* out, + size_t* outSize); + +/* Sends one request; fills *rp. Returns the reply's status, or -1 when the call + itself failed or the reply is not one of ours (no kext: PowerPlay refuses the + request). */ +static inline int ja_call(ja_transport t, void* ctx, uint32_t op, uint64_t a0, + uint64_t a1, const void* data, size_t dataBytes, + struct ja_reply* rp, void* outData, size_t outCap) { + uint8_t in[JA_MAX_IO], out[JA_MAX_IO]; + struct ja_request rq = {JA_HEADER_SIZE, JA_CODE, JA_PROTOCOL, op, a0, a1}; + if (dataBytes > JA_LOAD_PIECE) return -1; + memcpy(in, &rq, sizeof(rq)); + if (dataBytes != 0) memcpy(in + sizeof(rq), data, dataBytes); + size_t outSize = sizeof(out); + if (t(ctx, in, sizeof(rq) + dataBytes, out, &outSize) != 0) return -1; + if (outSize < sizeof(*rp) || outSize > sizeof(out)) return -1; + memcpy(rp, out, sizeof(*rp)); + if (rp->magic != JA_REPLY_MAGIC || sizeof(*rp) + rp->dataBytes != outSize) + return -1; + if (outData != NULL) + memcpy(outData, out + sizeof(*rp), + rp->dataBytes <= outCap ? rp->dataBytes : outCap); + return (int)rp->status; +} + +static inline uint64_t ja_now_ms(void) { + return clock_gettime_nsec_np(CLOCK_UPTIME_RAW) / 1000000u; +} + +/* Decodes one JPEG (already in the shape the block takes) into `surface` (NV12, + layout in *pic). Waits up to waitMs while another client holds the decoder. + Returns JA_OK or the failing status + (-1: transport). */ +static inline int ja_decode(ja_transport t, void* ctx, const uint8_t* jpeg, + size_t jpegBytes, uint8_t* surface, + size_t surfaceCap, uint32_t flags, unsigned waitMs, + struct ja_picture* pic, struct ja_reply* last) { + struct ja_reply rp; + memset(&rp, 0, sizeof(rp)); + uint64_t until = ja_now_ms() + waitMs; + int s; + while (1) { + s = ja_call(t, ctx, JA_OP_LOAD_USER, (uint64_t)(uintptr_t)jpeg, jpegBytes, + NULL, 0, &rp, NULL, 0); + if (s != JA_BUSY || ja_now_ms() >= until) break; + struct timespec ts = {0, 2000000}; + nanosleep(&ts, NULL); + } + if (s == JA_OK) { + memset(pic, 0, sizeof(*pic)); + s = ja_call(t, ctx, JA_OP_RUN, flags, 0, NULL, 0, &rp, pic, sizeof(*pic)); + if (s == JA_OK && rp.dataBytes != sizeof(*pic)) s = -1; + if (s == JA_OK && pic->surfaceBytes > surfaceCap) s = JA_BAD_REQUEST; + if (s == JA_OK) + s = ja_call(t, ctx, JA_OP_READ_USER, (uint64_t)(uintptr_t)surface, + surfaceCap, NULL, 0, &rp, NULL, 0); + } + if (s != JA_OK && s != JA_BUSY && s != -1) { + struct ja_reply ignored; + ja_call(t, ctx, JA_OP_RELEASE, 0, 0, NULL, 0, &ignored, NULL, 0); + } + if (last != NULL) *last = rp; + return s; +} + +/* Room the kext has now: JPEG bytes and surface bytes (0 when there is no + * door). */ +static inline int ja_info(ja_transport t, void* ctx, uint64_t* state, + uint64_t* jpegCap, uint64_t* surfaceCap) { + struct ja_reply rp; + int s = ja_call(t, ctx, JA_OP_INFO, 0, 0, NULL, 0, &rp, NULL, 0); + if (s != JA_OK) return s; + if (state) *state = rp.v[0]; + if (jpegCap) *jpegCap = rp.v[1]; + if (surfaceCap) *surfaceCap = rp.v[2]; + return JA_OK; +} + +#ifdef __APPLE__ +#include +#include + +/* A video context only answers once it is connected to a shared user client + (type 6) of the same task: IOConnectAddClient(video, shared) -> + IOAccelContext2::connectClient -> contextStart, which sets the method table. + Before that every selector returns kIOReturnNotReady + (IOAccelContext2::externalMethod checks the started flag at +1688). Seen on + hardware 2026-11-24: type 3 alone gave 0xE00002D8. The shared client stays + open as long as the video context: ja_iokit_close closes both. */ +#define JA_SHARED_TYPE 6u +#define JA_MAX_PAIRS 16 +static struct { + io_connect_t video, shared; +} ja_pairs[JA_MAX_PAIRS]; +static os_unfair_lock ja_pairs_lock = OS_UNFAIR_LOCK_INIT; + +/* Opens shared (6) + video (3) on the AMD accelerator and connects them: what + any process that decodes video does. Returns the video context, or + IO_OBJECT_NULL; *why (optional) gets the failing step's code. */ +static inline io_connect_t ja_iokit_open_why(kern_return_t* why, int* step) { + kern_return_t kr = kIOReturnNotFound; + int at = 0; + io_connect_t video = IO_OBJECT_NULL, shared = IO_OBJECT_NULL; + io_service_t s = IOServiceGetMatchingService( + kIOMainPortDefault, + IOServiceMatching("AMDRadeonX6000_AMDGraphicsAccelerator")); + if (s != IO_OBJECT_NULL) { + at = 1; + kr = IOServiceOpen(s, mach_task_self(), JA_SHARED_TYPE, &shared); + if (kr == KERN_SUCCESS) { + at = 2; + kr = IOServiceOpen(s, mach_task_self(), JA_VIDEO_CONTEXT_TYPE, &video); + } + if (kr == KERN_SUCCESS) { + at = 3; + kr = IOConnectAddClient(video, shared); + } + IOObjectRelease(s); + } + if (kr == KERN_SUCCESS) { + at = 4; + kr = kIOReturnNoResources; + os_unfair_lock_lock(&ja_pairs_lock); + for (int i = 0; i < JA_MAX_PAIRS; i++) + if (ja_pairs[i].video == IO_OBJECT_NULL) { + ja_pairs[i].video = video; + ja_pairs[i].shared = shared; + kr = KERN_SUCCESS; + break; + } + os_unfair_lock_unlock(&ja_pairs_lock); + } + if (why) *why = kr; + if (step) *step = at; + if (kr == KERN_SUCCESS) return video; + if (video != IO_OBJECT_NULL) IOServiceClose(video); + if (shared != IO_OBJECT_NULL) IOServiceClose(shared); + return IO_OBJECT_NULL; +} +static inline io_connect_t ja_iokit_open(void) { + return ja_iokit_open_why(NULL, NULL); +} + +/* Closes a video context from ja_iokit_open and its shared client. */ +static inline void ja_iokit_close(io_connect_t video) { + io_connect_t shared = IO_OBJECT_NULL; + os_unfair_lock_lock(&ja_pairs_lock); + for (int i = 0; i < JA_MAX_PAIRS; i++) + if (ja_pairs[i].video == video && video != IO_OBJECT_NULL) { + shared = ja_pairs[i].shared; + ja_pairs[i].video = ja_pairs[i].shared = IO_OBJECT_NULL; + break; + } + os_unfair_lock_unlock(&ja_pairs_lock); + if (video != IO_OBJECT_NULL) IOServiceClose(video); + if (shared != IO_OBJECT_NULL) IOServiceClose(shared); +} + +static inline int ja_iokit_call(void* ctx, const void* in, size_t inSize, + void* out, size_t* outSize) { + io_connect_t c = *(io_connect_t*)ctx; + return IOConnectCallStructMethod(c, JA_SELECTOR, in, inSize, out, outSize); +} +#endif + +#endif diff --git a/GPU/decode/jpeg/jpegprep.c b/GPU/decode/jpeg/jpegprep.c new file mode 100644 index 00000000..7f672f53 --- /dev/null +++ b/GPU/decode/jpeg/jpegprep.c @@ -0,0 +1,247 @@ +// jpegprep.c - see jpegprep.h. The same rewrite as +// jpeg/tests/jpeg_normalize.hpp (from the tool the first GPU tests used). On +// 2026-11-24 both gave the same bytes for six files (photos of 12 and 48 MP, a +// 640x480 MJPEG frame, the samples of tests/jpegsamples.h); tests/jpegtest.c +// checks the shape and the picture. This one also takes fill bytes and adds +// Annex K's tables where the kext's tool refuses. +#include "jpegprep.h" + +#include +#include +#include +#include + +#include "jpegstd.h" + +typedef struct { + bool haveQ[4]; + uint8_t q[4][64]; + bool haveH[2][2]; // [class 0 DC / 1 AC][id] + const uint8_t* h[2][2]; // 16 counts + values, inside the input + size_t hLen[2][2]; + uint16_t restart; + const uint8_t* sof; + size_t sofLen; + const uint8_t* sos; + size_t sosLen; + const uint8_t* scan; + size_t scanLen; +} Tables; + +static int fail(char* why, size_t whyLen, int code, const char* text) { + if (why && whyLen) snprintf(why, whyLen, "%s", text); + return code; +} + +static void put_seg(uint8_t* o, size_t* p, uint8_t marker, const uint8_t* body, + size_t len) { + o[(*p)++] = 0xff; + o[(*p)++] = marker; + o[(*p)++] = (uint8_t)((len + 2) >> 8); + o[(*p)++] = (uint8_t)(len + 2); + memcpy(o + *p, body, len); + *p += len; +} + +// Reads the standard tables out of jpegstd.h for the ones the picture lacks. +static void std_tables(Tables* t, bool* added) { + size_t p = 0; + while (p < sizeof(kJpegStdDht)) { + uint8_t tc = kJpegStdDht[p] >> 4, th = kJpegStdDht[p] & 15; + size_t count = 0; + for (int k = 0; k < 16; k++) count += kJpegStdDht[p + 1 + k]; + if (!t->haveH[tc][th]) { + t->haveH[tc][th] = true; + t->h[tc][th] = kJpegStdDht + p + 1; + t->hLen[tc][th] = 16 + count; + *added = true; + } + p += 17 + count; + } +} + +int jpeg_prepare(const uint8_t* d, size_t n, uint8_t** out, size_t* outLen, + JpegInfo* info, char* why, size_t whyLen) { + *out = NULL; + *outLen = 0; + memset(info, 0, sizeof(*info)); + if (!d || n < 4 || d[0] != 0xff || d[1] != 0xd8) + return fail(why, whyLen, JPEG_BAD, "not a JPEG (no SOI)"); + Tables t; + memset(&t, 0, sizeof(t)); + size_t i = 2; + bool gotScan = false; + while (!gotScan) { + // fill bytes (0xFF repeated) may come before a marker + while (i + 1 < n && d[i] == 0xff && d[i + 1] == 0xff) i++; + if (i + 4 > n) return fail(why, whyLen, JPEG_BAD, "no scan found"); + if (d[i] != 0xff) return fail(why, whyLen, JPEG_BAD, "marker expected"); + uint8_t m = d[i + 1]; + size_t len = ((size_t)d[i + 2] << 8) | d[i + 3]; + if (len < 2 || len > n - i - 2) + return fail(why, whyLen, JPEG_BAD, "a segment does not fit the file"); + const uint8_t* s = d + i + 4; + size_t body = len - 2; + if (m == 0xdb) { + size_t p = 0; + while (p < body) { + uint8_t pq = s[p] >> 4, tq = s[p] & 15; + if (pq != 0) + return fail(why, whyLen, JPEG_UNSUPPORTED, + "16-bit quantisation table"); + if (tq > 3 || body - p < 65) + return fail(why, whyLen, JPEG_BAD, "bad quantisation table"); + t.haveQ[tq] = true; + memcpy(t.q[tq], s + p + 1, 64); + p += 65; + } + } else if (m == 0xc4) { + size_t p = 0; + while (p < body) { + uint8_t tc = s[p] >> 4, th = s[p] & 15; + if (tc > 1 || th > 3 || body - p < 17) + return fail(why, whyLen, JPEG_BAD, "bad Huffman table"); + if (th > 1) + return fail(why, whyLen, JPEG_UNSUPPORTED, + "Huffman table id above 1 (Mesa gives the block two)"); + size_t count = 0; + for (int k = 0; k < 16; k++) count += s[p + 1 + k]; + if (count > (tc == 0 ? 12u : 162u) || body - p - 17 < count) + return fail(why, whyLen, JPEG_BAD, "bad Huffman table"); + t.haveH[tc][th] = true; + t.h[tc][th] = s + p + 1; + t.hLen[tc][th] = 16 + count; + p += 17 + count; + } + } else if (m == 0xdd) { + if (body != 2) + return fail(why, whyLen, JPEG_BAD, "bad restart interval segment"); + t.restart = (uint16_t)((s[0] << 8) | s[1]); + } else if (m == 0xc0) { + if (t.sof) + return fail(why, whyLen, JPEG_BAD, "more than one frame header"); + t.sof = s; + t.sofLen = body; + } else if (m == 0xda) { + t.sos = s; + t.sosLen = body; + gotScan = true; + } else if ((m >= 0xe0 && m <= 0xef) || m == 0xfe) { + // dropped, as Mesa does + } else if (m >= 0xc1 && m <= 0xcf && m != 0xc4 && m != 0xc8 && m != 0xcc) { + return fail(why, whyLen, JPEG_UNSUPPORTED, + "not a baseline JPEG (progressive, lossless or arithmetic)"); + } else { + return fail(why, whyLen, JPEG_UNSUPPORTED, + "a segment this decoder does not handle"); + } + i += 2 + len; + } + if (!t.sof) + return fail(why, whyLen, JPEG_BAD, "scan before the frame header"); + // frame header: P, Y, X, Nf, then Nf x (C, HV, Tq) + if (t.sofLen < 6 || t.sofLen != 6 + 3u * t.sof[5]) + return fail(why, whyLen, JPEG_BAD, "bad frame header"); + uint32_t height = ((uint32_t)t.sof[1] << 8) | t.sof[2]; + uint32_t width = ((uint32_t)t.sof[3] << 8) | t.sof[4]; + if (t.sof[0] != 8) + return fail(why, whyLen, JPEG_UNSUPPORTED, "not 8 bits per sample"); + if (width == 0 || height == 0) + return fail(why, whyLen, JPEG_UNSUPPORTED, "no size in the frame header"); + if (t.sof[5] != 3) + return fail(why, whyLen, JPEG_UNSUPPORTED, "not three components"); + if (t.sof[6] == t.sof[9] || t.sof[6] == t.sof[12] || t.sof[9] == t.sof[12]) + return fail(why, whyLen, JPEG_BAD, "two components with the same id"); + // sampling (Y, Cb, Cr) as Mesa's radeon_dec_jpeg_check_format: NV12 or YUYV + uint32_t sf = + ((uint32_t)t.sof[7] << 16) | ((uint32_t)t.sof[10] << 8) | t.sof[13]; + bool yuyv = sf == 0x211111 || sf == 0x221212 || sf == 0x222121; + if (sf != 0x221111 && !yuyv) + return fail(why, whyLen, JPEG_UNSUPPORTED, "not 4:2:0 or 4:2:2"); + for (int c = 0; c < 3; c++) { + uint8_t tq = t.sof[8 + 3 * c]; + if (tq > 3 || !t.haveQ[tq]) + return fail(why, whyLen, JPEG_BAD, + "a component's quantisation table is missing"); + } + // scan header: Ns, Ns x (C, Td/Ta), Ss, Se, Ah/Al + if (t.sosLen < 1 || t.sosLen != 4 + 2u * t.sos[0]) + return fail(why, whyLen, JPEG_BAD, "bad scan header"); + if (t.sos[0] != 3) + return fail(why, whyLen, JPEG_UNSUPPORTED, + "a scan without all three components"); + // the scan names the frame's components in the frame's order (T.81 B.2.3) + for (int c = 0; c < 3; c++) + if (t.sos[1 + 2 * c] != t.sof[6 + 3 * c]) + return fail(why, whyLen, JPEG_BAD, + "the scan names other components than the frame"); + // The scan runs to the first marker that is neither a stuffed FF00 nor RSTn. + size_t e = i; + while (1) { + if (e + 1 >= n) return fail(why, whyLen, JPEG_BAD, "no EOI after the scan"); + if (d[e] == 0xff && d[e + 1] != 0x00 && + !(d[e + 1] >= 0xd0 && d[e + 1] <= 0xd7)) + break; + e++; + } + // fill bytes before EOI belong to no segment + size_t f = e; + while (f + 1 < n && d[f + 1] == 0xff) f++; + // a sample that ends in fill bytes has no EOI after them + if (f + 1 >= n) return fail(why, whyLen, JPEG_BAD, "no EOI after the scan"); + if (d[f + 1] != 0xd9) + return fail(why, whyLen, JPEG_UNSUPPORTED, "more than one scan"); + t.scan = d + i; + t.scanLen = e - i; + bool added = false; + std_tables(&t, &added); + for (int c = 0; c < 3; c++) { + uint8_t td = t.sos[2 + 2 * c] >> 4, ta = t.sos[2 + 2 * c] & 15; + if (td > 1 || ta > 1 || !t.haveH[0][td] || !t.haveH[1][ta]) + return fail(why, whyLen, JPEG_BAD, + "a component's Huffman table is missing"); + } + uint8_t dqt[4 * 65], dht[4 * 179]; + size_t nq = 0, nh = 0; + for (int k = 0; k < 4; k++) { + if (!t.haveQ[k]) continue; + dqt[nq++] = (uint8_t)k; + memcpy(dqt + nq, t.q[k], 64); + nq += 64; + } + for (int c = 0; c < 2; c++) { + for (int k = 0; k < 2; k++) { + if (!t.haveH[c][k]) continue; + dht[nh++] = (uint8_t)((c << 4) | k); + memcpy(dht + nh, t.h[c][k], t.hLen[c][k]); + nh += t.hLen[c][k]; + } + } + size_t cap = 2 + (4 + nq) + (4 + nh) + 6 + (4 + t.sofLen) + (4 + t.sosLen) + + t.scanLen + 2; + uint8_t* o = malloc(cap); + if (!o) return fail(why, whyLen, JPEG_NO_MEMORY, "out of memory"); + size_t p = 0; + o[p++] = 0xff; + o[p++] = 0xd8; + put_seg(o, &p, 0xdb, dqt, nq); + put_seg(o, &p, 0xc4, dht, nh); + if (t.restart) { + uint8_t r[2] = {(uint8_t)(t.restart >> 8), (uint8_t)t.restart}; + put_seg(o, &p, 0xdd, r, 2); + } + put_seg(o, &p, 0xc0, t.sof, t.sofLen); + put_seg(o, &p, 0xda, t.sos, t.sosLen); + memcpy(o + p, t.scan, t.scanLen); + p += t.scanLen; + o[p++] = 0xff; + o[p++] = 0xd9; + *out = o; + *outLen = p; + info->width = width; + info->height = height; + info->restart = t.restart; + info->stdTables = added; + info->yuyv = yuyv; + return JPEG_OK; +} diff --git a/GPU/decode/jpeg/jpegprep.h b/GPU/decode/jpeg/jpegprep.h new file mode 100644 index 00000000..733f1e56 --- /dev/null +++ b/GPU/decode/jpeg/jpegprep.h @@ -0,0 +1,41 @@ +// jpegprep: turns one JPEG picture (a 'jpeg' or 'dmb1' sample) into the exact +// shape the VCN JPEG block is given on Linux by Mesa (vlVaGetJpegSliceHeader, +// src/gallium/frontends/va/picture_mjpeg.c): SOI, one DQT segment, one DHT +// segment (DC tables, then AC tables), DRI if there is a restart interval, +// SOF0, SOS, the scan, EOI. APPn and COM segments are dropped; a picture +// without Huffman tables (Motion JPEG) gets the standard ones of Annex K. +// +// What the block is given here is what the kext checks again before it takes +// the JPEG (VCNJpeg jc::parseStream): baseline, 8 bits, three components, +// one scan with all three, sampled as Mesa's radeon_dec_jpeg_check_format +// takes them on this block: 0x221111 (4:2:0, written as NV12) or 0x211111, +// 0x221212, 0x222121 (4:2:2, written as YUYV). Anything else is +// JPEG_UNSUPPORTED: progressive, 4:4:4, 4:4:0, grey. +// +// Pure code: no system call, no allocation but the output buffer. +#pragma once +#include +#include +#include + +enum { + JPEG_OK = 0, + JPEG_BAD = 1, // not a JPEG, or one that breaks the standard + JPEG_UNSUPPORTED = 2, // a valid JPEG the block is not given (see above) + JPEG_NO_MEMORY = 3, +}; + +typedef struct { + uint32_t width, height; + uint16_t restart; // restart interval, 0 = none + bool stdTables; // the Huffman tables of Annex K were added + bool yuyv; // 4:2:2: the block writes YUYV (else NV12) +} JpegInfo; + +// The output is at most the input plus kJpegPrepExtra bytes. +enum { kJpegPrepExtra = 1024 }; + +// Fills out (malloc'ed, free it) and *info. On failure *out is NULL and why +// holds a short reason. +int jpeg_prepare(const uint8_t* in, size_t n, uint8_t** out, size_t* outLen, + JpegInfo* info, char* why, size_t whyLen); diff --git a/GPU/decode/jpeg/jpegstd.h b/GPU/decode/jpeg/jpegstd.h new file mode 100644 index 00000000..7cad5013 --- /dev/null +++ b/GPU/decode/jpeg/jpegstd.h @@ -0,0 +1,45 @@ +// jpegstd.h - the four Huffman tables of ITU-T T.81 Annex K (K.3 to K.6), as +// one DHT segment body: DC luminance (class 0 id 0), DC chrominance (0/1), AC +// luminance (1/0), AC chrominance (1/1). Motion JPEG from cameras ('dmb1', AVI +// MJPEG) leaves the DHT out and means these tables. Copied byte for byte from a +// JPEG that FFmpeg wrote with -huffman default. +#pragma once +#include + +static const uint8_t kJpegStdDht[416] = { + 0x00, 0x00, 0x01, 0x05, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, + 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x01, 0x00, 0x03, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, + 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x10, 0x00, + 0x02, 0x01, 0x03, 0x03, 0x02, 0x04, 0x03, 0x05, 0x05, 0x04, 0x04, 0x00, + 0x00, 0x01, 0x7d, 0x01, 0x02, 0x03, 0x00, 0x04, 0x11, 0x05, 0x12, 0x21, + 0x31, 0x41, 0x06, 0x13, 0x51, 0x61, 0x07, 0x22, 0x71, 0x14, 0x32, 0x81, + 0x91, 0xa1, 0x08, 0x23, 0x42, 0xb1, 0xc1, 0x15, 0x52, 0xd1, 0xf0, 0x24, + 0x33, 0x62, 0x72, 0x82, 0x09, 0x0a, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x25, + 0x26, 0x27, 0x28, 0x29, 0x2a, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, + 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x53, 0x54, 0x55, 0x56, + 0x57, 0x58, 0x59, 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, + 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x83, 0x84, 0x85, 0x86, + 0x87, 0x88, 0x89, 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, + 0x9a, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, + 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, + 0xc7, 0xc8, 0xc9, 0xca, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, + 0xda, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xf1, + 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0x11, 0x00, 0x02, + 0x01, 0x02, 0x04, 0x04, 0x03, 0x04, 0x07, 0x05, 0x04, 0x04, 0x00, 0x01, + 0x02, 0x77, 0x00, 0x01, 0x02, 0x03, 0x11, 0x04, 0x05, 0x21, 0x31, 0x06, + 0x12, 0x41, 0x51, 0x07, 0x61, 0x71, 0x13, 0x22, 0x32, 0x81, 0x08, 0x14, + 0x42, 0x91, 0xa1, 0xb1, 0xc1, 0x09, 0x23, 0x33, 0x52, 0xf0, 0x15, 0x62, + 0x72, 0xd1, 0x0a, 0x16, 0x24, 0x34, 0xe1, 0x25, 0xf1, 0x17, 0x18, 0x19, + 0x1a, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, + 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x53, 0x54, 0x55, 0x56, + 0x57, 0x58, 0x59, 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, + 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x82, 0x83, 0x84, 0x85, + 0x86, 0x87, 0x88, 0x89, 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, + 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xb2, + 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3, 0xc4, 0xc5, + 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, + 0xd9, 0xda, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xf2, + 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, +}; diff --git a/GPU/decode/jpeg/vcnjpeg.c b/GPU/decode/jpeg/vcnjpeg.c new file mode 100644 index 00000000..a27ce5c3 --- /dev/null +++ b/GPU/decode/jpeg/vcnjpeg.c @@ -0,0 +1,368 @@ +// vcnjpeg.c - see vcnjpeg.h. +#include "vcnjpeg.h" + +#include +#include +#include +#include + +#include "jpegprep.h" + +int vcnjpeg_gpu_armed = 0; + +static void* iokit_open(void) { + io_connect_t c = ja_iokit_open(); + if (c == IO_OBJECT_NULL) return NULL; + io_connect_t* p = malloc(sizeof(*p)); + if (!p) { + ja_iokit_close(c); + return NULL; + } + *p = c; + return p; +} +static void iokit_close(void* ctx) { + if (!ctx) return; + ja_iokit_close( + *(io_connect_t*)ctx); // the video context and its shared client + free(ctx); +} +ja_transport vcnjpeg_transport = ja_iokit_call; +void* (*vcnjpeg_transport_open)(void) = iokit_open; +void (*vcnjpeg_transport_close)(void* ctx) = iokit_close; + +// How long a frame waits while another process holds the block before the +// session counts as broken: a picture of 48 MP takes the block well under that. +enum { kBusyWaitMs = 1000 }; + +struct VcnJpeg { + void* conn; + uint32_t maxW, maxH; + uint64_t surfaceRoom; // what the kext's picture buffer holds (INFO) + uint8_t* surface; // what the kext copies the picture into (its layout, see + // ja_picture) + size_t surfaceCap; + CVPixelBufferPoolRef pool; + uint32_t poolW, poolH; + OSType poolFormat; + int failure; + char err[160]; +}; + +static bool put_num(CFMutableDictionaryRef d, CFStringRef k, int32_t v) { + CFNumberRef n = CFNumberCreate(NULL, kCFNumberSInt32Type, &v); + if (!n) return false; + CFDictionarySetValue(d, k, n); + CFRelease(n); + return true; +} + +// formats: one OSType, or (format == 0) the session's two. +static CFDictionaryRef attributes(uint32_t w, uint32_t h, OSType format) { + CFMutableDictionaryRef a = + CFDictionaryCreateMutable(NULL, 0, &kCFTypeDictionaryKeyCallBacks, + &kCFTypeDictionaryValueCallBacks); + CFMutableDictionaryRef io = + CFDictionaryCreateMutable(NULL, 0, &kCFTypeDictionaryKeyCallBacks, + &kCFTypeDictionaryValueCallBacks); + if (!a || !io) { + if (a) CFRelease(a); + if (io) CFRelease(io); + return NULL; + } + bool ok = true; + if (format) { + ok = put_num(a, kCVPixelBufferPixelFormatTypeKey, (int32_t)format); + } else { + int32_t f[2] = {kCVPixelFormatType_420YpCbCr8BiPlanarFullRange, + kCVPixelFormatType_422YpCbCr8BiPlanarFullRange}; + CFNumberRef n0 = CFNumberCreate(NULL, kCFNumberSInt32Type, &f[0]); + CFNumberRef n1 = CFNumberCreate(NULL, kCFNumberSInt32Type, &f[1]); + CFTypeRef v[2] = {n0, n1}; + CFArrayRef arr = + n0 && n1 ? CFArrayCreate(NULL, v, 2, &kCFTypeArrayCallBacks) : NULL; + if (n0) CFRelease(n0); + if (n1) CFRelease(n1); + ok = arr != NULL; + if (arr) { + CFDictionarySetValue(a, kCVPixelBufferPixelFormatTypeKey, arr); + CFRelease(arr); + } + } + ok = put_num(a, kCVPixelBufferWidthKey, (int32_t)w) && ok; + ok = put_num(a, kCVPixelBufferHeightKey, (int32_t)h) && ok; + CFDictionarySetValue(a, kCVPixelBufferIOSurfacePropertiesKey, io); + CFDictionarySetValue(a, kCVPixelBufferMetalCompatibilityKey, kCFBooleanTrue); + CFRelease(io); + if (!ok) { + CFRelease(a); + return NULL; + } + return a; +} + +CFDictionaryRef vcnjpeg_copy_pixel_buffer_attributes(uint32_t w, uint32_t h, + bool ten) { + (void)ten; + return attributes(w, h, 0); +} + +static size_t surface_bytes(uint32_t w, uint32_t h, bool yuyv); +bool vcnjpeg_fits(VcnJpeg* d, uint32_t w, uint32_t h) { + size_t a = surface_bytes(w, h, false), b = surface_bytes(w, h, true); + return (a > b ? a : b) <= d->surfaceRoom; +} + +static int failed(VcnJpeg* d, int failure, const char* what, int status) { + d->failure = failure; + if (status == 0) + snprintf(d->err, sizeof(d->err), "%s", what); + else + snprintf(d->err, sizeof(d->err), "%s (status %d)", what, status); + return -1; +} + +VcnJpeg* vcnjpeg_create(uint32_t maxWidth, uint32_t maxHeight, char* err, + size_t errLen) { + if (!__atomic_load_n(&vcnjpeg_gpu_armed, __ATOMIC_RELAXED)) { + snprintf(err, errLen, "not armed"); + return NULL; + } + VcnJpeg* d = calloc(1, sizeof(*d)); + if (!d) { + snprintf(err, errLen, "out of memory"); + return NULL; + } + d->maxW = maxWidth; + d->maxH = maxHeight; + d->conn = vcnjpeg_transport_open(); + if (!d->conn) { + snprintf(err, errLen, "cannot open a video context on the AMD accelerator"); + free(d); + return NULL; + } + uint64_t state = 0, jcap = 0, scap = 0; + int s = ja_info(vcnjpeg_transport, d->conn, &state, &jcap, &scap); + if (s != JA_OK) { + // -1: the request went on to PowerPlay, which refused it: no kext with the + // door + snprintf(err, errLen, + s == -1 ? "no JPEG decoder: the VCNJpeg kext is not loaded" + : "the JPEG decoder is not ready (status %d)", + s); + vcnjpeg_transport_close(d->conn); + free(d); + return NULL; + } + if ((state & JA_STATE_STUCK) || !(state & JA_STATE_POOL) || + !(state & JA_STATE_CREATED)) { + snprintf(err, errLen, + (state & JA_STATE_STUCK) + ? "the JPEG decoder is stuck until the next restart" + : "the JPEG decoder has no queue or no buffers (state 0x%llx)", + (unsigned long long)state); + vcnjpeg_transport_close(d->conn); + free(d); + return NULL; + } + d->surfaceRoom = scap; + (void)jcap; + return d; +} + +void vcnjpeg_destroy(VcnJpeg* d) { + if (!d) return; + if (d->conn) { + struct ja_reply rp; + ja_call(vcnjpeg_transport, d->conn, JA_OP_RELEASE, 0, 0, NULL, 0, &rp, NULL, + 0); + vcnjpeg_transport_close(d->conn); + } + if (d->pool) CVPixelBufferPoolRelease(d->pool); + free(d->surface); + free(d); +} + +static CVPixelBufferRef new_target(VcnJpeg* d, uint32_t w, uint32_t h, + OSType format) { + if (d->pool && (d->poolW != w || d->poolH != h || d->poolFormat != format)) { + CVPixelBufferPoolRelease(d->pool); + d->pool = NULL; + } + if (!d->pool) { + CFDictionaryRef a = attributes(w, h, format); + if (!a) return NULL; + CVReturn r = CVPixelBufferPoolCreate(NULL, NULL, a, &d->pool); + CFRelease(a); + if (r) { + d->pool = NULL; + return NULL; + } + d->poolW = w; + d->poolH = h; + d->poolFormat = format; + } + CVPixelBufferRef pb = NULL; + if (CVPixelBufferPoolCreatePixelBuffer(NULL, d->pool, &pb)) return NULL; + return pb; +} + +// The kext's surface layout for a picture (VCNJpeg jc::outputLayout): +// NV12: rows of alignUp(alignUp(width, 16), 256) bytes, alignUp(height, 16) +// luma rows, then the interleaved chroma. YUYV (4:2:2): one plane, rows of +// alignUp(alignUp(width, 16) * 2, 256) bytes. +static size_t surface_bytes(uint32_t w, uint32_t h, bool yuyv) { + size_t rows = ((size_t)h + 15) / 16 * 16; + if (yuyv) return (((size_t)w + 15) / 16 * 16 * 2 + 255) / 256 * 256 * rows; + size_t pitch = (((size_t)w + 15) / 16 * 16 + 255) / 256 * 256; + return pitch * rows * 3 / 2; +} + +// YUYV rows (Y0 Cb Y1 Cr) into '422f': the Ys to plane 0, each Cb Cr pair to +// plane 1. +static bool copy_yuyv(const uint8_t* src, const struct ja_picture* pic, + CVPixelBufferRef pb) { + uint32_t w = pic->width, h = pic->height; + size_t row = ((size_t)w + 1) / 2 * 4; + if (pic->pitch < row || (size_t)pic->pitch * h > pic->surfaceBytes) + return false; + if (CVPixelBufferLockBaseAddress(pb, 0)) return false; + bool ok = CVPixelBufferGetPlaneCount(pb) == 2 && + CVPixelBufferGetWidthOfPlane(pb, 0) == w && + CVPixelBufferGetHeightOfPlane(pb, 0) == h && + CVPixelBufferGetHeightOfPlane(pb, 1) == h; + if (ok) { + uint8_t* y = CVPixelBufferGetBaseAddressOfPlane(pb, 0); + uint8_t* uv = CVPixelBufferGetBaseAddressOfPlane(pb, 1); + size_t ys = CVPixelBufferGetBytesPerRowOfPlane(pb, 0), + uvs = CVPixelBufferGetBytesPerRowOfPlane(pb, 1); + size_t pairs = ((size_t)w + 1) / 2; + ok = y && uv && ys >= w && uvs >= pairs * 2; + for (uint32_t r = 0; ok && r < h; r++) { + const uint8_t* s = src + (size_t)r * pic->pitch; + uint8_t* yr = y + r * ys; + uint8_t* cr = uv + r * uvs; + for (size_t p = 0; p < pairs; p++) { + yr[2 * p] = s[4 * p]; + if (2 * p + 1 < w) yr[2 * p + 1] = s[4 * p + 2]; + cr[2 * p] = s[4 * p + 1]; + cr[2 * p + 1] = s[4 * p + 3]; + } + } + } + CVPixelBufferUnlockBaseAddress(pb, 0); + return ok; +} + +// Copies the kext's surface into the planes of pb; false if the layout the kext +// reported does not fit the picture. +static bool copy_planes(const uint8_t* src, const struct ja_picture* pic, + CVPixelBufferRef pb) { + uint32_t w = pic->width, h = pic->height; + if (pic->pitch < w || (size_t)pic->pitch * h > pic->chromaOffset || + pic->chromaOffset + (size_t)pic->pitch * ((h + 1) / 2) > + pic->surfaceBytes) + return false; + if (CVPixelBufferLockBaseAddress(pb, 0)) return false; + bool ok = CVPixelBufferGetPlaneCount(pb) == 2 && + CVPixelBufferGetWidthOfPlane(pb, 0) == w && + CVPixelBufferGetHeightOfPlane(pb, 0) == h; + if (ok) { + uint8_t* y = CVPixelBufferGetBaseAddressOfPlane(pb, 0); + uint8_t* uv = CVPixelBufferGetBaseAddressOfPlane(pb, 1); + size_t ys = CVPixelBufferGetBytesPerRowOfPlane(pb, 0), + uvs = CVPixelBufferGetBytesPerRowOfPlane(pb, 1); + size_t cw = ((size_t)w + 1) / 2 * 2, + ch = CVPixelBufferGetHeightOfPlane(pb, 1); + ok = y && uv && ys >= w && uvs >= cw && ch == (h + 1) / 2 && + cw <= pic->pitch; + for (uint32_t r = 0; ok && r < h; r++) + memcpy(y + r * ys, src + (size_t)r * pic->pitch, w); + for (size_t r = 0; ok && r < ch; r++) + memcpy(uv + r * uvs, src + pic->chromaOffset + r * pic->pitch, cw); + } + CVPixelBufferUnlockBaseAddress(pb, 0); + return ok; +} + +int vcnjpeg_decode(VcnJpeg* d, const uint8_t* sample, size_t size, int64_t tag, + VcnJpegOutputFn fn, void* ctx) { + d->failure = VCNJPEG_FAIL_STREAM; + d->err[0] = 0; + uint8_t* jpeg = NULL; + size_t jpegLen = 0; + JpegInfo info; + char why[96]; + int p = jpeg_prepare(sample, size, &jpeg, &jpegLen, &info, why, sizeof(why)); + if (p == JPEG_NO_MEMORY) return failed(d, VCNJPEG_FAIL_MEMORY, why, 0); + if (p != JPEG_OK) return failed(d, VCNJPEG_FAIL_STREAM, why, 0); + if (info.width > d->maxW || info.height > d->maxH) { + free(jpeg); + return failed(d, VCNJPEG_FAIL_STREAM, + "picture larger than the session allows", 0); + } + size_t need = surface_bytes(info.width, info.height, info.yuyv); + // The size comes from the picture's own header, before the kext has seen it: + // a picture the kext cannot hold is refused here, so that a few bytes of SOF + // cannot make this process allocate hundreds of megabytes. + if (need > d->surfaceRoom) { + free(jpeg); + return failed(d, VCNJPEG_FAIL_STREAM, + "picture larger than the kext's buffer", 0); + } + if (need > d->surfaceCap) { + free(d->surface); + d->surface = malloc(need); + d->surfaceCap = d->surface ? need : 0; + if (!d->surface) { + free(jpeg); + return failed(d, VCNJPEG_FAIL_MEMORY, "out of memory", 0); + } + } + struct ja_picture pic; + struct ja_reply rp; + int s = ja_decode(vcnjpeg_transport, d->conn, jpeg, jpegLen, d->surface, + d->surfaceCap, 0, kBusyWaitMs, &pic, &rp); + free(jpeg); + if (s == JA_BAD_STREAM) + return failed(d, VCNJPEG_FAIL_STREAM, "the kext refused the picture", + (int)rp.detail); + if (s == JA_BAD_REQUEST) + return failed(d, VCNJPEG_FAIL_STREAM, + "the picture does not fit the kext's buffers", s); + if (s != JA_OK) + return failed(d, VCNJPEG_FAIL_DEVICE, "the JPEG decoder failed", s); + if (pic.width != info.width || pic.height != info.height || + pic.surfaceBytes > d->surfaceCap || pic.format != (info.yuyv ? 1u : 0u)) + return failed(d, VCNJPEG_FAIL_DEVICE, + "the kext's picture is not the one sent", 0); + CVPixelBufferRef pb = + new_target(d, info.width, info.height, + info.yuyv ? kCVPixelFormatType_422YpCbCr8BiPlanarFullRange + : kCVPixelFormatType_420YpCbCr8BiPlanarFullRange); + if (!pb) return failed(d, VCNJPEG_FAIL_MEMORY, "no pixel buffer", 0); + if (!(info.yuyv ? copy_yuyv(d->surface, &pic, pb) + : copy_planes(d->surface, &pic, pb))) { + CVPixelBufferRelease(pb); + return failed(d, VCNJPEG_FAIL_DEVICE, + "the kext's layout does not fit the picture", 0); + } + // JFIF: BT.601 matrix, full range (the pixel format says the range) + CVBufferSetAttachment(pb, kCVImageBufferYCbCrMatrixKey, + kCVImageBufferYCbCrMatrix_ITU_R_601_4, + kCVAttachmentMode_ShouldPropagate); + fn(ctx, pb, NULL, info.width, info.height, tag); + CVPixelBufferRelease(pb); + return 0; +} + +const char* vcnjpeg_last_error(VcnJpeg* d) { return d->err; } +int vcnjpeg_failure(VcnJpeg* d) { return d->failure; } +CVPixelBufferRef vcnjpeg_hidden_picture(VcnJpeg* d) { + (void)d; + return NULL; +} +unsigned vcnjpeg_firmware_errors(VcnJpeg* d) { + (void)d; + return 0; +} diff --git a/GPU/decode/jpeg/vcnjpeg.h b/GPU/decode/jpeg/vcnjpeg.h new file mode 100644 index 00000000..1fd5ab17 --- /dev/null +++ b/GPU/decode/jpeg/vcnjpeg.h @@ -0,0 +1,61 @@ +// vcnjpeg: one JPEG picture at a time on the JPEG block of the AMD VCN, through +// the VCNJpeg kext (GPU/jpeg). The kext owns the block, its queue +// and its buffers; a process reaches it through the accelerator's video context +// (selector 258, see jpeg_app.h), the connection any process that decodes +// video may open. Without that kext there is no decoder: vcnjpeg_create fails. +// +// The interface is the one of vcnvp9.h, so that the VideoToolbox side +// (JPEGVCNDecoder.c) and its tests (tests/plugintest.c) are the same code. +#pragma once +#include +#include +#include +#include + +#include "jpeg_app_client.h" + +typedef struct VcnJpeg VcnJpeg; +typedef void (*VcnJpegOutputFn)(void* ctx, CVPixelBufferRef pb, + const void* unused, uint32_t width, + uint32_t height, int64_t tag); + +// The plug-in sets this; nothing is sent to the kernel before it is set. +extern int vcnjpeg_gpu_armed; + +// The transport to the kext: the real one by default, a stand-in in the tests. +extern ja_transport vcnjpeg_transport; +extern void* (*vcnjpeg_transport_open)(void); +extern void (*vcnjpeg_transport_close)(void* ctx); + +// What the session may get, full range (a JPEG's samples are 0..255), IOSurface +// backed: NV12 ('420f') for 4:2:0 pictures, '422f' (Y plane + CbCr plane at +// full height) for 4:2:2 ones, which the block writes as YUYV and vcnjpeg +// splits. +CFDictionaryRef vcnjpeg_copy_pixel_buffer_attributes(uint32_t w, uint32_t h, + bool tenBit); + +// Fails when there is no kext with the door, or its decoder is not ready or is +// stuck (a job failed in a way that stops it until the next restart). +VcnJpeg* vcnjpeg_create(uint32_t maxWidth, uint32_t maxHeight, char* err, + size_t errLen); +// True when a picture of w x h, 4:2:0 or 4:2:2, fits the kext's buffers. +bool vcnjpeg_fits(VcnJpeg* d, uint32_t w, uint32_t h); +void vcnjpeg_destroy(VcnJpeg* d); +// Decodes one picture and calls fn with it. +int vcnjpeg_decode(VcnJpeg* d, const uint8_t* sample, size_t size, int64_t tag, + VcnJpegOutputFn fn, void* ctx); +const char* vcnjpeg_last_error(VcnJpeg* d); +enum { + VCNJPEG_FAIL_STREAM = + 0, // the picture cannot be decoded as it is (or not by the block) + VCNJPEG_FAIL_DEVICE = + 1, // the kext is gone, refused, timed out, or stays busy + VCNJPEG_FAIL_MEMORY = 2, + VCNJPEG_FAIL_REFERENCE = 3, // never: a JPEG needs no other picture +}; +int vcnjpeg_failure(VcnJpeg* d); +// A JPEG has no hidden pictures: always NULL. +CVPixelBufferRef vcnjpeg_hidden_picture(VcnJpeg* d); +// Pictures the block decoded but the kext reported as wrong: none can be told +// apart yet, always 0. +unsigned vcnjpeg_firmware_errors(VcnJpeg* d); diff --git a/GPU/decode/loader/build.sh b/GPU/decode/loader/build.sh index ebe3fe76..90520938 100755 --- a/GPU/decode/loader/build.sh +++ b/GPU/decode/loader/build.sh @@ -7,7 +7,7 @@ # # The kext only lets through the exact plug-in builds listed in it. The list is made here, # from three places: -# 1. the five plug-in bundles of decode/build/ (AV1, VP9, MPEG-2, VC-1, MPEG-4; built +# 1. the six plug-in bundles of decode/build/ (AV1, VP9, MPEG-2, VC-1, MPEG-4, JPEG; built # first if one is missing) # 2. released-builds.txt in this folder: the builds of published releases # 3. any bundle given on the command line @@ -38,7 +38,7 @@ OBJ=$B/loader FINAL=$B/$NAME.kext OUT=$OBJ/$NAME.kext # assembled here; it replaces $FINAL only when everything worked # Every plug-in decode/build.sh makes; a kext that lists only some would refuse the others. -PLUGINS=(AV1VCNDecoder VP9VCNDecoder MPEG2VCNDecoder VC1VCNDecoder MPEG4VCNDecoder) +PLUGINS=(AV1VCNDecoder VP9VCNDecoder MPEG2VCNDecoder VC1VCNDecoder MPEG4VCNDecoder JPEGVCNDecoder) for p in $PLUGINS; do [[ -d $B/$p.bundle ]] || { $DECODE/build.sh; break; } done diff --git a/GPU/decode/mpeg4/vcnmpeg4.c b/GPU/decode/mpeg4/vcnmpeg4.c index 1bf31217..f3a3566a 100644 --- a/GPU/decode/mpeg4/vcnmpeg4.c +++ b/GPU/decode/mpeg4/vcnmpeg4.c @@ -6,27 +6,9 @@ int vcnmpeg4_index_mode = 0; int vcnmpeg4_block_mode = 0; -int vcnmpeg4_matrix_mode = 0; +int vcnmpeg4_cut_mode = 0; -// Zigzag scan of ISO 14496-2 figure 7-3. -static const uint8_t kZigzag[64] = { - 0, 1, 8, 16, 9, 2, 3, 10, 17, 24, 32, 25, 18, 11, 4, 5, - 12, 19, 26, 33, 40, 48, 41, 34, 27, 20, 13, 6, 7, 14, 21, 28, - 35, 42, 49, 56, 57, 50, 43, 36, 29, 22, 15, 23, 30, 37, 44, 51, - 58, 59, 52, 45, 38, 31, 39, 46, 53, 60, 61, 54, 47, 55, 62, 63}; - -static void put_matrix(uint8_t* out, const uint8_t* stream) { - if (vcnmpeg4_matrix_mode != 1) { - memcpy(out, stream, 64); - return; - } - uint8_t block[64]; - for (int i = 0; i < 64; i++) block[kZigzag[i]] = stream[i]; - for (int i = 0; i < 64; i++) { - unsigned at = kZigzag[i]; - out[i] = block[(at & 7) * 8 + (at >> 3)]; - } -} +static uint16_t al16(uint32_t v) { return (uint16_t)((v + 15) & ~15u); } typedef struct { Mpeg4Parser parser; @@ -60,8 +42,11 @@ void vcnmpeg4_fill_block(VcnMpeg4Msg* m, const Mpeg4Parser* p, m->forward_ref_pic_idx = ref_index(frameNumber, forwardRef); m->backward_ref_pic_idx = ref_index(frameNumber, backwardRef); } - m->video_object_layer_width = (uint16_t)p->width; - m->video_object_layer_height = (uint16_t)p->height; + // Aligned to whole macroblocks, as Mesa's radeon_create_decoder makes + // dec->base.width/height for this codec (mesa-25.0.0 radeon_vcn_dec.c, + // get_mpeg4_msg): 1920x1080 goes out as 1920x1088. + m->video_object_layer_width = al16(p->width); + m->video_object_layer_height = al16(p->height); m->vop_time_increment_resolution = p->time_increment_resolution; uint32_t fl = VCN_MPEG4_COMPLEXITY_ESTIMATION_DISABLE; if (p->interlaced) fl |= VCN_MPEG4_INTERLACED; @@ -75,8 +60,8 @@ void vcnmpeg4_fill_block(VcnMpeg4Msg* m, const Mpeg4Parser* p, m->profile_and_level_indication = 0xF0; m->video_object_layer_verid = 5; fl |= VCN_MPEG4_LOAD_INTRA_QUANT_MAT | VCN_MPEG4_LOAD_NONINTRA_QUANT_MAT; - put_matrix(m->intra_quant_mat, p->intra_matrix); - put_matrix(m->nonintra_quant_mat, p->nonintra_matrix); + memcpy(m->intra_quant_mat, p->intra_matrix, 64); + memcpy(m->nonintra_quant_mat, p->nonintra_matrix, 64); // Mode 2: and the B-VOP's time distances, which direct mode scales its // motion vectors by. Mode 3: the whole VOP part. if (vcnmpeg4_block_mode == 2) { @@ -103,8 +88,8 @@ void vcnmpeg4_fill_block(VcnMpeg4Msg* m, const Mpeg4Parser* p, if (p->obmc_disable) fl |= VCN_MPEG4_OBMC_DISABLE; if (p->quant_type) { fl |= VCN_MPEG4_LOAD_INTRA_QUANT_MAT | VCN_MPEG4_LOAD_NONINTRA_QUANT_MAT; - put_matrix(m->intra_quant_mat, p->intra_matrix); - put_matrix(m->nonintra_quant_mat, p->nonintra_matrix); + memcpy(m->intra_quant_mat, p->intra_matrix, 64); + memcpy(m->nonintra_quant_mat, p->nonintra_matrix, 64); } m->vop.vop_data_present = 1; m->vop.vop_coding_type = pic->coding_type; @@ -156,6 +141,7 @@ static int on_picture(void* ctx, Mpeg4Parser* p, const Mpeg4Picture* pic) { .messageId = VCN_MESSAGE_MPEG4_ASP_VLD, .width = p->width, .height = p->height, + .alignSizeTo16 = true, .logSubsystem = "com.droga.vtmpeg4vcn"}; d->vcn = vcnlegacy_create(&cfg, d->err, sizeof(d->err)); if (!d->vcn) { @@ -172,6 +158,19 @@ static int on_picture(void* ctx, Mpeg4Parser* p, const Mpeg4Picture* pic) { "MPEG-4 B-VOPs are not decoded on this GPU yet"); return -1; } + // Direct mode scales the co-located motion vectors by TRB / TRD. A B-VOP + // whose reference VOPs carry the same time (or times the parser could not + // order) has TRD 0, and a firmware that divides by it unguarded may never + // finish: such a B-VOP never goes to the GPU, whatever VCNMPEG4_ALLOW_B + // says. It fails as a missing reference, on which FFmpeg goes on with the + // next frame. + if (pic->coding_type == MPEG4_B && pic->vop_coded && !pic->trd) { + snprintf(d->err, sizeof(d->err), + "MPEG-4 B-VOP with no time distance between its reference VOPs " + "(TRD 0); not sent to the GPU"); + d->failure = VCNLEGACY_FAIL_REFERENCE; + return -1; + } int need = pic->coding_type == MPEG4_B ? 2 : pic->coding_type == MPEG4_P ? 1 : 0; @@ -208,7 +207,11 @@ static int on_picture(void* ctx, Mpeg4Parser* p, const Mpeg4Picture* pic) { } VcnMpeg4Msg msg; vcnmpeg4_fill_block(&msg, p, pic, n, fwd, back); - VcnLegacyBytes part = {pic->data, pic->size}; + // Cut mode 1 (experiments only): from the VOP start code on, without the + // headers in front of it (visual object sequence, VOL, GOV). Mesa's VA path + // never sends a VOL in the bitstream either. + size_t skip = vcnmpeg4_cut_mode == 1 ? pic->vopOffset : 0; + VcnLegacyBytes part = {pic->data + skip, pic->size - skip}; if (vcnlegacy_decode(d->vcn, &msg, sizeof(msg), &part, 1, target)) { snprintf(d->err, sizeof(d->err), "%s", vcnlegacy_last_error(d->vcn)); d->failure = vcnlegacy_failure(d->vcn); diff --git a/GPU/decode/mpeg4/vcnmpeg4.h b/GPU/decode/mpeg4/vcnmpeg4.h index fa0c0d99..62974779 100644 --- a/GPU/decode/mpeg4/vcnmpeg4.h +++ b/GPU/decode/mpeg4/vcnmpeg4.h @@ -27,12 +27,19 @@ extern int vcnmpeg4_index_mode; // busy about 2 s with no picture, and three in a row hung the video engine // (2026-11-23). So B-VOPs are refused: a configuration whose VOL does not rule // them out fails create(), and a B-VOP fails decode (VCNMPEG4_ALLOW_B=1 lets -// both through, for experiments only). +// both through, for experiments only). A B-VOP whose TRD is 0 is refused even +// then. extern int vcnmpeg4_block_mode; -// The quantiser matrices: 0 = in the order the stream sends them (zigzag), -// what MPEG-2 needs on this card; 1 = the transposed matrix in zigzag order, -// what Mesa's VA-API path sends for MPEG-2. Only for experiments. -extern int vcnmpeg4_matrix_mode; +// The quantiser matrices always go in the order the stream sends them +// (zigzag), the order MPEG-2 needs on this card (a transposed order, as Mesa's +// VA-API path sends for MPEG-2, gave 23-27 dB there, 2026-11-23). +// +// What goes to the firmware as the bitstream of a VOP: 0 (the default) = the +// access unit from its first start code, with the headers in front of the VOP +// (visual object sequence, VOL, GOV) when there are any; 1 = from the VOP start +// code on. Only for experiments; a unit that is a VOP alone is the same in +// both. +extern int vcnmpeg4_cut_mode; void vcnmpeg4_fill_block(VcnMpeg4Msg* m, const Mpeg4Parser* p, const Mpeg4Picture* pic, uint32_t frameNumber, diff --git a/GPU/decode/tests/gpu/README.md b/GPU/decode/tests/gpu/README.md index 4ff98ea4..3bec9916 100644 --- a/GPU/decode/tests/gpu/README.md +++ b/GPU/decode/tests/gpu/README.md @@ -24,6 +24,8 @@ Mac has to be reset. Before any run marked "can hang" below: | `vtlegacytest` | yes, through VideoToolbox | **yes** | `VCNLEGACY_ALLOW_GPU=yes-i-know-it-can-hang` (without it, it only cuts the stream into samples) | | `vtav1test` | yes, through VideoToolbox | **yes** | none: a decode run is armed | | `vtvp9test` | yes, through VideoToolbox | **yes** | none: a decode run is armed | +| `vtjpegtest` | yes, through VideoToolbox and the VCNJpeg kext | **yes** | none: a decode run is armed (`-apple` runs on the CPU only) | +| `mkmjpeg422` | no | no | none | | `vtchurn` | yes, through VideoToolbox | **yes** | none: every session decodes | | `probe_ctx` | yes | low risk: it opens a session, it decodes nothing | none | | `tools/driver/dryrun.py`, `dryrun_vp9.py` | yes, under lldb | the driver's own setup goes out; our commands do not | the scripts arm the program themselves | @@ -147,6 +149,23 @@ VCNVP9_SESSION=vp9 VCNVP9_ALLOW_GPU=yes-i-know-it-can-hang \ A pass: one line per frame ending in `OK`, then `N frames, 0 mismatches`, and exit status 0. +## vtjpegtest + +Motion JPEG through VideoToolbox, every frame compared with FFmpeg's decode (within 2: the +block's IDCT rounds a little differently). It needs `VCNJpeg.kext` running +([jpeg/README.md](../../../jpeg/README.md)). + +```bash +ffmpeg -f lavfi -i testsrc2=size=1280x720:rate=30 -frames:v 30 -pix_fmt yuvj420p -c:v mjpeg -q:v 3 -f mjpeg c420.mjpeg +ffmpeg -i c420.mjpeg -f rawvideo -pix_fmt yuvj420p r420.yuv +decode/build/gpu/vtjpegtest -apple c420.mjpeg r420.yuv 1280 720 420 # CPU only: checks the clip +decode/build/gpu/vtjpegtest -load decode/build/JPEGVCNDecoder.bundle c420.mjpeg r420.yuv 1280 720 420 +decode/build/gpu/vtjpegtest -system c420.mjpeg r420.yuv 1280 720 420 # the installed plug-in +``` + +`-dmb1` sends the same pictures as OpenDML. `mkmjpeg422` writes the 4:2:2 sampling webcams +use (luma 2x1), which FFmpeg does not write. + ## vtav1test and vtvp9test They decode through the public VideoToolbox API, the way Safari does. They test the plug-in @@ -165,8 +184,11 @@ decode/build/gpu/vtvp9test -load decode/build/VP9VCNDecoder.bundle v.ivf v.ivf.m bundle cannot be registered. Pass `-id` with the decoder ID that `list` prints for it, or VideoToolbox may pick the installed decoder instead of the one you loaded. - `-n` reads no pixels. `-a` decodes asynchronously. `-pace fps` feeds frames at a fixed - rate and reports how late they come out. `vtvp9test` also has `-loop N` (the file N times - in one session), `-frames N` and `-sw` (does not ask for hardware). `vtav1test -sw` decodes + rate and reports how late they come out. `-loop N` feeds the file N times in one session + and prints a line with the time after each pass; `-renew` makes a new session for every + pass, in the same process. Together they make the sleep test: `-loop 100 -pace 30` across + `pmset sleepnow` (`docs/testing.md`). `vtvp9test` also has `-frames N` and `-sw` (does + not ask for hardware). `vtav1test -sw` decodes in software only: it turns hardware decoders off and stops before the first frame if VideoToolbox gives one anyway. (Apple's software AV1 decoder refused every stream here on macOS 26.7.3, 8-bit too: -12906.) diff --git a/GPU/decode/tests/gpu/build.sh b/GPU/decode/tests/gpu/build.sh index 713a8235..2ef93de2 100755 --- a/GPU/decode/tests/gpu/build.sh +++ b/GPU/decode/tests/gpu/build.sh @@ -12,6 +12,9 @@ # test's own process, nothing installed (armed by VCNLEGACY_ALLOW_GPU) # vtav1test AV1 through VideoToolbox, as Safari does (no switch: see README.md) # vtvp9test VP9 through VideoToolbox, as Safari does (no switch: see README.md) +# vtjpegtest Motion JPEG through VideoToolbox, our decoder only (loaded in the process, or the +# installed one with -system), compared with FFmpeg (no switch) +# mkmjpeg422 writes Motion JPEG sampled as webcams do (4:2:2, luma 2x1); CPU only # vtchurn many sessions in one process, counts ports and IOKit connections (no switch) # probe_ctx asks the driver for one decode context (no switch: see README.md) # driveruuid prints the build identifier of the installed driver @@ -79,6 +82,8 @@ build vtlegacytest -Impeg2 -Ivc1 -Impeg4 $T/vtlegacytest.c mpeg2/MPEG2VCNDecoder build vtav1test $T/vtav1test.c av1/av1parse.c $CF $VT build vtvp9test $T/vtvp9test.c vp9/vp9parse.c $CF $VT +build vtjpegtest $T/vtjpegtest.c $CF $VT +build mkmjpeg422 $T/mkmjpeg422.c build vtchurn $T/vtchurn.c $CF $VT build probe_ctx $T/probe_ctx.c common/vcndriver.c $CF $IOKIT build driveruuid $T/driveruuid.c common/vcndriver.c $CF $IOKIT diff --git a/GPU/decode/tests/gpu/decode_legacy.c b/GPU/decode/tests/gpu/decode_legacy.c index 9f1c85fa..f86047a8 100644 --- a/GPU/decode/tests/gpu/decode_legacy.c +++ b/GPU/decode/tests/gpu/decode_legacy.c @@ -18,7 +18,7 @@ // VCNMPEG2_ALLOW_FIELDS=1 send field pictures (refused by default) // VCNMPEG4_INDEX=0|1 vcnmpeg4_index_mode // VCNMPEG4_BLOCK=0..3 vcnmpeg4_block_mode (Mesa's block / VOP part filled) -// VCNMPEG4_MATRIX=0|1 vcnmpeg4_matrix_mode (stream order / transposed) +// VCNMPEG4_CUT=0|1 vcnmpeg4_cut_mode (whole unit / from the VOP) // VCNMPEG4_ALLOW_B=1 send B-VOPs too (each can hang the video engine) // VCNLEGACY_DB_HEIGHT=0|1 vcnlegacy_db_height_mode (aligned / 0) // VCNLEGACY_CLEAR_DPB=0|1 vcnlegacy_clear_dpb (zero the DPB first) @@ -137,7 +137,7 @@ int main(int argc, char** argv) { vcnmpeg2_field_mode = env_int("VCNMPEG2_FIELD", vcnmpeg2_field_mode); vcnmpeg4_index_mode = env_int("VCNMPEG4_INDEX", vcnmpeg4_index_mode); vcnmpeg4_block_mode = env_int("VCNMPEG4_BLOCK", vcnmpeg4_block_mode); - vcnmpeg4_matrix_mode = env_int("VCNMPEG4_MATRIX", vcnmpeg4_matrix_mode); + vcnmpeg4_cut_mode = env_int("VCNMPEG4_CUT", vcnmpeg4_cut_mode); vcnlegacy_debug = env_int("VCNLEGACY_DEBUG", vcnlegacy_debug); vcnlegacy_db_height_mode = env_int("VCNLEGACY_DB_HEIGHT", vcnlegacy_db_height_mode); diff --git a/GPU/decode/tests/gpu/mkmjpeg422.c b/GPU/decode/tests/gpu/mkmjpeg422.c new file mode 100644 index 00000000..4c1679f3 --- /dev/null +++ b/GPU/decode/tests/gpu/mkmjpeg422.c @@ -0,0 +1,293 @@ +// mkmjpeg422: writes a Motion JPEG stream sampled the way webcams do it +// (4:2:2 as luma 2x1, chroma 1x1, 1x1), which FFmpeg's encoder cannot write +// (it writes 4:2:2 as 2x2, 1x2, 1x2) and Apple's encoder neither (4:2:0 only). +// +// mkmjpeg422 in.yuv width height out.mjpeg [quality] +// +// in.yuv: planar 4:2:2 frames (FFmpeg's yuvj422p), width a multiple of 16, +// height a multiple of 8. Each frame becomes one baseline JPEG: standard +// quantisation tables of Annex K scaled as libjpeg does for the quality (90 by +// default), the standard Huffman tables of Annex K, one interleaved scan. +// Runs on the CPU only. +#include +#include +#include +#include +#include + +static const uint8_t kZigzag[64] = { + 0, 1, 8, 16, 9, 2, 3, 10, 17, 24, 32, 25, 18, 11, 4, 5, + 12, 19, 26, 33, 40, 48, 41, 34, 27, 20, 13, 6, 7, 14, 21, 28, + 35, 42, 49, 56, 57, 50, 43, 36, 29, 22, 15, 23, 30, 37, 44, 51, + 58, 59, 52, 45, 38, 31, 39, 46, 53, 60, 61, 54, 47, 55, 62, 63}; +static const uint8_t kStdLuma[64] = { + 16, 11, 10, 16, 24, 40, 51, 61, 12, 12, 14, 19, 26, 58, 60, 55, + 14, 13, 16, 24, 40, 57, 69, 56, 14, 17, 22, 29, 51, 87, 80, 62, + 18, 22, 37, 56, 68, 109, 103, 77, 24, 35, 55, 64, 81, 104, 113, 92, + 49, 64, 78, 87, 103, 121, 120, 101, 72, 92, 95, 98, 112, 100, 103, 99}; +static const uint8_t kStdChroma[64] = { + 17, 18, 24, 47, 99, 99, 99, 99, 18, 21, 26, 66, 99, 99, 99, 99, + 24, 26, 56, 99, 99, 99, 99, 99, 47, 66, 99, 99, 99, 99, 99, 99, + 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, + 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}; +// Annex K.3: bits (count of codes of each length 1..16) and values +static const uint8_t kDcLumaBits[16] = {0, 1, 5, 1, 1, 1, 1, 1, + 1, 0, 0, 0, 0, 0, 0, 0}; +static const uint8_t kDcLumaVals[12] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11}; +static const uint8_t kDcChromaBits[16] = {0, 3, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 0, 0, 0, 0, 0}; +static const uint8_t kDcChromaVals[12] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11}; +static const uint8_t kAcLumaBits[16] = {0, 2, 1, 3, 3, 2, 4, 3, + 5, 5, 4, 4, 0, 0, 1, 0x7d}; +static const uint8_t kAcLumaVals[162] = { + 0x01, 0x02, 0x03, 0x00, 0x04, 0x11, 0x05, 0x12, 0x21, 0x31, 0x41, 0x06, + 0x13, 0x51, 0x61, 0x07, 0x22, 0x71, 0x14, 0x32, 0x81, 0x91, 0xa1, 0x08, + 0x23, 0x42, 0xb1, 0xc1, 0x15, 0x52, 0xd1, 0xf0, 0x24, 0x33, 0x62, 0x72, + 0x82, 0x09, 0x0a, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x25, 0x26, 0x27, 0x28, + 0x29, 0x2a, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x43, 0x44, 0x45, + 0x46, 0x47, 0x48, 0x49, 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, + 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x73, 0x74, 0x75, + 0x76, 0x77, 0x78, 0x79, 0x7a, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, + 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0xa2, 0xa3, + 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, + 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, + 0xca, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xe1, 0xe2, + 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xf1, 0xf2, 0xf3, 0xf4, + 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa}; +static const uint8_t kAcChromaBits[16] = {0, 2, 1, 2, 4, 4, 3, 4, + 7, 5, 4, 4, 0, 1, 2, 0x77}; +static const uint8_t kAcChromaVals[162] = { + 0x00, 0x01, 0x02, 0x03, 0x11, 0x04, 0x05, 0x21, 0x31, 0x06, 0x12, 0x41, + 0x51, 0x07, 0x61, 0x71, 0x13, 0x22, 0x32, 0x81, 0x08, 0x14, 0x42, 0x91, + 0xa1, 0xb1, 0xc1, 0x09, 0x23, 0x33, 0x52, 0xf0, 0x15, 0x62, 0x72, 0xd1, + 0x0a, 0x16, 0x24, 0x34, 0xe1, 0x25, 0xf1, 0x17, 0x18, 0x19, 0x1a, 0x26, + 0x27, 0x28, 0x29, 0x2a, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x43, 0x44, + 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, + 0x59, 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x73, 0x74, + 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, + 0x88, 0x89, 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, + 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4, + 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, + 0xc8, 0xc9, 0xca, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, + 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xf2, 0xf3, 0xf4, + 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa}; + +typedef struct { + uint16_t code[256]; + uint8_t len[256]; +} Huff; +static void build_huff(Huff* h, const uint8_t bits[16], const uint8_t* vals) { + memset(h, 0, sizeof(*h)); + uint16_t code = 0; + int k = 0; + for (int l = 1; l <= 16; l++) { + for (int i = 0; i < bits[l - 1]; i++) { + h->code[vals[k]] = code++; + h->len[vals[k]] = (uint8_t)l; + k++; + } + code <<= 1; + } +} + +typedef struct { + uint8_t* d; + size_t n, cap; + uint32_t acc; + int nbits; +} Out; +static void put(Out* o, uint8_t b) { + if (o->n == o->cap) { + o->cap = o->cap ? o->cap * 2 : 1 << 20; + o->d = realloc(o->d, o->cap); + if (!o->d) exit(3); + } + o->d[o->n++] = b; +} +static void put16(Out* o, int v) { + put(o, (uint8_t)(v >> 8)); + put(o, (uint8_t)v); +} +static void bits(Out* o, uint32_t v, int n) { + for (int i = n - 1; i >= 0; i--) { + o->acc = (o->acc << 1) | ((v >> i) & 1); + if (++o->nbits == 8) { + put(o, (uint8_t)o->acc); + if ((uint8_t)o->acc == 0xff) put(o, 0); // byte stuffing + o->acc = 0; + o->nbits = 0; + } + } +} +static void flush_bits(Out* o) { + while (o->nbits) bits(o, 1, 1); // pad with ones +} +static int magnitude(int v) { + int a = v < 0 ? -v : v, n = 0; + while (a) { + n++; + a >>= 1; + } + return n; +} +static void put_value(Out* o, int v, int n) { + if (n) bits(o, (uint32_t)(v < 0 ? v + (1 << n) - 1 : v), n); +} + +static void fdct(const uint8_t* src, int stride, double out[64]) { + static double c[8][8]; + static int init; + if (!init) { + for (int u = 0; u < 8; u++) + for (int x = 0; x < 8; x++) + c[u][x] = (u ? sqrt(2.0 / 8) : sqrt(1.0 / 8)) * + cos((2 * x + 1) * u * M_PI / 16); + init = 1; + } + double tmp[64]; + for (int y = 0; y < 8; y++) + for (int u = 0; u < 8; u++) { + double s = 0; + for (int x = 0; x < 8; x++) s += c[u][x] * (src[y * stride + x] - 128.0); + tmp[y * 8 + u] = s; + } + for (int u = 0; u < 8; u++) + for (int v = 0; v < 8; v++) { + double s = 0; + for (int y = 0; y < 8; y++) s += c[v][y] * tmp[y * 8 + u]; + out[v * 8 + u] = s; + } +} + +static void block(Out* o, const uint8_t* src, int stride, const uint8_t q[64], + int* dcPred, const Huff* dc, const Huff* ac) { + double f[64]; + fdct(src, stride, f); + int z[64]; + for (int i = 0; i < 64; i++) + z[i] = (int)lround(f[kZigzag[i]] / q[kZigzag[i]]); + int diff = z[0] - *dcPred; + *dcPred = z[0]; + int n = magnitude(diff); + bits(o, dc->code[n], dc->len[n]); + put_value(o, diff, n); + int run = 0; + for (int i = 1; i < 64; i++) { + if (!z[i]) { + run++; + continue; + } + while (run > 15) { + bits(o, ac->code[0xf0], ac->len[0xf0]); + run -= 16; + } + n = magnitude(z[i]); + int sym = (run << 4) | n; + bits(o, ac->code[sym], ac->len[sym]); + put_value(o, z[i], n); + run = 0; + } + if (run) bits(o, ac->code[0], ac->len[0]); +} + +static void dht(Out* o, int cls, int id, const uint8_t b[16], + const uint8_t* v) { + int n = 0; + for (int i = 0; i < 16; i++) n += b[i]; + put(o, (uint8_t)((cls << 4) | id)); + for (int i = 0; i < 16; i++) put(o, b[i]); + for (int i = 0; i < n; i++) put(o, v[i]); +} + +int main(int argc, char** argv) { + if (argc != 5 && argc != 6) { + fprintf(stderr, + "usage: mkmjpeg422 in.yuv(yuvj422p) width height out.mjpeg " + "[quality]\n"); + return 1; + } + int w = atoi(argv[2]), h = atoi(argv[3]), + quality = argc == 6 ? atoi(argv[5]) : 90; + if (w < 16 || h < 8 || w % 16 || h % 8 || w > 8192 || h > 8192 || + quality < 1 || quality > 100) { + fprintf(stderr, + "width must be a multiple of 16, height of 8, quality 1..100\n"); + return 1; + } + int scale = quality < 50 ? 5000 / quality : 200 - quality * 2; + uint8_t ql[64], qc[64]; + for (int i = 0; i < 64; i++) { + int a = (kStdLuma[i] * scale + 50) / 100, + b = (kStdChroma[i] * scale + 50) / 100; + ql[i] = (uint8_t)(a < 1 ? 1 : a > 255 ? 255 : a); + qc[i] = (uint8_t)(b < 1 ? 1 : b > 255 ? 255 : b); + } + Huff dcl, dcc, acl, acc; + build_huff(&dcl, kDcLumaBits, kDcLumaVals); + build_huff(&dcc, kDcChromaBits, kDcChromaVals); + build_huff(&acl, kAcLumaBits, kAcLumaVals); + build_huff(&acc, kAcChromaBits, kAcChromaVals); + FILE* in = fopen(argv[1], "rb"); + FILE* out = fopen(argv[4], "wb"); + if (!in || !out) { + fprintf(stderr, "cannot open the files\n"); + return 1; + } + size_t frameBytes = (size_t)w * h * 2; + uint8_t* f = malloc(frameBytes); + int frames = 0; + while (f && fread(f, 1, frameBytes, in) == frameBytes) { + const uint8_t *Y = f, *U = f + (size_t)w * h, *V = U + (size_t)w / 2 * h; + Out o = {0}; + put16(&o, 0xffd8); + put16(&o, 0xffdb); // DQT: two 8-bit tables, zigzag order + put16(&o, 2 + 2 * 65); + put(&o, 0); + for (int i = 0; i < 64; i++) put(&o, ql[kZigzag[i]]); + put(&o, 1); + for (int i = 0; i < 64; i++) put(&o, qc[kZigzag[i]]); + put16(&o, 0xffc0); // SOF0: 8 bits, three components, Y 2x1, Cb 1x1, Cr 1x1 + put16(&o, 17); + put(&o, 8); + put16(&o, h); + put16(&o, w); + put(&o, 3); + put(&o, 1), put(&o, 0x21), put(&o, 0); + put(&o, 2), put(&o, 0x11), put(&o, 1); + put(&o, 3), put(&o, 0x11), put(&o, 1); + put16(&o, 0xffc4); // DHT: the four standard tables + put16(&o, 2 + 4 * 17 + 12 + 12 + 162 + 162); + dht(&o, 0, 0, kDcLumaBits, kDcLumaVals); + dht(&o, 1, 0, kAcLumaBits, kAcLumaVals); + dht(&o, 0, 1, kDcChromaBits, kDcChromaVals); + dht(&o, 1, 1, kAcChromaBits, kAcChromaVals); + put16(&o, 0xffda); // SOS + put16(&o, 12); + put(&o, 3); + put(&o, 1), put(&o, 0x00); + put(&o, 2), put(&o, 0x11); + put(&o, 3), put(&o, 0x11); + put(&o, 0), put(&o, 63), put(&o, 0); + int py = 0, pu = 0, pv = 0; + for (int my = 0; my < h; my += 8) + for (int mx = 0; mx < w; mx += 16) { + block(&o, Y + (size_t)my * w + mx, w, ql, &py, &dcl, &acl); + block(&o, Y + (size_t)my * w + mx + 8, w, ql, &py, &dcl, &acl); + block(&o, U + (size_t)my * (w / 2) + mx / 2, w / 2, qc, &pu, &dcc, + &acc); + block(&o, V + (size_t)my * (w / 2) + mx / 2, w / 2, qc, &pv, &dcc, + &acc); + } + flush_bits(&o); + put16(&o, 0xffd9); + fwrite(o.d, 1, o.n, out); + free(o.d); + frames++; + } + free(f); + fclose(in); + fclose(out); + printf("wrote %d frames of %dx%d, 4:2:2 sampled 2x1/1x1/1x1, quality %d\n", + frames, w, h, quality); + return frames ? 0 : 2; +} diff --git a/GPU/decode/tests/gpu/vtav1test.c b/GPU/decode/tests/gpu/vtav1test.c index 04fab5a3..d8fb28d7 100644 --- a/GPU/decode/tests/gpu/vtav1test.c +++ b/GPU/decode/tests/gpu/vtav1test.c @@ -5,20 +5,23 @@ // shows the av01 decoders VideoToolbox knows about (LIST_ALL=1: all of // them) // vtav1test [-load bundle] file.ivf [file.md5] [-n] [-a] [-pace fps] -// [-id decoder] [-sw] [-attach] +// [-loop N] [-renew] [-id decoder] [-sw] [-attach] // decodes the file with a VTDecompressionSession that requires // hardware, compares the MD5 of every frame as I420 with the reference, // and reports timing // // -load registers the bundle in this process only, nothing is installed on the // system. -n reads no pixels, -a decodes asynchronously, -pace feeds at a fixed -// rate and reports lateness, -id picks one decoder when several handle av01 -// (the installed one and a -load'ed build). -sw decodes in software only: -// with -id com.apple.videotoolbox.videodecoder.av1.sw, Apple's decoder; a -// session VideoToolbox gives a hardware decoder anyway decodes nothing. -attach -// prints the colour attachments of the first picture, and again whenever they -// change. VTAV1_DUMP_Y= appends the 8-bit luma of every frame to that -// file. +// rate and reports lateness, -loop feeds the file N times in one session (the +// reference starts again each time), -renew makes that a new session for every +// pass, in this same process; with -loop a line per pass says when it ended and +// how it went (for a run across a system sleep). -id picks one decoder when +// several handle av01 (the installed one and a -load'ed build). -sw decodes in +// software only: with -id com.apple.videotoolbox.videodecoder.av1.sw, Apple's +// decoder; a session VideoToolbox gives a hardware decoder anyway decodes +// nothing. -attach prints the colour attachments of the first picture, and +// again whenever they change. VTAV1_DUMP_Y= appends the 8-bit luma of +// every frame to that file. // // There is no switch to arm here: a decode run goes to the GPU as soon as an // AV1 hardware decoder is installed or loaded. @@ -29,10 +32,12 @@ #include #include #include +#include #include #include #include #include +#include #include #include "av1parse.h" @@ -247,7 +252,7 @@ static int usage(void) { fprintf(stderr, "usage: vtav1test [-load bundle] list\n" " vtav1test [-load bundle] file.ivf [file.md5] [-n] [-a] " - "[-pace fps] [-id decoder] [-sw] [-attach]\n" + "[-pace fps] [-loop N] [-renew] [-id decoder] [-sw] [-attach]\n" "A decode run goes to the GPU: there is no switch to arm.\n"); return 1; } @@ -268,7 +273,7 @@ int main(int argc, char** argv) { if (!strcmp(argv[1], "list")) return list(); if (argv[1][0] == '-') return usage(); Ctx c = {0}; - int async = 0, require_hw = 1; + int async = 0, require_hw = 1, loops = 1, renew = 0; double pace = 0; // feed frames at this rate (fps) and report output latency const char *decoderID = NULL, *md5Path = NULL; for (int i = 2; i < argc; i++) { @@ -286,6 +291,14 @@ int main(int argc, char** argv) { double v = strtod(s, &end); if (!end || end == s || *end || !(v >= 0)) return fail("invalid -pace"); pace = v; + } else if (!strcmp(argv[i], "-loop") && i + 1 < argc) { + char* end = NULL; + long v = strtol(argv[++i], &end, 10); + if (!end || *end || v < 1 || v > INT_MAX / 2) + return fail("invalid -loop"); + loops = (int)v; + } else if (!strcmp(argv[i], "-renew")) { + renew = 1; } else if (!strcmp(argv[i], "-id") && i + 1 < argc) { decoderID = argv[++i]; } else if (argv[i][0] == '-' || md5Path) { @@ -393,9 +406,10 @@ int main(int argc, char** argv) { CFDictionarySetValue(spec, CFSTR("DecoderID"), id); CFRelease(id); } + size_t total = cnt * (size_t)loops; if (pace > 0) { - c.fed = calloc(cnt, sizeof(double)); - c.lat = calloc(cnt, sizeof(double)); + c.fed = calloc(total, sizeof(double)); + c.lat = calloc(total, sizeof(double)); if (!c.fed || !c.lat) return fail("out of memory"); } VTDecompressionOutputCallbackRecord cb = {out_cb, &c}; @@ -416,7 +430,37 @@ int main(int argc, char** argv) { return fail("-sw: VideoToolbox gave a hardware decoder; nothing decoded"); double t0 = now_ms(); - for (size_t i = 0; i < cnt; i++) { + int passFrames = 0, passMismatches = 0, passErrors = 0; + for (size_t i = 0; i < total; i++) { + size_t k = i % cnt; // the temporal unit of the file + if (k == 0 && i > 0) { + // The pass before is all out: say how it went, with the wall clock, so + // that a pass across a sleep can be told from the ones before and after. + VTDecompressionSessionWaitForAsynchronousFrames(sess); + time_t now = time(NULL); + char when[32]; + strftime(when, sizeof(when), "%H:%M:%S", localtime(&now)); + printf("pass %zu ended %s: %d frames, %d mismatches, %d errors\n", + i / cnt, when, c.frames - passFrames, + c.mismatches - passMismatches, c.errors - passErrors); + fflush(stdout); + passFrames = c.frames; + passMismatches = c.mismatches; + passErrors = c.errors; + if (c.md5) rewind(c.md5); + if (renew) { + VTDecompressionSessionInvalidate(sess); + CFRelease(sess); + sess = NULL; + st = VTDecompressionSessionCreate(NULL, fmt, spec, NULL, &cb, &sess); + if (st) { + printf("pass %zu: VTDecompressionSessionCreate = %d\n", i / cnt + 1, + (int)st); + c.errors++; + break; + } + } + } if (pace > 0) { double due = t0 + i * 1000.0 / pace; while (now_ms() < due) usleep(200); @@ -425,12 +469,12 @@ int main(int argc, char** argv) { c.fed[i] = due; } CMBlockBufferRef bb = NULL; - CMBlockBufferCreateWithMemoryBlock(NULL, tus[i], sizes[i], kCFAllocatorNull, - NULL, 0, sizes[i], 0, &bb); + CMBlockBufferCreateWithMemoryBlock(NULL, tus[k], sizes[k], kCFAllocatorNull, + NULL, 0, sizes[k], 0, &bb); CMSampleBufferRef sb = NULL; CMSampleTimingInfo ti = {CMTimeMake(1, 30), CMTimeMake((int64_t)i, 30), kCMTimeInvalid}; - size_t ss = sizes[i]; + size_t ss = sizes[k]; if (bb) CMSampleBufferCreateReady(NULL, bb, fmt, 1, 1, &ti, 1, &ss, &sb); if (!sb) { printf("frame %zu: no sample buffer\n", i); @@ -446,15 +490,23 @@ int main(int argc, char** argv) { CFRelease(sb); CFRelease(bb); } - VTDecompressionSessionWaitForAsynchronousFrames(sess); + if (sess) VTDecompressionSessionWaitForAsynchronousFrames(sess); double t = now_ms() - t0; + if (loops > 1) { + time_t now = time(NULL); + char when[32]; + strftime(when, sizeof(when), "%H:%M:%S", localtime(&now)); + printf("last pass ended %s: %d frames, %d mismatches, %d errors\n", when, + c.frames - passFrames, c.mismatches - passMismatches, + c.errors - passErrors); + } printf("%s: %d frames, %d mismatches, %d errors, %.1f ms (%.1f fps%s)\n", argv[1], c.frames, c.mismatches, c.errors, t, c.frames * 1000.0 / t, c.nohash ? (async ? ", async" : "") : ", incl. CPU hashing"); if (pace > 0) { int late33 = 0, late50 = 0; double mx = 0, sum = 0; - for (size_t i = 0; i < cnt; i++) { + for (size_t i = 0; i < total; i++) { double l = c.lat[i]; sum += l; if (l > mx) mx = l; @@ -464,9 +516,11 @@ int main(int argc, char** argv) { printf( "paced %.0f fps: latency avg %.1f ms, max %.1f ms, >2 frames late %d, " ">3 frames late %d (of %zu)\n", - pace, sum / cnt, mx, late33, late50, cnt); + pace, sum / total, mx, late33, late50, total); + } + if (sess) { + VTDecompressionSessionInvalidate(sess); + CFRelease(sess); } - VTDecompressionSessionInvalidate(sess); - CFRelease(sess); - return c.mismatches || c.errors || c.frames != (int)cnt ? 2 : 0; + return c.mismatches || c.errors || c.frames != (int)total ? 2 : 0; } diff --git a/GPU/decode/tests/gpu/vtjpegtest.c b/GPU/decode/tests/gpu/vtjpegtest.c new file mode 100644 index 00000000..0a3f7ac9 --- /dev/null +++ b/GPU/decode/tests/gpu/vtjpegtest.c @@ -0,0 +1,410 @@ +// vtjpegtest: drives our Motion JPEG decoder through the public VideoToolbox +// API and compares every frame with FFmpeg's decode of the same file. +// +// vtjpegtest -load bundle clip.mjpeg reference.yuv width height 420|422 +// [-dmb1] [-frames N] +// vtjpegtest -system clip.mjpeg reference.yuv width height 420|422 +// [-dmb1] [-frames N] +// the decoder VideoToolbox picks for a hardware decoder, as an app gets +// it: the installed JPEGVCNDecoder.bundle when it is in place (fails when +// it is not, or when its kext is not ready) +// vtjpegtest -apple clip.mjpeg reference.yuv width height 420|422 [-dmb1] +// the same with Apple's own software decoder, asked for the same pixel +// format: runs on the CPU only, checks the clip, the reference and this +// program's comparison without the GPU +// +// clip.mjpeg is a raw Motion JPEG stream (JPEG pictures one after the other, as +// `ffmpeg -c:v mjpeg -f mjpeg` writes it). reference.yuv holds the same frames +// as FFmpeg decodes them, planar and full range: yuvj420p for 420, yuvj422p for +// 422 (`ffmpeg -i clip.mjpeg -f rawvideo -pix_fmt yuvj4xxp reference.yuv`). +// +// -load registers the bundle in this process only, under the ID +// com.droga.vtjpegtest (VideoToolbox lists it as com.droga.vtjpegtest.jpeg or +// .dmb1), and the session asks for exactly that decoder: an installed plug-in +// or Apple's software decoders cannot serve it. Nothing is installed. +// -dmb1 uses the OpenDML codec type instead of 'jpeg'. -frames stops early. +// +// Checks, per frame: decoded without error, the pixel format is the one our +// decoder gives for the sampling ('420f' for 4:2:0, '422f' for 4:2:2), and +// every sample is within 2 of FFmpeg's (the block's IDCT rounds differently, +// a difference of 1 was seen on hardware). +// +// There is no switch to arm: a run goes to the GPU as soon as the VCNJpeg +// kext is loaded (it starts the block for the first picture). +// +// Exit status: 0 = every frame decoded and matched, 2 = a frame failed, +// differs or is missing, 1 = anything else. +#include +#include +#include +#include +#include +#include +#include +#include +#include + +static double now_ms(void) { + static mach_timebase_info_data_t tb; + if (!tb.denom) mach_timebase_info(&tb); + return (double)mach_absolute_time() * tb.numer / tb.denom / 1e6; +} + +static void copy_kv(const void* k, const void* v, void* dict) { + CFDictionarySetValue(dict, k, v); +} + +// Registers the bundle's decoder for one codec in this process only, under our +// own ID. Fails when nothing was registered. +static int load_bundle(const char* path, FourCharCode codec, + const char* fourcc) { + CFURLRef url = CFURLCreateFromFileSystemRepresentation( + NULL, (const UInt8*)path, (CFIndex)strlen(path), true); + CFBundleRef b = url ? CFBundleCreate(NULL, url) : NULL; + if (url) CFRelease(url); + if (!b || !CFBundleLoadExecutable(b)) { + fprintf(stderr, "cannot load %s\n", path); + return -1; + } + CFArrayRef impls = + CFBundleGetValueForInfoDictionaryKey(b, CFSTR("CMClassImplementations")); + OSStatus (*reg)(FourCharCode, CFDictionaryRef, void*) = + dlsym(RTLD_DEFAULT, "VTRegisterVideoDecoderWithInfo"); + CFStringRef want = + CFStringCreateWithCString(NULL, fourcc, kCFStringEncodingASCII); + int registered = 0; + for (CFIndex i = 0; impls && reg && want && i < CFArrayGetCount(impls); i++) { + CFDictionaryRef impl = CFArrayGetValueAtIndex(impls, i); + CFDictionaryRef match = CFDictionaryGetValue(impl, CFSTR("CMMatchingInfo")); + CFStringRef type = + match ? CFDictionaryGetValue(match, CFSTR("VTCodecType")) : NULL; + if (!type || !CFEqual(type, want)) continue; + CFStringRef fn = CFDictionaryGetValue(impl, CFSTR("CMFactoryFunction")); + void* factory = fn ? CFBundleGetFunctionPointerForName(b, fn) : NULL; + if (!factory) continue; + CFMutableDictionaryRef info = CFDictionaryCreateMutableCopy(NULL, 0, impl); + // dynamic registration ignores CMMatchingInfo: lift its keys to the top + CFDictionaryApplyFunction(match, copy_kv, info); + CFDictionarySetValue(info, CFSTR("CMClassImplementationID"), + CFSTR("com.droga.vtjpegtest")); + CFDictionarySetValue(info, CFSTR("IsHardwareAccelerated"), kCFBooleanTrue); + CFStringRef name = + CFDictionaryGetValue(impl, CFSTR("CMClassImplementationName")); + if (name) CFDictionarySetValue(info, CFSTR("CodecName"), name); + OSStatus st = reg(codec, info, factory); + CFRelease(info); + printf("registered %s from %s -> %d\n", fourcc, path, (int)st); + if (!st) registered++; + } + if (want) CFRelease(want); + if (!registered) { + fprintf(stderr, "no %s decoder of %s could be registered\n", fourcc, path); + return -1; + } + return 0; +} + +static uint8_t* read_all(const char* path, size_t* n) { + FILE* f = fopen(path, "rb"); + if (!f) return NULL; + fseek(f, 0, SEEK_END); + long len = ftell(f); + fseek(f, 0, SEEK_SET); + uint8_t* d = len > 0 ? malloc((size_t)len) : NULL; + if (d && fread(d, 1, (size_t)len, f) != (size_t)len) { + free(d); + d = NULL; + } + fclose(f); + *n = d ? (size_t)len : 0; + return d; +} + +// The next JPEG picture of a raw Motion JPEG stream: SOI, segments up to the +// scan, the scan (where FF is always stuffed or a restart marker), EOI. +static bool next_picture(const uint8_t* d, size_t n, size_t* at, size_t* start, + size_t* len) { + size_t i = *at; + while (i + 1 < n && !(d[i] == 0xff && d[i + 1] == 0xd8)) i++; + if (i + 1 >= n) return false; + size_t s = i; + i += 2; + while (1) { + if (i + 4 > n || d[i] != 0xff) return false; + uint8_t m = d[i + 1]; + if (m == 0xff) { // fill byte + i++; + continue; + } + size_t l = ((size_t)d[i + 2] << 8) | d[i + 3]; + if (l < 2 || i + 2 + l > n) return false; + i += 2 + l; + if (m == 0xda) break; + } + while (i + 1 < n) { + if (d[i] == 0xff && d[i + 1] != 0x00 && + !(d[i + 1] >= 0xd0 && d[i + 1] <= 0xd7)) { + if (d[i + 1] != 0xd9) return false; + *start = s; + *len = i + 2 - s; + *at = i + 2; + return true; + } + i++; + } + return false; +} + +typedef struct { + const uint8_t* ref; // reference frames, planar + size_t refFrames, frameBytes; + int w, h, chromaRows; + OSType wantFormat; + int frames, errors, wrongFormat, mismatches, missing; + int maxDiff; + double sqErr, samples; + double firstOut; +} Ctx; + +static void out_cb(void* refcon, void* frameRefcon, OSStatus st, + VTDecodeInfoFlags flags, CVImageBufferRef img, CMTime pts, + CMTime dur) { + (void)pts, (void)dur; + Ctx* c = refcon; + long idx = (long)frameRefcon; + if (st || !img) { + c->errors++; + printf("frame %ld: error %d flags %x\n", idx, (int)st, flags); + return; + } + c->frames++; + OSType f = CVPixelBufferGetPixelFormatType(img); + if (f != c->wantFormat) { + c->wrongFormat++; + printf( + "frame %ld: pixel format '%c%c%c%c', not the one our decoder gives\n", + idx, (char)(f >> 24), (char)(f >> 16), (char)(f >> 8), (char)f); + return; + } + if ((size_t)idx >= c->refFrames) { + c->missing++; + printf("frame %ld: no reference frame for it\n", idx); + return; + } + const uint8_t* ry = c->ref + (size_t)idx * c->frameBytes; + int cw = (c->w + 1) / 2; + const uint8_t* ru = ry + (size_t)c->w * c->h; + const uint8_t* rv = ru + (size_t)cw * c->chromaRows; + CVPixelBufferLockBaseAddress(img, kCVPixelBufferLock_ReadOnly); + const uint8_t* y = CVPixelBufferGetBaseAddressOfPlane(img, 0); + const uint8_t* uv = CVPixelBufferGetBaseAddressOfPlane(img, 1); + size_t ys = CVPixelBufferGetBytesPerRowOfPlane(img, 0), + uvs = CVPixelBufferGetBytesPerRowOfPlane(img, 1); + bool sizes = (int)CVPixelBufferGetWidth(img) == c->w && + (int)CVPixelBufferGetHeight(img) == c->h && + (int)CVPixelBufferGetHeightOfPlane(img, 1) == c->chromaRows; + int frameMax = 0; + if (sizes) { + for (int r = 0; r < c->h; r++) + for (int x = 0; x < c->w; x++) { + int dd = abs((int)y[r * ys + x] - (int)ry[(size_t)r * c->w + x]); + if (dd > frameMax) frameMax = dd; + c->sqErr += (double)dd * dd; + c->samples++; + } + for (int r = 0; r < c->chromaRows; r++) + for (int x = 0; x < cw; x++) { + int du = abs((int)uv[r * uvs + 2 * x] - (int)ru[(size_t)r * cw + x]); + int dv = + abs((int)uv[r * uvs + 2 * x + 1] - (int)rv[(size_t)r * cw + x]); + int dd = du > dv ? du : dv; + if (dd > frameMax) frameMax = dd; + c->sqErr += (double)du * du + (double)dv * dv; + c->samples += 2; + } + } + CVPixelBufferUnlockBaseAddress(img, kCVPixelBufferLock_ReadOnly); + if (!sizes) { + c->mismatches++; + printf("frame %ld: %zux%zu, not %dx%d\n", idx, CVPixelBufferGetWidth(img), + CVPixelBufferGetHeight(img), c->w, c->h); + return; + } + if (frameMax > c->maxDiff) c->maxDiff = frameMax; + if (frameMax > 2) { + c->mismatches++; + printf("frame %ld: differs from FFmpeg by up to %d\n", idx, frameMax); + } +} + +static int usage(void) { + fprintf(stderr, + "usage: vtjpegtest -load bundle clip.mjpeg reference.yuv width " + "height 420|422 [-dmb1] [-frames N]\n" + " vtjpegtest -system clip.mjpeg reference.yuv width height " + "420|422 [-dmb1] [-frames N] (the installed plug-in)\n" + " vtjpegtest -apple clip.mjpeg reference.yuv width height " + "420|422 [-dmb1] (CPU only)\n" + "A run goes to the GPU: there is no switch to arm.\n"); + return 1; +} + +int main(int argc, char** argv) { + const char* bundle = NULL; + bool apple = false, system = false; + const char* pos[5]; + int npos = 0, maxFrames = INT_MAX; + bool dmb1 = false; + for (int i = 1; i < argc; i++) { + if (!strcmp(argv[i], "-load") && i + 1 < argc) + bundle = argv[++i]; + else if (!strcmp(argv[i], "-apple")) + apple = true; + else if (!strcmp(argv[i], "-system")) + system = true; + else if (!strcmp(argv[i], "-dmb1")) + dmb1 = true; + else if (!strcmp(argv[i], "-frames") && i + 1 < argc) + maxFrames = atoi(argv[++i]); + else if (npos < 5) + pos[npos++] = argv[i]; + else + return usage(); + } + if ((!!bundle + apple + system) != 1 || npos != 5 || maxFrames < 1) + return usage(); + int w = atoi(pos[2]), h = atoi(pos[3]); + bool s422 = !strcmp(pos[4], "422"); + if (w < 1 || h < 1 || w > 16384 || h > 16384 || + (!s422 && strcmp(pos[4], "420"))) + return usage(); + FourCharCode codec = + dmb1 ? kCMVideoCodecType_JPEG_OpenDML : kCMVideoCodecType_JPEG; + const char* fourcc = dmb1 ? "dmb1" : "jpeg"; + if (bundle && load_bundle(bundle, codec, fourcc)) return 1; + + size_t clipLen = 0, refLen = 0; + uint8_t* clip = read_all(pos[0], &clipLen); + uint8_t* ref = read_all(pos[1], &refLen); + if (!clip || !ref) + return fprintf(stderr, "cannot read %s or %s\n", pos[0], pos[1]), 1; + Ctx c = {0}; + c.ref = ref; + c.w = w; + c.h = h; + c.chromaRows = s422 ? h : (h + 1) / 2; + c.frameBytes = (size_t)w * h + 2 * (size_t)((w + 1) / 2) * c.chromaRows; + c.refFrames = refLen / c.frameBytes; + c.wantFormat = s422 ? kCVPixelFormatType_422YpCbCr8BiPlanarFullRange + : kCVPixelFormatType_420YpCbCr8BiPlanarFullRange; + + CMVideoFormatDescriptionRef fmt = NULL; + OSStatus st = CMVideoFormatDescriptionCreate(NULL, codec, w, h, NULL, &fmt); + if (st) return fprintf(stderr, "format description %d\n", (int)st), 1; + CFMutableDictionaryRef spec = + CFDictionaryCreateMutable(NULL, 0, &kCFTypeDictionaryKeyCallBacks, + &kCFTypeDictionaryValueCallBacks); + CFMutableDictionaryRef dest = NULL; + if (system) { + // Apple's JPEG decoders are software ones: a hardware decoder for 'jpeg' + // or 'dmb1' on this Mac can only be ours. + CFDictionarySetValue( + spec, + kVTVideoDecoderSpecification_RequireHardwareAcceleratedVideoDecoder, + kCFBooleanTrue); + printf( + "asking VideoToolbox for any hardware decoder (the installed one)\n"); + } else if (!apple) { + CFDictionarySetValue( + spec, + kVTVideoDecoderSpecification_RequireHardwareAcceleratedVideoDecoder, + kCFBooleanTrue); + CFStringRef id = CFStringCreateWithFormat( + NULL, NULL, CFSTR("com.droga.vtjpegtest.%s"), fourcc); + CFDictionarySetValue(spec, CFSTR("DecoderID"), id); + printf( + "asking for decoder com.droga.vtjpegtest.%s (ours, loaded in this " + "process)\n", + fourcc); + CFRelease(id); + } else { + // Apple's decoder, converted by VideoToolbox to the format ours gives + dest = CFDictionaryCreateMutable(NULL, 0, &kCFTypeDictionaryKeyCallBacks, + &kCFTypeDictionaryValueCallBacks); + int32_t pf = (int32_t)c.wantFormat; + CFNumberRef n = CFNumberCreate(NULL, kCFNumberSInt32Type, &pf); + CFDictionarySetValue(dest, kCVPixelBufferPixelFormatTypeKey, n); + CFRelease(n); + printf( + "Apple's software decoder (no -load), output asked as the format ours " + "gives\n"); + } + VTDecompressionOutputCallbackRecord cb = {out_cb, &c}; + VTDecompressionSessionRef sess = NULL; + if (dest && + getenv("VTJPEG_NODEST")) { // debugging: Apple's own output format + CFRelease(dest); + dest = NULL; + } + st = VTDecompressionSessionCreate(NULL, fmt, spec, dest, &cb, &sess); + CFRelease(spec); + if (dest) CFRelease(dest); + printf("VTDecompressionSessionCreate = %d\n", (int)st); + if (st || !sess) return 1; + CFBooleanRef hw = NULL; + VTSessionCopyProperty( + sess, kVTDecompressionPropertyKey_UsingHardwareAcceleratedVideoDecoder, + NULL, &hw); + printf("UsingHardwareAcceleratedVideoDecoder = %s\n", + hw == kCFBooleanTrue ? "yes" : "no"); + if (hw) CFRelease(hw); + + size_t at = 0, start = 0, len = 0; + long fed = 0; + double t0 = now_ms(); + while (fed < maxFrames && next_picture(clip, clipLen, &at, &start, &len)) { + CMBlockBufferRef bb = NULL; + CMSampleBufferRef sb = NULL; + st = CMBlockBufferCreateWithMemoryBlock( + NULL, clip + start, len, kCFAllocatorNull, NULL, 0, len, 0, &bb); + CMSampleTimingInfo ti = {CMTimeMake(1, 30), CMTimeMake(fed, 30), + kCMTimeInvalid}; + size_t ss = len; + if (!st) + st = CMSampleBufferCreateReady(NULL, bb, fmt, 1, 1, &ti, 1, &ss, &sb); + if (!st) { + VTDecodeInfoFlags info = 0; + st = VTDecompressionSessionDecodeFrame(sess, sb, 0, (void*)fed, &info); + if (st) printf("DecodeFrame %ld -> %d\n", fed, (int)st); + } + if (sb) CFRelease(sb); + if (bb) CFRelease(bb); + if (st) c.errors++; + fed++; + } + VTDecompressionSessionWaitForAsynchronousFrames(sess); + double ms = now_ms() - t0; + VTDecompressionSessionInvalidate(sess); + CFRelease(sess); + CFRelease(fmt); + double psnr = + c.sqErr > 0 ? 10 * log10(255.0 * 255.0 * c.samples / c.sqErr) : INFINITY; + printf( + "fed %ld pictures (%s %s %dx%d), got %d frames in %.1f ms (%.2f ms " + "each)\n", + fed, fourcc, s422 ? "4:2:2" : "4:2:0", w, h, c.frames, ms, + fed ? ms / (double)fed : 0.0); + printf( + "errors %d, wrong pixel format %d, differ %d, no reference %d; max " + "difference %d, PSNR %.2f dB\n", + c.errors, c.wrongFormat, c.mismatches, c.missing, c.maxDiff, psnr); + bool ok = fed > 0 && c.frames == fed && !c.errors && !c.wrongFormat && + !c.mismatches && !c.missing; + printf("%s\n", + ok ? (apple ? "PASS: every frame from Apple's decoder, matching FFmpeg" + : "PASS: every frame from our decoder, matching FFmpeg") + : "FAIL"); + free(clip); + free(ref); + return ok ? 0 : 2; +} diff --git a/GPU/decode/tests/gpu/vtvp9test.c b/GPU/decode/tests/gpu/vtvp9test.c index 1f17af0f..62bc90df 100644 --- a/GPU/decode/tests/gpu/vtvp9test.c +++ b/GPU/decode/tests/gpu/vtvp9test.c @@ -4,7 +4,7 @@ // vtvp9test [-load bundle] list // shows the vp09 decoders VideoToolbox knows about // vtvp9test [-load bundle] file [reference] [-n] [-a] [-pace fps] [-loop N] -// [-frames N] [-id decoder] [-sw] [-attach] +// [-renew] [-frames N] [-id decoder] [-sw] [-attach] // [-color primaries,transfer,matrix] [-hdr] // decodes the file (IVF or WebM) and compares the MD5 of every frame as // I420 with a reference in the format of FFmpeg's FATE suite @@ -12,7 +12,10 @@ // -load registers the bundle in this process only, nothing is installed on the // system. -n reads no pixels, -a decodes asynchronously, -pace feeds at a fixed // rate and reports lateness, -loop feeds the file N times in one session (a -// seek back to a keyframe), -frames stops after N container frames, -id picks +// seek back to a keyframe), -renew makes that a new session for every pass, in +// this same process (a browser that opens one video after another), and with +// -loop a line per pass says when it ended and how it went (for a run across a +// system sleep), -frames stops after N container frames, -id picks // one decoder when several handle vp09, -sw doesn't ask for hardware. // -attach prints the colour attachments of the first picture, and again // whenever they change. The format description carries no colour unless @@ -36,6 +39,7 @@ #include #include #include +#include #include #include "container.h" @@ -231,7 +235,8 @@ static int usage(void) { fprintf(stderr, "usage: vtvp9test [-load bundle] list\n" " vtvp9test [-load bundle] file [reference] [-n] [-a] " - "[-pace fps] [-loop N] [-frames N] [-id decoder] [-sw] [-attach]\n" + "[-pace fps] [-loop N] [-renew] [-frames N] [-id decoder] [-sw] " + "[-attach]\n" " [-color primaries,transfer,matrix] [-hdr]\n" "A decode run goes to the GPU: there is no switch to arm.\n"); return 1; @@ -265,7 +270,7 @@ int main(int argc, char** argv) { if (!strcmp(argv[1], "list")) return list(); if (argv[1][0] == '-') return usage(); Ctx c = {0}; - int async = 0, loops = 1, limit = 0, require_hw = 1; + int async = 0, loops = 1, limit = 0, require_hw = 1, renew = 0; // -color: the colour a container would give (vpcC and the format // description's extensions), as Safari passes a WebM Colour element. 2 = // unspecified, what a stream with no container colour gets. @@ -296,6 +301,8 @@ int main(int argc, char** argv) { pace = v; } else if (!strcmp(argv[i], "-loop") && i + 1 < argc) { if ((loops = parse_count(argv[++i], 1)) < 0) return fail("invalid -loop"); + } else if (!strcmp(argv[i], "-renew")) { + renew = 1; } else if (!strcmp(argv[i], "-frames") && i + 1 < argc) { if ((limit = parse_count(argv[++i], 0)) < 0) return fail("invalid -frames"); @@ -442,7 +449,34 @@ int main(int argc, char** argv) { double t0 = now_ms(); size_t fed = 0; + int passFrames = 0, passMismatches = 0, passErrors = 0; for (int l = 0; l < loops; l++) { + if (l > 0 && loops > 1) { + // The pass before is all out: say how it went, with the wall clock, so + // that a pass across a sleep can be told from the ones before and after. + VTDecompressionSessionWaitForAsynchronousFrames(sess); + time_t now = time(NULL); + char when[32]; + strftime(when, sizeof(when), "%H:%M:%S", localtime(&now)); + printf("pass %d ended %s: %d frames, %d mismatches, %d errors\n", l, when, + c.frames - passFrames, c.mismatches - passMismatches, + c.errors - passErrors); + fflush(stdout); + passFrames = c.frames; + passMismatches = c.mismatches; + passErrors = c.errors; + } + if (l > 0 && renew) { + VTDecompressionSessionInvalidate(sess); + CFRelease(sess); + sess = NULL; + st = VTDecompressionSessionCreate(NULL, fmt, spec, NULL, &cb, &sess); + if (st) { + printf("pass %d: VTDecompressionSessionCreate = %d\n", l + 1, (int)st); + c.errors++; + break; + } + } if (c.ref) { // Every pass over the file starts the reference again, once the frames // of the pass before are all out. @@ -482,8 +516,16 @@ int main(int argc, char** argv) { CFRelease(bb); } } - VTDecompressionSessionWaitForAsynchronousFrames(sess); + if (sess) VTDecompressionSessionWaitForAsynchronousFrames(sess); double t = now_ms() - t0; + if (loops > 1) { + time_t now = time(NULL); + char when[32]; + strftime(when, sizeof(when), "%H:%M:%S", localtime(&now)); + printf("last pass ended %s: %d frames, %d mismatches, %d errors\n", when, + c.frames - passFrames, c.mismatches - passMismatches, + c.errors - passErrors); + } // A decoder that shows fewer frames than the reference lists must not pass. // With -frames the file was cut short on purpose. int missing = 0; @@ -513,8 +555,10 @@ int main(int argc, char** argv) { "50 ms %d (of %zu)\n", pace, sum / (double)total, mx, late33, late50, total); } - VTDecompressionSessionInvalidate(sess); - CFRelease(sess); + if (sess) { + VTDecompressionSessionInvalidate(sess); + CFRelease(sess); + } return c.mismatches || missing || c.errors || c.frames + c.dropped != (int)total ? 2 diff --git a/GPU/decode/tests/jpegsamples.h b/GPU/decode/tests/jpegsamples.h new file mode 100644 index 00000000..3b1d79b6 --- /dev/null +++ b/GPU/decode/tests/jpegsamples.h @@ -0,0 +1,310 @@ +// jpegsamples.h - small JPEGs for tests/jpegtest.c, made with FFmpeg's testsrc and +// -pix_fmt yuvj420p (or yuvj422p) -huffman default -q:v 4. Generated; do not edit. +#pragma once +#include + +static const uint8_t kJpeg16x16[777] = { + 0xff, 0xd8, 0xff, 0xe0, 0x00, 0x10, 0x4a, 0x46, 0x49, 0x46, 0x00, 0x01, 0x02, 0x00, 0x00, 0x01, + 0x00, 0x01, 0x00, 0x00, 0xff, 0xfe, 0x00, 0x10, 0x4c, 0x61, 0x76, 0x63, 0x36, 0x33, 0x2e, 0x32, + 0x34, 0x2e, 0x31, 0x30, 0x30, 0x00, 0xff, 0xdb, 0x00, 0x43, 0x00, 0x08, 0x08, 0x08, 0x09, 0x08, + 0x09, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0d, 0x0c, 0x0d, 0x0d, 0x0d, 0x0d, 0x0d, 0x0d, 0x0d, + 0x0d, 0x0d, 0x0d, 0x0d, 0x0e, 0x0e, 0x0e, 0x11, 0x11, 0x11, 0x0e, 0x0e, 0x0e, 0x0d, 0x0d, 0x0e, + 0x0e, 0x10, 0x10, 0x11, 0x11, 0x12, 0x13, 0x12, 0x11, 0x11, 0x11, 0x11, 0x13, 0x13, 0x14, 0x14, + 0x14, 0x18, 0x18, 0x17, 0x17, 0x1c, 0x1c, 0x1d, 0x22, 0x22, 0x29, 0xff, 0xc4, 0x01, 0xa2, 0x00, + 0x00, 0x01, 0x05, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x01, 0x00, 0x03, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x02, + 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x10, 0x00, 0x02, 0x01, 0x03, 0x03, 0x02, + 0x04, 0x03, 0x05, 0x05, 0x04, 0x04, 0x00, 0x00, 0x01, 0x7d, 0x01, 0x02, 0x03, 0x00, 0x04, 0x11, + 0x05, 0x12, 0x21, 0x31, 0x41, 0x06, 0x13, 0x51, 0x61, 0x07, 0x22, 0x71, 0x14, 0x32, 0x81, 0x91, + 0xa1, 0x08, 0x23, 0x42, 0xb1, 0xc1, 0x15, 0x52, 0xd1, 0xf0, 0x24, 0x33, 0x62, 0x72, 0x82, 0x09, + 0x0a, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x34, 0x35, 0x36, 0x37, + 0x38, 0x39, 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, + 0x58, 0x59, 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, + 0x78, 0x79, 0x7a, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96, + 0x97, 0x98, 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4, + 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2, + 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, + 0xe9, 0xea, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0x11, 0x00, 0x02, 0x01, + 0x02, 0x04, 0x04, 0x03, 0x04, 0x07, 0x05, 0x04, 0x04, 0x00, 0x01, 0x02, 0x77, 0x00, 0x01, 0x02, + 0x03, 0x11, 0x04, 0x05, 0x21, 0x31, 0x06, 0x12, 0x41, 0x51, 0x07, 0x61, 0x71, 0x13, 0x22, 0x32, + 0x81, 0x08, 0x14, 0x42, 0x91, 0xa1, 0xb1, 0xc1, 0x09, 0x23, 0x33, 0x52, 0xf0, 0x15, 0x62, 0x72, + 0xd1, 0x0a, 0x16, 0x24, 0x34, 0xe1, 0x25, 0xf1, 0x17, 0x18, 0x19, 0x1a, 0x26, 0x27, 0x28, 0x29, + 0x2a, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x53, + 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x73, + 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, + 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, + 0xa9, 0xaa, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, + 0xc7, 0xc8, 0xc9, 0xca, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xe2, 0xe3, 0xe4, + 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xff, + 0xc0, 0x00, 0x11, 0x08, 0x00, 0x10, 0x00, 0x10, 0x03, 0x01, 0x22, 0x00, 0x02, 0x11, 0x00, 0x03, + 0x11, 0x00, 0xff, 0xda, 0x00, 0x0c, 0x03, 0x01, 0x00, 0x02, 0x11, 0x03, 0x11, 0x00, 0x3f, 0x00, + 0xe6, 0x4d, 0xa5, 0xcf, 0x87, 0xbc, 0x35, 0x65, 0x24, 0x53, 0xbc, 0x57, 0x17, 0x30, 0xc7, 0x72, + 0x65, 0x82, 0x57, 0x42, 0x12, 0x73, 0x1c, 0x91, 0x2a, 0xb0, 0x08, 0xca, 0x44, 0x53, 0x61, 0xc0, + 0xfe, 0x22, 0xc3, 0x24, 0x62, 0xbb, 0x6d, 0x73, 0x58, 0x4f, 0x06, 0xea, 0x90, 0xdc, 0x5a, 0xc1, + 0x14, 0x56, 0xc9, 0x2c, 0x7e, 0x7c, 0x10, 0xc3, 0x18, 0x0d, 0x0b, 0x79, 0x4b, 0x27, 0x96, 0xaa, + 0x62, 0x02, 0x40, 0xb2, 0x3b, 0x47, 0xf3, 0x2a, 0xf9, 0x98, 0xdd, 0x91, 0x9a, 0xca, 0xbb, 0x8a, + 0xc3, 0x58, 0xf0, 0xf6, 0x9e, 0xbf, 0xda, 0x36, 0xd0, 0x88, 0x2d, 0xad, 0xad, 0x5d, 0xb7, 0xc6, + 0xe0, 0x79, 0x31, 0xc5, 0x18, 0x76, 0xfd, 0xea, 0x6d, 0xde, 0x61, 0x3f, 0x29, 0x3c, 0x13, 0x8c, + 0x9c, 0x54, 0x3e, 0x2d, 0xb5, 0xd4, 0x3c, 0x47, 0x7d, 0x71, 0x6a, 0x96, 0x37, 0x51, 0x6c, 0xc6, + 0x19, 0x62, 0x92, 0x6d, 0xfc, 0x21, 0xe1, 0x42, 0x27, 0x68, 0xf3, 0xd4, 0xf0, 0x6a, 0x71, 0x16, + 0xcc, 0xe3, 0x95, 0x4b, 0x2b, 0xb2, 0xfa, 0xb3, 0xc7, 0xff, 0x00, 0x68, 0x5b, 0xfd, 0x95, 0xcd, + 0xff, 0x00, 0xb3, 0xdb, 0x99, 0x55, 0xf6, 0x6f, 0x11, 0xca, 0x95, 0x4f, 0x83, 0x9f, 0x95, 0x3e, + 0x97, 0x15, 0x26, 0xaa, 0x66, 0x18, 0x4c, 0x0e, 0x2e, 0xcf, 0x13, 0x0f, 0xae, 0x2a, 0xb1, 0xab, + 0x6e, 0x46, 0xf9, 0x73, 0x05, 0x82, 0xbd, 0x59, 0x7e, 0xe6, 0x6e, 0x31, 0x78, 0x2f, 0x63, 0x69, + 0x37, 0x1e, 0x4a, 0x6d, 0x5b, 0x93, 0x4f, 0xff, 0xd9, +}; +static const uint8_t kJpeg48x32[1410] = { + 0xff, 0xd8, 0xff, 0xe0, 0x00, 0x10, 0x4a, 0x46, 0x49, 0x46, 0x00, 0x01, 0x02, 0x00, 0x00, 0x01, + 0x00, 0x01, 0x00, 0x00, 0xff, 0xfe, 0x00, 0x10, 0x4c, 0x61, 0x76, 0x63, 0x36, 0x33, 0x2e, 0x32, + 0x34, 0x2e, 0x31, 0x30, 0x30, 0x00, 0xff, 0xdb, 0x00, 0x43, 0x00, 0x08, 0x08, 0x08, 0x09, 0x08, + 0x09, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0d, 0x0c, 0x0d, 0x0d, 0x0d, 0x0d, 0x0d, 0x0d, 0x0d, + 0x0d, 0x0d, 0x0d, 0x0d, 0x0e, 0x0e, 0x0e, 0x11, 0x11, 0x11, 0x0e, 0x0e, 0x0e, 0x0d, 0x0d, 0x0e, + 0x0e, 0x10, 0x10, 0x11, 0x11, 0x12, 0x13, 0x12, 0x11, 0x11, 0x11, 0x11, 0x13, 0x13, 0x14, 0x14, + 0x14, 0x18, 0x18, 0x17, 0x17, 0x1c, 0x1c, 0x1d, 0x22, 0x22, 0x29, 0xff, 0xc4, 0x01, 0xa2, 0x00, + 0x00, 0x01, 0x05, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x01, 0x00, 0x03, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x02, + 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x10, 0x00, 0x02, 0x01, 0x03, 0x03, 0x02, + 0x04, 0x03, 0x05, 0x05, 0x04, 0x04, 0x00, 0x00, 0x01, 0x7d, 0x01, 0x02, 0x03, 0x00, 0x04, 0x11, + 0x05, 0x12, 0x21, 0x31, 0x41, 0x06, 0x13, 0x51, 0x61, 0x07, 0x22, 0x71, 0x14, 0x32, 0x81, 0x91, + 0xa1, 0x08, 0x23, 0x42, 0xb1, 0xc1, 0x15, 0x52, 0xd1, 0xf0, 0x24, 0x33, 0x62, 0x72, 0x82, 0x09, + 0x0a, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x34, 0x35, 0x36, 0x37, + 0x38, 0x39, 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, + 0x58, 0x59, 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, + 0x78, 0x79, 0x7a, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96, + 0x97, 0x98, 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4, + 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2, + 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, + 0xe9, 0xea, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0x11, 0x00, 0x02, 0x01, + 0x02, 0x04, 0x04, 0x03, 0x04, 0x07, 0x05, 0x04, 0x04, 0x00, 0x01, 0x02, 0x77, 0x00, 0x01, 0x02, + 0x03, 0x11, 0x04, 0x05, 0x21, 0x31, 0x06, 0x12, 0x41, 0x51, 0x07, 0x61, 0x71, 0x13, 0x22, 0x32, + 0x81, 0x08, 0x14, 0x42, 0x91, 0xa1, 0xb1, 0xc1, 0x09, 0x23, 0x33, 0x52, 0xf0, 0x15, 0x62, 0x72, + 0xd1, 0x0a, 0x16, 0x24, 0x34, 0xe1, 0x25, 0xf1, 0x17, 0x18, 0x19, 0x1a, 0x26, 0x27, 0x28, 0x29, + 0x2a, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x53, + 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x73, + 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, + 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, + 0xa9, 0xaa, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, + 0xc7, 0xc8, 0xc9, 0xca, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xe2, 0xe3, 0xe4, + 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xff, + 0xc0, 0x00, 0x11, 0x08, 0x00, 0x20, 0x00, 0x30, 0x03, 0x01, 0x22, 0x00, 0x02, 0x11, 0x00, 0x03, + 0x11, 0x00, 0xff, 0xda, 0x00, 0x0c, 0x03, 0x01, 0x00, 0x02, 0x11, 0x03, 0x11, 0x00, 0x3f, 0x00, + 0xf1, 0x5d, 0x0a, 0x37, 0x9b, 0x53, 0xb6, 0x8d, 0x06, 0x59, 0xd9, 0x95, 0x47, 0x03, 0x2c, 0xc8, + 0xc0, 0x0c, 0x9c, 0x0e, 0xbe, 0xb5, 0xec, 0xf7, 0xba, 0x7c, 0x7a, 0x6d, 0xb5, 0xac, 0x6a, 0x06, + 0xf6, 0xde, 0xd3, 0x36, 0x73, 0xbd, 0xc0, 0x4e, 0xf8, 0x1f, 0x2a, 0xe4, 0x84, 0x18, 0x18, 0x07, + 0xd4, 0x9a, 0xe1, 0xfe, 0x19, 0xda, 0xc3, 0x71, 0xac, 0xdc, 0xc9, 0x22, 0xee, 0x6b, 0x6b, 0x09, + 0x26, 0x84, 0xe5, 0x86, 0xc9, 0x0d, 0xc5, 0xbc, 0x25, 0xb0, 0x08, 0x0d, 0xfb, 0xb9, 0x64, 0x5c, + 0x36, 0x47, 0xcd, 0x9c, 0x64, 0x0a, 0xf4, 0x9f, 0x10, 0xff, 0x00, 0xcb, 0xbf, 0xfd, 0xb5, 0xff, + 0x00, 0xd9, 0x2b, 0xdc, 0xc8, 0x70, 0xb4, 0xe5, 0x8b, 0x58, 0x89, 0x25, 0x29, 0xab, 0xc2, 0x37, + 0x57, 0xe5, 0xb4, 0x5c, 0xae, 0xbc, 0xdd, 0xf7, 0xf2, 0x2b, 0x2a, 0xce, 0xf1, 0x4b, 0x89, 0xf2, + 0x6c, 0x9e, 0x2f, 0x97, 0x0c, 0xe5, 0x8b, 0xc6, 0xd5, 0x49, 0xbf, 0xde, 0xcd, 0xe0, 0xeb, 0x42, + 0x11, 0x9a, 0xd9, 0xc6, 0x9b, 0xa5, 0xcf, 0x15, 0xfc, 0xce, 0xfb, 0xa4, 0x79, 0x0e, 0xb1, 0xff, + 0x00, 0x1f, 0xf3, 0x7f, 0xc0, 0x3f, 0xf4, 0x5a, 0xd7, 0xd3, 0xfa, 0xc7, 0xfc, 0x78, 0x4d, 0xff, + 0x00, 0x00, 0xff, 0x00, 0xd1, 0x8b, 0x5f, 0x30, 0x6b, 0x1f, 0xf1, 0xff, 0x00, 0x37, 0xfc, 0x03, + 0xff, 0x00, 0x45, 0xad, 0x7d, 0x3f, 0xac, 0x7f, 0xc7, 0x84, 0xdf, 0xf0, 0x0f, 0xfd, 0x18, 0xb5, + 0xe1, 0xf8, 0xcb, 0xff, 0x00, 0x34, 0xc7, 0xfd, 0xcd, 0xff, 0x00, 0xee, 0x99, 0x39, 0xcf, 0xfc, + 0xd4, 0x1f, 0xf7, 0x3b, 0xff, 0x00, 0xb9, 0x8f, 0x2c, 0xd5, 0x6f, 0xae, 0x2c, 0x24, 0xb6, 0x92, + 0x17, 0x2b, 0xcc, 0x85, 0x97, 0x9d, 0x8f, 0x8d, 0xbc, 0x3a, 0xe7, 0x04, 0x72, 0x7d, 0xc6, 0x72, + 0x08, 0x35, 0xed, 0x1e, 0x1c, 0xb9, 0x8e, 0xf3, 0x48, 0xb5, 0x9e, 0x2c, 0xec, 0x71, 0x21, 0x19, + 0x18, 0x23, 0x12, 0xb8, 0x20, 0x8f, 0x50, 0x41, 0x1c, 0x71, 0xe8, 0x6b, 0xc3, 0x3c, 0x43, 0xff, + 0x00, 0x2e, 0xff, 0x00, 0xf6, 0xd7, 0xff, 0x00, 0x64, 0xae, 0xa7, 0xe1, 0x35, 0xd4, 0xcf, 0x36, + 0xbf, 0x6a, 0x5b, 0x30, 0xc5, 0x2d, 0x8c, 0xc8, 0x98, 0x5f, 0x96, 0x49, 0xe1, 0x75, 0x91, 0xb7, + 0x63, 0x71, 0xdc, 0xb0, 0xc6, 0x30, 0x49, 0x03, 0x6f, 0x00, 0x64, 0xd7, 0xcf, 0xe4, 0x15, 0xea, + 0x7d, 0x59, 0x51, 0xe6, 0xbc, 0x35, 0x9a, 0x4f, 0xa4, 0x94, 0xda, 0xd3, 0xb5, 0xf9, 0xb5, 0xf9, + 0x17, 0x95, 0x65, 0x38, 0x35, 0xc2, 0x19, 0x2e, 0x66, 0xa9, 0xa8, 0xe2, 0xaf, 0x8b, 0xc2, 0xca, + 0xa4, 0x52, 0x4e, 0xa5, 0x29, 0xe2, 0xeb, 0xce, 0xd5, 0x34, 0xbc, 0x9c, 0x1d, 0x25, 0xc8, 0xdb, + 0xf7, 0x53, 0x92, 0xea, 0x79, 0x77, 0xc3, 0x09, 0x63, 0x8f, 0x57, 0xbd, 0x57, 0x74, 0x46, 0x97, + 0x4e, 0x74, 0x8c, 0x33, 0x00, 0x64, 0x71, 0x77, 0x6a, 0xe5, 0x10, 0x13, 0x96, 0x6d, 0x88, 0xcf, + 0x81, 0x93, 0xb5, 0x49, 0xe8, 0x2b, 0xd1, 0x7c, 0x43, 0xff, 0x00, 0x2e, 0xff, 0x00, 0xf6, 0xd7, + 0xff, 0x00, 0x64, 0xae, 0x47, 0xc3, 0x7e, 0x33, 0xd3, 0x6d, 0xe6, 0x8e, 0x26, 0x8a, 0xec, 0xb1, + 0xcf, 0x21, 0x22, 0xc7, 0xca, 0x09, 0xef, 0x30, 0x3d, 0xbd, 0x2b, 0xd1, 0x2f, 0xbc, 0x43, 0x63, + 0x73, 0x0c, 0x73, 0x47, 0xe6, 0x32, 0xcb, 0xbb, 0x03, 0x0b, 0xb9, 0x19, 0x71, 0x95, 0x71, 0xbf, + 0x82, 0x37, 0x0f, 0x5f, 0x51, 0xc6, 0x2b, 0xd8, 0xcb, 0xb3, 0xfc, 0xd3, 0x0d, 0x8b, 0x54, 0x28, + 0x64, 0xb5, 0xb1, 0x52, 0xf7, 0xa7, 0xee, 0xd6, 0x51, 0x6d, 0x35, 0xcb, 0x7b, 0x38, 0x31, 0xd5, + 0xc9, 0xea, 0x65, 0xdc, 0x41, 0x80, 0xce, 0x70, 0x32, 0x96, 0x69, 0xec, 0x7d, 0xb6, 0x16, 0x95, + 0x1a, 0x54, 0xdc, 0x15, 0x6a, 0x9f, 0x57, 0xaf, 0x27, 0x15, 0x56, 0xf2, 0x51, 0x6a, 0x9c, 0xdc, + 0xec, 0xe3, 0xaa, 0x8e, 0xe7, 0x85, 0xeb, 0x1f, 0xf1, 0xff, 0x00, 0x37, 0xfc, 0x03, 0xff, 0x00, + 0x45, 0xad, 0x7d, 0x3f, 0xac, 0x7f, 0xc7, 0x84, 0xdf, 0xf0, 0x0f, 0xfd, 0x18, 0xb5, 0xe5, 0x12, + 0x78, 0xc3, 0x4f, 0xb1, 0x99, 0xa2, 0x92, 0x2b, 0xa2, 0xcb, 0x8c, 0x95, 0x48, 0x88, 0xe4, 0x03, + 0xc6, 0x66, 0x07, 0xbf, 0xa5, 0x6e, 0x78, 0x93, 0xc3, 0x17, 0xd7, 0x10, 0xc9, 0x2a, 0xc9, 0x6e, + 0x14, 0x63, 0x82, 0xd2, 0x67, 0xe6, 0x20, 0x76, 0x88, 0x8e, 0xfe, 0xb5, 0xe8, 0x71, 0x8d, 0x2a, + 0x5c, 0x43, 0x1c, 0x91, 0xe7, 0x15, 0x57, 0x0e, 0xba, 0x1e, 0xdf, 0xd9, 0x2a, 0xeb, 0xeb, 0x1f, + 0x58, 0xe6, 0xfa, 0xbf, 0x37, 0x2f, 0x2b, 0xa7, 0xcb, 0xc9, 0xcb, 0x1b, 0xde, 0xff, 0x00, 0x19, + 0xf3, 0x98, 0xbc, 0xcf, 0x32, 0xc4, 0xd5, 0xcd, 0x63, 0x5f, 0x2a, 0xab, 0x85, 0x8d, 0x6f, 0xac, + 0xfb, 0x69, 0xca, 0xa2, 0x92, 0xc3, 0x73, 0x7b, 0x4e, 0x6e, 0x65, 0xc8, 0xb9, 0xb9, 0x2e, 0xef, + 0xb6, 0xc7, 0x39, 0xe2, 0x1f, 0xf9, 0x77, 0xff, 0x00, 0xb6, 0xbf, 0xfb, 0x25, 0x74, 0xbf, 0x09, + 0x62, 0x94, 0x5d, 0xf8, 0x86, 0x52, 0x8e, 0x23, 0x76, 0xd3, 0x91, 0x64, 0x2a, 0x76, 0x33, 0xc7, + 0x14, 0xc5, 0xd1, 0x5b, 0x18, 0x2c, 0xa1, 0xd0, 0xb0, 0x07, 0x20, 0x32, 0xe7, 0xa8, 0xaf, 0x3f, + 0x83, 0x44, 0xbc, 0xb0, 0x92, 0x08, 0x9b, 0x64, 0xaf, 0x29, 0x21, 0x16, 0x22, 0xc7, 0xee, 0xe3, + 0x39, 0xde, 0xa8, 0x00, 0xe7, 0x39, 0xe8, 0x06, 0x49, 0xae, 0xf2, 0x3f, 0x01, 0xea, 0xb7, 0xd0, + 0xac, 0xb1, 0xcd, 0x64, 0x15, 0xb3, 0x80, 0xcf, 0x30, 0x3c, 0x12, 0x39, 0xc4, 0x04, 0x76, 0xf5, + 0xae, 0x5a, 0x19, 0x36, 0x5f, 0x80, 0xc3, 0xba, 0xb8, 0x3c, 0xd6, 0x9e, 0x62, 0xa3, 0x78, 0x7b, + 0x94, 0x9c, 0x13, 0x6d, 0xf3, 0x5a, 0xee, 0x72, 0xd7, 0x43, 0xef, 0x32, 0x37, 0x96, 0x54, 0xe1, + 0x7c, 0xb3, 0x2b, 0xa9, 0x98, 0xd0, 0xa5, 0xca, 0xeb, 0xe2, 0x69, 0x54, 0x6a, 0xee, 0xb5, 0x35, + 0x88, 0xac, 0xa7, 0x25, 0x4d, 0x3b, 0xc6, 0x31, 0xa9, 0x51, 0xd3, 0xe6, 0x6f, 0x57, 0x17, 0x63, + 0xff, 0xd9, +}; +static const uint8_t kJpeg50x30[1532] = { + 0xff, 0xd8, 0xff, 0xe0, 0x00, 0x10, 0x4a, 0x46, 0x49, 0x46, 0x00, 0x01, 0x02, 0x00, 0x00, 0x01, + 0x00, 0x01, 0x00, 0x00, 0xff, 0xfe, 0x00, 0x10, 0x4c, 0x61, 0x76, 0x63, 0x36, 0x33, 0x2e, 0x32, + 0x34, 0x2e, 0x31, 0x30, 0x30, 0x00, 0xff, 0xdb, 0x00, 0x43, 0x00, 0x08, 0x08, 0x08, 0x09, 0x08, + 0x09, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0d, 0x0c, 0x0d, 0x0d, 0x0d, 0x0d, 0x0d, 0x0d, 0x0d, + 0x0d, 0x0d, 0x0d, 0x0d, 0x0e, 0x0e, 0x0e, 0x11, 0x11, 0x11, 0x0e, 0x0e, 0x0e, 0x0d, 0x0d, 0x0e, + 0x0e, 0x10, 0x10, 0x11, 0x11, 0x12, 0x13, 0x12, 0x11, 0x11, 0x11, 0x11, 0x13, 0x13, 0x14, 0x14, + 0x14, 0x18, 0x18, 0x17, 0x17, 0x1c, 0x1c, 0x1d, 0x22, 0x22, 0x29, 0xff, 0xc4, 0x01, 0xa2, 0x00, + 0x00, 0x01, 0x05, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x01, 0x00, 0x03, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x02, + 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x10, 0x00, 0x02, 0x01, 0x03, 0x03, 0x02, + 0x04, 0x03, 0x05, 0x05, 0x04, 0x04, 0x00, 0x00, 0x01, 0x7d, 0x01, 0x02, 0x03, 0x00, 0x04, 0x11, + 0x05, 0x12, 0x21, 0x31, 0x41, 0x06, 0x13, 0x51, 0x61, 0x07, 0x22, 0x71, 0x14, 0x32, 0x81, 0x91, + 0xa1, 0x08, 0x23, 0x42, 0xb1, 0xc1, 0x15, 0x52, 0xd1, 0xf0, 0x24, 0x33, 0x62, 0x72, 0x82, 0x09, + 0x0a, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x34, 0x35, 0x36, 0x37, + 0x38, 0x39, 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, + 0x58, 0x59, 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, + 0x78, 0x79, 0x7a, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96, + 0x97, 0x98, 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4, + 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2, + 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, + 0xe9, 0xea, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0x11, 0x00, 0x02, 0x01, + 0x02, 0x04, 0x04, 0x03, 0x04, 0x07, 0x05, 0x04, 0x04, 0x00, 0x01, 0x02, 0x77, 0x00, 0x01, 0x02, + 0x03, 0x11, 0x04, 0x05, 0x21, 0x31, 0x06, 0x12, 0x41, 0x51, 0x07, 0x61, 0x71, 0x13, 0x22, 0x32, + 0x81, 0x08, 0x14, 0x42, 0x91, 0xa1, 0xb1, 0xc1, 0x09, 0x23, 0x33, 0x52, 0xf0, 0x15, 0x62, 0x72, + 0xd1, 0x0a, 0x16, 0x24, 0x34, 0xe1, 0x25, 0xf1, 0x17, 0x18, 0x19, 0x1a, 0x26, 0x27, 0x28, 0x29, + 0x2a, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x53, + 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x73, + 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, + 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, + 0xa9, 0xaa, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, + 0xc7, 0xc8, 0xc9, 0xca, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xe2, 0xe3, 0xe4, + 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xff, + 0xc0, 0x00, 0x11, 0x08, 0x00, 0x1e, 0x00, 0x32, 0x03, 0x01, 0x22, 0x00, 0x02, 0x11, 0x00, 0x03, + 0x11, 0x00, 0xff, 0xda, 0x00, 0x0c, 0x03, 0x01, 0x00, 0x02, 0x11, 0x03, 0x11, 0x00, 0x3f, 0x00, + 0xf0, 0xab, 0x05, 0x67, 0xbd, 0xb6, 0x55, 0x05, 0x99, 0xa7, 0x88, 0x00, 0x06, 0x49, 0x25, 0xc6, + 0x00, 0x03, 0x92, 0x4d, 0x7b, 0xcd, 0xce, 0x9c, 0xba, 0x6e, 0x97, 0x14, 0x7f, 0x29, 0x91, 0xa6, + 0x53, 0x2b, 0xa8, 0x3f, 0x33, 0x6d, 0x7c, 0x0e, 0x79, 0xc2, 0x8e, 0x07, 0x4f, 0x5c, 0x02, 0x4d, + 0x79, 0x6f, 0xc3, 0xf8, 0xa3, 0x9b, 0xc4, 0xf6, 0x4b, 0x22, 0x24, 0x8a, 0x12, 0xf5, 0xc0, 0x75, + 0x0c, 0x03, 0xc7, 0x63, 0x3b, 0xa3, 0xe0, 0x82, 0x37, 0x23, 0xaa, 0xba, 0x9e, 0xaa, 0xc0, 0x11, + 0xc8, 0xaf, 0x65, 0xd7, 0xff, 0x00, 0xe3, 0xd1, 0x3f, 0xeb, 0xb2, 0xff, 0x00, 0xe8, 0x0f, 0x5e, + 0xce, 0x47, 0x42, 0x0f, 0x17, 0x1a, 0xcd, 0x5e, 0x71, 0xf7, 0x23, 0xfd, 0xd4, 0xf5, 0x76, 0xf3, + 0x7b, 0x7a, 0x1c, 0xb4, 0xb3, 0x6c, 0x5d, 0x3c, 0xfb, 0x23, 0xcb, 0x21, 0x2e, 0x4c, 0x3d, 0x6c, + 0x62, 0xc4, 0xd6, 0x4b, 0x7a, 0xb2, 0x84, 0x5c, 0x61, 0x19, 0x7f, 0x76, 0x1a, 0xcb, 0x97, 0x67, + 0x26, 0x9b, 0xd6, 0x28, 0xf2, 0x2f, 0x10, 0x7f, 0xc7, 0xda, 0x7f, 0xd7, 0x15, 0xff, 0x00, 0xd0, + 0xde, 0xbe, 0x8f, 0xf0, 0xef, 0xfc, 0x80, 0xf4, 0xaf, 0xfa, 0xf0, 0xb3, 0xff, 0x00, 0xd1, 0x09, + 0x5f, 0x38, 0x78, 0x83, 0xfe, 0x3e, 0xd3, 0xfe, 0xb8, 0xaf, 0xfe, 0x86, 0xf5, 0xf4, 0x7f, 0x87, + 0x7f, 0xe4, 0x07, 0xa5, 0x7f, 0xd7, 0x85, 0x9f, 0xfe, 0x88, 0x4a, 0xf3, 0x7c, 0x64, 0xff, 0x00, + 0x91, 0x2e, 0x4f, 0xff, 0x00, 0x61, 0x15, 0x7f, 0xf4, 0xd9, 0xef, 0xe3, 0x7f, 0xe4, 0x73, 0x8f, + 0xff, 0x00, 0x1f, 0xf9, 0x1e, 0x77, 0xaa, 0xb3, 0x25, 0x94, 0xac, 0xa4, 0xab, 0x29, 0x8c, 0x82, + 0x0e, 0x08, 0x22, 0x45, 0xc1, 0x04, 0x72, 0x08, 0xae, 0xf7, 0xc0, 0x7a, 0x88, 0xd4, 0x6d, 0x67, + 0x63, 0xfe, 0xb6, 0x3f, 0x25, 0x25, 0x19, 0x5c, 0x96, 0xc3, 0xfc, 0xf8, 0x18, 0xc0, 0x7e, 0xdc, + 0x0e, 0x72, 0x07, 0x4a, 0xe0, 0x75, 0x8f, 0xf8, 0xf0, 0x9b, 0xfe, 0x01, 0xff, 0x00, 0xa3, 0x16, + 0xa6, 0xf8, 0x6d, 0x2c, 0xa3, 0xc4, 0x12, 0xc4, 0x1d, 0xc4, 0x6f, 0xa7, 0x5c, 0x3b, 0x46, 0x18, + 0xec, 0x67, 0x8e, 0xe2, 0xd4, 0x23, 0xb2, 0xe7, 0x05, 0x94, 0x3b, 0x85, 0x24, 0x64, 0x06, 0x6c, + 0x75, 0x35, 0xf1, 0xdc, 0x39, 0x5e, 0xa5, 0x38, 0xce, 0x92, 0x7e, 0xed, 0x59, 0x35, 0x25, 0xfe, + 0x18, 0xa9, 0x27, 0xeb, 0xa5, 0xbd, 0x19, 0xf3, 0xdc, 0x23, 0x94, 0xe1, 0x71, 0x9c, 0x23, 0x5b, + 0x1d, 0x38, 0x7e, 0xff, 0x00, 0x01, 0x9a, 0xd5, 0x95, 0x19, 0xad, 0xed, 0x5b, 0x0d, 0x85, 0xa5, + 0x3a, 0x6d, 0xff, 0x00, 0x2b, 0x53, 0xe6, 0xb7, 0xf3, 0x45, 0x1e, 0xeb, 0x45, 0x14, 0x57, 0xd4, + 0x9d, 0x67, 0xc9, 0x7e, 0x02, 0xd1, 0x35, 0x1b, 0x6d, 0x7e, 0xd6, 0xee, 0x58, 0x36, 0xc2, 0x91, + 0xde, 0x2b, 0x3f, 0x99, 0x11, 0xc1, 0x96, 0xca, 0x68, 0xd3, 0xe5, 0x57, 0x2d, 0xcb, 0xba, 0x8e, + 0x9c, 0x67, 0x27, 0x8a, 0xf5, 0x8d, 0x72, 0xc2, 0xe6, 0x4b, 0x75, 0x55, 0x8f, 0x24, 0x48, 0x18, + 0x8d, 0xc9, 0xd3, 0x6b, 0x73, 0xcb, 0x7b, 0x8a, 0xf0, 0x6d, 0x2f, 0xc5, 0x3a, 0xd5, 0xb5, 0xc4, + 0x09, 0x1d, 0xd6, 0xd5, 0x32, 0x46, 0xa4, 0x79, 0x30, 0x1e, 0x0b, 0x00, 0x7a, 0xc4, 0x4d, 0x7b, + 0x11, 0xd7, 0xaf, 0x2f, 0x34, 0xa8, 0xe6, 0x32, 0x62, 0x55, 0x9b, 0xc9, 0x91, 0xb6, 0x20, 0x0d, + 0x84, 0x2d, 0x90, 0x30, 0x47, 0x23, 0x6e, 0x78, 0x1f, 0x36, 0x70, 0x31, 0x59, 0x65, 0xf5, 0xf8, + 0x85, 0x63, 0x63, 0x47, 0x0b, 0xfd, 0x99, 0xef, 0x27, 0x35, 0xed, 0x96, 0x23, 0xa6, 0x9f, 0x63, + 0xd4, 0xdb, 0x17, 0x95, 0x50, 0xa9, 0x98, 0xe5, 0xb9, 0x9e, 0x5d, 0xed, 0x9d, 0x4a, 0x58, 0xc8, + 0x61, 0x68, 0x2c, 0x4c, 0xa1, 0xec, 0xd5, 0x5a, 0x90, 0x9c, 0xe2, 0xeb, 0x46, 0x0b, 0x9d, 0xc2, + 0xd1, 0x69, 0xb8, 0x3b, 0xde, 0xda, 0x1c, 0x36, 0xad, 0xe1, 0xed, 0x56, 0xf2, 0xe5, 0x5a, 0x1b, + 0x7d, 0xe0, 0x46, 0x14, 0x9f, 0x36, 0x15, 0xe4, 0x33, 0x1c, 0x7c, 0xd2, 0x0f, 0x5a, 0xf6, 0x7d, + 0x3b, 0x54, 0xb2, 0xd2, 0xb4, 0x8d, 0x3e, 0x1b, 0xb9, 0x7c, 0xa9, 0x21, 0xb3, 0xb6, 0x8e, 0x45, + 0xd9, 0x23, 0xed, 0x74, 0x85, 0x55, 0x86, 0x63, 0x56, 0x07, 0x04, 0x11, 0x90, 0x48, 0xf4, 0xaf, + 0x18, 0xd5, 0xbc, 0x43, 0xaa, 0xd9, 0xdc, 0xaa, 0xc3, 0x71, 0xb0, 0x18, 0xc3, 0x11, 0xe5, 0x42, + 0xdc, 0x96, 0x61, 0x9f, 0x9a, 0x33, 0xe9, 0x5e, 0xcf, 0xa7, 0x69, 0x76, 0x5a, 0xae, 0x91, 0xa7, + 0xcd, 0x77, 0x17, 0x9b, 0x24, 0xd6, 0x76, 0xd2, 0x48, 0xdb, 0xe4, 0x4d, 0xce, 0xf0, 0xab, 0x31, + 0xc4, 0x6c, 0xa0, 0x64, 0x92, 0x70, 0x00, 0x1e, 0x95, 0xdb, 0xc7, 0x9f, 0xf2, 0x2b, 0xcb, 0x3f, + 0xd6, 0x5f, 0xe1, 0x7b, 0x69, 0xfb, 0x1f, 0xec, 0x9f, 0x8f, 0x9b, 0x93, 0x5f, 0x69, 0xf5, 0xaf, + 0x76, 0xd6, 0xda, 0xdd, 0x4f, 0x3f, 0x11, 0xfe, 0xb2, 0x7f, 0x6b, 0x62, 0xbd, 0xaf, 0xf6, 0x5f, + 0x37, 0x3f, 0xef, 0x79, 0x3e, 0xb1, 0xcb, 0xff, 0x00, 0x6e, 0x5f, 0x5f, 0xbc, 0xf3, 0x5d, 0x43, + 0x59, 0xd3, 0xee, 0x6d, 0xa5, 0x86, 0x29, 0xb7, 0x48, 0x76, 0xfc, 0xbe, 0x5c, 0xa3, 0xa3, 0xa9, + 0xea, 0xc8, 0x07, 0x4f, 0x7a, 0xb9, 0xe0, 0x9b, 0xcb, 0x7d, 0x23, 0x5a, 0x37, 0x77, 0x8f, 0xe4, + 0xc0, 0x6c, 0x2e, 0x21, 0x0f, 0xb5, 0x9f, 0xf7, 0x8f, 0x3d, 0xab, 0xaa, 0xed, 0x8c, 0x33, 0x72, + 0xb1, 0xb9, 0xce, 0x31, 0xc7, 0x5e, 0x95, 0x4f, 0x50, 0xd1, 0xb4, 0xfb, 0x6b, 0x69, 0x66, 0x8a, + 0x1d, 0xb2, 0x0d, 0xbf, 0x37, 0x99, 0x29, 0xea, 0xea, 0x3a, 0x33, 0x91, 0xd3, 0xda, 0xbd, 0x13, + 0xc3, 0x9e, 0x15, 0xd2, 0xe7, 0xb7, 0x64, 0xbb, 0x83, 0xcf, 0x78, 0xd6, 0x2c, 0xb7, 0x9b, 0x32, + 0x8d, 0xcd, 0xbb, 0x76, 0x3c, 0xb6, 0x8f, 0x8c, 0x8c, 0x2e, 0x46, 0x70, 0x39, 0xe6, 0xb8, 0x32, + 0xba, 0x1c, 0x37, 0x52, 0x95, 0x5a, 0x98, 0x0f, 0xed, 0x5b, 0xd1, 0xd5, 0xfd, 0x65, 0xe1, 0xad, + 0xcd, 0x34, 0xa3, 0x6f, 0xdd, 0xeb, 0x63, 0xab, 0x84, 0xb3, 0x6c, 0xa7, 0x05, 0xc3, 0xdf, 0x52, + 0x9f, 0xd6, 0x9d, 0x1c, 0xc7, 0x30, 0xaf, 0x04, 0xa3, 0x18, 0x3a, 0xca, 0xae, 0x1f, 0x0f, 0x87, + 0xad, 0x52, 0x5c, 0xd7, 0x54, 0xd5, 0x25, 0x15, 0x4d, 0x2b, 0xde, 0x4e, 0x52, 0x7a, 0x5b, 0x53, + 0xa0, 0xff, 0x00, 0x84, 0xdf, 0xc3, 0x9f, 0xf3, 0xfd, 0xff, 0x00, 0x92, 0xf7, 0x5f, 0xfc, 0x62, + 0x8f, 0xf8, 0x4d, 0xfc, 0x39, 0xff, 0x00, 0x3f, 0xdf, 0xf9, 0x2f, 0x75, 0xff, 0x00, 0xc6, 0x28, + 0xff, 0x00, 0x84, 0x23, 0xc3, 0x9f, 0xf3, 0xe3, 0xff, 0x00, 0x93, 0x17, 0x5f, 0xfc, 0x7e, 0x8f, + 0xf8, 0x42, 0x3c, 0x39, 0xff, 0x00, 0x3e, 0x3f, 0xf9, 0x31, 0x75, 0xff, 0x00, 0xc7, 0xeb, 0x7d, + 0x4f, 0x7f, 0xfe, 0x31, 0xcf, 0xfa, 0x9a, 0x7f, 0xe5, 0xb9, 0xff, 0xd9, +}; +static const uint8_t kJpeg422[1001] = { + 0xff, 0xd8, 0xff, 0xe0, 0x00, 0x10, 0x4a, 0x46, 0x49, 0x46, 0x00, 0x01, 0x02, 0x00, 0x00, 0x01, + 0x00, 0x01, 0x00, 0x00, 0xff, 0xfe, 0x00, 0x10, 0x4c, 0x61, 0x76, 0x63, 0x36, 0x33, 0x2e, 0x32, + 0x34, 0x2e, 0x31, 0x30, 0x30, 0x00, 0xff, 0xdb, 0x00, 0x43, 0x00, 0x08, 0x08, 0x08, 0x09, 0x08, + 0x09, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0d, 0x0c, 0x0d, 0x0d, 0x0d, 0x0d, 0x0d, 0x0d, 0x0d, + 0x0d, 0x0d, 0x0d, 0x0d, 0x0e, 0x0e, 0x0e, 0x11, 0x11, 0x11, 0x0e, 0x0e, 0x0e, 0x0d, 0x0d, 0x0e, + 0x0e, 0x10, 0x10, 0x11, 0x11, 0x12, 0x13, 0x12, 0x11, 0x11, 0x11, 0x11, 0x13, 0x13, 0x14, 0x14, + 0x14, 0x18, 0x18, 0x17, 0x17, 0x1c, 0x1c, 0x1d, 0x22, 0x22, 0x29, 0xff, 0xc4, 0x01, 0xa2, 0x00, + 0x00, 0x01, 0x05, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x01, 0x00, 0x03, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x02, + 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x10, 0x00, 0x02, 0x01, 0x03, 0x03, 0x02, + 0x04, 0x03, 0x05, 0x05, 0x04, 0x04, 0x00, 0x00, 0x01, 0x7d, 0x01, 0x02, 0x03, 0x00, 0x04, 0x11, + 0x05, 0x12, 0x21, 0x31, 0x41, 0x06, 0x13, 0x51, 0x61, 0x07, 0x22, 0x71, 0x14, 0x32, 0x81, 0x91, + 0xa1, 0x08, 0x23, 0x42, 0xb1, 0xc1, 0x15, 0x52, 0xd1, 0xf0, 0x24, 0x33, 0x62, 0x72, 0x82, 0x09, + 0x0a, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x34, 0x35, 0x36, 0x37, + 0x38, 0x39, 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, + 0x58, 0x59, 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, + 0x78, 0x79, 0x7a, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96, + 0x97, 0x98, 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4, + 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2, + 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, + 0xe9, 0xea, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0x11, 0x00, 0x02, 0x01, + 0x02, 0x04, 0x04, 0x03, 0x04, 0x07, 0x05, 0x04, 0x04, 0x00, 0x01, 0x02, 0x77, 0x00, 0x01, 0x02, + 0x03, 0x11, 0x04, 0x05, 0x21, 0x31, 0x06, 0x12, 0x41, 0x51, 0x07, 0x61, 0x71, 0x13, 0x22, 0x32, + 0x81, 0x08, 0x14, 0x42, 0x91, 0xa1, 0xb1, 0xc1, 0x09, 0x23, 0x33, 0x52, 0xf0, 0x15, 0x62, 0x72, + 0xd1, 0x0a, 0x16, 0x24, 0x34, 0xe1, 0x25, 0xf1, 0x17, 0x18, 0x19, 0x1a, 0x26, 0x27, 0x28, 0x29, + 0x2a, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x53, + 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x73, + 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, + 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, + 0xa9, 0xaa, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, + 0xc7, 0xc8, 0xc9, 0xca, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xe2, 0xe3, 0xe4, + 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xff, + 0xc0, 0x00, 0x11, 0x08, 0x00, 0x10, 0x00, 0x20, 0x03, 0x01, 0x22, 0x00, 0x02, 0x12, 0x00, 0x03, + 0x12, 0x00, 0xff, 0xda, 0x00, 0x0c, 0x03, 0x01, 0x00, 0x02, 0x11, 0x03, 0x11, 0x00, 0x3f, 0x00, + 0xe0, 0x3e, 0x1e, 0xd9, 0xc7, 0x79, 0x7f, 0x38, 0x94, 0x06, 0x48, 0xd1, 0x25, 0x28, 0x46, 0x43, + 0xe0, 0xb0, 0x00, 0xf2, 0x38, 0xcb, 0x03, 0xce, 0x41, 0xc6, 0x08, 0xe6, 0x9d, 0xe2, 0x2f, 0xf9, + 0x76, 0xff, 0x00, 0xb6, 0xbf, 0xfb, 0x25, 0x74, 0xfe, 0x00, 0xd3, 0x34, 0xfb, 0x29, 0x67, 0x9b, + 0xfb, 0x5a, 0xd6, 0x47, 0x96, 0x35, 0x8f, 0xc9, 0xcc, 0x4a, 0xc1, 0x8b, 0x64, 0x0f, 0xf5, 0xec, + 0x49, 0x3d, 0x00, 0xdb, 0x4d, 0xd5, 0xb4, 0x3b, 0x1b, 0x97, 0x89, 0x64, 0xd5, 0xad, 0xa0, 0x09, + 0xbf, 0x0c, 0xde, 0x5e, 0x1f, 0x3b, 0x73, 0x8c, 0xce, 0xbd, 0x31, 0xef, 0xd6, 0xbe, 0xd7, 0x82, + 0xa9, 0x46, 0x15, 0xab, 0xcf, 0xed, 0x54, 0xa8, 0xae, 0xfc, 0xa3, 0x49, 0xa4, 0xbe, 0x5a, 0xbf, + 0x99, 0xf2, 0x3c, 0x2f, 0xc4, 0xf9, 0x8d, 0x0c, 0x74, 0xe8, 0x53, 0xc8, 0xf1, 0x75, 0xe3, 0xed, + 0x17, 0x35, 0x58, 0x3a, 0xb6, 0x8d, 0xe0, 0xf7, 0x4b, 0x0b, 0x25, 0xb6, 0xbf, 0x11, 0xe9, 0xd3, + 0xc7, 0xd5, 0xc4, 0x65, 0xb9, 0xa6, 0x15, 0xb7, 0xec, 0xb0, 0x98, 0x4c, 0xb3, 0x92, 0x37, 0xba, + 0xe7, 0xad, 0x98, 0x62, 0xe5, 0x3a, 0x89, 0x59, 0x59, 0xc9, 0x2a, 0x71, 0x7a, 0xbf, 0x81, 0x33, + 0xcb, 0xce, 0xa5, 0x88, 0xc8, 0x69, 0xe6, 0x3f, 0x56, 0xc3, 0x55, 0xcc, 0xe9, 0x63, 0x29, 0x60, + 0xa0, 0xeb, 0x51, 0x8c, 0x95, 0x3a, 0x51, 0xc3, 0x62, 0x2b, 0xc9, 0x4d, 0xb8, 0x42, 0xb4, 0x64, + 0xaa, 0x4a, 0x6e, 0x9a, 0xf7, 0xa3, 0x69, 0x45, 0xea, 0xde, 0x87, 0xaa, 0x78, 0x8b, 0xfe, 0x5d, + 0xbf, 0xed, 0xaf, 0xfe, 0xc9, 0x55, 0x3e, 0x1a, 0x5e, 0x49, 0x3d, 0xbd, 0xec, 0x2e, 0x4b, 0x79, + 0x06, 0xdf, 0x63, 0x13, 0x9f, 0x91, 0xc4, 0x98, 0x4e, 0x99, 0xc2, 0xed, 0x38, 0xc9, 0x3c, 0x1c, + 0x70, 0x05, 0x63, 0x78, 0x9f, 0x5b, 0xbe, 0x8e, 0x48, 0x50, 0x69, 0x57, 0x2e, 0x14, 0xb8, 0x0c, + 0x3c, 0xcc, 0x36, 0x76, 0xf2, 0x3f, 0x70, 0x7a, 0x63, 0xd7, 0xbd, 0x53, 0xf0, 0x6e, 0xa3, 0x7f, + 0xa3, 0xc3, 0x73, 0x2d, 0xbe, 0x97, 0x73, 0xa8, 0x0b, 0x9f, 0x27, 0xfd, 0x50, 0x90, 0x04, 0xf2, + 0x8c, 0x83, 0xaa, 0x43, 0x2e, 0x72, 0x58, 0x8e, 0xd8, 0xdb, 0x5f, 0x9e, 0xf0, 0x6d, 0x59, 0x42, + 0x32, 0x8a, 0xda, 0xa4, 0x79, 0x5f, 0xca, 0x72, 0x92, 0xfc, 0x8f, 0xaf, 0xca, 0x78, 0x5f, 0x2d, + 0xcb, 0xb0, 0x7f, 0x58, 0xc3, 0x67, 0xb8, 0x4c, 0xc2, 0x71, 0x8b, 0x93, 0xa3, 0x45, 0x52, 0xe6, + 0x5a, 0xc9, 0x6b, 0xc9, 0x8a, 0xaa, 0xd6, 0xb2, 0xb7, 0xc3, 0xb9, 0x18, 0x0c, 0x05, 0x2c, 0x56, + 0x23, 0x88, 0xeb, 0xcd, 0x2e, 0x7c, 0x15, 0x6c, 0xa2, 0xb5, 0x39, 0x5b, 0x5b, 0xd4, 0xc3, 0xd7, + 0xa1, 0x28, 0xa7, 0x75, 0x64, 0xd5, 0x5b, 0xbd, 0xd3, 0xe5, 0x5a, 0x5e, 0xcd, 0x77, 0x70, 0x9c, + 0xe8, 0xe3, 0x23, 0x9d, 0x7d, 0x6a, 0xb5, 0x3c, 0xbe, 0x79, 0x8b, 0xcb, 0xa1, 0x2a, 0x75, 0xa5, + 0x15, 0x2c, 0x3c, 0xe8, 0x42, 0x73, 0x8c, 0x1a, 0x9b, 0xa4, 0xe5, 0x2a, 0xb0, 0x8c, 0xe7, 0x14, + 0xd4, 0x1f, 0x2c, 0x24, 0xd5, 0xd2, 0x67, 0xff, 0xd9, +}; diff --git a/GPU/decode/tests/jpegtest.c b/GPU/decode/tests/jpegtest.c new file mode 100644 index 00000000..ca151265 --- /dev/null +++ b/GPU/decode/tests/jpegtest.c @@ -0,0 +1,610 @@ +// jpegtest: the JPEG plug-in below its VideoToolbox side, with nothing sent to +// the GPU or the kernel. It checks: +// +// 1. jpeg/jpegprep.c gives the block the shape Mesa gives it (SOI, DQT, DHT, +// SOF0, SOS, scan, EOI) and the same picture: ImageIO decodes the +// original and the rewritten file to the same pixels; +// 2. a picture without Huffman tables (Motion JPEG) gets those of Annex K, +// and APPn/COM segments and fill bytes change nothing; +// 3. 4:2:2 is taken (as YUYV), what the block is not given (4:4:4, grey) is +// refused, and no +// prefix or damaged copy of a sample is read outside its buffer (the +// address sanitizer stops the program if one is); +// 4. jpeg/vcnjpeg.c against a made-up kext behind the transport: the +// session needs the plug-in armed and the kext's door; a picture comes +// back in an NV12 full-range buffer with the kext's pixels in place; a +// refused picture, a failed job, a decoder that stays busy and a reply +// that does not match are reported as the right kind of failure. +// +// usage: jpegtest (exit status 0 = pass) +#include +#include +#include +#include +#include +#include + +#include "jpegprep.h" +#include "jpegsamples.h" +#include "vcnjpeg.h" + +static int failures; +static void expect(const char* what, bool ok) { + printf("%s %s\n", ok ? "PASS" : "FAIL", what); + if (!ok) failures++; +} + +// RGBA pixels as ImageIO decodes them; NULL if it cannot. +static uint8_t* rgba(const uint8_t* d, size_t n, size_t* w, size_t* h) { + CFDataRef data = CFDataCreate(NULL, d, (CFIndex)n); + CGImageSourceRef src = CGImageSourceCreateWithData(data, NULL); + CGImageRef img = src ? CGImageSourceCreateImageAtIndex(src, 0, NULL) : NULL; + uint8_t* px = NULL; + if (img) { + *w = CGImageGetWidth(img); + *h = CGImageGetHeight(img); + px = calloc(*w * *h, 4); + CGColorSpaceRef cs = CGColorSpaceCreateWithName(kCGColorSpaceSRGB); + CGContextRef ctx = CGBitmapContextCreate(px, *w, *h, 8, *w * 4, cs, + kCGImageAlphaPremultipliedLast); + CGContextDrawImage(ctx, CGRectMake(0, 0, *w, *h), img); + CGContextRelease(ctx); + CGColorSpaceRelease(cs); + CGImageRelease(img); + } + if (src) CFRelease(src); + CFRelease(data); + return px; +} + +static bool same_picture(const uint8_t* a, size_t an, const uint8_t* b, + size_t bn) { + size_t aw = 0, ah = 0, bw = 0, bh = 0; + uint8_t* x = rgba(a, an, &aw, &ah); + uint8_t* y = rgba(b, bn, &bw, &bh); + bool ok = x && y && aw == bw && ah == bh && !memcmp(x, y, aw * ah * 4); + free(x); + free(y); + return ok; +} + +// The markers of a prepared file, in order, as text ("d8 db c4 c0 da d9"). +static void shape(const uint8_t* d, size_t n, char* out, size_t cap) { + size_t i = 2, p = 0; + p += snprintf(out + p, cap - p, "d8"); + while (i + 4 <= n && p + 8 < cap) { + uint8_t m = d[i + 1]; + p += snprintf(out + p, cap - p, " %02x", m); + size_t len = ((size_t)d[i + 2] << 8) | d[i + 3]; + i += 2 + len; + if (m == 0xda) break; + } + if (n >= 2 && d[n - 2] == 0xff && d[n - 1] == 0xd9) + snprintf(out + p, cap - p, " d9"); +} + +// A copy of a sample with one segment of marker `m` cut out (all of them). +static uint8_t* without(const uint8_t* d, size_t n, uint8_t m, size_t* outN) { + uint8_t* o = malloc(n); + size_t i = 2, p = 2; + memcpy(o, d, 2); + while (i + 4 <= n) { + uint8_t mk = d[i + 1]; + size_t len = ((size_t)d[i + 2] << 8) | d[i + 3]; + if (mk == 0xda) break; + if (mk != m) { + memcpy(o + p, d + i, 2 + len); + p += 2 + len; + } + i += 2 + len; + } + memcpy(o + p, d + i, n - i); + *outN = p + n - i; + return o; +} + +// ---- a made-up kext behind the transport +// --------------------------------------------- +static struct { + int calls, opens, closes; + int infoStatus; // what INFO answers (-1: no door) + uint32_t infoState; // the state bits INFO gives (JA_STATE_*) + uint64_t infoRoom; // and the room of the picture buffer + int runStatus; // what RUN answers + bool busy; // LOAD_USER says busy, always + int widthOff; // added to the width RUN reports + uint8_t jpeg[1 << 16]; // what LOAD_USER copied + size_t jpegLen; + uint32_t w, h, pitch, rows; + bool yuyv; // the picture is 4:2:2: one YUYV plane +} K; +static size_t k_bytes(void) { + return K.yuyv ? (size_t)K.pitch * K.rows : (size_t)K.pitch * K.rows * 3 / 2; +} +static uint8_t pattern(size_t i) { return (uint8_t)(i * 13 + 5); } +static int fake_call(void* ctx, const void* in, size_t inSize, void* out, + size_t* outSize) { + (void)ctx; + K.calls++; + struct ja_request rq; + memcpy(&rq, in, sizeof(rq)); + if (inSize < sizeof(rq) || rq.code != JA_CODE) return 0x2c2; + if (K.infoStatus == -1) return 0x2c2; // PowerPlay's refusal: no door + struct ja_reply rp = {JA_REPLY_MAGIC, JA_OK, 0, 0, {0}}; + uint8_t* data = (uint8_t*)out + sizeof(rp); + switch (rq.op) { + case JA_OP_INFO: + rp.status = (uint32_t)K.infoStatus; + rp.v[0] = K.infoState; + rp.v[1] = sizeof(K.jpeg); + rp.v[2] = K.infoRoom; + break; + case JA_OP_LOAD_USER: { + if (K.busy) { + rp.status = JA_BUSY; + break; + } + if (rq.arg1 > sizeof(K.jpeg)) { + rp.status = JA_BAD_REQUEST; + break; + } + memcpy(K.jpeg, (const void*)(uintptr_t)rq.arg0, rq.arg1); + K.jpegLen = rq.arg1; + JpegInfo info; + uint8_t* again = NULL; + size_t againLen = 0; + // the kext checks the stream again; a prepared file must come out + // unchanged + if (jpeg_prepare(K.jpeg, K.jpegLen, &again, &againLen, &info, NULL, 0) != + JPEG_OK || + againLen != K.jpegLen || memcmp(again, K.jpeg, againLen)) { + free(again); + rp.status = JA_BAD_STREAM; + break; + } + free(again); + K.w = info.width; + K.h = info.height; + K.yuyv = info.yuyv; + K.pitch = K.yuyv + ? (uint32_t)(((K.w + 15) / 16 * 16 * 2 + 255) / 256 * 256) + : (uint32_t)(((K.w + 15) / 16 * 16 + 255) / 256 * 256); + K.rows = (K.h + 15) / 16 * 16; + rp.v[0] = K.w; + rp.v[1] = K.h; + break; + } + case JA_OP_RUN: { + rp.status = (uint32_t)K.runStatus; + if (K.runStatus != JA_OK) break; + struct ja_picture pic = {K.w + (uint32_t)K.widthOff, + K.h, + K.pitch, + K.rows, + K.yuyv ? 0 : K.pitch * K.rows, + (uint32_t)k_bytes(), + 3, + K.yuyv ? 1u : 0u}; + memcpy(data, &pic, sizeof(pic)); + rp.dataBytes = sizeof(pic); + break; + } + case JA_OP_READ_USER: { + size_t bytes = k_bytes(); + if (rq.arg1 < bytes) { + rp.status = JA_BAD_REQUEST; + break; + } + uint8_t* dst = (uint8_t*)(uintptr_t)rq.arg0; + for (size_t i = 0; i < bytes; i++) dst[i] = pattern(i); + rp.v[0] = bytes; + break; + } + case JA_OP_RELEASE: + break; + default: + rp.status = JA_BAD_REQUEST; + } + memcpy(out, &rp, sizeof(rp)); + *outSize = sizeof(rp) + rp.dataBytes; + return 0; +} +static bool openFails; +static int dummyConn; +static void* fake_open(void) { + K.opens++; + return openFails ? NULL : &dummyConn; +} +static void fake_close(void* ctx) { + (void)ctx; + K.closes++; +} + +static CVPixelBufferRef got; +static uint32_t gotW, gotH; +static void on_picture(void* ctx, CVPixelBufferRef pb, const void* unused, + uint32_t w, uint32_t h, int64_t tag) { + (void)ctx, (void)unused, (void)tag; + if (got) CVPixelBufferRelease(got); + got = CVPixelBufferRetain(pb); + gotW = w; + gotH = h; +} + +// The kext's pattern is where the plug-in put it: luma row r at r * pitch, +// chroma after the luma rows. '422f' from the YUYV the made-up kext wrote: Y +// from the even bytes, Cb Cr from the odd ones. +static bool planes_hold_pattern_422(CVPixelBufferRef pb, uint32_t w, + uint32_t h) { + if (CVPixelBufferGetPixelFormatType(pb) != + kCVPixelFormatType_422YpCbCr8BiPlanarFullRange) + return false; + CVPixelBufferLockBaseAddress(pb, kCVPixelBufferLock_ReadOnly); + const uint8_t* y = CVPixelBufferGetBaseAddressOfPlane(pb, 0); + const uint8_t* uv = CVPixelBufferGetBaseAddressOfPlane(pb, 1); + size_t ys = CVPixelBufferGetBytesPerRowOfPlane(pb, 0), + uvs = CVPixelBufferGetBytesPerRowOfPlane(pb, 1); + bool ok = CVPixelBufferGetWidth(pb) == w && CVPixelBufferGetHeight(pb) == h && + CVPixelBufferGetHeightOfPlane(pb, 1) == h; + for (uint32_t r = 0; ok && r < h; r++) { + for (uint32_t c = 0; ok && c < w; c++) + ok = y[r * ys + c] == pattern((size_t)r * K.pitch + 2 * c); + for (uint32_t c = 0; ok && c < (w + 1) / 2 * 2; c++) + ok = uv[r * uvs + c] == pattern((size_t)r * K.pitch + 2 * c + 1); + } + CVPixelBufferUnlockBaseAddress(pb, kCVPixelBufferLock_ReadOnly); + return ok; +} +static bool planes_hold_pattern(CVPixelBufferRef pb, uint32_t w, uint32_t h) { + if (CVPixelBufferGetPixelFormatType(pb) != + kCVPixelFormatType_420YpCbCr8BiPlanarFullRange) + return false; + CVPixelBufferLockBaseAddress(pb, kCVPixelBufferLock_ReadOnly); + const uint8_t* y = CVPixelBufferGetBaseAddressOfPlane(pb, 0); + const uint8_t* uv = CVPixelBufferGetBaseAddressOfPlane(pb, 1); + size_t ys = CVPixelBufferGetBytesPerRowOfPlane(pb, 0), + uvs = CVPixelBufferGetBytesPerRowOfPlane(pb, 1); + bool ok = CVPixelBufferGetWidth(pb) == w && CVPixelBufferGetHeight(pb) == h; + for (uint32_t r = 0; ok && r < h; r++) + for (uint32_t c = 0; ok && c < w; c++) + ok = y[r * ys + c] == pattern((size_t)r * K.pitch + c); + size_t chromaAt = (size_t)K.pitch * K.rows; + for (uint32_t r = 0; ok && r < (h + 1) / 2; r++) + for (uint32_t c = 0; ok && c < (w + 1) / 2 * 2; c++) + ok = uv[r * uvs + c] == pattern(chromaAt + (size_t)r * K.pitch + c); + CVPixelBufferUnlockBaseAddress(pb, kCVPixelBufferLock_ReadOnly); + return ok; +} + +int main(void) { + setvbuf(stdout, NULL, _IOLBF, 0); + struct { + const uint8_t* d; + size_t n; + uint32_t w, h; + } ok420[] = {{kJpeg16x16, sizeof(kJpeg16x16), 16, 16}, + {kJpeg48x32, sizeof(kJpeg48x32), 48, 32}, + {kJpeg50x30, sizeof(kJpeg50x30), 50, 30}}; + char why[96], text[64]; + + // ---- 1. shape and picture ---- + bool shapes = true, pictures = true, sizes = true; + for (size_t k = 0; k < 3; k++) { + uint8_t* o = NULL; + size_t on = 0; + JpegInfo info; + int r = + jpeg_prepare(ok420[k].d, ok420[k].n, &o, &on, &info, why, sizeof(why)); + if (r != JPEG_OK) { + printf(" %s\n", why); + shapes = pictures = sizes = false; + continue; + } + shape(o, on, text, sizeof(text)); + shapes = shapes && !strcmp(text, "d8 db c4 c0 da d9"); + pictures = pictures && same_picture(ok420[k].d, ok420[k].n, o, on); + sizes = sizes && info.width == ok420[k].w && info.height == ok420[k].h && + on <= ok420[k].n + kJpegPrepExtra; + // what comes out goes in again unchanged (the kext checks it again) + uint8_t* o2 = NULL; + size_t on2 = 0; + shapes = shapes && + jpeg_prepare(o, on, &o2, &on2, &info, NULL, 0) == JPEG_OK && + on2 == on && !memcmp(o, o2, on); + free(o2); + free(o); + } + expect( + "16x16, 48x32 and 50x30: SOI, DQT, DHT, SOF0, SOS, scan, EOI, and " + "nothing else", + shapes); + expect( + "ImageIO decodes the original and the rewritten file to the same pixels", + pictures); + expect("the size comes from the frame header", sizes); + + // ---- 2. Motion JPEG without tables; segments that are dropped ---- + uint8_t *base = NULL, *o = NULL; + size_t baseN = 0, on = 0, cutN = 0; + JpegInfo info; + jpeg_prepare(kJpeg48x32, sizeof(kJpeg48x32), &base, &baseN, &info, NULL, 0); + uint8_t* cut = without(kJpeg48x32, sizeof(kJpeg48x32), 0xc4, &cutN); + int r = jpeg_prepare(cut, cutN, &o, &on, &info, why, sizeof(why)); + expect( + "without its DHT the picture gets Annex K's tables, byte for byte what " + "FFmpeg wrote", + r == JPEG_OK && info.stdTables && on == baseN && !memcmp(o, base, on)); + expect("and ImageIO, given the result, decodes the original picture", + r == JPEG_OK && same_picture(kJpeg48x32, sizeof(kJpeg48x32), o, on)); + free(o); + free(cut); + // APP1 + COM + fill bytes in front of SOF0 + size_t extraN = sizeof(kJpeg48x32) + 32; + uint8_t* extra = malloc(extraN); + memcpy(extra, kJpeg48x32, 2); + static const uint8_t junk[] = {0xff, 0xe1, 0x00, 0x08, 'E', 'x', 'i', 'f', + 0, 0, 0xff, 0xfe, 0x00, 0x06, 'h', 'e', + 'l', 'l', 0xff, 0xff, 0xff, 0xe2, 0x00, 0x0a, + 1, 2, 3, 4, 5, 6, 7, 8}; + memcpy(extra + 2, junk, sizeof(junk)); + memcpy(extra + 2 + sizeof(junk), kJpeg48x32 + 2, sizeof(kJpeg48x32) - 2); + o = NULL; + r = jpeg_prepare(extra, extraN, &o, &on, &info, why, sizeof(why)); + expect("APP1, COM and fill bytes are dropped: the same bytes as without them", + r == JPEG_OK && on == baseN && !memcmp(o, base, on)); + free(o); + free(extra); + + // ---- 3. refused, cut and damaged ---- + o = NULL; + r = jpeg_prepare(kJpeg422, sizeof(kJpeg422), &o, &on, &info, why, + sizeof(why)); + expect("4:2:2 (ffmpeg's 2x2/1x2/1x2) is taken, as YUYV", + r == JPEG_OK && o && info.yuyv && info.width == 32); + free(o); + { + // the other sampling forms Mesa takes or refuses on this block + static const uint8_t forms[][4] = {{0x21, 0x11, 0x11, JPEG_OK}, + {0x22, 0x21, 0x21, JPEG_OK}, + {0x11, 0x11, 0x11, JPEG_UNSUPPORTED}, + {0x12, 0x11, 0x11, JPEG_UNSUPPORTED}}; + bool all = true; + for (size_t f = 0; f < sizeof(forms) / sizeof(forms[0]); f++) { + uint8_t* c = malloc(sizeof(kJpeg48x32)); + memcpy(c, kJpeg48x32, sizeof(kJpeg48x32)); + for (size_t i = 2; i + 20 < sizeof(kJpeg48x32); i++) + if (c[i] == 0xff && c[i + 1] == 0xc0) { + c[i + 11] = forms[f][0]; + c[i + 14] = forms[f][1]; + c[i + 17] = forms[f][2]; + break; + } + o = NULL; + int rr = + jpeg_prepare(c, sizeof(kJpeg48x32), &o, &on, &info, why, sizeof(why)); + all = all && rr == forms[f][3] && (rr != JPEG_OK || info.yuyv) && + (rr == JPEG_OK || !o); + free(o); + free(c); + } + expect( + "sampling 211111 and 222121 are YUYV too; 4:4:4 and 4:4:0 are refused", + all); + } + { + // EOI replaced by fill bytes: the sample ends in 0xff 0xff. The copy has + // the exact size, so a read past its end is caught by the sanitizer. + size_t n = sizeof(kJpeg48x32); + uint8_t* c = malloc(n); + memcpy(c, kJpeg48x32, n); + c[n - 1] = 0xff; + o = NULL; + r = jpeg_prepare(c, n, &o, &on, &info, why, sizeof(why)); + expect( + "a sample that ends in fill bytes instead of EOI is refused, nothing " + "read past it", + r != JPEG_OK && !o); + free(o); + free(c); + } + { + // a scan that names another component than the frame: refused here, and + // by the kext again + uint8_t* c = malloc(sizeof(kJpeg48x32)); + memcpy(c, kJpeg48x32, sizeof(kJpeg48x32)); + bool found = false; + for (size_t i = 2; i + 6 < sizeof(kJpeg48x32); i++) + if (c[i] == 0xff && c[i + 1] == 0xda) { + c[i + 5] ^= 0x40; + found = true; + break; + } + o = NULL; + r = jpeg_prepare(c, sizeof(kJpeg48x32), &o, &on, &info, why, sizeof(why)); + expect("a scan that names other components than the frame is refused", + found && r == JPEG_BAD && !o); + free(o); + free(c); + } + bool prefixes = true; + for (size_t n = 0; n < sizeof(kJpeg48x32) - 1; n++) { + uint8_t* copy = malloc(n ? n : 1); + memcpy(copy, kJpeg48x32, n); + o = NULL; + r = jpeg_prepare(copy, n, &o, &on, &info, NULL, 0); + // a prefix that ends inside the scan has no EOI: refused + prefixes = prefixes && r != JPEG_OK && !o; + free(copy); + } + expect("every prefix of a sample is refused, nothing read past it", prefixes); + uint32_t seed = 1, accepted = 0; + for (int k = 0; k < 40000; k++) { + size_t n = ok420[k % 3].n; + uint8_t* copy = malloc(n); + memcpy(copy, ok420[k % 3].d, n); + int flips = 1 + k % 8; + for (int f = 0; f < flips; f++) { + seed = seed * 1664525u + 1013904223u; + size_t at = + (seed >> 8) % (k % 2 ? 200 : n); // half of them in the headers + seed = seed * 1664525u + 1013904223u; + copy[at] = k % 5 == 0 ? (uint8_t)(seed >> 24) + : copy[at] ^ (uint8_t)(1u << ((seed >> 8) % 8)); + } + o = NULL; + r = jpeg_prepare(copy, n, &o, &on, &info, NULL, 0); + if (r == JPEG_OK) { + accepted++; + if (on > n + kJpegPrepExtra) prefixes = false; + } + free(o); + free(copy); + } + printf(" (%u of 40000 damaged copies still had the shape of a JPEG)\n", + accepted); + expect("40000 damaged copies are read without a fault", prefixes); + + // ---- 4. the session against a made-up kext ---- + vcnjpeg_transport = fake_call; + vcnjpeg_transport_open = fake_open; + vcnjpeg_transport_close = fake_close; + char err[160] = ""; + VcnJpeg* d = vcnjpeg_create(16384, 16384, err, sizeof(err)); + expect("no session before the plug-in arms it, and nothing is opened", + !d && K.opens == 0); + vcnjpeg_gpu_armed = 1; + K.infoStatus = -1; + d = vcnjpeg_create(16384, 16384, err, sizeof(err)); + expect( + "no session without the kext's door (PowerPlay refuses the request), and " + "the connection is closed", + !d && K.opens == 1 && K.closes == 1 && strstr(err, "not loaded")); + K.infoStatus = JA_NOT_READY; + d = vcnjpeg_create(16384, 16384, err, sizeof(err)); + expect("no session while the kext's decoder is not ready", + !d && K.closes == 2); + openFails = true; + d = vcnjpeg_create(16384, 16384, err, sizeof(err)); + expect("no session when the accelerator cannot be opened", + !d && K.closes == 2); + openFails = false; + K.infoStatus = JA_OK; + K.infoRoom = 1u << 24; + K.infoState = JA_STATE_POOL | JA_STATE_CREATED | JA_STATE_STUCK; + int closesBefore = K.closes; + d = vcnjpeg_create(16384, 16384, err, sizeof(err)); + expect( + "no session while the kext's decoder is stuck, and the connection is " + "closed", + !d && K.closes == closesBefore + 1 && strstr(err, "stuck")); + K.infoState = JA_STATE_CREATED; + d = vcnjpeg_create(16384, 16384, err, sizeof(err)); + expect("no session when the kext has no buffers", + !d && K.closes == closesBefore + 2); + K.infoState = JA_STATE_POOL | JA_STATE_CREATED; + K.runStatus = JA_OK; + d = vcnjpeg_create(16384, 16384, err, sizeof(err)); + expect("a session with the door open", d != NULL); + // 16 MiB of room: 2048x2048 fits in both layouts, 4:2:2 at 2896x2896 does not + expect( + "the size check: 1920x1080 and 2048x2048 fit 16 MiB, 2896x2896 and " + "16384x16384 do not", + d && vcnjpeg_fits(d, 1920, 1080) && vcnjpeg_fits(d, 2048, 2048) && + !vcnjpeg_fits(d, 2896, 2896) && !vcnjpeg_fits(d, 16384, 16384)); + { + // A small frame whose SOF says 4096x4096: more than the kext's 16 MiB. It + // must be refused before anything is allocated for it or sent. + uint8_t* big = malloc(sizeof(kJpeg16x16)); + memcpy(big, kJpeg16x16, sizeof(kJpeg16x16)); + for (size_t i = 2; i + 9 < sizeof(kJpeg16x16); i++) + if (big[i] == 0xff && big[i + 1] == 0xc0) { + big[i + 5] = 0x10, big[i + 6] = 0x00; // height 4096 + big[i + 7] = 0x10, big[i + 8] = 0x00; // width 4096 + break; + } + int before = K.calls; + expect( + "a frame whose header asks for more than the kext's buffer is refused " + "as the stream's, nothing sent", + d && vcnjpeg_decode(d, big, sizeof(kJpeg16x16), 0, on_picture, NULL) && + vcnjpeg_failure(d) == VCNJPEG_FAIL_STREAM && K.calls == before && + strstr(vcnjpeg_last_error(d), "kext's buffer")); + free(big); + } + bool pics = d != NULL; + for (size_t k = 0; pics && k < 3; k++) { + int calls = K.calls; + pics = !vcnjpeg_decode(d, ok420[k].d, ok420[k].n, 0, on_picture, NULL) && + got && gotW == ok420[k].w && gotH == ok420[k].h && + planes_hold_pattern(got, ok420[k].w, ok420[k].h) && + K.calls == calls + 3; + if (!pics) printf(" %s\n", vcnjpeg_last_error(d)); + } + expect( + "16x16, 48x32 and 50x30 come back in NV12 full range, the kext's pixels " + "in place, in three calls", + pics); + CFTypeRef matrix = + got ? CVBufferCopyAttachment(got, kCVImageBufferYCbCrMatrixKey, NULL) + : NULL; + expect("the picture says BT.601 (JFIF)", + matrix && CFEqual(matrix, kCVImageBufferYCbCrMatrix_ITU_R_601_4)); + if (matrix) CFRelease(matrix); + int calls = K.calls; + bool p422 = + d && + !vcnjpeg_decode(d, kJpeg422, sizeof(kJpeg422), 0, on_picture, NULL) && + got && gotW == 32 && gotH == 16 && planes_hold_pattern_422(got, 32, 16) && + K.calls == calls + 3; + if (!p422 && d) printf(" %s\n", vcnjpeg_last_error(d)); + expect( + "a 4:2:2 picture comes back as '422f', the kext's YUYV split into its " + "planes, in three calls", + p422); + if (d) { + vcnjpeg_destroy(d); + d = vcnjpeg_create(32, 32, err, sizeof(err)); + } + calls = K.calls; + expect( + "a picture larger than the session allows fails as the stream's, nothing " + "sent", + d && + vcnjpeg_decode(d, kJpeg48x32, sizeof(kJpeg48x32), 0, on_picture, + NULL) && + vcnjpeg_failure(d) == VCNJPEG_FAIL_STREAM && K.calls == calls); + vcnjpeg_destroy(d); + d = vcnjpeg_create(16384, 16384, err, sizeof(err)); + K.runStatus = JA_FAILED; + expect("a job that fails in the kext is a device failure", + d && + vcnjpeg_decode(d, kJpeg16x16, sizeof(kJpeg16x16), 0, on_picture, + NULL) && + vcnjpeg_failure(d) == VCNJPEG_FAIL_DEVICE); + K.runStatus = JA_OK; + K.widthOff = 16; + expect("a picture of another size than the one sent is a device failure", + d && + vcnjpeg_decode(d, kJpeg16x16, sizeof(kJpeg16x16), 0, on_picture, + NULL) && + vcnjpeg_failure(d) == VCNJPEG_FAIL_DEVICE); + K.widthOff = 0; + K.busy = true; + CFAbsoluteTime t0 = CFAbsoluteTimeGetCurrent(); + bool busy = + d && + vcnjpeg_decode(d, kJpeg16x16, sizeof(kJpeg16x16), 0, on_picture, NULL) && + vcnjpeg_failure(d) == VCNJPEG_FAIL_DEVICE; + double waited = CFAbsoluteTimeGetCurrent() - t0; + expect( + "a decoder another process keeps busy for a second is a device failure", + busy && waited >= 0.9 && waited < 3); + K.busy = false; + int closes = K.closes; + vcnjpeg_destroy(d); + expect("destroy gives the decoder back and closes the connection", + K.closes == closes + 1); + if (got) CVPixelBufferRelease(got); + free(base); + return failures ? 1 : 0; +} diff --git a/GPU/decode/tests/layertest.c b/GPU/decode/tests/layertest.c index f57e9154..2a7d2b2f 100644 --- a/GPU/decode/tests/layertest.c +++ b/GPU/decode/tests/layertest.c @@ -1,4 +1,4 @@ -// layertest: the MPEG-2 and VC-1 codec layers (mpeg2/vcnmpeg2.c, +// layertest: the MPEG-2, VC-1 and MPEG-4 codec layers (mpeg2/vcnmpeg2.c, // vc1/vcnvc1.c) on a stand-in for common/vcnlegacy.c: nothing opens the GPU // or the driver. The stand-in records every command the layer would send to // the firmware, so the test sees what goes out for a stream and which picture @@ -11,7 +11,12 @@ // VCNMPEG2_ALLOW_FIELDS=1; with it, the two field pictures of a frame go // into one picture, with two commands, the frame is shown once, after its // second field, and with numbered indices both fields carry the frame's -// number (field mode 1). +// number (field mode 1); +// 3. MPEG-4: a B-VOP whose TRD is 0 never gets a command, even with +// VCNMPEG4_ALLOW_B=1; without that switch no B-VOP does; with it, a B-VOP +// with its time distances goes out in block mode 3 with TRB/TRD; cut mode +// 1 sends a unit from its VOP start code; the session asks for the size +// aligned to 16. #include #include #include @@ -20,6 +25,7 @@ #include "mpeg2msg.h" #include "vcnlegacy.h" #include "vcnmpeg2.h" +#include "vcnmpeg4.h" #include "vcnvc1.h" static int failures; @@ -33,10 +39,12 @@ enum { MAX_CMDS = 64 }; static struct { CVPixelBufferRef target; size_t size; + uint8_t head[4]; // the first bytes of the bitstream uint8_t block[512]; uint32_t blockSize; } g_cmd[MAX_CMDS]; static int g_cmds, g_created, g_destroyed; +static VcnLegacyConfig g_cfg; // of the last session made struct VcnLegacy { VcnLegacyConfig cfg; @@ -48,6 +56,7 @@ VcnLegacy* vcnlegacy_create(const VcnLegacyConfig* cfg, char* err, VcnLegacy* d = calloc(1, sizeof(*d)); if (!d) abort(); d->cfg = *cfg; + g_cfg = *cfg; g_created++; return d; } @@ -69,7 +78,12 @@ int vcnlegacy_decode(VcnLegacy* d, const void* block, uint32_t blockSize, (void)d; if (g_cmds == MAX_CMDS) abort(); size_t size = 0; - for (int i = 0; i < nparts; i++) size += parts[i].size; + memset(g_cmd[g_cmds].head, 0, sizeof(g_cmd[0].head)); + for (int i = 0; i < nparts; i++) { + for (size_t j = 0; j < parts[i].size && size + j < 4; j++) + g_cmd[g_cmds].head[size + j] = parts[i].data[j]; + size += parts[i].size; + } g_cmd[g_cmds].target = target; g_cmd[g_cmds].size = size; g_cmd[g_cmds].blockSize = blockSize; @@ -306,9 +320,143 @@ static void test_mpeg2_fields(void) { unsetenv("VCNMPEG2_ALLOW_FIELDS"); } +// ---- MPEG-4 +// Visual object sequence and an Advanced Simple VOL of 640x480 that can carry +// B-VOPs (low_delay 0), time resolution 25 (5 bits). +static void mpeg4_headers(W* w) { + start(w, 0xB0); + put(w, 0xF5, 8); + start(w, 0x20); + put(w, 0, 1); // random_accessible_vol + put(w, 17, 8); // Advanced Simple + put(w, 0, 1); // no is_object_layer_identifier: version 1 + put(w, 1, 4); // aspect ratio + put(w, 1, 1); // vol_control_parameters + put(w, 1, 2); // chroma_format + put(w, 0, 1); // low_delay + put(w, 0, 1); // no vbv parameters + put(w, 0, 2); // rectangular + put(w, 1, 1); + put(w, 25, 16); + put(w, 1, 1); + put(w, 0, 1); // no fixed_vop_rate + put(w, 1, 1); + put(w, 640, 13); + put(w, 1, 1); + put(w, 480, 13); + put(w, 1, 1); + put(w, 0, 1); // progressive + put(w, 1, 1); // obmc_disable + put(w, 0, 1); // no sprite + put(w, 0, 1); // 8 bit + put(w, 0, 1); // H.263 quantiser + put(w, 1, 1); // complexity_estimation_disable + put(w, 1, 1); // resync_marker_disable + put(w, 0, 1); // data_partitioned + put(w, 0, 1); // scalability +} +static void mpeg4_vop(W* w, int type, int increment) { + start(w, 0xB6); + put(w, (uint32_t)type, 2); + put(w, 0, 1); // modulo_time_base + put(w, 1, 1); + put(w, (uint32_t)increment, 5); + put(w, 1, 1); + put(w, 1, 1); // vop_coded + if (type == 1) put(w, 0, 1); // rounding + put(w, 0, 3); // intra_dc_vlc_thr + put(w, 8, 5); // quant + if (type != 0) put(w, 1, 3); + if (type == 2) put(w, 1, 3); + put(w, 0x3c3c3c, 24); +} +// I, P, B at the given ticks; the size of the first unit (headers + I). +static size_t mpeg4_stream(W* w, int pTick, int bTick, size_t* first) { + memset(w, 0, sizeof(*w)); + mpeg4_headers(w); + mpeg4_vop(w, 0, 0); + *first = bytes(w); + mpeg4_vop(w, 1, pTick); + mpeg4_vop(w, 2, bTick); + return bytes(w); +} + +static void test_mpeg4_b(void) { + W w; + size_t first = 0; + char err[256] = ""; + // By default: I and P go out, the B-VOP is refused before any command. + size_t n = mpeg4_stream(&w, 3, 1, &first); + void* d = vcnmpeg4_codec.create(NULL, 0, 0, 0, err, sizeof(err)); + int r = vcnmpeg4_codec.decode(d, w.d, n, on_frame, NULL); + expect("mpeg4: by default the B-VOP is refused, after its I and P went out", + d && r == -1 && g_cmds == 2 && g_outs == 2 && + strstr(vcnmpeg4_codec.last_error(d), "B-VOPs")); + expect("mpeg4: the session asks for the size aligned to 16", + g_created == 1 && g_cfg.alignSizeTo16 && g_cfg.width == 640 && + g_cfg.height == 480); + vcnmpeg4_codec.destroy(d); + reset(); + + // TRD 0: the P-VOP carries the I-VOP's time. + setenv("VCNMPEG4_ALLOW_B", "1", 1); + n = mpeg4_stream(&w, 0, 0, &first); + d = vcnmpeg4_codec.create(NULL, 0, 0, 0, err, sizeof(err)); + r = vcnmpeg4_codec.decode(d, w.d, n, on_frame, NULL); + expect( + "mpeg4: a B-VOP with TRD 0 gets no command, even with " + "VCNMPEG4_ALLOW_B=1, and asks for the next frame", + d && r == -1 && g_cmds == 2 && g_outs == 2 && + strstr(vcnmpeg4_codec.last_error(d), "TRD 0") && + vcnmpeg4_codec.failure(d) == VCNLEGACY_FAIL_REFERENCE); + vcnmpeg4_codec.destroy(d); + reset(); + + // TRD 3, TRB 1, block mode 3: the whole VOP part goes with it. + vcnmpeg4_block_mode = 3; + n = mpeg4_stream(&w, 3, 1, &first); + d = vcnmpeg4_codec.create(NULL, 0, 0, 0, err, sizeof(err)); + r = vcnmpeg4_codec.decode(d, w.d, n, on_frame, NULL); + VcnMpeg4Msg m[3]; + for (int i = 0; i < 3 && i < g_cmds; i++) + memcpy(&m[i], g_cmd[i].block, sizeof(m[i])); + expect("mpeg4: with VCNMPEG4_ALLOW_B=1 the B-VOP goes out in mode 3", + d && r == 0 && g_cmds == 3 && g_outs == 3 && + g_out[2].use == VCNLEGACY_PIC_B && + g_cmd[2].blockSize == sizeof(VcnMpeg4Msg) && + m[2].vop.vop_data_present == 1 && + m[2].vop.vop_coding_type == MPEG4_B && m[2].vop.TRD[0] == 3 && + m[2].vop.TRD[1] == 3 && m[2].vop.TRB[0] == 1 && + m[2].vop.TRB[1] == 1 && m[2].decoded_pic_idx == 3 && + m[2].forward_ref_pic_idx == 1 && m[2].backward_ref_pic_idx == 2); + static const uint8_t vos[4] = {0, 0, 1, 0xB0}, vop[4] = {0, 0, 1, 0xB6}; + size_t whole = g_cmd[0].size, bSize = g_cmd[2].size; + expect("mpeg4: cut mode 0 sends the first unit with its headers", + whole == first && !memcmp(g_cmd[0].head, vos, 4) && + !memcmp(g_cmd[2].head, vop, 4)); + vcnmpeg4_codec.destroy(d); + reset(); + + vcnmpeg4_cut_mode = 1; + d = vcnmpeg4_codec.create(NULL, 0, 0, 0, err, sizeof(err)); + r = vcnmpeg4_codec.decode(d, w.d, n, on_frame, NULL); + expect( + "mpeg4: cut mode 1 sends the first unit from its VOP start code, the " + "B-VOP as before", + d && r == 0 && g_cmds == 3 && !memcmp(g_cmd[0].head, vop, 4) && + g_cmd[0].size < whole && g_cmd[0].size > 4 && + !memcmp(g_cmd[2].head, vop, 4) && g_cmd[2].size == bSize); + vcnmpeg4_codec.destroy(d); + reset(); + vcnmpeg4_cut_mode = 0; + vcnmpeg4_block_mode = 0; + unsetenv("VCNMPEG4_ALLOW_B"); +} + int main(void) { test_vc1_skipped(); test_mpeg2_fields(); + test_mpeg4_b(); printf("%s\n", failures ? "FAILED" : "all passed"); return failures ? 1 : 0; } diff --git a/GPU/decode/tests/legacyparse.c b/GPU/decode/tests/legacyparse.c index 69a3ef2b..468a66dc 100644 --- a/GPU/decode/tests/legacyparse.c +++ b/GPU/decode/tests/legacyparse.c @@ -371,6 +371,26 @@ static void test_mpeg2(void) { lm.blockSize = 160; expect("message: a message that does not fit is refused", vcnlegacy_build_message(msg, 403, &lm) == 0); + // MPEG-4: the size in whole macroblocks, the rest as before. + lm.width = 1918; + lm.height = 1080; + lm.pitch = 1920; + lm.texHeight = 1080; + uint8_t plain[1024]; + uint32_t plainSize = vcnlegacy_build_message(plain, sizeof(plain), &lm); + lm.alignSizeTo16 = true; + uint32_t alignedSize = vcnlegacy_build_message(msg, sizeof(msg), &lm); + expect("message: alignSizeTo16 sends 1918x1080 as 1920x1088", + plainSize == 404 && alignedSize == 404 && + *(const uint32_t*)(plain + 56 + 8) == 1918 && + *(const uint32_t*)(plain + 56 + 12) == 1080 && D32(8) == 1920 && + D32(12) == 1088); + // Every other byte the same: db_pitch, db_aligned_height and the target + // offsets come from the real size and give the same values. + memcpy(plain + 56 + 8, msg + 56 + 8, 8); + expect("message: alignSizeTo16 changes nothing else", + !memcmp(plain, msg, 404) && D32(72) == 1920 && D32(76) == 1088); + lm.alignSizeTo16 = false; #undef D32 expect("dpb: six pictures and room for the firmware's side buffers", vcnlegacy_dpb_size(VCN_CODEC_MPEG2_VLD, 720, 576) >= 0x3a4000 && @@ -817,17 +837,34 @@ static void test_mpeg4(void) { VCN_MPEG4_RESYNC_MARKER_DISABLE) && b.quant_type == 1 && b.intra_quant_mat[0] == 9 && b.vop.vop_data_present == 0); - // intra matrix in zigzag order: 9, 10, 11, 11, ... The transposed one in - // zigzag order swaps the 2nd and 3rd entries (raster 1 and 8). - vcnmpeg4_matrix_mode = 1; - VcnMpeg4Msg t; - vcnmpeg4_fill_block(&t, &p, &m.pic[2], 3, 1, 2); - vcnmpeg4_matrix_mode = 0; - expect("mpeg4: matrices go in stream order; mode 1 sends the transposed one", + // intra matrix in zigzag order: 9, 10, 11, 11, ... + expect("mpeg4: matrices go in stream order", b.intra_quant_mat[1] == 10 && b.intra_quant_mat[2] == 11 && - t.intra_quant_mat[0] == 9 && t.intra_quant_mat[1] == 11 && - t.intra_quant_mat[2] == 10 && t.intra_quant_mat[63] == 11 && - t.nonintra_quant_mat[63] == 33); + b.intra_quant_mat[63] == 11 && b.nonintra_quant_mat[63] == 33 && + !memcmp(b.intra_quant_mat, p.intra_matrix, 64) && + !memcmp(b.nonintra_quant_mat, p.nonintra_matrix, 64)); + // The size in whole macroblocks, as Mesa's dec->base for this codec. + Mpeg4Parser big = p; + big.width = 1918; + big.height = 1080; + VcnMpeg4Msg a; + vcnmpeg4_fill_block(&a, &big, &m.pic[2], 3, 1, 2); + expect("mpeg4: the VOL size goes aligned to 16 (1918x1080 as 1920x1088)", + a.video_object_layer_width == 1920 && + a.video_object_layer_height == 1088); + vcnmpeg4_block_mode = 3; + vcnmpeg4_fill_block(&a, &p, &m.pic[2], 3, 1, 2); + expect("mpeg4: block mode 3 is Mesa's block with the whole VOP part", + a.vop.vop_data_present == 1 && a.vop.vop_coding_type == MPEG4_B && + a.vop.vop_quant == 12 && a.vop.vop_coded == 1 && + a.vop.intra_dc_vlc_thr == 5 && a.vop.top_field_first == 1 && + a.vop.vop_fcode_forward == 3 && a.vop.vop_fcode_backward == 4 && + a.vop.TRB[0] == 1 && a.vop.TRB[1] == 1 && a.vop.TRD[0] == 3 && + a.vop.TRD[1] == 3 && a.profile_and_level_indication == 0xF0 && + a.video_object_layer_verid == 5 && + !memcmp(a.intra_quant_mat, b.intra_quant_mat, 64) && + a.decoded_pic_idx == 3 && a.forward_ref_pic_idx == 1 && + a.backward_ref_pic_idx == 2); vcnmpeg4_block_mode = 1; vcnmpeg4_fill_block(&b, &p, &m.pic[2], 3, 1, 2); expect("mpeg4: block with the VOP part filled", diff --git a/GPU/decode/tests/plugintest.c b/GPU/decode/tests/plugintest.c index 16709908..d6a69f54 100644 --- a/GPU/decode/tests/plugintest.c +++ b/GPU/decode/tests/plugintest.c @@ -1,8 +1,9 @@ // plugintest: the VideoToolbox side of a decoder plug-in, with the decoder // session replaced by a stand-in (nothing opens the GPU or the driver). Built -// once for each plug-in, with -DTEST_AV1, -DTEST_VP9, -DTEST_MPEG2, -DTEST_VC1 -// or -DTEST_MPEG4 (the last three share common/vtlegacy.h and have no hidden -// frames: their sample 6 is one more shown frame). It checks: +// once for each plug-in, with -DTEST_AV1, -DTEST_VP9, -DTEST_JPEG, +// -DTEST_MPEG2, -DTEST_VC1 or -DTEST_MPEG4 (the last three share +// common/vtlegacy.h and have no hidden frames: their sample 6 is one more shown +// frame). It checks: // // 1. the factory refuses a NULL result pointer; // 2. a second session start replaces the decoder of the first; @@ -76,6 +77,12 @@ typedef VcnAV1OutputFn OutputFn; #define CREATE VP9VCN_VTDecoder_CreateInstance typedef VcnVP9 Vcn; typedef VcnVP9OutputFn OutputFn; +#elif defined(TEST_JPEG) +#include "../jpeg/JPEGVCNDecoder.c" +#define CODEC kCMVideoCodecType_JPEG +#define CREATE JPEGVCN_VTDecoder_CreateInstance +typedef VcnJpeg Vcn; +typedef VcnJpegOutputFn OutputFn; #elif defined(TEST_MPEG2) || defined(TEST_VC1) || defined(TEST_MPEG4) #define TEST_LEGACY 1 #if defined(TEST_MPEG2) @@ -98,7 +105,7 @@ typedef void Vcn; typedef VcnLegacyOutputFn OutputFn; #else #error \ - "build with -DTEST_AV1, -DTEST_VP9, -DTEST_MPEG2, -DTEST_VC1 or -DTEST_MPEG4" + "build with -DTEST_AV1, -DTEST_VP9, -DTEST_JPEG, -DTEST_MPEG2, -DTEST_VC1 or -DTEST_MPEG4" #endif #undef dispatch_semaphore_wait #undef dispatch_sync @@ -333,7 +340,7 @@ const VcnLegacyCodec FAKE_CODEC = {.name = "stand-in", .last_error = legacy_last_error, .failure = legacy_failure, .firmware_errors = legacy_firmware_errors}; -#else +#elif defined(TEST_VP9) int vcnvp9_gpu_armed; VcnVP9* vcnvp9_create(uint32_t w, uint32_t h, char* err, size_t n) { (void)w, (void)h, (void)err, (void)n; @@ -378,6 +385,50 @@ void vcnvp9_color(VcnVP9* d, VcnColor* c) { (void)d; *c = streamColor; } +#else +int vcnjpeg_gpu_armed; +VcnJpeg* vcnjpeg_create(uint32_t w, uint32_t h, char* err, size_t n) { + (void)w, (void)h, (void)err, (void)n; + return fake_create(); +} +void vcnjpeg_destroy(VcnJpeg* d) { fake_destroy(d); } +bool vcnjpeg_fits(VcnJpeg* d, uint32_t w, uint32_t h) { + (void)d, (void)w, (void)h; + return true; +} +const char* vcnjpeg_last_error(VcnJpeg* d) { + (void)d; + return "stand-in"; +} +unsigned vcnjpeg_firmware_errors(VcnJpeg* d) { + (void)d; + return 0; +} +CFDictionaryRef vcnjpeg_copy_pixel_buffer_attributes(uint32_t w, uint32_t h, + bool t) { + (void)w, (void)h, (void)t; + return CFDictionaryCreate(NULL, NULL, NULL, 0, NULL, NULL); +} +int vcnjpeg_decode(VcnJpeg* d, const uint8_t* chunk, size_t size, int64_t tag, + VcnJpegOutputFn fn, void* ctx) { + (void)size; + fake_decode_begin(d); + if (chunk[0] == 5) slow_decode(); + if (chunk[0] == 1 || chunk[0] == 2 || chunk[0] == 5) + fn(ctx, picture, NULL, 16, 16, tag); + hiddenOnly = chunk[0] == 6; + lastFailure = fake_failure(chunk[0]); + fake_decode_end(); + return (chunk[0] >= 2 && chunk[0] <= 4) || chunk[0] == 7 ? -1 : 0; +} +int vcnjpeg_failure(VcnJpeg* d) { + (void)d; + return lastFailure; +} +CVPixelBufferRef vcnjpeg_hidden_picture(VcnJpeg* d) { + (void)d; + return hiddenOnly ? picture : NULL; +} #endif #if defined(TEST_AV1) @@ -394,13 +445,20 @@ static int fake_failure(uint8_t what) { : what == 7 ? VCNLEGACY_FAIL_REFERENCE : VCNLEGACY_FAIL_STREAM; } -#else +#elif defined(TEST_VP9) static int fake_failure(uint8_t what) { return what == 3 ? VCNVP9_FAIL_DEVICE : what == 4 ? VCNVP9_FAIL_MEMORY : what == 7 ? VCNVP9_FAIL_REFERENCE : VCNVP9_FAIL_STREAM; } +#else +static int fake_failure(uint8_t what) { + return what == 3 ? VCNJPEG_FAIL_DEVICE + : what == 4 ? VCNJPEG_FAIL_MEMORY + : what == 7 ? VCNJPEG_FAIL_REFERENCE + : VCNJPEG_FAIL_STREAM; +} #endif // ---- helpers @@ -445,7 +503,7 @@ static CMVideoFormatDescriptionRef format(CMVideoCodecType codec, return f; } -#if !defined(TEST_LEGACY) +#if defined(TEST_AV1) || defined(TEST_VP9) static VTVideoDecoderRef dec; // Test 16: a format description with colour extensions; NULL values are left // out. @@ -757,7 +815,7 @@ int main(void) { CFRelease(nomem); expect("a new start takes the format again", !dec_start_session(dec, NULL, fmt) && dec_can_accept_format(dec, fmt)); -#if !defined(TEST_LEGACY) +#if defined(TEST_AV1) || defined(TEST_VP9) color_tests(); expect("the session takes the first format again", !dec_start_session(dec, NULL, fmt) && dec_can_accept_format(dec, fmt)); diff --git a/GPU/decode/tests/sessiontest.c b/GPU/decode/tests/sessiontest.c index 98a2d54c..e52d6258 100644 --- a/GPU/decode/tests/sessiontest.c +++ b/GPU/decode/tests/sessiontest.c @@ -35,7 +35,25 @@ // 11. (AV1) a 12-bit sequence header is refused as unsupported (VideoToolbox // then gives the stream to the software decoder); a 10-bit BT.2020 PQ // one is taken, and the session reports its colour and the light level -// of its metadata OBU (vcnav1_color). +// of its metadata OBU (vcnav1_color); +// 12. a system sleep (a made-up sleep mark, standing in for the clocks and +// kern.waketime), 0.3.7: a key frame right after it rebuilds the driver +// objects and decodes on the new ones; an inter frame after it still +// decodes on the old ones, with no error and no frame dropped, and the +// next key frame rebuilds; a second sleep rebuilds again; with no key +// frame the old session decodes on past the drop limit; when the old +// session fails after the wake (ScheduleAVDCommands, a command that does +// not finish within the longer wake limit, a firmware result) it is +// rebuilt at once, the frame is dropped with no error, the frames up to +// the next key frame too, and the key frame decodes; a command that did +// not finish has its accelerator closed on the background queue; with no +// key frame after such a failure the session stops as a device failure +// at the limit; a rebuild that fails stops the session; a session only +// closed after the wake, or stuck when the sleep came, closes quietly on +// the background queue (only AVD_DestroyAVDAccelerator); a new wake time +// alone or a wall clock that ran ahead counts as a sleep, a change of +// the time asleep under 1 ms or both clocks moving together does not; a +// new session opens beside one from before the sleep and decodes. // // usage: sessiontest [clip with hidden frames] // Exit status 0 = pass. @@ -46,6 +64,7 @@ #include #include #include +#include #include #include "vcndriver.h" @@ -110,6 +129,7 @@ static struct { bool useAfterDestroy; // a driver call after the accelerator was destroyed bool deleteCtxOnMain; // DeleteContexts ran on the test's own thread bool gateTimedOut; // DeleteContexts waited at the gate in vain + bool destroyOnMain; // a gated close destroyed on the test's own thread } st; // What it should get wrong. static struct { @@ -121,10 +141,12 @@ static struct { bool hang; // commands never finish unsigned firmware; // result of every finished command bool noDestroy; // the build has no AVD_DestroyAVDAccelerator + bool + rebuildFail; // CreateDriver fails: the rebuild after a sleep cannot open } fault; enum { kFakeBuffer = 1 << 20 }; // larger than any frame of the test clips -typedef struct { +typedef struct FakeDrv { void* va; // +8 holds the VAContext pointer, as the real driver's does void* factory; // what va+75072 points to (VP9 swaps its class pointer) bool poolAllocated; @@ -135,11 +157,16 @@ typedef struct { AVD_Accelerator a; bool destroyed; } FakeAccel; +// The start of every bitstream buffer of the last driver made, to see that +// nothing was written into the pool after a sleep. +static FakeDrv* lastDrv; +static uint8_t poolSnapshot[VCN_NUM_BS][64]; static int f_create_driver(void** out, AVD_DriverCreate* dc) { st.createDrivers++; if (((FakeAccel*)dc->accel)->destroyed) st.useAfterDestroy = true; if (fault.createDriver) return fault.createDriver; + if (fault.rebuildFail) return 7; // the rebuild's own CreateDriver FakeDrv* d = calloc(1, sizeof(*d)); d->va = calloc(1, 75080); d->factory = calloc(1, 16); @@ -153,10 +180,21 @@ static int f_create_driver(void** out, AVD_DriverCreate* dc) { // keep FakeDrv reachable from the handle: raw[0] raw[0] = d; st.liveDrivers++; + lastDrv = d; *out = raw; return 0; } static FakeDrv* drv_of(void* h) { return ((void**)h)[0]; } +static void snapshot_pool(void) { + for (int i = 0; lastDrv && i < VCN_NUM_BS; i++) + if (lastDrv->buffers[i]) memcpy(poolSnapshot[i], lastDrv->buffers[i], 64); +} +static bool pool_untouched(void) { + for (int i = 0; lastDrv && i < VCN_NUM_BS; i++) + if (lastDrv->buffers[i] && memcmp(poolSnapshot[i], lastDrv->buffers[i], 64)) + return false; + return lastDrv != NULL; +} static int f_delete_driver(void* h) { st.deleteDrivers++; st.seqDeleteDriver = ++st.seq; @@ -216,6 +254,17 @@ static int f_delete_ctx(void* h, AVD_DriverContextDelete* del) { } return del->count == 1 && del->contexts[0] ? 0 : 5; } +// What vcn_sleep_mark reports: the test moves it to make a sleep. +static VcnSleepMark fakeSleep = {.asleepNs = 5000000000ull, + .wakeUs = 1795000000000000ll, + .wallUs = 1795000000000000ll}; +static void sleep_for(uint64_t ns) { + fakeSleep.asleepNs += ns; + fakeSleep.wakeUs += 1000000; + // The wall clock counts through a sleep, mach_absolute_time does not. + fakeSleep.wallUs += (int64_t)(ns / 1000); +} + static int f_schedule(void* h, AVD_CmdList* l, AVD_RefConList* r) { (void)h, (void)l; st.schedules++; @@ -276,6 +325,8 @@ static int f_create_accel(AVD_Accelerator** out, AVD_AcceleratorCreate* in, } static int f_destroy_accel(AVD_Accelerator* acc) { st.destroys++; + if (closeGate && pthread_equal(pthread_self(), mainThread)) + st.destroyOnMain = true; st.seqDestroy = ++st.seq; FakeAccel* a = (FakeAccel*)acc; if (a->destroyed) st.useAfterDestroy = true; @@ -299,6 +350,7 @@ bool vcn_driver_uuid(char out[33]) { snprintf(out, 33, "1181E2CA31B33DF090E23AE70552D753"); return true; } +void vcn_sleep_mark(VcnSleepMark* m) { *m = fakeSleep; } bool vcn_driver_load(VcnDriverLib* lib, char* err, size_t errLen) { (void)err, (void)errLen; *lib = (VcnDriverLib){.create = f_create_accel, @@ -340,6 +392,15 @@ static bool released_in_order(void) { } return true; } +// After a rebuild the driver handle from before the sleep is still open: that +// is the leak F4 of the review describes, one per rebuild, left behind on +// purpose because only the driver could free it and it may be wedged. What +// must hold is that every accelerator is closed, and that exactly the dropped +// drivers are left. +static bool closed_after_rebuild(int dropped) { + return st.liveAccels == 0 && st.liveDrivers == dropped && + !st.useAfterDestroy && !st.freeWithoutPool; +} static bool all_released(void) { return st.liveAccels == 0 && st.liveDrivers == 0 && !st.useAfterDestroy && !st.freeWithoutPool; @@ -365,6 +426,23 @@ static bool closed_in_background(Vcn* d) { !st.gateTimedOut; } +// Destroys a session from before a sleep: its close runs on the background +// queue and calls nothing of the driver but AVD_DestroyAVDAccelerator. The +// driver handle it never deleted stays: the made-up driver counts it live. +static bool closed_quietly(Vcn* d) { + int before = st.deleteCtx + st.frees + st.deleteDrivers; + closeGate = dispatch_semaphore_create(0); + DESTROY(d); + // Nothing calls DeleteContexts, so nothing waits at the gate: open it anyway. + dispatch_semaphore_signal(closeGate); + bool drained = vcn_teardown_drain(10000); + if (drained) dispatch_release(closeGate); + closeGate = NULL; + return drained && st.deleteCtx + st.frees + st.deleteDrivers == before && + st.destroys == 1 && st.liveAccels == 0 && !st.useAfterDestroy && + !st.destroyOnMain; +} + // ---- samples split the way FFmpeg sends them typedef struct { uint8_t* data; @@ -372,6 +450,10 @@ typedef struct { } Sample; static Sample clip[64]; static int clipCount; +static void clip_clear(void) { + for (int i = 0; i < clipCount; i++) free(clip[i].data); + clipCount = 0; +} static bool read_clip(const char* path) { FILE* f = fopen(path, "rb"); uint8_t h[32], fh[12]; @@ -676,6 +758,314 @@ int main(int argc, char** argv) { d && rj != 0 && FAILURE(d) == FAIL_STREAM && st.schedules == 0); if (d) DESTROY(d); + // 12. A system sleep, and the rebuild that follows it instead of failing + // every frame (plan B, job 178). + clip_clear(); + bool haveSamples = read_clip(argv[1]); + if (!haveSamples) printf(" the clip did not read for the sleep tests\n"); + bool haveInter = haveSamples && clipCount > 1; + // A second sample only exercises "dropped until a key frame" if it really + // needs references: on a fresh session such a frame fails as a reference + // error, while a second key frame would decode. + bool interUsable = false; // reported below: the tests it gates must run + if (haveInter) { + reset(); + Vcn* probe = make(); +#if defined(TEST_AV1) + // An AV1 frame needs the sequence header of the first sample, and the + // references dropped after it. + if (probe) DECODE(probe, clip[0].data, clip[0].size, 0, on_out, NULL); + if (probe) vcnav1_flush(probe); +#endif + if (probe) DECODE(probe, clip[1].data, clip[1].size, 0, on_out, NULL); + interUsable = probe && FAILURE(probe) == FAIL_REFERENCE; + if (probe) DESTROY(probe); + } + + reset(); + d = make(); + int rb = d ? DECODE(d, frame0, frame0Size, 0, on_out, NULL) : -1; + expect("before the sleep, a frame decodes", d && rb == 0); + int createsBefore12 = st.creates, ctxBefore12 = st.createCtx; + sleep_for(30000000000ull); + int shown12 = 0; + int ra = d ? DECODE(d, frame0, frame0Size, 1, on_out, &shown12) : -1; + printf(" after the sleep: %s\n", d && ra ? LASTERR(d) : "driver rebuilt"); + expect( + "after it, the session rebuilds the driver and decodes the key frame on " + "it, with no error", + d && ra == 0 && shown12 == 1 && st.creates == createsBefore12 + 1 && + st.createCtx == ctxBefore12 + 1); + if (d) DESTROY(d); + expect("and the rebuilt session closes fully, only the dropped driver left", + closed_after_rebuild(1)); + + // Closed after the wake without a frame: still the quiet close of PR 160, + // because no rebuild happened. + reset(); + d = make(); + sleep_for(10000000000ull); + expect("a session only closed after the wake closes quietly", + d && closed_quietly(d) && st.schedules == 0); + + reset(); + d = make(); + fault.hang = true; + int rs12 = d ? DECODE(d, frame0, frame0Size, 0, on_out, NULL) : 0; + sleep_for(10000000000ull); + expect("a session stuck when the sleep came closes the same way", + rs12 != 0 && d && closed_quietly(d)); + + reset(); + d = make(); + fakeSleep.wakeUs += 1000000; // a wake whose time asleep was not counted + int rw = d ? DECODE(d, frame0, frame0Size, 0, on_out, NULL) : -1; + expect("a new wake time alone counts as a sleep, and the session rebuilds", + d && rw == 0 && st.creates == 2); + if (d) DESTROY(d); + + reset(); + d = make(); + fakeSleep.asleepNs += 900000; // 0.9 ms: the reading's error, no sleep + int rj12 = d ? DECODE(d, frame0, frame0Size, 0, on_out, NULL) : -1; + if (d) DESTROY(d); + expect("a change of the time asleep under 1 ms is not a sleep", + rj12 == 0 && st.deleteCtx == 1 && st.creates == 1 && all_released()); + + reset(); + d = make(); + // A machine whose sleep path skipped the kernel's wake accounting: the + // counters do not move, only the wall clock does (the RTC counts through a + // sleep even when the kernel counted none of it). + fakeSleep.wallUs += 30000000; + int rwall = d ? DECODE(d, frame0, frame0Size, 0, on_out, NULL) : -1; + expect("a wall clock that ran ahead of the counters counts as a sleep", + d && rwall == 0 && st.creates == 2); + if (d) DESTROY(d); + fakeSleep.wallUs -= 30000000; + + reset(); + d = make(); + fakeSleep.wallUs += 2000000; // the same two seconds on both clocks + fakeSleep.monoNs += 2000000000ull; + int rboth = d ? DECODE(d, frame0, frame0Size, 0, on_out, NULL) : -1; + if (d) DESTROY(d); + expect("the wall clock and the counters moving together is not a sleep", + rboth == 0 && st.deleteCtx == 1 && st.creates == 1); + fakeSleep.wallUs -= 2000000; + fakeSleep.monoNs -= 2000000000ull; + + expect( + "the clip's second sample needs references (the inter frame tests run)", + interUsable); + if (interUsable) { + // An inter frame after the sleep decodes on the driver objects from before + // it (a real sleep on this Mac did not break them), and the next key frame + // rebuilds them. + reset(); + d = make(); + int k0 = d ? DECODE(d, clip[0].data, clip[0].size, 0, on_out, NULL) : -1; + sleep_for(10000000000ull); + int createsB = st.creates, ctxB = st.createCtx, schedB = st.schedules; + int shownI = 0; + int di = d ? DECODE(d, clip[1].data, clip[1].size, 1, on_out, &shownI) : -1; + if (di) printf(" inter frame after the sleep: %s\n", LASTERR(d)); + expect( + "an inter frame after the sleep decodes on the old session: shown, no " + "error, no rebuild", + d && k0 == 0 && di == 0 && shownI == 1 && st.creates == createsB && + st.schedules == schedB + 1); + int shownK = 0; + int dk = d ? DECODE(d, clip[0].data, clip[0].size, 2, on_out, &shownK) : -1; + if (dk) printf(" key frame after it: %s\n", d ? LASTERR(d) : ""); + expect("the next key frame rebuilds the driver and decodes on the new one", + d && dk == 0 && shownK == 1 && st.creates == createsB + 1 && + st.createCtx == ctxB + 1); + int shownI2 = 0; + int di2 = + d ? DECODE(d, clip[1].data, clip[1].size, 3, on_out, &shownI2) : -1; + expect("an inter frame after the rebuild decodes, no second rebuild", + d && di2 == 0 && shownI2 == 1 && st.creates == createsB + 1); + sleep_for(10000000000ull); + int shownK2 = 0; + int dk2 = + d ? DECODE(d, clip[0].data, clip[0].size, 4, on_out, &shownK2) : -1; + expect("a second sleep: the next key frame rebuilds again", + d && dk2 == 0 && shownK2 == 1 && st.creates == createsB + 2); + if (d) DESTROY(d); + expect("and that session closes, only the two dropped drivers left", + closed_after_rebuild(2)); + + // With no key frame at all, the old session simply decodes on: nothing is + // dropped, past the limit that applies after a failure. + reset(); + d = make(); + if (d) DECODE(d, clip[0].data, clip[0].size, 0, on_out, NULL); + sleep_for(10000000000ull); + int shownN = 0, failedN = 0; + for (int i = 0; d && i < 700; i++) + if (DECODE(d, clip[1].data, clip[1].size, i, on_out, &shownN)) failedN++; + expect( + "with no key frame the old session decodes on: 700 frames shown, no " + "error, no rebuild", + d && failedN == 0 && shownN == 700 && st.creates == 1); + if (d) DESTROY(d); + bool drainedN = vcn_teardown_drain(10000); + expect("and, never rebuilt, it closes quietly: nothing but the accelerator", + drainedN && st.deleteCtx == 0 && st.liveAccels == 0 && + st.liveDrivers == 1); + + // The old session fails after the wake: rebuilt at once, the frame + // dropped with no picture and no error, the frames up to the next key + // frame too, and the key frame decodes on the new driver. + reset(); + d = make(); + if (d) DECODE(d, clip[0].data, clip[0].size, 0, on_out, NULL); + sleep_for(10000000000ull); + fault.schedule = 3; + int shownF = 0; + int df = d ? DECODE(d, clip[1].data, clip[1].size, 1, on_out, &shownF) : -1; + fault.schedule = 0; + if (df) printf(" schedule failure after the sleep: %s\n", LASTERR(d)); + expect( + "a ScheduleAVDCommands failure after the sleep rebuilds at once and " + "drops the frame, with no error", + d && df == 0 && shownF == 0 && st.creates == 2); + int schedF = st.schedules, shownD = 0; + int dd = d ? DECODE(d, clip[1].data, clip[1].size, 2, on_out, &shownD) : -1; + expect("the next inter frame is dropped too, sending nothing", + d && dd == 0 && shownD == 0 && st.schedules == schedF); + int shownFK = 0; + int dfk = + d ? DECODE(d, clip[0].data, clip[0].size, 3, on_out, &shownFK) : -1; + expect("and the key frame decodes on the rebuilt driver", + d && dfk == 0 && shownFK == 1 && st.creates == 2); + if (d) DESTROY(d); + expect("and that session closes fully, only the dropped driver left", + closed_after_rebuild(1)); + + // A command on the old session that does not finish: it is waited for up + // to the wake limit (longer than the usual one), then the session is + // rebuilt and the old accelerator closed on the background queue. + reset(); + d = make(); + if (d) DECODE(d, clip[0].data, clip[0].size, 0, on_out, NULL); + sleep_for(10000000000ull); + vcn_wake_command_timeout_ms = 1500; // above the usual 1000 ms + fault.hang = true; + closeGate = dispatch_semaphore_create(0); // marks a destroy on this thread + int shownH = 0; + double h0 = (double)clock_gettime_nsec_np(CLOCK_UPTIME_RAW) / 1e6; + int dh = d ? DECODE(d, clip[1].data, clip[1].size, 1, on_out, &shownH) : -1; + double waited = (double)clock_gettime_nsec_np(CLOCK_UPTIME_RAW) / 1e6 - h0; + fault.hang = false; + vcn_wake_command_timeout_ms = VCN_WAKE_COMMAND_TIMEOUT_MS; + printf(" waited %.0f ms for the command on the old session\n", waited); + bool drainedH = vcn_teardown_drain(10000); + if (drainedH) dispatch_release(closeGate); + closeGate = NULL; + expect( + "a command on the old session that does not finish is waited for up " + "to the wake limit, not the usual one", + waited >= 1400); + expect( + "then the session is rebuilt, the frame dropped with no error, and the " + "old accelerator closed on the background queue", + d && dh == 0 && shownH == 0 && st.creates == 2 && drainedH && + st.destroys == 1 && !st.destroyOnMain && st.deleteCtx == 0); + int shownHK = 0; + int dhk = + d ? DECODE(d, clip[0].data, clip[0].size, 2, on_out, &shownHK) : -1; + expect("and the key frame decodes on the rebuilt driver", + d && dhk == 0 && shownHK == 1); + if (d) DESTROY(d); + expect("and that session closes fully, only the dropped driver left", + closed_after_rebuild(1)); + + // A firmware result on the old session after the wake: its picture is not + // trusted, the session is rebuilt and the frame dropped. + reset(); + d = make(); + if (d) DECODE(d, clip[0].data, clip[0].size, 0, on_out, NULL); + sleep_for(10000000000ull); + fault.firmware = 6; + int shownW = 0; + int dw = d ? DECODE(d, clip[1].data, clip[1].size, 1, on_out, &shownW) : -1; + fault.firmware = 0; + expect( + "a firmware result on the old session after the sleep rebuilds and " + "drops the frame, with no error", + d && dw == 0 && shownW == 0 && st.creates == 2); + int shownWK = 0; + int dwk = + d ? DECODE(d, clip[0].data, clip[0].size, 2, on_out, &shownWK) : -1; + expect("and the key frame decodes on the rebuilt driver", + d && dwk == 0 && shownWK == 1); + if (d) DESTROY(d); + expect("and that session closes fully, only the dropped driver left", + closed_after_rebuild(1)); + + // A stream that never sends a key frame after such a failure: frames are + // dropped for a while, then the session stops the way PR 160 stopped it. + reset(); + d = make(); + if (d) DECODE(d, clip[0].data, clip[0].size, 0, on_out, NULL); + sleep_for(10000000000ull); + fault.schedule = 3; + int dl = d ? DECODE(d, clip[1].data, clip[1].size, 1, on_out, NULL) : -1; + fault.schedule = 0; + int stopped = 0, iters = 0; + for (; d && dl == 0 && iters < 1000 && !stopped; iters++) + stopped = DECODE(d, clip[1].data, clip[1].size, iters, on_out, NULL) != 0; + expect( + "with no key frame after a failure the frames are dropped up to the " + "limit, then the session stops as a device failure", + d && dl == 0 && stopped && FAILURE(d) == FAIL_DEVICE); + if (d) DESTROY(d); + expect("and it still releases everything, only the dropped driver left", + closed_after_rebuild(1)); + } + + // A rebuild that fails is the case the refusal is left for. + reset(); + d = make(); + if (d) DECODE(d, frame0, frame0Size, 0, on_out, NULL); + sleep_for(10000000000ull); + fault.rebuildFail = true; + int rf = d ? DECODE(d, frame0, frame0Size, 1, on_out, NULL) : 0; + printf(" rebuild failure: %s\n", d ? LASTERR(d) : ""); + fault.rebuildFail = false; + expect("a rebuild that fails stops the session, as PR 160 did", + d && rf != 0 && FAILURE(d) == FAIL_DEVICE); + int rf2 = d ? DECODE(d, frame0, frame0Size, 2, on_out, NULL) : 0; + expect("and later frames fail without opening anything else", + d && rf2 != 0 && st.creates == 2); + if (d) DESTROY(d); + expect("the failed rebuild leaves nothing open, only the dropped driver", + closed_after_rebuild(1)); + + // A new session opens beside one from before the sleep: no process-wide + // refusal any more, each session rebuilds for itself. + reset(); + Vcn* before = make(); + sleep_for(10000000000ull); + int createsB = st.creates; + Vcn* beside = make(); + expect("a new session opens beside one from before the sleep", + before && beside && st.creates == createsB + 1); + int rn = beside ? DECODE(beside, frame0, frame0Size, 0, on_out, NULL) : -1; + expect("and decodes on its own driver", beside && rn == 0); + if (beside) DESTROY(beside); + if (before) closed_quietly(before); + + reset(); + d = make(); + int rn2 = d ? DECODE(d, frame0, frame0Size, 0, on_out, NULL) : -1; + if (d) DESTROY(d); + expect("a session opened after the wake decodes and closes fully", + rn2 == 0 && st.deleteCtx == 1 && st.destroys == 1 && all_released()); + + clip_clear(); if (argc == 3) hidden_frames(argv[2]); free(frame0); diff --git a/GPU/decode/tests/stalelib.c b/GPU/decode/tests/stalelib.c new file mode 100644 index 00000000..8fe65cff --- /dev/null +++ b/GPU/decode/tests/stalelib.c @@ -0,0 +1,81 @@ +// stalelib: one plug-in's copy of common/vcnsession.c with a made-up driver, +// built twice as two libraries for staletest.c. Two copies in one process are +// what two plug-in bundles (VP9 and AV1) are: each has its own list of open +// sessions, and they find each other's sessions from before a sleep through +// the local notification center. Nothing here opens the real driver. +#include +#include + +#include "vcndriver.h" + +#define EXPORT __attribute__((visibility("default"))) + +// The sleep mark comes from the test program, the same for both copies. +static void (*g_mark)(VcnSleepMark*); +void vcn_sleep_mark(VcnSleepMark* m) { + if (g_mark) + g_mark(m); + else + *m = (VcnSleepMark){0}; +} + +static int f_create_driver(void** out, AVD_DriverCreate* dc) { + (void)dc; + *out = calloc(1, 16); + return 0; +} +static int f_delete_driver(void* h) { + free(h); + return 0; +} +static void* g_buffers[VCN_NUM_BS]; +static int f_alloc(void* h, AVD_BitstreamPool* p) { + (void)h; + for (int i = 0; i < VCN_NUM_BS; i++) p->addressesOut[i] = &g_buffers[i]; + return 0; +} +static int f_free(void* h, uint32_t type) { + (void)h, (void)type; + return 0; +} +static int f_delete_ctx(void* h, AVD_DriverContextDelete* del) { + (void)h, (void)del; + return 0; +} +static int g_live; // accelerators made and not destroyed +static int f_create_accel(AVD_Accelerator** out, AVD_AcceleratorCreate* in, + void* info) { + (void)in, (void)info; + AVD_Accelerator* a = calloc(1, sizeof(*a)); + a->fn[AVD_FN_CreateDriver] = (void*)f_create_driver; + a->fn[AVD_FN_DeleteDriver] = (void*)f_delete_driver; + a->fn[AVD_FN_DeleteContexts] = (void*)f_delete_ctx; + a->fn[AVD_FN_AllocateBitstreamBufferPool] = (void*)f_alloc; + a->fn[AVD_FN_FreeBitstreamBufferPool] = (void*)f_free; + g_live++; + *out = a; + return 0; +} +static int f_destroy_accel(AVD_Accelerator* a) { + free(a); + g_live--; + return 0; +} + +EXPORT void stale_set_mark(void (*mark)(VcnSleepMark*)) { g_mark = mark; } + +// Opens a session on a made-up driver; NULL, with err set, when it is refused. +EXPORT VcnDriverSession* stale_open(char* err, size_t errLen) { + VcnDriverSession* s = calloc(1, sizeof(*s)); + VcnDriverLib lib = {.create = f_create_accel, .destroy = f_destroy_accel}; + if (!s || !vcn_session_open(s, &lib, 0, OS_LOG_DEFAULT, err, errLen)) { + free(s); + return NULL; + } + return s; +} +EXPORT void stale_close(VcnDriverSession* s) { + vcn_session_close(s); + free(s); +} +EXPORT int stale_live(void) { return g_live; } diff --git a/GPU/decode/tests/staletest.c b/GPU/decode/tests/staletest.c new file mode 100644 index 00000000..515f58bb --- /dev/null +++ b/GPU/decode/tests/staletest.c @@ -0,0 +1,83 @@ +// staletest: two plug-ins in one process (two copies of common/vcnsession.c, +// libstale-a and libstale-b, built from stalelib.c) with a made-up driver and a +// made-up sleep. A session of one that opened before a sleep and is still open +// is seen by the other plug-in (the local notification center), but it no +// longer stops it from opening one: each session rebuilds for itself after a +// sleep (plan B of the sleep fix). Without a sleep both open side by side. +// +// usage: staletest . Exit status 0 = pass. +#include +#include + +#include "vcndriver.h" + +static VcnSleepMark g_now = {.asleepNs = 1000000000ull, .wakeUs = 1}; +static void mark(VcnSleepMark* m) { *m = g_now; } + +typedef struct { + void (*setMark)(void (*)(VcnSleepMark*)); + VcnDriverSession* (*open)(char*, size_t); + void (*close)(VcnDriverSession*); + int (*live)(void); +} Lib; + +static bool load(const char* path, Lib* l) { + void* h = dlopen(path, RTLD_NOW | RTLD_LOCAL); + if (!h) { + printf("FAIL cannot load %s: %s\n", path, dlerror()); + return false; + } + l->setMark = dlsym(h, "stale_set_mark"); + l->open = dlsym(h, "stale_open"); + l->close = dlsym(h, "stale_close"); + l->live = dlsym(h, "stale_live"); + if (!l->setMark || !l->open || !l->close || !l->live) { + printf("FAIL %s lacks its functions\n", path); + return false; + } + l->setMark(mark); + return true; +} + +static int failures; +static void expect(const char* what, bool ok) { + printf("%s %s\n", ok ? "PASS" : "FAIL", what); + if (!ok) failures++; +} + +int main(int argc, char** argv) { + if (argc != 3) { + fprintf(stderr, "usage: staletest \n"); + return 1; + } + Lib a, b; + if (!load(argv[1], &a) || !load(argv[2], &b)) return 1; + char err[256] = ""; + VcnDriverSession* sa = a.open(err, sizeof(err)); + VcnDriverSession* sb = b.open(err, sizeof(err)); + expect("without a sleep, both plug-ins open a session", sa && sb); + if (sb) b.close(sb); + g_now.asleepNs += 20000000000ull; // a 20 s sleep + g_now.wakeUs += 1; + err[0] = 0; + sb = b.open(err, sizeof(err)); + printf(" refused: %s\n", err); + expect( + "after it, one plug-in's session from before the sleep, still open, no " + "longer stops the other from opening one", + sa && sb && b.live() == 1); + if (sb) b.close(sb); + VcnDriverSession* sa2 = a.open(err, sizeof(err)); + expect("nor the same plug-in from opening another", sa && sa2); + if (sa2) a.close(sa2); + if (sa) a.close(sa); + expect("its close (without the driver's teardown) frees the accelerator", + a.live() == 0); + sb = b.open(err, sizeof(err)); + sa2 = a.open(err, sizeof(err)); + expect("once it is closed, both open sessions again", sb && sa2); + if (sb) b.close(sb); + if (sa2) a.close(sa2); + expect("and close them", a.live() == 0 && b.live() == 0); + return failures ? 1 : 0; +} diff --git a/GPU/decode/vp9/vcnvp9.c b/GPU/decode/vp9/vcnvp9.c index f0c062c2..8c25df3a 100644 --- a/GPU/decode/vp9/vcnvp9.c +++ b/GPU/decode/vp9/vcnvp9.c @@ -26,6 +26,11 @@ int vcnvp9_gpu_armed = 0; #define VCN_MODE_VCN0 \ 4 // VP9 runs on both instances, but AV1 contexts only work on VCN0 #define NUM_DPB 9 +// A session that failed after a sleep is rebuilt and waits for a key frame, +// dropping the frames before it; at 60 fps this is ten seconds of frames. A +// stream that does not send one by then is stopped the way PR 160 stopped it, +// so the host can hand it to another decoder. +#define REBUILD_MAX_DROPPED 600 #define NUM_BS VCN_NUM_BS #define BS_SIZE VCN_BS_SIZE #define FRAME_BYTES 4096 @@ -68,8 +73,16 @@ struct VcnVP9 { bool poolTen; bool stuck; // a command never finished: the GPU may still hold it bool broken; // stuck, or a driver call failed: nothing more goes out - int failure; // VCNVP9_FAIL_* of the last error - bool shown; // the current decode call output a frame + // The system slept since the driver side opened: frames still go to it, and + // it is rebuilt at the next key frame (on_frame). + bool rebuildAtKey; + unsigned keptAfterWake; // frames decoded on it since the sleep was seen + bool needKey; // rebuilt after a failure: drop frames until a key frame + unsigned dropped; // frames dropped since that rebuild + unsigned rebuilds; // driver objects rebuilt in this session (one per sleep) + uint32_t lastFw; // firmware result of the last command that finished + int failure; // VCNVP9_FAIL_* of the last error + bool shown; // the current decode call output a frame CVPixelBufferRef hidden; // retained: last frame it decoded without showing unsigned fwErrors; // decodes the firmware reported as failed unsigned done; // decode commands that finished @@ -96,6 +109,9 @@ static const char* const kValidatedDrivers[] = { "8D3BA61E7BC73BDFADB3A7866360B6DE", // macOS 26.7.1 (25G241) "1181E2CA31B33DF090E23AE70552D753", // macOS 26.7.2 (25G332) and 26.7.3 // (25G342, same binary) + "F7D8F5849EC139DB857C769697294957", // macOS 26.7.4 (25G422): same code + // as 26.7.3 (2760/2760 functions + // identical, only a build path) }; static bool being_traced(void) { struct kinfo_proc info; @@ -522,6 +538,78 @@ static CVPixelBufferRef new_target(VcnVP9* d, uint32_t w, uint32_t h, return pb; } +// One VP9 context on the driver handle this session has open: what a create and +// a rebuild after a sleep both need. The factory's class pointer is swapped +// only for the length of CreateContexts, as it always was. +static int vp9_create_context(VcnVP9* d, char* err, size_t errLen) { + AVD_ContextList list = {0}; + void* ctxOut[2] = {0}; + AVD_FunctionInfo* fis[1] = {&list.inlineInfo}; + list.count = 1; + list.functions = fis; + list.contextsOut = ctxOut; + list.inlineInfo = (AVD_FunctionInfo){.kind = 1, + .function = AVD_FUNC_AV1, + .mode = VCN_MODE_VCN0, + .pixelRate = d->maxW * d->maxH * 60, + .width = d->maxW, + .height = d->maxH, + .inFormat = 0x72617762, + .inFormatCount = 1, + .outFormat = 0x4e563132, + .outFormatCount = 1}; + AVD_DriverContextInit ci = {.list = &list}; + // Swap the vtable pointer on this driver's factory, only for the length of + // CreateContexts. + static pthread_mutex_t create_lock = PTHREAD_MUTEX_INITIALIZER; + // The wrapped copy of the factory's class vtable. Built once, under + // create_lock, before any factory points at it: threads of other sessions + // may read it at any time once it is published, so it never changes again. + static void* factoryVt[FACTORY_SLOTS + 2]; + static void** factoryOrigVt; + // driver+8 is the VAContext, VAContext+75072 its VAFactory (avd.h, + // AVD_CreateDriver_fn). Each is checked before it is read through: a NULL + // fails the start like any other step instead of a read at a small address. + uint8_t* va = PTR(d->s.drv, 8); + if (!va) { + snprintf(err, errLen, "no VAContext"); + return 1; + } + void*** factory = (void***)PTR(va, 75072); + if (!factory || !*factory) { + snprintf(err, errLen, "no factory"); + return 1; + } + vcnvp9_dryrun_checkpoint(1); + pthread_mutex_lock(&create_lock); + void** origFactoryVt = *factory; + if (!factoryOrigVt) { + memcpy(factoryVt, origFactoryVt - 2, sizeof(factoryVt)); + g_orig_create_processor = + (void* (*)(void*, int, void*))origFactoryVt[FACTORY_CREATE_PROCESSOR]; + factoryVt[2 + FACTORY_CREATE_PROCESSOR] = (void*)hook_create_processor; + factoryOrigVt = origFactoryVt; + } + if (origFactoryVt != factoryOrigVt) { + pthread_mutex_unlock(&create_lock); + snprintf(err, errLen, "the driver's factory class changed (%p, was %p)", + (void*)origFactoryVt, (void*)factoryOrigVt); + return 1; + } + __atomic_store_n(factory, &factoryVt[2], __ATOMIC_RELEASE); + t_creating = 1; + int r = FN(CreateContexts)(d->s.drv, &ci); + t_creating = 0; + __atomic_store_n(factory, origFactoryVt, __ATOMIC_RELEASE); + pthread_mutex_unlock(&create_lock); + if (r || !ctxOut[0]) { + snprintf(err, errLen, "CreateContexts %d", r); + return 1; + } + d->s.ctx = ctxOut[0]; + return 0; +} + VcnVP9* vcnvp9_create(uint32_t maxWidth, uint32_t maxHeight, char* err, size_t errLen) { #define FAIL(...) \ @@ -580,66 +668,132 @@ VcnVP9* vcnvp9_create(uint32_t maxWidth, uint32_t maxHeight, char* err, // included. if (!vcn_session_open(&d->s, &lib, svc, vlog(), why, sizeof(why))) FAIL("%s", why); - AVD_ContextList list = {0}; - void* ctxOut[2] = {0}; - AVD_FunctionInfo* fis[1] = {&list.inlineInfo}; - list.count = 1; - list.functions = fis; - list.contextsOut = ctxOut; - list.inlineInfo = (AVD_FunctionInfo){.kind = 1, - .function = AVD_FUNC_AV1, - .mode = VCN_MODE_VCN0, - .pixelRate = maxWidth * maxHeight * 60, - .width = maxWidth, - .height = maxHeight, - .inFormat = 0x72617762, - .inFormatCount = 1, - .outFormat = 0x4e563132, - .outFormatCount = 1}; - AVD_DriverContextInit ci = {.list = &list}; - // Swap the vtable pointer on this driver's factory, only for the length of - // CreateContexts. - static pthread_mutex_t create_lock = PTHREAD_MUTEX_INITIALIZER; - // The wrapped copy of the factory's class vtable. Built once, under - // create_lock, before any factory points at it: threads of other sessions - // may read it at any time once it is published, so it never changes again. - static void* factoryVt[FACTORY_SLOTS + 2]; - static void** factoryOrigVt; - // driver+8 is the VAContext, VAContext+75072 its VAFactory (avd.h, - // AVD_CreateDriver_fn). Each is checked before it is read through: a NULL - // fails the start like any other step instead of a read at a small address. - uint8_t* va = PTR(d->s.drv, 8); - if (!va) FAIL("no VAContext"); - void*** factory = (void***)PTR(va, 75072); - if (!factory || !*factory) FAIL("no factory"); - vcnvp9_dryrun_checkpoint(1); - pthread_mutex_lock(&create_lock); - void** origFactoryVt = *factory; - if (!factoryOrigVt) { - memcpy(factoryVt, origFactoryVt - 2, sizeof(factoryVt)); - g_orig_create_processor = - (void* (*)(void*, int, void*))origFactoryVt[FACTORY_CREATE_PROCESSOR]; - factoryVt[2 + FACTORY_CREATE_PROCESSOR] = (void*)hook_create_processor; - factoryOrigVt = origFactoryVt; - } - if (origFactoryVt != factoryOrigVt) { - pthread_mutex_unlock(&create_lock); - FAIL("the driver's factory class changed (%p, was %p)", - (void*)origFactoryVt, (void*)factoryOrigVt); - } - __atomic_store_n(factory, &factoryVt[2], __ATOMIC_RELEASE); - t_creating = 1; - int r = FN(CreateContexts)(d->s.drv, &ci); - t_creating = 0; - __atomic_store_n(factory, origFactoryVt, __ATOMIC_RELEASE); - pthread_mutex_unlock(&create_lock); - if (r || !ctxOut[0]) FAIL("CreateContexts %d", r); - d->s.ctx = ctxOut[0]; + if (vp9_create_context(d, why, sizeof(why))) FAIL("%s", why); DBG("created: driver %s session=%s drv=%p ctx=%p\n", lib.uuid, sess, d->s.drv, d->s.ctx); return d; } +// Rebuilds the driver side of a session the system slept through: the objects +// from before the sleep are dropped without a word to the driver, and a fresh +// accelerator, driver, context and bitstream pool are opened for the same +// plug-in session, so the host's decoder object lives on. The references live +// in the old driver's DPB and the probability contexts in its context, so the +// pictures and the reference slots go; the parser keeps the header being +// decoded. busy: the old session's last command may still be on the GPU, so +// its accelerator is closed on the teardown queue and the pictures are let go +// only after that. False when the rebuild fails: the caller then stops the +// session as PR 160 did. +static bool vp9_rebuild(VcnVP9* d, bool busy, char* why, size_t whyLen) { + CVPixelBufferRef old[NUM_DPB + 1]; + int n = 0; + for (int i = 0; i < NUM_DPB; i++) + if (d->dpb[i]) { + old[n++] = d->dpb[i]; + d->dpb[i] = NULL; + } + if (d->hidden) { // its own reference to one of them + old[n++] = d->hidden; + d->hidden = NULL; + } + if (busy) { + // Without memory for the list the pictures are never let go: a command + // still on the GPU may write into them. + CVPixelBufferRef* keep = n ? malloc((size_t)n * sizeof(*keep)) : NULL; + if (keep) memcpy(keep, old, (size_t)n * sizeof(*keep)); + int kept = keep ? n : 0; + vcn_session_drop_later(&d->s, "VP9 session from before the sleep", ^{ + for (int i = 0; i < kept; i++) CVPixelBufferRelease(keep[i]); + free(keep); + }); + } else { + vcn_session_drop(&d->s); + for (int i = 0; i < n; i++) CVPixelBufferRelease(old[i]); + } + memset(d->dpbRefs, 0, sizeof(d->dpbRefs)); + for (size_t i = 0; i < sizeof(d->parser.ref) / sizeof(d->parser.ref[0]); + i++) { + d->parser.ref[i].valid = 0; + d->parser.ref[i].dpb_slot = -1; + } + d->bsNext = 0; + VcnDriverLib lib; + if (!vcn_driver_load(&lib, why, whyLen)) return false; + bool validated = false; + for (size_t i = 0; i < sizeof(kValidatedDrivers) / sizeof(*kValidatedDrivers); + i++) + if (!strcmp(lib.uuid, kValidatedDrivers[i])) validated = true; + if (!validated) { + snprintf(why, whyLen, "AMDRadeonVADriver2 build %s not validated for VP9", + lib.uuid); + return false; + } + io_service_t svc = vcn_find_accelerator(); + if (!svc) { + snprintf(why, whyLen, "no AMD accelerator"); + return false; + } + if (!vcn_session_reopen(&d->s, &lib, svc, vlog(), why, whyLen)) return false; + if (vp9_create_context(d, why, whyLen)) { + vcn_session_drop(&d->s); + return false; + } + d->rebuilds++; + return true; +} + +// Rebuilds now (vp9_rebuild) and leaves the session decoding on the new driver; +// dropUntilKey: the frames before the next key frame are dropped. False, with +// the session stopped as a device failure, when the rebuild fails. +static bool rebuild_now(VcnVP9* d, bool busy, bool dropUntilKey, + const char* cause) { + char why[200]; + unsigned kept = d->keptAfterWake; + if (!vp9_rebuild(d, busy, why, sizeof(why))) { + d->rebuildAtKey = false; + d->broken = true; + d->failure = VCNVP9_FAIL_DEVICE; + snprintf(d->err, sizeof(d->err), + "session stopped: the system slept since it opened and the " + "rebuild failed (%s)", + why); + return false; + } + // What these said was about the old driver objects. + d->rebuildAtKey = false; + d->stuck = d->broken = false; + d->keptAfterWake = 0; + d->needKey = dropUntilKey; + d->dropped = 0; + if (dropUntilKey) + os_log_error( + vlog(), + "the session from before the sleep failed after the wake " + "(%{public}s, %u frames decoded on it before): driver rebuilt, " + "frames are dropped until the next key frame", + cause, kept); + else + os_log_error(vlog(), + "driver rebuilt at the first key frame after the sleep (%u " + "frames decoded on the session from before it), no frame " + "dropped", + kept); + return true; +} + +// The session from before the sleep failed on the frame being decoded: it is +// rebuilt at once and this frame is dropped, like the ones after it until a +// key frame. 0, or -1 when the rebuild fails. +static int failed_after_wake(VcnVP9* d, bool busy) { + char cause[256]; + snprintf(cause, sizeof(cause), "%s", d->err); + if (!rebuild_now(d, busy, true, cause)) return -1; + d->err[0] = 0; + d->failure = VCNVP9_FAIL_STREAM; + d->dropped = 1; + return 0; +} + static void destroy_now(VcnVP9* d) { vcn_session_close(&d->s); // The pictures go after the driver: a stuck command may still write one. @@ -655,7 +809,7 @@ static void destroy_now(VcnVP9* d) { void vcnvp9_destroy(VcnVP9* d) { if (!d) return; - vcn_teardown(d->stuck, vlog(), "VP9 session", ^{ + vcn_teardown(d->stuck, vcn_session_lost(&d->s), vlog(), "VP9 session", ^{ destroy_now(d); }); } @@ -709,16 +863,18 @@ static int submit(VcnVP9* d, VP9Params* prm) { } uint32_t fw = 0; int ds = 0; - VcnWaitResult w = - vcn_wait_command(FN(QueryAVDCommandStatus), d->s.drv, refcons[0], - VCN_COMMAND_TIMEOUT_MS, &fw, &ds); + // Longer on the session from before a sleep: right after a wake the driver + // can take seconds before a command runs (vcndriver.h). + unsigned limit = + d->rebuildAtKey ? vcn_wake_command_timeout_ms : VCN_COMMAND_TIMEOUT_MS; + VcnWaitResult w = vcn_wait_command(FN(QueryAVDCommandStatus), d->s.drv, + refcons[0], limit, &fw, &ds); if (w == VCN_WAIT_TIMEOUT) { // The GPU still holds this command. Sending more work, or reading the // target, could only make things worse: the session stops here. d->stuck = d->broken = true; snprintf(d->err, sizeof(d->err), - "the GPU did not finish a frame in %d ms; session stopped", - VCN_COMMAND_TIMEOUT_MS); + "the GPU did not finish a frame in %u ms; session stopped", limit); return -1; } if (w != VCN_WAIT_DONE) { @@ -730,6 +886,7 @@ static int submit(VcnVP9* d, VP9Params* prm) { } d->failure = VCNVP9_FAIL_STREAM; d->done++; + d->lastFw = fw; // Counted, not refused: the VP9 result goes through the AV1 processor's // status reader, and what it reports for VP9 has not been checked on a GPU. // The first one of a session is logged at once, the count goes in the stats @@ -746,6 +903,45 @@ static int on_frame(void* vctx, VP9Parser* p, VP9ParseResult kind, const uint8_t* data, size_t size) { VcnVP9* d = vctx; const VP9Frame* h = &p->fh; + // A frame after which nothing decoded before it is used: a key frame + // (refreshes every slot and resets the four probability contexts), or an + // intra-only frame that does both (all eight slots refreshed, and + // error_res or reset_frame_context 3). Another intra-only frame keeps + // slots or contexts the frames after it may use, which live in the old + // driver's DPB and context. + bool restart = + kind == VP9_PARSE_DECODE && + (h->frame_type == 0 || (h->intra_only && h->refresh_frame_flags == 0xff && + (h->error_res || h->reset_frame_context == 3))); + // The system slept since the driver side opened, and it kept decoding (a + // real sleep on this Mac did not break it): it is replaced at the first such + // frame, which then decodes on the new one. + if (d->rebuildAtKey && restart && !rebuild_now(d, false, false, NULL)) + return -1; + // After a rebuild that followed a failure nothing from before it can be + // used: every frame but such a key frame is dropped, with no picture and no + // error, and the key frame starts the decoder again. Bounded: a stream that + // never sends one is stopped as a device failure, PR 160's behaviour. + if (d->needKey) { + if (!restart) { + if (++d->dropped > REBUILD_MAX_DROPPED) { + d->broken = true; + d->failure = VCNVP9_FAIL_DEVICE; + snprintf(d->err, sizeof(d->err), + "no key frame in %u frames after the system sleep", + d->dropped); + return -1; + } + return 0; + } + for (size_t i = 0; i < sizeof(p->ref) / sizeof(p->ref[0]); i++) { + p->ref[i].valid = 0; + p->ref[i].dpb_slot = -1; + } + memset(d->dpbRefs, 0, sizeof(d->dpbRefs)); + d->needKey = false; + d->dropped = 0; + } if (kind == VP9_PARSE_SHOW_EXISTING) { const VP9Ref* r = &p->ref[h->frame_to_show]; if (!r->valid || r->dpb_slot < 0 || r->dpb_slot >= NUM_DPB || @@ -845,7 +1041,18 @@ static int on_frame(void* vctx, VP9Parser* p, VP9ParseResult kind, "refresh=%02x\n", h->frame_type, h->intra_only, h->show_frame, h->width, h->height, h->bit_depth, h->base_q_idx, size, slot, h->refresh_frame_flags); - if (submit(d, &prm)) return -1; + if (submit(d, &prm)) + // On the session from before a sleep, a driver failure is taken for the + // sleep's doing: rebuilt at once, instead of stopping the session. + return d->rebuildAtKey && d->broken ? failed_after_wake(d, d->stuck) : -1; + if (d->rebuildAtKey) { + if (d->lastFw) { + // A firmware error on it after the wake: its picture is not trusted. + snprintf(d->err, sizeof(d->err), "firmware result %u", d->lastFw); + return failed_after_wake(d, false); + } + d->keptAfterWake++; + } vp9_frame_done(p, slot); recount_refs(d); if (h->show_frame) { @@ -870,6 +1077,15 @@ int vcnvp9_decode(VcnVP9* d, const uint8_t* chunk, size_t size, int64_t tag, CVPixelBufferRelease(d->hidden); d->hidden = NULL; } + // A sleep since the driver side opened: it keeps decoding, and on_frame + // rebuilds it at the next key frame (or at once if it fails). + if (!d->broken && !d->rebuildAtKey && vcn_session_lost(&d->s)) { + d->rebuildAtKey = true; + d->keptAfterWake = 0; + os_log_error(vlog(), + "VP9 session from before the sleep: it keeps decoding and is " + "rebuilt at the next key frame"); + } if (d->broken) { snprintf(d->err, sizeof(d->err), "session stopped: %s", d->stuck ? "the GPU did not finish an earlier frame" diff --git a/GPU/docs/how-it-works.md b/GPU/docs/how-it-works.md index 146523a7..4ff87d83 100644 --- a/GPU/docs/how-it-works.md +++ b/GPU/docs/how-it-works.md @@ -145,6 +145,70 @@ ends. A failed driver call or a stuck command is reported to VideoToolbox as a m `canAcceptFormatDescription` says no from then on. It reads the format under a lock of its own, so it never waits for a frame the GPU is decoding. +### A system sleep (0.3.7) + +Apple's kernel driver keeps a decoder's video context across a sleep, but restarts the +video engine under it. Read in IDA (AMDRadeonX6000, 26.7.3 KDK): `systemWillSleep` calls +each video context's `setSuspendResumeState(false)`, which waits for the last command of +every VCN ring and then stops the rings; `saveVCNSession`, called on the way down, is +empty. At wake, `powerUpHW` and `internalDidWake` start the rings again, and +`restoreVCNSession` only sends the context's clocks and power client again. Nothing tells +the program: AMDRadeonVADriver2, AppleGVA and VideoToolbox have no sleep handling at all. + +What that does to a session was measured on this Mac (RX 6800 XT, 26.7.3, 2026-11-25): with +0.3.5 the sessions open across a real sleep kept decoding after the wake, every frame +matching its reference; one frame of each decode took about 10 s around the wake, inside +Apple's calls. A reporter on another machine (RX 6900 XT, Sequoia) saw broken pictures and +a hang after a wake, which was not reproduced here. + +So an AV1 or VP9 session from before a sleep keeps decoding (`vcn_session_lost` in +`decode/common/vcnsession.c` only notices the sleep), and its driver objects are replaced at +its next key frame, where nothing decoded before is needed any more (`rebuild_now` in +`vcnav1.c` and `vcnvp9.c`): an AV1 key frame that refreshes all eight reference slots, a VP9 +key frame, or a VP9 intra-only frame that refreshes all eight and resets all four +probability contexts. The old accelerator is closed with `AVD_DestroyAVDAccelerator` only, +a new accelerator, driver, context and bitstream pool are opened in the same plug-in +session, and the key frame decodes on them; no frame is dropped. If the old session fails +after the wake (a driver call fails, a command does not finish, or the firmware reports an +error), it is replaced at once and the frames up to the next such key frame are dropped: +noErr with no picture, as for a hidden frame, at most 600 of them, then a malfunction +(-12911). A command that did not finish has its accelerator closed on the background +queue, and its pictures are let go after that. Until the replacement, a command on the old +session may take 15 s instead of 1 s. A replacement that fails stops the session with +-12911, and VideoToolbox makes a new decoder. + +A sleep is seen without any notification: the time the Mac has spent asleep +(`mach_continuous_time` minus `mach_absolute_time`), the time of the last wake +(`kern.waketime`), or a wall clock that ran ahead of `mach_absolute_time` changed since the +session opened. A notification could not be used anyway: VideoToolbox's decoder service +runs in a sandbox (`VTDecoderSandboxProfile.sb`) that does not allow the power domain's user +client `IORegisterForSystemPower` opens. + +Closing a session from before a sleep that was never replaced skips `DeleteContexts`, +`FreeBitstreamBufferPool` and `DeleteDriver`: the first sends the engine a destroy-session +command and waits for it with no time limit, and `DeleteDriver` does the same for a context +still open. Only `AVD_DestroyAVDAccelerator` runs, on the background queue: it closes the +three IOKit connections, and the kernel's own close of the video context sends the engine +nothing (`submitDestroyCommand` returns at once). What the driver allocated in the process +(its handle, context and bitstream pool) stays until the process ends, once per replacement +or such close. + +New sessions open while one from before a sleep is still open; the plug-ins only count those +for the log, through the process's local notification center +(`CFNotificationCenterGetLocalCenter`, which calls every observer on the posting thread), +because each plug-in bundle has its own copy of the session code. The MPEG-2, VC-1 and +MPEG-4 decoders (`vcnlegacy.c`) do not replace their sessions: one from before a sleep +fails its pictures as a malfunction, as in 0.3.6. + +What still waits with no limit the plug-in can set is inside Apple's code: the driver calls +themselves (`ScheduleAVDCommands`, `QueryAVDCommandStatus`, `CreateAVDAccelerator`, +`CreateDriver`, `AllocateBitstreamBufferPool`, `CreateContexts`, +`AVD_DestroyAVDAccelerator`, and in a normal close `DeleteContexts` and `DeleteDriver`), +the pixel buffer pool, and the kernel's own wait for the last command before a sleep. The +plug-in's VideoToolbox side waits for its own decode queue (a free queue slot, the queued +frames on finish and invalidate, the decode lock on invalidate); those waits end when the +frame being decoded ends, so they too wait as long as a driver call does. + ### The parsers The engine decodes the tile data; the host must read the headers. Each decoder has its own diff --git a/GPU/docs/macos-updates.md b/GPU/docs/macos-updates.md index 4b049e42..83ae09fa 100644 --- a/GPU/docs/macos-updates.md +++ b/GPU/docs/macos-updates.md @@ -17,6 +17,7 @@ the parts installed. The second part is for whoever adds support for a new build | VCNVTLoader | your OpenCore EFI | Still there. It acts only if AMFI's function starts as it expects | | Encoding fix | the service in `/usr/local/libexec` and `/Library/LaunchDaemons`, the kext on your EFI | Still there. Both halves stay off on a build they were not validated for | | GPU sensors | your OpenCore EFI | Still there. It acts only if the driver's function starts as it expects | +| JPEG decoder (optional) | the kext on your EFI, the plug-in on the system volume | The plug-in is gone like the decoders. The kext stays off: it knows 26.7.3 (25G342) only | **The decoders are lost.** `install/decoders.sh install` put them into a changed copy of the system volume and booted from a new snapshot of it. A macOS update writes a new system @@ -273,6 +274,20 @@ driver, the fine points in that of 26.7.3 ([sensors/README.md](../sensors/README After booting a new build, `sensors/build/gpusensors --compare` must show the same values as macOS for the readings both publish (see [testing.md](testing.md)). +### VCNJpeg + +The kext knows one build: `jpeg/kext/hwlibs_expect.hpp` holds the LC_UUID of +`AMDRadeonX6000HWLibs` and `AMDRadeonX6000` of 26.7.3, and the offset and first 16 bytes of +the 20 functions it calls or routes. `jpeg/kext/jpeg_layout.hpp` holds the offsets it reads +inside the driver's objects. On another build it stays off (`off: AMDRadeonX6000HWLibs +build not validated`), and the JPEG plug-in finds no decoder, so VideoToolbox uses Apple's. + +Adding a build means reading the code that uses each function and offset again in that +build's KDK (or kernel collection), regenerating the table with `jpeg/tools/gen_expect.py`, +and a run of `decode/tests/gpu/vtjpegtest` on a card. Until then its `jpeg` value in +`install/validated-builds.json` stays `false` (`install/check_lists.sh` refuses anything +else for a build the table does not name). + ### A new macOS version The version limits are in each kext's `PluginConfiguration` (`kern_start.cpp`): diff --git a/GPU/docs/status.md b/GPU/docs/status.md index 86f304a1..5926fc64 100644 --- a/GPU/docs/status.md +++ b/GPU/docs/status.md @@ -15,6 +15,7 @@ running on a GPU: compared in a disassembler, run on the CPU, or tested with fil | AV1 vectors and playback | pass | 0.1 | RX 6900 XT, Sequoia 15.8.2 (Izzy) | | VP9 check clip (640x360, 30 frames) | 0 mismatches | 0.2 | RX 6900 XT, Sequoia 15.8.2 (Izzy) | | Driver of 15.8.3 and 26.7.3 | same binary (same UUID) as 15.8.2 and 26.7.2 | static | | +| Driver of 26.7.4 (25G422) | new UUID `F7D8F5849EC139DB857C769697294957`, read from the installer's cryptex (`rawpatch`) before updating: all 2760 functions identical to 26.7.3 (`dscdiff.py diff`), every section identical except one Apple build path in `__cstring`; listed as `untested-on-gpu` | static | macOS 26.7.4 RC, 2026-11-24 | | Parser reads the public test streams as 0.2 did | identical digests | 0.3.0 | static, `tests/run.sh` | | Parser on damaged input, under sanitizers | no finding in 14100 damaged copies of 47 local streams, and 4500 of the 15 public ones in `tests/run.sh` | 0.3.0 | static | | Only AMD's accelerator is taken | rule tested; on a Mac with no iGPU the choice is the same as 0.2 | 0.3.0 | static, RX 6800 XT | diff --git a/GPU/docs/testing.md b/GPU/docs/testing.md index 7ffb7ada..aa66c24a 100644 --- a/GPU/docs/testing.md +++ b/GPU/docs/testing.md @@ -63,6 +63,10 @@ them, when, on which card and macOS build, and add the result to `docs/status.md - Decoding against references, in a test process, without installing anything: see `decode/tests/gpu/README.md`. +- JPEG, after the reboot that starts `VCNJpeg.kext`: `install/jpeg.sh check` must end in + "working"; `decode/tests/gpu/vtjpegtest` on 4:2:0, 4:2:2 and `dmb1` clips must match + FFmpeg within 2; `ioreg -rd1 -c IOResources | grep VCNJpeg` must show `Powered` = Yes + while it decodes and No two seconds later, and `Jobs` going up. - Encoding: `test.sh` (two short encodes with reference numbers, three with `--wide`) and `doctor.sh`, run from the built package folder `encode/dist/VCNEncodeFix-` (the copies in `encode/scripts` look for `bin/vtenc` next to themselves). Close any video @@ -109,4 +113,14 @@ them, when, on which card and macOS build, and add the result to `docs/status.md leaves no context to delete, and `QueryAVDCommandStatus` with `.wait = 0` returns at once (status 1 done, 2 running). Still open: how long the kernel's own wait can last after a GPU restart. +- Decoders 0.3.7, a system sleep during a decode: `vtvp9test` and `vtav1test` with + `-loop N -pace 30` keep one session going across `pmset sleepnow`, and `-renew` makes a + new session for every pass in the same process. No pass may have errors or frames that + differ from the reference, before or after the wake, and the kernel log must show no GPU + restart and no hang. The plug-ins log "the system slept since this session opened", then + "keeps decoding and is rebuilt at the next key frame" and "driver rebuilt at the first key + frame after the sleep"; "failed after the wake" means the old session failed and frames + were dropped up to a key frame. A first real run of 0.3.6 on this Mac (2026-11-25) failed + every frame of the old sessions; 0.3.5 passed. Only `sessiontest` and `staletest` (made-up + driver and sleep) have run for 0.3.7. - Everything at once: `install/check.sh` ends in one line. diff --git a/GPU/encode/CHANGELOG.md b/GPU/encode/CHANGELOG.md index c94c7639..c2628b00 100644 --- a/GPU/encode/CHANGELOG.md +++ b/GPU/encode/CHANGELOG.md @@ -1,6 +1,18 @@ # Changelog -## 1.3.0 (not released) +## macOS 26.7.4 (25G422) (RyzenStatus 1.90.0) + +- Kext: 26.7.4 added to `kX6000Builds` (`F8070234-57B0-3107-AC79-F3AA1C816072`) and + `kX6800Builds` (`C3C1D191-CC3D-38F3-BBBE-2F99B74FE0F1`), routed by symbol: + `_PEM_CWDDEPM_PMRequest` is still exported, and its Hex-Rays output is identical to 26.7.3's. +- Service: 26.7.4 added to `kPresetBuilds` and `kHevc10Builds` (`AMDRadeonVADriver2` + `F7D8F584-9EC1-39DB-857C-769697294957`, same code as 26.7.3; each site found once) and to + `kWideBuilds` (`AppleGVAHEVCEncoder` `01F6B94A-A77D-3549-B18B-CBA81F4630B3`: `__TEXT` and + `__DATA` byte-identical to 26.7.3, site `0x13601`, cave `0xE78`). The wide patch's CPU test + now runs at the 26.7.4 site too. +- Checked from the 26.7.4 installer (release candidate) only; not run on a card on 26.7.4. + +## 1.3.0 (RyzenStatus 1.90.0) - New service fix, *cc* (on by default; `--no-cc` turns it off), in every `ContinuityCaptureAgent` and `avconferenced`, the processes that handle Continuity Camera and FaceTime calls. Three changes in VideoProcessing: diff --git a/GPU/encode/kext/kern_start.cpp b/GPU/encode/kext/kern_start.cpp index c047cf43..5a53bdc3 100644 --- a/GPU/encode/kext/kern_start.cpp +++ b/GPU/encode/kext/kern_start.cpp @@ -94,6 +94,11 @@ struct HWLibsBuild { uint8_t prologue[32]; // the function's first bytes when routed by offset }; static const HWLibsBuild kX6000Builds[]{ + {"26.7.4 (25G422)", + {0xf8, 0x07, 0x02, 0x34, 0x57, 0xb0, 0x31, 0x07, 0xac, 0x79, 0xf3, 0xaa, + 0x1c, 0x81, 0x60, 0x72}, + 0, + {}}, {"26.7.3 (25G342)", {0x5c, 0xd4, 0xbc, 0x0c, 0xc2, 0x25, 0x36, 0x5f, 0xa8, 0x72, 0xc8, 0x85, 0x57, 0x5b, 0x9a, 0x19}, @@ -113,6 +118,11 @@ static const HWLibsBuild kX6000Builds[]{ 0xd6, 0x49, 0x89, 0xf7, 0x49, 0x89, 0xfc, 0x48, 0x89, 0x7d}}, }; static const HWLibsBuild kX6800Builds[]{ + {"26.7.4 (25G422)", + {0xc3, 0xc1, 0xd1, 0x91, 0xcc, 0x3d, 0x38, 0xf3, 0xbb, 0xbe, 0x2f, 0x99, + 0xb7, 0x4f, 0xe0, 0xf1}, + 0, + {}}, {"26.7.3 (25G342)", {0x27, 0x7b, 0x80, 0x59, 0x8c, 0x8e, 0x3a, 0x34, 0x8b, 0x72, 0x19, 0x4a, 0xe9, 0x37, 0xaa, 0xe1}, diff --git a/GPU/encode/scripts/install.sh b/GPU/encode/scripts/install.sh index f81107be..75a147bc 100755 --- a/GPU/encode/scripts/install.sh +++ b/GPU/encode/scripts/install.sh @@ -25,6 +25,23 @@ say() { print -r -- "$@"; } die() { print -r -- "error: $*" >&2; exit 1; } step() { print -r -- ""; print -r -- "== $*"; } plist_value() { /usr/libexec/PlistBuddy -c "Print :$2" "$1" 2>/dev/null; } # plist key +# The service runs as root from /usr/local/libexec. Refuse a folder another user could change. +libexec_unsafe() { + local d=$1 owner mode + while [[ $d != / ]]; do + if [[ -e $d || -L $d ]]; then + [[ -d $d && ! -L $d ]] || { print -r -- "$d is not a folder"; return 0; } + owner=$(/usr/bin/stat -f '%Su' "$d") + mode=$(/usr/bin/stat -f '%Lp' "$d") + [[ $owner == root ]] || { print -r -- "$d belongs to $owner, not root"; return 0; } + (( (8#$mode & 8#022) == 0 )) || { print -r -- "$d can be written by others than root (mode $mode)"; return 0; } + [[ $(/bin/ls -lde "$d" 2>/dev/null | head -1 | cut -c11) == "+" ]] && + { print -r -- "$d has an access control list"; return 0; } + fi + d=${d:h} + done + return 1 +} efi="" force=0 args=() while (( $# )); do @@ -96,7 +113,14 @@ if [[ -e /Library/LaunchDaemons/com.droga.vcnpreset.plist ]] || launchctl print rm -f /Library/LaunchDaemons/com.droga.vcnpreset.plist /usr/local/libexec/vcnpreset fi # Everything is staged next to its place first; the running service is only stopped once that worked. -mkdir -p /usr/local/libexec || die "cannot create /usr/local/libexec. Nothing was changed." +if [[ ! -e /usr/local/libexec ]]; then + why=$(libexec_unsafe /usr/local) || true + [[ -z $why ]] || die "will not create /usr/local/libexec: $why. Nothing was changed." + mkdir -p -m 755 /usr/local/libexec || die "cannot create /usr/local/libexec. Nothing was changed." + chown root:wheel /usr/local/libexec || die "cannot make /usr/local/libexec root-owned." +fi +why=$(libexec_unsafe /usr/local/libexec) || true +[[ -z $why ]] || die "will not install the service: $why." rm -f $bin_dst.new $plist_dst.tmp install -m 755 -o root -g wheel $tool $bin_dst.new || { rm -f $bin_dst.new; die "cannot write $bin_dst.new. Nothing was changed."; } argxml="" diff --git a/GPU/encode/tests/wide_test.c b/GPU/encode/tests/wide_test.c index cbe42c97..77b8b70c 100644 --- a/GPU/encode/tests/wide_test.c +++ b/GPU/encode/tests/wide_test.c @@ -27,6 +27,7 @@ static const struct { const char* uuid; uint64_t callVm, caveVm; } kSites[] = { + {"01F6B94A-A77D-3549-B18B-CBA81F4630B3", 0x13601, 0xe78}, // 26.7.4 {"D2B848E1-ACD9-396B-8948-0882C65F601F", 0x13601, 0xe78}, // 26.7.3 {"FD24EB7C-0B0E-3438-A43B-133E93E94EFA", 0x13780, 0xe78}, // 15.8.2, 15.8.3 {"0FD1FA9F-5DF9-3E5F-A316-21AF738EBBAD", 0x142ca, 0xec8}, // 14.8.9 diff --git a/GPU/encode/tool/patches.c b/GPU/encode/tool/patches.c index 0c9ed6a8..6721523e 100644 --- a/GPU/encode/tool/patches.c +++ b/GPU/encode/tool/patches.c @@ -120,6 +120,15 @@ const char* const kPresetImage = // when it is not 0, stores it in the frame parameters (+0x30) and sets the flag // that appends the preset packet (compared in Hex-Rays against 26.7.3). static const PresetBuild kPresetBuilds[] = { + {"26.7.4 (25G422)", + "F7D8F584-9EC1-39DB-857C-769697294957", + // 26.7.4: same driver code as 26.7.3 (all 2760 functions identical; only a + // build path in __cstring differs) + {0x8b, 0x83, 0xa0, 0x00, 0x00, 0x00, // mov eax, [rbx+0A0h] + 0x85, 0xc0, // test eax, eax + 0x74, 0x11, // jz +11h + 0x48, 0x8b, 0x8b, 0x58, 0x04, 0x00, 0x00, // mov rcx, [rbx+458h] + 0x89, 0x41, 0x30}}, // mov [rcx+30h], eax {"26.7.3 (25G342)", "1181E2CA-31B3-3DF0-90E2-3AE70552D753", {0x8b, 0x83, 0xa0, 0x00, 0x00, 0x00, // mov eax, [rbx+0A0h] @@ -164,6 +173,14 @@ const char* const kWideImage = // in every build. The Metal kernel (frameStats16x16Tex) uses only // thread_position_in_grid in all of them. static const WideBuild kWideBuilds[] = { + {"26.7.4 (25G422)", + "01F6B94A-A77D-3549-B18B-CBA81F4630B3", // site 0x13601, cave 0xE78 + // __TEXT and __DATA byte-identical to 26.7.3; only LC_UUID, the SDK in + // LC_BUILD_VERSION and the signature differ + {0x48, 0x8b, 0x35, 0xb8, 0x1f, 0x02, 0x00, 0x48, 0x8b, 0x45, 0xa8, 0x48, + 0x89, 0x44, 0x24, 0x28, 0x0f, 0x10, 0x45, 0x98, 0x0f, 0x11, 0x44, 0x24, + 0x18, 0x48, 0x8b, 0x45, 0x90, 0x48, 0x89, 0x44, 0x24, 0x10, 0x0f, 0x10, + 0x45, 0x80, 0x0f, 0x11, 0x04, 0x24, 0x49, 0x89, 0xdd, 0x48, 0x89, 0xdf}}, {"26.7.3 (25G342)", "D2B848E1-ACD9-396B-8948-0882C65F601F", // site 0x13601, cave 0xE78 {0x48, 0x8b, 0x35, 0xb8, 0x1f, 0x02, @@ -685,6 +702,38 @@ int cc_site_state(const CcSite* s, const uint8_t* cur, const uint8_t* curTgt) { // Validated builds of AMDRadeonVADriver2 for the 10-bit HEVC VCN 3 fixes. static const Hevc10Build kHevc10Builds[] = { + {"26.7.4 (25G422)", + "F7D8F584-9EC1-39DB-857C-769697294957", + // 26.7.4: same driver code as 26.7.3 (all 2760 functions identical; only a + // build path in __cstring differs) + // Site A: Vcn3Encoder::setInputAndOutputFormatParams +0x2a (96 bytes) + {0x74, 0x29, 0x3d, 0x72, 0x30, 0x31, 0x6c, 0x74, 0x11, 0x3d, 0x62, 0x67, + 0x72, 0x61, 0x75, 0x23, 0xc5, 0xfb, 0x10, 0x05, 0x4e, 0x92, 0x04, 0x00, + 0xeb, 0x08, 0xc5, 0xfb, 0x10, 0x05, 0x34, 0x92, 0x04, 0x00, 0xb0, 0x01, + 0xb9, 0x01, 0x00, 0x00, 0x00, 0xeb, 0x0c, 0xc5, 0xfa, 0x10, 0x05, 0xcb, + 0x98, 0x03, 0x00, 0x31, 0xc9, 0x31, 0xc0, 0x89, 0x4d, 0xc4, 0x89, 0x4d, + 0xcc, 0xc5, 0xf8, 0x13, 0x45, 0xd4, 0x80, 0xbb, 0x2c, 0x05, 0x00, 0x00, + 0x01, 0x75, 0x0a, 0x0f, 0xb6, 0x8b, 0x2c, 0x04, 0x00, 0x00, 0x89, 0x4d, + 0xec, 0x84, 0xc0, 0x74, 0x07, 0xc7, 0x45, 0xe8, 0x01, 0x00, 0x00, 0x00}, + {0x74, 0x35, 0x3d, 0x72, 0x30, 0x31, 0x6c, 0x74, 0x11, 0x3d, 0x62, 0x67, + 0x72, 0x61, 0x75, 0x27, 0xc5, 0xfb, 0x10, 0x05, 0x4e, 0x92, 0x04, 0x00, + 0xeb, 0x08, 0xc5, 0xfb, 0x10, 0x05, 0x34, 0x92, 0x04, 0x00, 0xb8, 0x01, + 0x00, 0x00, 0x00, 0x89, 0x45, 0xc4, 0x89, 0x45, 0xcc, 0x89, 0x45, 0xe8, + 0xc5, 0xf8, 0x13, 0x45, 0xd4, 0xeb, 0x02, 0x31, 0xc0, 0x80, 0xbb, 0x2c, + 0x05, 0x00, 0x00, 0x01, 0x75, 0x14, 0x0f, 0xb6, 0x8b, 0x2c, 0x04, 0x00, + 0x00, 0x89, 0x4d, 0xec, 0x84, 0xc0, 0x75, 0x06, 0x89, 0x4d, 0xd4, 0x89, + 0x4d, 0xd8, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90}, + // Site B: AVDVcn3HevcEncDataProcessor::setupDeblocking +0x83 (find 52, + // write 45) + {0x48, 0x8b, 0x49, 0x28, 0x48, 0x89, 0x4d, 0xd0, 0x49, 0x8b, 0x4e, + 0x20, 0x48, 0x8b, 0x91, 0x50, 0x03, 0x00, 0x00, 0x31, 0xc9, 0x80, + 0xba, 0x9d, 0x02, 0x00, 0x00, 0x00, 0x75, 0x0c, 0x31, 0xc9, 0x80, + 0xba, 0x9e, 0x02, 0x00, 0x00, 0x00, 0x0f, 0x94, 0xc1, 0x89, 0x4d, + 0xd8, 0x80, 0x3d, 0xfa, 0x94, 0xe5, 0x32, 0x01}, + {0x49, 0x8b, 0x97, 0x50, 0x03, 0x00, 0x00, 0xc5, 0xfa, 0x7e, 0x41, 0x28, + 0xc5, 0xfa, 0x7e, 0x8a, 0x84, 0x07, 0x00, 0x00, 0xc5, 0xf9, 0xfe, 0xc1, + 0xc5, 0xf9, 0xd6, 0x45, 0xd0, 0x31, 0xc9, 0x66, 0x83, 0xba, 0x9d, 0x02, + 0x00, 0x00, 0x00, 0x0f, 0x94, 0xc1, 0x89, 0x4d, 0xd8}}, {"26.7.3 (25G342)", "1181E2CA-31B3-3DF0-90E2-3AE70552D753", // Site A: Vcn3Encoder::setInputAndOutputFormatParams +0x2a (96 bytes) diff --git a/GPU/install/README.md b/GPU/install/README.md index f77b9b03..03ff3c88 100644 --- a/GPU/install/README.md +++ b/GPU/install/README.md @@ -48,6 +48,7 @@ when they fail: it lets in only these plug-ins and the next run needs it. | `decoders.sh` | Installs, repairs or removes the AV1 and VP9 decoder plug-ins | | `loader.sh` | Puts VCNVTLoader, the kext the plug-ins need on a Mac without AMFIPass, on your EFI, or takes it off | | `sensors.sh` | Puts GPUSensors, the optional kext that shows the GPU readings macOS hides, on your EFI, or takes it off | +| `jpeg.sh` | Puts VCNJpeg, the optional kext that decodes JPEG on the GPU (macOS 26.7.3 only), on your EFI, or takes it off. The plug-in that uses it goes in with `decoders.sh install --jpeg`; see [jpeg/README.md](../jpeg/README.md) | | `encoder.sh` | Installs or removes the optional encoding fix | | `validated-builds.json` | The list of macOS builds that were checked. Both tools read it | | `check_lists.sh` | Checks that this list agrees with the lists compiled into the decoders | @@ -70,6 +71,7 @@ Or remove individual parts (then reboot after any EFI or system-volume change): - Decoders: `sudo install/decoders.sh uninstall` - Loader kext: `sudo install/loader.sh uninstall [--efi diskNsM]` - GPU sensors kext: `sudo install/sensors.sh uninstall [--efi diskNsM]` +- JPEG kext: `sudo install/jpeg.sh uninstall [--efi diskNsM]` - Encoding fix: `sudo install/encoder.sh uninstall [--efi diskNsM|auto]` If the Mac does not boot after a change: @@ -77,7 +79,7 @@ If the Mac does not boot after a change: - Boot your rescue USB EFI and copy the backup (`config.plist.backup--