From 1a74a39d5d9c718f1bad3fde432fb8148277cafb Mon Sep 17 00:00:00 2001 From: DrogaBox Date: Sun, 22 Nov 2026 18:01:05 -0300 Subject: [PATCH 01/35] Harden privileged GPU installer paths Stage and verify the GPU payload before root runs it, and refuse /usr/local/libexec when another user can change it. --- GPU/encode/scripts/install.sh | 26 +++++++++- GPU/install/common.zsh | 63 +++++++++++++++++++++++++ GPU/install/encoder.sh | 12 +++-- GPU/install/sensors.sh | 16 +------ GPU/installer/main.swift | 32 +++++++++++-- GPU/tests/install_paths.sh | 40 ++++++++++++++++ GPU/tests/run.sh | 1 + Tests/Suites/GPUInstallerDMGTests.swift | 38 +++++++++++++++ 8 files changed, 205 insertions(+), 23 deletions(-) create mode 100755 GPU/tests/install_paths.sh diff --git a/GPU/encode/scripts/install.sh b/GPU/encode/scripts/install.sh index 5934c2bf..11bfac5a 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/install/common.zsh b/GPU/install/common.zsh index eb10f2a8..ca1b5860 100644 --- a/GPU/install/common.zsh +++ b/GPU/install/common.zsh @@ -80,6 +80,69 @@ displays_report() { /usr/sbin/system_profiler SPDisplaysDataType 2>/dev/null } +# ---- root-owned folders and packages -------------------------------------------------------- +# A root script may only run from, or write to, a folder no other user can change. This is the +# rule for /usr/local/bin and /usr/local/libexec: every part of the path must be a real folder +# owned by root, writable by root only, with no ACL. +gpu_dir_unsafe() { # folder + 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 +} + +# Copies a package into a new root-only folder, makes the copy root-owned and checks every +# file against its SHA256SUMS. Sets STAGE_PKG to the copy; stage_cleanup removes it. +STAGE_PKG="" +stage_package() { # package folder + local src=$1 dst listed present + STAGE_PKG="" + [[ $EUID -eq 0 ]] || { print -r -u2 -- "only root can stage a package"; return 1; } + [[ -f $src/SHA256SUMS && ! -L $src/SHA256SUMS ]] || + { print -r -u2 -- "$src has no SHA256SUMS"; return 1; } + dst=$(/usr/bin/mktemp -d /private/tmp/ryzenstatus-pkg.XXXXXX) || return 1 + /bin/chmod 700 "$dst" || { /bin/rm -rf "$dst"; return 1; } + if ! /usr/bin/ditto --norsrc --noextattr "$src" "$dst/pkg"; then + /bin/rm -rf "$dst" + print -r -u2 -- "could not copy $src" + return 1 + fi + if ! /usr/bin/chown -R root:wheel "$dst/pkg" || ! /bin/chmod -R go-w "$dst/pkg" || + ! /bin/chmod -R -N "$dst/pkg" 2>/dev/null; then + /bin/rm -rf "$dst" + print -r -u2 -- "could not make the copy of $src root-owned" + return 1 + fi + if ! (cd "$dst/pkg" && /usr/bin/shasum -a 256 -c -s SHA256SUMS) || + [[ -n $(/usr/bin/find "$dst/pkg" -type l -print -quit) ]]; then + /bin/rm -rf "$dst" + print -r -u2 -- "the copy of $src does not match its SHA256SUMS" + return 1 + fi + listed=$(cd "$dst/pkg" && /usr/bin/awk '{ sub(/^[0-9a-f]+ /, ""); print }' SHA256SUMS | LC_ALL=C /usr/bin/sort) + present=$(cd "$dst/pkg" && /usr/bin/find . -type f ! -path ./SHA256SUMS -print | LC_ALL=C /usr/bin/sort) + if [[ $listed != "$present" ]]; then + /bin/rm -rf "$dst" + print -r -u2 -- "SHA256SUMS does not list exactly the files of $src" + return 1 + fi + STAGE_PKG=$dst/pkg +} +stage_cleanup() { + [[ -n $STAGE_PKG ]] && /bin/rm -rf "${STAGE_PKG:h}" + STAGE_PKG="" +} + # ---- the GPU sensors' commands in /usr/local/bin --------------------------------------------- # sensors.sh copies gpucontrol and gpusensors there. Ours are signed with the identifiers # com.droga.gpucontrol and com.droga.gpusensors; anything else under those names is someone diff --git a/GPU/install/encoder.sh b/GPU/install/encoder.sh index 8aafc251..0cfcf2cc 100755 --- a/GPU/install/encoder.sh +++ b/GPU/install/encoder.sh @@ -409,6 +409,8 @@ do_install() { preflight [[ $CAN_INSTALL -eq 1 ]] || { echo "the encoding fix cannot be installed on this Mac (see the checks)" >&2; print -rl -u2 -- "${CHECK_LINES[@]}"; exit 2; } local rc + stage_package "$PKG" || { echo "cannot verify a root-owned copy of the encoding fix package" >&2; exit 1; } + trap stage_cleanup EXIT resolve_efi if [[ -n "$EFI_ID" ]]; then OPEN_ID=$EFI_ID @@ -420,14 +422,14 @@ do_install() { echo "config.plist on $EFI_ID: ${ENTRY_WHY:-cannot be checked}. Fix or remove the VCNEncodeFloor.kext entry by hand (or enable Lilu), then run this again. Nothing was changed." >&2 exit 3 fi - /bin/zsh "$PKG/install.sh" --efi "$EFI_MP" 2>&1 + /bin/zsh "$STAGE_PKG/install.sh" --efi "$EFI_MP" 2>&1 rc=$? # the record of this install, for the checks until the reboot (common.zsh) (( rc == 0 )) && record_write VCNEncodeFloor "$(efi_field $EFI_ID 'Disk / Partition UUID')" "$(efi_field $EFI_ID 'Volume Name')" $EFI_ID \ com.droga.VCNEncodeFloor "$(pkg_version)" "$(files_hash "$PKG_KEXT_BIN")" enc_cleanup else - /bin/zsh "$PKG/install.sh" 2>&1 + /bin/zsh "$STAGE_PKG/install.sh" 2>&1 rc=$? fi [[ $rc -eq 0 ]] || { echo "VCNEncodeFix install.sh failed ($rc); see the lines above" >&2; exit $rc; } @@ -438,17 +440,19 @@ do_uninstall() { need_root uninstall [[ -f $PKG/uninstall.sh ]] || { echo "$(pick "no VCNEncodeFix package in $PKG; build it with encode/build.sh" "no VCNEncodeFix package inside RyzenStatus GPU.app; $APP_DAMAGED")" >&2; exit 1; } local rc + stage_package "$PKG" || { echo "cannot verify a root-owned copy of the encoding fix package" >&2; exit 1; } + trap stage_cleanup EXIT resolve_efi if [[ -n "$EFI_ID" ]]; then # taking the kext off needs no Lilu on that EFI OPEN_ID=$EFI_ID efi_open "$EFI_ID" || { OPEN_ID=""; exit 1; } record_remove VCNEncodeFloor - /bin/zsh "$PKG/uninstall.sh" --efi "$EFI_MP" 2>&1 + /bin/zsh "$STAGE_PKG/uninstall.sh" --efi "$EFI_MP" 2>&1 rc=$? enc_cleanup else - /bin/zsh "$PKG/uninstall.sh" 2>&1 + /bin/zsh "$STAGE_PKG/uninstall.sh" 2>&1 rc=$? fi [[ $rc -eq 0 ]] || { echo "VCNEncodeFix uninstall.sh failed ($rc); see the lines above" >&2; exit $rc; } diff --git a/GPU/install/sensors.sh b/GPU/install/sensors.sh index ff81f62c..0c5cdc39 100755 --- a/GPU/install/sensors.sh +++ b/GPU/install/sensors.sh @@ -358,21 +358,7 @@ TOOL_DIR=$GPU_TOOL_DIR TOOLS=($GPU_TOOL_NAMES) tool_id() { gpu_tool_id "$1"; } has_acl() { [[ $(/bin/ls -lde "$1" 2>/dev/null | head -1 | cut -c11) == "+" ]]; } -tool_dir_unsafe() { - local d=$TOOL_DIR 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; } - has_acl "$d" && { print -r -- "$d has an access control list"; return 0; } - fi - d=${d:h} - done - return 1 -} +tool_dir_unsafe() { gpu_dir_unsafe "$TOOL_DIR"; } tool_file_unsound() { # file name local f=$1 owner mode [[ -f $f && ! -L $f ]] || { print -r -- "$f is not a plain file"; return 0; } diff --git a/GPU/installer/main.swift b/GPU/installer/main.swift index 5a439ec8..ec9e92b5 100644 --- a/GPU/installer/main.swift +++ b/GPU/installer/main.swift @@ -408,9 +408,7 @@ final class Engine: ObservableObject { phase = .running(title) lastActionTitle = title lastOutput = "" - let scriptPath = root.appendingPathComponent(script).path - let argStr = args.map { Self.shq($0) }.joined(separator: " ") - let inner = "/bin/zsh \(Self.shq(scriptPath))\(argStr.isEmpty ? "" : " " + argStr) 2>&1" + let inner = Self.stagedCommand(root: root, script: script, args: args) DispatchQueue.global().async { let result = self.runPrivileged(inner) @@ -480,6 +478,34 @@ final class Engine: ObservableObject { "'" + s.replacingOccurrences(of: "'", with: "'\\''") + "'" } + /// Copies the parts into a root-only folder, checks every copied file against the + /// package's SHA256SUMS, and runs the copy. The app bundle belongs to the user, so + /// root must not run a script from it. + /// + /// The SHA256SUMS file itself is not pinned here yet: Tools/make-dmg.sh holds + /// GPU_PAYLOAD_SUMS_SHA256, and the build script would have to pass it to swiftc. + /// Until then, this checks every copied file but not the list itself. + static func stagedCommand(root: URL, script: String, args: [String]) -> String { + let argStr = args.map { Self.shq($0) }.joined(separator: " ") + let lines = [ + "stage=$(/usr/bin/mktemp -d /private/tmp/ryzenstatus-gpu.XXXXXX) || exit 1", + "trap '/bin/rm -rf \"$stage\"' EXIT HUP INT TERM", + "/usr/bin/ditto --norsrc --noextattr \(Self.shq(root.path)) \"$stage/GPU\" || exit 1", + "/usr/bin/chown -R root:wheel \"$stage/GPU\" || exit 1", + "/bin/chmod -R go-w \"$stage/GPU\" || exit 1", + "/bin/chmod -R -N \"$stage/GPU\" 2>/dev/null || exit 1", + "cd \"$stage/GPU\" || exit 1", + "[ -f SHA256SUMS ] && [ ! -L SHA256SUMS ] || { echo 'the parts have no SHA256SUMS'; exit 1; }", + "/usr/bin/shasum -a 256 -c -s SHA256SUMS || exit 1", + "listed=$(/usr/bin/awk '{ sub(/^[0-9a-f]+ /, \"\"); print }' SHA256SUMS | LC_ALL=C /usr/bin/sort) || exit 1", + "present=$(/usr/bin/find . -type f ! -path ./SHA256SUMS -print | LC_ALL=C /usr/bin/sort) || exit 1", + "[ \"$listed\" = \"$present\" ] || { echo 'SHA256SUMS does not list exactly the files of the parts'; exit 1; }", + "[ -z $(/usr/bin/find . -type l -print -quit) ] || { echo 'the parts hold a link'; exit 1; }", + "/bin/zsh \"$stage/GPU/\(script)\"\(argStr.isEmpty ? "" : " " + argStr) 2>&1", + ] + return "/bin/zsh -c \(Self.shq(lines.joined(separator: "; ")))" + } + static func asq(_ s: String) -> String { s.replacingOccurrences(of: "\\", with: "\\\\") .replacingOccurrences(of: "\"", with: "\\\"") diff --git a/GPU/tests/install_paths.sh b/GPU/tests/install_paths.sh new file mode 100755 index 00000000..888a6453 --- /dev/null +++ b/GPU/tests/install_paths.sh @@ -0,0 +1,40 @@ +#!/bin/zsh +# install_paths.sh - the rule root installers use for folders they write to. Every part of +# the path must be a real folder owned by root, writable by root only, with no ACL. +# +# tests/install_paths.sh exit 0 when the rule accepts and refuses the right folders +emulate -L zsh +setopt no_unset +ROOT=${0:A:h:h} +source $ROOT/install/common.zsh + +failed=0 +expect() { # text condition + if eval "$2"; then + print -r -- " ok $1" + else + print -r -- " FAIL $1" + failed=1 + fi +} +unsafe() { # folder + local why + why=$(gpu_dir_unsafe "$1") || true + [[ -n $why ]] +} +safe() { # folder + local why + why=$(gpu_dir_unsafe "$1") || true + [[ -z $why ]] +} + +tmp=$(mktemp -d -t install_paths) || exit 1 +trap '/bin/rm -rf "$tmp"' EXIT +/bin/ln -s /usr/local/bin "$tmp/link" + +expect "a folder owned by the user is not safe" 'unsafe "$tmp"' +expect "a link is not a folder" 'unsafe "$tmp/link"' +expect "a world-writable folder is not safe" 'unsafe /private/tmp' +expect "/usr/local/bin is safe on this Mac" 'safe /usr/local/bin' + +(( ! failed )) diff --git a/GPU/tests/run.sh b/GPU/tests/run.sh index 28440d39..b0187f0b 100755 --- a/GPU/tests/run.sh +++ b/GPU/tests/run.sh @@ -72,6 +72,7 @@ syntax() { check "every shell script parses" syntax check "the validated builds list agrees with the decoders' driver lists" install/check_lists.sh check "install.sh plan decides as expected on made-up Macs" tests/install_plan.sh +check "root installers refuse folders another user can change" tests/install_paths.sh step "decoders: build" build_twice() { diff --git a/Tests/Suites/GPUInstallerDMGTests.swift b/Tests/Suites/GPUInstallerDMGTests.swift index c2370e04..fd971770 100644 --- a/Tests/Suites/GPUInstallerDMGTests.swift +++ b/Tests/Suites/GPUInstallerDMGTests.swift @@ -188,6 +188,44 @@ enum GPUInstallerDMGTests { toolsOffered(suite, root, main) scriptCalls(suite, main, parts) windowStates(suite, main, parts) + installerCopies(suite, root, main) + } + + /// Root runs a verified copy of the parts, not the app bundle the user owns. + private static func installerCopies(_ suite: TestSuite, _ root: URL, _ main: String) { + suite.expect(main.contains("static func stagedCommand(root: URL, script: String, args: [String]) -> String") + && main.contains("let inner = Self.stagedCommand(root: root, script: script, args: args)"), + "runAction runs the staged copy, not the script in the selected folder") + suite.expect(main.contains("mktemp -d /private/tmp/ryzenstatus-gpu") + && main.contains("ditto --norsrc --noextattr") + && main.contains("chown -R root:wheel") && main.contains("chmod -R go-w"), + "the installer copies the parts into a fresh root-only folder") + suite.expect(main.contains("shasum -a 256 -c -s SHA256SUMS") + && main.contains("SHA256SUMS does not list exactly the files of the parts") + && main.contains("find . -type l"), + "the installer checks every copied file against SHA256SUMS before it runs one") + if let mktemp = main.range(of: "mktemp -d /private/tmp/ryzenstatus-gpu"), + let sums = main.range(of: "shasum -a 256 -c -s SHA256SUMS"), + let run = main.range(of: "/bin/zsh \\\"$stage/GPU/") { + suite.expect(mktemp.lowerBound < sums.lowerBound && sums.lowerBound < run.lowerBound, + "the copy and its SHA256SUMS check come before the zsh run") + } else { + suite.expect(false, "stagedCommand has a copy, a SHA256SUMS check and a zsh run") + } + let encode = text(root, "GPU/encode/scripts/install.sh") + suite.expect(encode.contains("libexec_unsafe /usr/local/libexec") + && encode.contains("mkdir -p -m 755 /usr/local/libexec") + && encode.contains("chown root:wheel /usr/local/libexec"), + "the encoding fix creates or checks a root-owned /usr/local/libexec") + suite.expect(encode.contains("stage_package \"$PKG\"") + && encode.contains("$STAGE_PKG/install.sh") + && encode.contains("$STAGE_PKG/uninstall.sh"), + "the encoding fix runs its package from a verified root-owned copy") + let common = text(root, "GPU/install/common.zsh") + let sensors = text(root, "GPU/install/sensors.sh") + suite.expect(common.contains("gpu_dir_unsafe()") + && sensors.contains("tool_dir_unsafe() { gpu_dir_unsafe \"$TOOL_DIR\"; }"), + "sensors.sh uses the shared folder rule without changing what it refuses") } /// Every script the installer runs, with every literal argument it passes, is in the From 6e55932ee836ff37ca8211c9ed5b3f5eca1f9329 Mon Sep 17 00:00:00 2001 From: DrogaBox Date: Sun, 22 Nov 2026 18:06:38 -0300 Subject: [PATCH 02/35] GPU installer: keep the app wording when root runs the staged copy The scripts decide by their own path whether they run from the app. The staged copy lives in /private/tmp, so pass the original folder in GPU_APP_ROOT and use it for that choice and for the Terminal hint. --- GPU/install/common.zsh | 4 +++- GPU/installer/main.swift | 1 + 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/GPU/install/common.zsh b/GPU/install/common.zsh index ca1b5860..b5034817 100644 --- a/GPU/install/common.zsh +++ b/GPU/install/common.zsh @@ -28,6 +28,8 @@ export PATH=/usr/bin:/bin:/usr/sbin:/sbin # folders of a checkout, which the person in front of the app does not have. IN_APP=0 [[ ${${(%):-%x}:A:h:h} == *.app/Contents/Resources/GPU ]] && IN_APP=1 +# The app runs a root-owned copy of these files from /private/tmp, and says where it came from. +[[ ${GPU_APP_ROOT:-} == *.app/Contents/Resources/GPU ]] && IN_APP=1 # pick pick() { if (( IN_APP )); then print -rn -- "$2"; else print -rn -- "$1"; fi; } # What a missing or broken file of the package means in the app. @@ -389,7 +391,7 @@ efi_choice_help() { # kind "script [options]" [[ $2 == *" "* ]] && opts=" ${2#* }" local term if (( IN_APP )); then - term="name the partition in Terminal: sudo '$SELF_DIR/$script'$opts --efi diskNsM (diskutil list shows them)" + term="name the partition in Terminal: sudo '${GPU_APP_ROOT:+$GPU_APP_ROOT/install}${GPU_APP_ROOT:-$SELF_DIR}/$script'$opts --efi diskNsM (diskutil list shows them)" else term="name it: sudo install/$script$opts --efi diskNsM (diskutil list shows them)" fi diff --git a/GPU/installer/main.swift b/GPU/installer/main.swift index ec9e92b5..4387b58d 100644 --- a/GPU/installer/main.swift +++ b/GPU/installer/main.swift @@ -501,6 +501,7 @@ final class Engine: ObservableObject { "present=$(/usr/bin/find . -type f ! -path ./SHA256SUMS -print | LC_ALL=C /usr/bin/sort) || exit 1", "[ \"$listed\" = \"$present\" ] || { echo 'SHA256SUMS does not list exactly the files of the parts'; exit 1; }", "[ -z $(/usr/bin/find . -type l -print -quit) ] || { echo 'the parts hold a link'; exit 1; }", + "export GPU_APP_ROOT=\(Self.shq(root.path))", "/bin/zsh \"$stage/GPU/\(script)\"\(argStr.isEmpty ? "" : " " + argStr) 2>&1", ] return "/bin/zsh -c \(Self.shq(lines.joined(separator: "; ")))" From d751b90ed64cafbfad2c2ae5557fb1dd7c055e63 Mon Sep 17 00:00:00 2001 From: DrogaBox Date: Sun, 22 Nov 2026 18:26:19 -0300 Subject: [PATCH 03/35] GPU installer: verify SHA256SUMS against the build pin The release build compiles the pinned digest of the GPU parts' SHA256SUMS into the installer. Root now compares the staged list with that digest before checking any file it names. A development build has no pin, so it says the list is not pinned instead of trusting it. --- GPU/installer/build.sh | 17 ++++++++++++++++- GPU/installer/main.swift | 15 ++++++++++++--- Tests/Suites/GPUInstallerDMGTests.swift | 22 ++++++++++++++++++++++ Tools/make-dmg.sh | 2 +- 4 files changed, 51 insertions(+), 5 deletions(-) diff --git a/GPU/installer/build.sh b/GPU/installer/build.sh index e7318a6a..a02fc955 100755 --- a/GPU/installer/build.sh +++ b/GPU/installer/build.sh @@ -13,10 +13,25 @@ APP="build/RyzenStatus GPU.app" rm -rf "$APP" mkdir -p "$APP/Contents/MacOS" "$APP/Contents/Resources" +# The release build passes the SHA-256 of the GPU parts' SHA256SUMS. A +# development checkout has no pin and the installer says the list is not pinned. +PIN="${GPU_PAYLOAD_SUMS_SHA256:-}" +if [[ -n "$PIN" && ! "$PIN" =~ '^[0-9a-f]{64}$' ]]; then + echo "error: GPU_PAYLOAD_SUMS_SHA256 must be 64 lowercase hex characters" >&2 + exit 1 +fi +PIN_FILE="build/PayloadPin.swift" +mkdir -p build +{ + print -r -- 'enum InstallerPin {' + print -r -- " static let payloadSumsSHA256 = \"$PIN\"" + print -r -- '}' +} > "$PIN_FILE" + # x86_64 only: the GPU parts target Intel/AMD Hackintoshes with Navi 21 GPUs. xcrun swiftc -parse-as-library -O -warnings-as-errors \ -target x86_64-apple-macos14.0 \ - main.swift -o "$APP/Contents/MacOS/RyzenStatusGPUInstaller" + main.swift "$PIN_FILE" -o "$APP/Contents/MacOS/RyzenStatusGPUInstaller" if [[ ! -f assets/AppIcon.icns ]]; then echo "error: missing installer/assets/AppIcon.icns" >&2 diff --git a/GPU/installer/main.swift b/GPU/installer/main.swift index 4387b58d..9e0bd2b4 100644 --- a/GPU/installer/main.swift +++ b/GPU/installer/main.swift @@ -482,11 +482,19 @@ final class Engine: ObservableObject { /// package's SHA256SUMS, and runs the copy. The app bundle belongs to the user, so /// root must not run a script from it. /// - /// The SHA256SUMS file itself is not pinned here yet: Tools/make-dmg.sh holds - /// GPU_PAYLOAD_SUMS_SHA256, and the build script would have to pass it to swiftc. - /// Until then, this checks every copied file but not the list itself. + /// The SHA256SUMS file itself is pinned by the build: Tools/make-dmg.sh + /// passes GPU_PAYLOAD_SUMS_SHA256 to build.sh, which writes InstallerPin.swift. + /// A development build has no pin and says so instead of checking one. static func stagedCommand(root: URL, script: String, args: [String]) -> String { let argStr = args.map { Self.shq($0) }.joined(separator: " ") + let pin = InstallerPin.payloadSumsSHA256 + let pinCheck: String + if pin.isEmpty { + pinCheck = "echo 'the parts have no pinned SHA256SUMS (development build); the list is not pinned'" + } else { + pinCheck = "actual=$(/usr/bin/shasum -a 256 SHA256SUMS | /usr/bin/awk '{print $1}') || exit 1; " + + "[ \"$actual\" = \(Self.shq(pin)) ] || { echo 'SHA256SUMS is not the pinned list'; exit 1; }" + } let lines = [ "stage=$(/usr/bin/mktemp -d /private/tmp/ryzenstatus-gpu.XXXXXX) || exit 1", "trap '/bin/rm -rf \"$stage\"' EXIT HUP INT TERM", @@ -496,6 +504,7 @@ final class Engine: ObservableObject { "/bin/chmod -R -N \"$stage/GPU\" 2>/dev/null || exit 1", "cd \"$stage/GPU\" || exit 1", "[ -f SHA256SUMS ] && [ ! -L SHA256SUMS ] || { echo 'the parts have no SHA256SUMS'; exit 1; }", + pinCheck, "/usr/bin/shasum -a 256 -c -s SHA256SUMS || exit 1", "listed=$(/usr/bin/awk '{ sub(/^[0-9a-f]+ /, \"\"); print }' SHA256SUMS | LC_ALL=C /usr/bin/sort) || exit 1", "present=$(/usr/bin/find . -type f ! -path ./SHA256SUMS -print | LC_ALL=C /usr/bin/sort) || exit 1", diff --git a/Tests/Suites/GPUInstallerDMGTests.swift b/Tests/Suites/GPUInstallerDMGTests.swift index fd971770..5ddf662e 100644 --- a/Tests/Suites/GPUInstallerDMGTests.swift +++ b/Tests/Suites/GPUInstallerDMGTests.swift @@ -193,6 +193,8 @@ enum GPUInstallerDMGTests { /// Root runs a verified copy of the parts, not the app bundle the user owns. private static func installerCopies(_ suite: TestSuite, _ root: URL, _ main: String) { + let build = text(root, "GPU/installer/build.sh") + let script = text(root, "Tools/make-dmg.sh") suite.expect(main.contains("static func stagedCommand(root: URL, script: String, args: [String]) -> String") && main.contains("let inner = Self.stagedCommand(root: root, script: script, args: args)"), "runAction runs the staged copy, not the script in the selected folder") @@ -226,6 +228,26 @@ enum GPUInstallerDMGTests { suite.expect(common.contains("gpu_dir_unsafe()") && sensors.contains("tool_dir_unsafe() { gpu_dir_unsafe \"$TOOL_DIR\"; }"), "sensors.sh uses the shared folder rule without changing what it refuses") + + // The root shell must compare the list itself with the pin compiled + // into this build, before it trusts any file the list names. + if let start = main.range(of: "static func stagedCommand"), + let end = main.range(of: "static func asq") { + let body = String(main[start.lowerBound.. /dev/null +GPU_PAYLOAD_SUMS_SHA256="$GPU_PAYLOAD_SUMS_SHA256" zsh GPU/installer/build.sh > /dev/null codesign --verify --deep --strict "$GPU_APP_BUILD" if [[ ! -f "$GPU_ZIP" ]]; then echo "✗ Error: $GPU_ZIP is missing; build it with Tools/build-gpu-assets.sh." >&2 From c0f051aa16640c93e5dd5efe9773a1ea0ebf7b17 Mon Sep 17 00:00:00 2001 From: DrogaBox Date: Sun, 22 Nov 2026 18:15:45 -0300 Subject: [PATCH 04/35] GPU installer test: read the encoder staging from encoder.sh stage_package and $STAGE_PKG live in GPU/install/encoder.sh, not in encode/scripts/install.sh. (cherry picked from commit f82ad087811523427e56c89cd4577d4c7d468fbf) --- Tests/Suites/GPUInstallerDMGTests.swift | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/Tests/Suites/GPUInstallerDMGTests.swift b/Tests/Suites/GPUInstallerDMGTests.swift index 5ddf662e..3702ac9f 100644 --- a/Tests/Suites/GPUInstallerDMGTests.swift +++ b/Tests/Suites/GPUInstallerDMGTests.swift @@ -219,9 +219,10 @@ enum GPUInstallerDMGTests { && encode.contains("mkdir -p -m 755 /usr/local/libexec") && encode.contains("chown root:wheel /usr/local/libexec"), "the encoding fix creates or checks a root-owned /usr/local/libexec") - suite.expect(encode.contains("stage_package \"$PKG\"") - && encode.contains("$STAGE_PKG/install.sh") - && encode.contains("$STAGE_PKG/uninstall.sh"), + let encoder = text(root, "GPU/install/encoder.sh") + suite.expect(encoder.contains("stage_package \"$PKG\"") + && encoder.contains("$STAGE_PKG/install.sh") + && encoder.contains("$STAGE_PKG/uninstall.sh"), "the encoding fix runs its package from a verified root-owned copy") let common = text(root, "GPU/install/common.zsh") let sensors = text(root, "GPU/install/sensors.sh") From 1772007bbcd955b57e174e3d247bc7848bce7a50 Mon Sep 17 00:00:00 2001 From: DrogaBox Date: Sun, 22 Nov 2026 18:51:46 -0300 Subject: [PATCH 05/35] GPU installer: name the app install folder once in the Terminal hint --- GPU/install/common.zsh | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/GPU/install/common.zsh b/GPU/install/common.zsh index b5034817..5dcf81de 100644 --- a/GPU/install/common.zsh +++ b/GPU/install/common.zsh @@ -391,7 +391,8 @@ efi_choice_help() { # kind "script [options]" [[ $2 == *" "* ]] && opts=" ${2#* }" local term if (( IN_APP )); then - term="name the partition in Terminal: sudo '${GPU_APP_ROOT:+$GPU_APP_ROOT/install}${GPU_APP_ROOT:-$SELF_DIR}/$script'$opts --efi diskNsM (diskutil list shows them)" + local dir=${GPU_APP_ROOT:+$GPU_APP_ROOT/install} + term="name the partition in Terminal: sudo '${dir:-$SELF_DIR}/$script'$opts --efi diskNsM (diskutil list shows them)" else term="name it: sudo install/$script$opts --efi diskNsM (diskutil list shows them)" fi From a0358ab06b616678e7ebe65cb071e8fdf02f9b36 Mon Sep 17 00:00:00 2001 From: DrogaBox Date: Tue, 24 Nov 2026 12:25:59 -0300 Subject: [PATCH 06/35] GPU decode: JPEG and Motion JPEG plug-in on the VCN JPEG block (off) A VideoToolbox plug-in for 'jpeg' and 'dmb1'. It is the VP9 plug-in's VideoToolbox side with the VP9 parts taken out, over a backend that hands each picture to the apps build of the VCNJpegProbe kext through the AMD accelerator's video context (selector 258), which any process that decodes video may open. Off: ./build.sh builds the bundle only with VCN_JPEG=1, and no installer puts it anywhere. Nothing of it has run on the GPU. - jpeg/jpegprep.c rewrites a picture into the shape Mesa gives the block (SOI, DQT, DHT, SOF0, SOS, scan, EOI), adds Annex K's Huffman tables for Motion JPEG without them, and refuses what the block is not given (progressive, 4:2:2, 4:4:4, grey). - jpeg/vcnjpeg.c: session, picture into an NV12 full-range buffer (BT.601). - tests: plugintest with -DTEST_JPEG, and jpegtest (the preparer against ImageIO, 40000 damaged copies, the session against a made-up kext). --- GPU/decode/build.sh | 14 +- GPU/decode/jpeg/Info.plist | 81 ++++ GPU/decode/jpeg/JPEGVCNDecoder.c | 749 ++++++++++++++++++++++++++++++ GPU/decode/jpeg/jpeg_app.h | 92 ++++ GPU/decode/jpeg/jpeg_app_client.h | 104 +++++ GPU/decode/jpeg/jpegprep.c | 223 +++++++++ GPU/decode/jpeg/jpegprep.h | 38 ++ GPU/decode/jpeg/jpegstd.h | 35 ++ GPU/decode/jpeg/vcnjpeg.c | 245 ++++++++++ GPU/decode/jpeg/vcnjpeg.h | 48 ++ GPU/decode/tests/jpegsamples.h | 310 +++++++++++++ GPU/decode/tests/jpegtest.c | 404 ++++++++++++++++ GPU/decode/tests/plugintest.c | 65 ++- GPU/tests/run.sh | 6 + 14 files changed, 2406 insertions(+), 8 deletions(-) create mode 100644 GPU/decode/jpeg/Info.plist create mode 100644 GPU/decode/jpeg/JPEGVCNDecoder.c create mode 100644 GPU/decode/jpeg/jpeg_app.h create mode 100644 GPU/decode/jpeg/jpeg_app_client.h create mode 100644 GPU/decode/jpeg/jpegprep.c create mode 100644 GPU/decode/jpeg/jpegprep.h create mode 100644 GPU/decode/jpeg/jpegstd.h create mode 100644 GPU/decode/jpeg/vcnjpeg.c create mode 100644 GPU/decode/jpeg/vcnjpeg.h create mode 100644 GPU/decode/tests/jpegsamples.h create mode 100644 GPU/decode/tests/jpegtest.c diff --git a/GPU/decode/build.sh b/GPU/decode/build.sh index b0144bba..8061ccd7 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, only with VCN_JPEG=1 (off by default: +# it needs the apps build of the VCNJpegProbe kext, and nothing installs it) # 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,11 @@ 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 +if [[ ${VCN_JPEG:-0} == 1 ]]; then + build_bundle JPEGVCNDecoder jpeg jpeg/JPEGVCNDecoder.c jpeg/vcnjpeg.c jpeg/jpegprep.c +else + rm -rf $B/JPEGVCNDecoder.bundle +fi # 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. @@ -80,8 +87,8 @@ if [[ ${1:-} == tests ]]; then xcrun clang $TFLAGS -Iav1 -Ivp9 tests/parsefuzz.c av1/av1parse.c vp9/vp9parse.c -o $T/parsefuzz xcrun clang $TFLAGS -Iav1 tests/av1state.c av1/av1parse.c -o $T/av1state xcrun clang $TFLAGS -Ivp9 tests/vp9state.c vp9/vp9parse.c -o $T/vp9state - for c in AV1 VP9; do - xcrun clang $TFLAGS -DTEST_$c tests/plugintest.c -framework CoreFoundation -framework CoreMedia \ + for c in AV1 VP9 JPEG; do + xcrun clang $TFLAGS -DTEST_$c -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 @@ -113,6 +120,9 @@ if [[ ${1:-} == tests ]]; then 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/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..b634a98d --- /dev/null +++ b/GPU/decode/jpeg/JPEGVCNDecoder.c @@ -0,0 +1,749 @@ +// 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. +// +// Not built by default: ./build.sh builds it only with VCN_JPEG=1, and no +// installer puts it anywhere. It needs the apps build of the VCNJpegProbe kext, +// which nothing installs either. +#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, and vcnjpeg refuses one the block is not + // given (progressive, 4:2:2, 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; + } + // 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..4d8d6cb2 --- /dev/null +++ b/GPU/decode/jpeg/jpeg_app.h @@ -0,0 +1,92 @@ +/* + * jpeg_app.h - how a program asks the "apps" build of VCNJpegProbe 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 (jp::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 */ +}; + +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 reserved; +}; + +#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..c536bd3e --- /dev/null +++ b/GPU/decode/jpeg/jpeg_app_client.h @@ -0,0 +1,104 @@ +/* + * jpeg_app_client.h - the caller's side of jpeg_app.h: one picture through the + * apps build of VCNJpegProbe. Plain C, header only; jpegprobe and the + * VideoToolbox plug-in use it (the plug-in keeps a copy of this file). + * + * 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 + +/* Opens a video context (type 3) on the AMD accelerator: what any process that decodes video may do. */ +static inline io_connect_t ja_iokit_open(void) { + io_service_t s = IOServiceGetMatchingService(kIOMainPortDefault, + IOServiceMatching("AMDRadeonX6000_AMDGraphicsAccelerator")); + if (s == IO_OBJECT_NULL) return IO_OBJECT_NULL; + io_connect_t c = IO_OBJECT_NULL; + kern_return_t kr = IOServiceOpen(s, mach_task_self(), JA_VIDEO_CONTEXT_TYPE, &c); + IOObjectRelease(s); + return kr == KERN_SUCCESS ? c : IO_OBJECT_NULL; +} + +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..142ef416 --- /dev/null +++ b/GPU/decode/jpeg/jpegprep.c @@ -0,0 +1,223 @@ +// jpegprep.c - see jpegprep.h. The same rewrite as VCNJpegProbe's +// tools/jpeg_normalize.hpp (the tool the first GPU tests use). 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[7] != 0x22 || t.sof[10] != 0x11 || t.sof[13] != 0x11) + return fail(why, whyLen, JPEG_UNSUPPORTED, "not 4:2:0"); + 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 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++; + 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; + return JPEG_OK; +} diff --git a/GPU/decode/jpeg/jpegprep.h b/GPU/decode/jpeg/jpegprep.h new file mode 100644 index 00000000..ac0d9f99 --- /dev/null +++ b/GPU/decode/jpeg/jpegprep.h @@ -0,0 +1,38 @@ +// 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 (VCNJpegProbe jc::parseStream): baseline, 8 bits, three components, +// 4:2:0 (luma 2x2, chroma 1x1), one scan with all three. Anything else is +// JPEG_UNSUPPORTED: progressive, 4:2:2 (many webcams), 4:4:4, 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 +} 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..8b482bcc --- /dev/null +++ b/GPU/decode/jpeg/jpegstd.h @@ -0,0 +1,35 @@ +// 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..a20c268b --- /dev/null +++ b/GPU/decode/jpeg/vcnjpeg.c @@ -0,0 +1,245 @@ +// 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) { + IOServiceClose(c); + return NULL; + } + *p = c; + return p; +} +static void iokit_close(void* ctx) { + if (!ctx) return; + IOServiceClose(*(io_connect_t*)ctx); + 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; + uint8_t* surface; // what the kext copies the picture into (its layout, see ja_picture) + size_t surfaceCap; + CVPixelBufferPoolRef pool; + uint32_t poolW, poolH; + 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; +} + +CFDictionaryRef vcnjpeg_copy_pixel_buffer_attributes(uint32_t w, uint32_t h, bool ten) { + (void)ten; + 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 = put_num(a, kCVPixelBufferPixelFormatTypeKey, kCVPixelFormatType_420YpCbCr8BiPlanarFullRange); + 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; +} + +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 apps build of VCNJpegProbe is not loaded" + : "the JPEG decoder is not ready (status %d)", s); + vcnjpeg_transport_close(d->conn); + free(d); + return NULL; + } + 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) { + if (d->pool && (d->poolW != w || d->poolH != h)) { + CVPixelBufferPoolRelease(d->pool); + d->pool = NULL; + } + if (!d->pool) { + CFDictionaryRef a = vcnjpeg_copy_pixel_buffer_attributes(w, h, false); + 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; + } + CVPixelBufferRef pb = NULL; + if (CVPixelBufferPoolCreatePixelBuffer(NULL, d->pool, &pb)) return NULL; + return pb; +} + +// The kext's surface layout for a picture (VCNJpegProbe jc::outputLayout): +// rows of alignUp(alignUp(width, 16), 256) bytes, alignUp(height, 16) luma rows, +// then the interleaved chroma. +static size_t surface_bytes(uint32_t w, uint32_t h) { + size_t pitch = (((size_t)w + 15) / 16 * 16 + 255) / 256 * 256; + size_t rows = ((size_t)h + 15) / 16 * 16; + return pitch * rows * 3 / 2; +} + +// 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); + 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) + 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); + if (!pb) return failed(d, VCNJPEG_FAIL_MEMORY, "no pixel buffer", 0); + if (!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..0c4f9b5d --- /dev/null +++ b/GPU/decode/jpeg/vcnjpeg.h @@ -0,0 +1,48 @@ +// vcnjpeg: one JPEG picture at a time on the JPEG block of the AMD VCN, through +// the apps build of the VCNJpegProbe kext. 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); + +// NV12 full range (a JPEG's samples are 0..255), IOSurface backed. +CFDictionaryRef vcnjpeg_copy_pixel_buffer_attributes(uint32_t w, uint32_t h, bool tenBit); + +VcnJpeg* vcnjpeg_create(uint32_t maxWidth, uint32_t maxHeight, char* err, size_t errLen); +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/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..0270e9a0 --- /dev/null +++ b/GPU/decode/tests/jpegtest.c @@ -0,0 +1,404 @@ +// 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. what the block is not given (4:2:2) is refused as unsupported, 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) + 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; +} K; +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[1] = sizeof(K.jpeg); + rp.v[2] = 1u << 24; + 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.pitch = (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.pitch * K.rows, + K.pitch * K.rows * 3 / 2, 3, 0}; + memcpy(data, &pic, sizeof(pic)); + rp.dataBytes = sizeof(pic); + break; + } + case JA_OP_READ_USER: { + size_t bytes = (size_t)K.pitch * K.rows * 3 / 2; + 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. +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 is refused as unsupported", r == JPEG_UNSUPPORTED && !o && strstr(why, "4:2:0")); + 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.runStatus = JA_OK; + d = vcnjpeg_create(16384, 16384, err, sizeof(err)); + expect("a session with the door open", d != NULL); + 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 refused = d && vcnjpeg_decode(d, kJpeg422, sizeof(kJpeg422), 0, on_picture, NULL) && + vcnjpeg_failure(d) == VCNJPEG_FAIL_STREAM && K.calls == calls; + expect("a 4:2:2 picture fails as the stream's, before anything is sent", refused); + 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/plugintest.c b/GPU/decode/tests/plugintest.c index a052c191..f55b70df 100644 --- a/GPU/decode/tests/plugintest.c +++ b/GPU/decode/tests/plugintest.c @@ -1,8 +1,8 @@ // 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; @@ -72,6 +72,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) @@ -94,7 +100,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 @@ -323,7 +329,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; @@ -363,6 +369,46 @@ CVPixelBufferRef vcnvp9_hidden_picture(VcnVP9* d) { (void)d; return hiddenOnly ? picture : NULL; } +#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); } +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) @@ -379,13 +425,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 diff --git a/GPU/tests/run.sh b/GPU/tests/run.sh index e135b84c..80125259 100755 --- a/GPU/tests/run.sh +++ b/GPU/tests/run.sh @@ -132,6 +132,12 @@ check "the MPEG-2 and VC-1 codec layers send the firmware only what it decodes" pick() { decode/build/tests/legacypick > decode/build/tests/legacypick.txt || { cat decode/build/tests/legacypick.txt; return 1; }; } check "VideoToolbox gives our MPEG-4 plug-in the streams it takes, and Apple's the rest" pick +jpeg_plugin() { + decode/build/tests/plugintest-jpeg > decode/build/tests/plugintest-jpeg.txt || + { cat decode/build/tests/plugintest-jpeg.txt; return 1; } + decode/build/tests/jpegtest > decode/build/tests/jpegtest.txt || { grep -v ^PASS decode/build/tests/jpegtest.txt; return 1; } +} +check "the JPEG plug-in (built only with VCN_JPEG=1): VideoToolbox side, preparer, session against a made-up kext" jpeg_plugin damaged() {$PD --mutate $rounds tests/media/av1/*.ivf tests/media/vp9/*.ivf > decode/build/tests/damaged.txt; } check "$rounds damaged copies of each stream are survived" damaged From 9f1a3ab9cb9eab6d597a9f5d524d41b6f5f61012 Mon Sep 17 00:00:00 2001 From: DrogaBox Date: Tue, 24 Nov 2026 15:52:39 -0300 Subject: [PATCH 07/35] GPU decode: JPEG door opens a shared client and connects the video context A video context answers no selector until it is connected to a shared user client (type 6) of the same task: IOConnectAddClient -> IOAccelContext2::connectClient -> contextStart. Type 3 alone returned kIOReturnNotReady on hardware. ja_iokit_open now opens both and connects them; ja_iokit_close closes both. --- GPU/decode/jpeg/jpeg_app_client.h | 72 ++++++++++++++++++++++++++++--- GPU/decode/jpeg/vcnjpeg.c | 4 +- 2 files changed, 67 insertions(+), 9 deletions(-) diff --git a/GPU/decode/jpeg/jpeg_app_client.h b/GPU/decode/jpeg/jpeg_app_client.h index c536bd3e..5fa57dc0 100644 --- a/GPU/decode/jpeg/jpeg_app_client.h +++ b/GPU/decode/jpeg/jpeg_app_client.h @@ -83,16 +83,74 @@ static inline int ja_info(ja_transport t, void* ctx, uint64_t* state, uint64_t* #ifdef __APPLE__ #include +#include -/* Opens a video context (type 3) on the AMD accelerator: what any process that decodes video may do. */ -static inline io_connect_t ja_iokit_open(void) { +/* 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) return IO_OBJECT_NULL; - io_connect_t c = IO_OBJECT_NULL; - kern_return_t kr = IOServiceOpen(s, mach_task_self(), JA_VIDEO_CONTEXT_TYPE, &c); - IOObjectRelease(s); - return kr == KERN_SUCCESS ? c : IO_OBJECT_NULL; + 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) { diff --git a/GPU/decode/jpeg/vcnjpeg.c b/GPU/decode/jpeg/vcnjpeg.c index a20c268b..21c54cef 100644 --- a/GPU/decode/jpeg/vcnjpeg.c +++ b/GPU/decode/jpeg/vcnjpeg.c @@ -15,7 +15,7 @@ static void* iokit_open(void) { if (c == IO_OBJECT_NULL) return NULL; io_connect_t* p = malloc(sizeof(*p)); if (!p) { - IOServiceClose(c); + ja_iokit_close(c); return NULL; } *p = c; @@ -23,7 +23,7 @@ static void* iokit_open(void) { } static void iokit_close(void* ctx) { if (!ctx) return; - IOServiceClose(*(io_connect_t*)ctx); + ja_iokit_close(*(io_connect_t*)ctx); // the video context and its shared client free(ctx); } ja_transport vcnjpeg_transport = ja_iokit_call; From b5a9a9e8996fa1323f5b2da4942cfc013d5523d4 Mon Sep 17 00:00:00 2001 From: DrogaBox Date: Tue, 24 Nov 2026 17:12:58 -0300 Subject: [PATCH 08/35] GPU decode: Motion JPEG 4:2:2 on the VCN JPEG block, and a VideoToolbox test The JPEG 2.0 block has no output-format register: the sampling in the frame header decides. As Mesa does on this block (radeon_dec_jpeg_check_format), 0x221111 is written as NV12 and 0x211111 (webcams), 0x221212 (FFmpeg) and 0x222121 as one packed YUYV plane. jpegprep takes the three 4:2:2 forms, vcnjpeg hands 4:2:2 pictures to VideoToolbox as '422f' (the YUYV split on the CPU) and 4:2:0 ones as '420f'; the session attributes list both. tests/gpu/vtjpegtest registers the bundle in its own process only, asks for exactly that decoder and compares every frame with FFmpeg (-apple runs the same check with Apple's software decoder, on the CPU). tests/gpu/mkmjpeg422 writes Motion JPEG with the webcam sampling, which neither FFmpeg nor Apple's encoder writes. Run on an RX 6800 XT (macOS 26.7.3, VCNJpegProbe apps build): 1280x720, max difference 1 against FFmpeg in all four runs; 4:2:0 jpeg 3.79 ms a frame (PSNR 74.7 dB), dmb1 3.98 ms, 4:2:2 FFmpeg form 4.59 ms, webcam form 4.56 ms. --- GPU/decode/jpeg/JPEGVCNDecoder.c | 4 +- GPU/decode/jpeg/jpeg_app.h | 2 +- GPU/decode/jpeg/jpegprep.c | 8 +- GPU/decode/jpeg/jpegprep.h | 7 +- GPU/decode/jpeg/vcnjpeg.c | 86 ++++++-- GPU/decode/jpeg/vcnjpeg.h | 4 +- GPU/decode/tests/gpu/build.sh | 4 + GPU/decode/tests/gpu/mkmjpeg422.c | 263 +++++++++++++++++++++++ GPU/decode/tests/gpu/vtjpegtest.c | 341 ++++++++++++++++++++++++++++++ GPU/decode/tests/jpegtest.c | 62 +++++- 10 files changed, 750 insertions(+), 31 deletions(-) create mode 100644 GPU/decode/tests/gpu/mkmjpeg422.c create mode 100644 GPU/decode/tests/gpu/vtjpegtest.c diff --git a/GPU/decode/jpeg/JPEGVCNDecoder.c b/GPU/decode/jpeg/JPEGVCNDecoder.c index b634a98d..1740cdb6 100644 --- a/GPU/decode/jpeg/JPEGVCNDecoder.c +++ b/GPU/decode/jpeg/JPEGVCNDecoder.c @@ -355,8 +355,8 @@ static OSStatus start_session(State* s, VTVideoDecoderSession session, return kVTVideoDecoderUnsupportedDataFormatErr; // A JPEG format description says nothing about sampling or precision: - // each picture carries its own, and vcnjpeg refuses one the block is not - // given (progressive, 4:2:2, 4:4:4, grey). + // 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; diff --git a/GPU/decode/jpeg/jpeg_app.h b/GPU/decode/jpeg/jpeg_app.h index 4d8d6cb2..bea75fb7 100644 --- a/GPU/decode/jpeg/jpeg_app.h +++ b/GPU/decode/jpeg/jpeg_app.h @@ -83,7 +83,7 @@ struct ja_picture { uint32_t chromaOffset; /* from the start of the surface */ uint32_t surfaceBytes; uint32_t elapsedMs; /* submit to completion, in the kernel */ - uint32_t reserved; + 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)) diff --git a/GPU/decode/jpeg/jpegprep.c b/GPU/decode/jpeg/jpegprep.c index 142ef416..7ae97ebc 100644 --- a/GPU/decode/jpeg/jpegprep.c +++ b/GPU/decode/jpeg/jpegprep.c @@ -146,8 +146,11 @@ int jpeg_prepare(const uint8_t* d, size_t n, uint8_t** out, size_t* outLen, 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[7] != 0x22 || t.sof[10] != 0x11 || t.sof[13] != 0x11) - return fail(why, whyLen, JPEG_UNSUPPORTED, "not 4:2:0"); + // 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]) @@ -219,5 +222,6 @@ int jpeg_prepare(const uint8_t* d, size_t n, uint8_t** out, size_t* outLen, 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 index ac0d9f99..7e481d74 100644 --- a/GPU/decode/jpeg/jpegprep.h +++ b/GPU/decode/jpeg/jpegprep.h @@ -7,8 +7,10 @@ // // What the block is given here is what the kext checks again before it takes // the JPEG (VCNJpegProbe jc::parseStream): baseline, 8 bits, three components, -// 4:2:0 (luma 2x2, chroma 1x1), one scan with all three. Anything else is -// JPEG_UNSUPPORTED: progressive, 4:2:2 (many webcams), 4:4:4, grey. +// 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 @@ -27,6 +29,7 @@ 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. diff --git a/GPU/decode/jpeg/vcnjpeg.c b/GPU/decode/jpeg/vcnjpeg.c index 21c54cef..edf46e74 100644 --- a/GPU/decode/jpeg/vcnjpeg.c +++ b/GPU/decode/jpeg/vcnjpeg.c @@ -41,6 +41,7 @@ struct VcnJpeg { size_t surfaceCap; CVPixelBufferPoolRef pool; uint32_t poolW, poolH; + OSType poolFormat; int failure; char err[160]; }; @@ -53,8 +54,8 @@ static bool put_num(CFMutableDictionaryRef d, CFStringRef k, int32_t v) { return true; } -CFDictionaryRef vcnjpeg_copy_pixel_buffer_attributes(uint32_t w, uint32_t h, bool ten) { - (void)ten; +// 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, @@ -64,7 +65,23 @@ CFDictionaryRef vcnjpeg_copy_pixel_buffer_attributes(uint32_t w, uint32_t h, boo if (io) CFRelease(io); return NULL; } - bool ok = put_num(a, kCVPixelBufferPixelFormatTypeKey, kCVPixelFormatType_420YpCbCr8BiPlanarFullRange); + 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); @@ -77,6 +94,11 @@ CFDictionaryRef vcnjpeg_copy_pixel_buffer_attributes(uint32_t w, uint32_t h, boo return a; } +CFDictionaryRef vcnjpeg_copy_pixel_buffer_attributes(uint32_t w, uint32_t h, bool ten) { + (void)ten; + return attributes(w, h, 0); +} + static int failed(VcnJpeg* d, int failure, const char* what, int status) { d->failure = failure; if (status == 0) @@ -129,13 +151,13 @@ void vcnjpeg_destroy(VcnJpeg* d) { free(d); } -static CVPixelBufferRef new_target(VcnJpeg* d, uint32_t w, uint32_t h) { - if (d->pool && (d->poolW != w || d->poolH != h)) { +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 = vcnjpeg_copy_pixel_buffer_attributes(w, h, false); + CFDictionaryRef a = attributes(w, h, format); if (!a) return NULL; CVReturn r = CVPixelBufferPoolCreate(NULL, NULL, a, &d->pool); CFRelease(a); @@ -145,6 +167,7 @@ static CVPixelBufferRef new_target(VcnJpeg* d, uint32_t w, uint32_t h) { } d->poolW = w; d->poolH = h; + d->poolFormat = format; } CVPixelBufferRef pb = NULL; if (CVPixelBufferPoolCreatePixelBuffer(NULL, d->pool, &pb)) return NULL; @@ -152,14 +175,46 @@ static CVPixelBufferRef new_target(VcnJpeg* d, uint32_t w, uint32_t h) { } // The kext's surface layout for a picture (VCNJpegProbe jc::outputLayout): -// rows of alignUp(alignUp(width, 16), 256) bytes, alignUp(height, 16) luma rows, -// then the interleaved chroma. -static size_t surface_bytes(uint32_t w, uint32_t h) { - size_t pitch = (((size_t)w + 15) / 16 * 16 + 255) / 256 * 256; +// 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) { @@ -199,7 +254,7 @@ int vcnjpeg_decode(VcnJpeg* d, const uint8_t* sample, size_t size, int64_t tag, free(jpeg); return failed(d, VCNJPEG_FAIL_STREAM, "picture larger than the session allows", 0); } - size_t need = surface_bytes(info.width, info.height); + size_t need = surface_bytes(info.width, info.height, info.yuyv); if (need > d->surfaceCap) { free(d->surface); d->surface = malloc(need); @@ -217,11 +272,14 @@ int vcnjpeg_decode(VcnJpeg* d, const uint8_t* sample, size_t size, int64_t tag, 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) + 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); + 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 (!copy_planes(d->surface, &pic, pb)) { + 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); } diff --git a/GPU/decode/jpeg/vcnjpeg.h b/GPU/decode/jpeg/vcnjpeg.h index 0c4f9b5d..fe19f822 100644 --- a/GPU/decode/jpeg/vcnjpeg.h +++ b/GPU/decode/jpeg/vcnjpeg.h @@ -26,7 +26,9 @@ extern ja_transport vcnjpeg_transport; extern void* (*vcnjpeg_transport_open)(void); extern void (*vcnjpeg_transport_close)(void* ctx); -// NV12 full range (a JPEG's samples are 0..255), IOSurface backed. +// 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); VcnJpeg* vcnjpeg_create(uint32_t maxWidth, uint32_t maxHeight, char* err, size_t errLen); diff --git a/GPU/decode/tests/gpu/build.sh b/GPU/decode/tests/gpu/build.sh index 713a8235..d31c3843 100755 --- a/GPU/decode/tests/gpu/build.sh +++ b/GPU/decode/tests/gpu/build.sh @@ -12,6 +12,8 @@ # 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, 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 +81,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/mkmjpeg422.c b/GPU/decode/tests/gpu/mkmjpeg422.c new file mode 100644 index 00000000..8cce9302 --- /dev/null +++ b/GPU/decode/tests/gpu/mkmjpeg422.c @@ -0,0 +1,263 @@ +// 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/vtjpegtest.c b/GPU/decode/tests/gpu/vtjpegtest.c new file mode 100644 index 00000000..3ce450a7 --- /dev/null +++ b/GPU/decode/tests/gpu/vtjpegtest.c @@ -0,0 +1,341 @@ +// 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 -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 apps build +// of VCNJpegProbe is loaded and its JPEG queue is started. +// +// 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 -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; + 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], "-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 || 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 (!apple && 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 (!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/jpegtest.c b/GPU/decode/tests/jpegtest.c index 0270e9a0..457227f2 100644 --- a/GPU/decode/tests/jpegtest.c +++ b/GPU/decode/tests/jpegtest.c @@ -6,7 +6,7 @@ // 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. what the block is not given (4:2:2) is refused as unsupported, and no +// 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 @@ -109,7 +109,9 @@ static struct { 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; @@ -150,7 +152,9 @@ static int fake_call(void* ctx, const void* in, size_t inSize, void* out, size_t free(again); K.w = info.width; K.h = info.height; - K.pitch = (uint32_t)(((K.w + 15) / 16 * 16 + 255) / 256 * 256); + 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; @@ -159,14 +163,14 @@ static int fake_call(void* ctx, const void* in, size_t inSize, void* out, size_t 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.pitch * K.rows, - K.pitch * K.rows * 3 / 2, 3, 0}; + 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 = (size_t)K.pitch * K.rows * 3 / 2; + size_t bytes = k_bytes(); if (rq.arg1 < bytes) { rp.status = JA_BAD_REQUEST; break; @@ -207,6 +211,21 @@ static void on_picture(void* ctx, CVPixelBufferRef pb, const void* unused, uint3 } // 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); @@ -294,7 +313,31 @@ int main(void) { // ---- 3. refused, cut and damaged ---- o = NULL; r = jpeg_prepare(kJpeg422, sizeof(kJpeg422), &o, &on, &info, why, sizeof(why)); - expect("4:2:2 is refused as unsupported", r == JPEG_UNSUPPORTED && !o && strstr(why, "4:2:0")); + 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); + } bool prefixes = true; for (size_t n = 0; n < sizeof(kJpeg48x32) - 1; n++) { uint8_t* copy = malloc(n ? n : 1); @@ -365,9 +408,10 @@ int main(void) { expect("the picture says BT.601 (JFIF)", matrix && CFEqual(matrix, kCVImageBufferYCbCrMatrix_ITU_R_601_4)); if (matrix) CFRelease(matrix); int calls = K.calls; - bool refused = d && vcnjpeg_decode(d, kJpeg422, sizeof(kJpeg422), 0, on_picture, NULL) && - vcnjpeg_failure(d) == VCNJPEG_FAIL_STREAM && K.calls == calls; - expect("a 4:2:2 picture fails as the stream's, before anything is sent", refused); + 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)); From 25079efd4409324f04f392313855c56c0f36ddf2 Mon Sep 17 00:00:00 2001 From: DrogaBox Date: Wed, 25 Nov 2026 01:42:07 -0300 Subject: [PATCH 09/35] GPU: VCNJpeg, the JPEG block of the VCN as a product kext (off by default) Apple's AMDRadeonX6000HWLibs carries the driver of the Navi 21 JPEG block but never creates its queue. VCNJpeg (jpeg/) is the product side of the test kext that decoded through it: the queue and one block of buffers (128 MiB, vcnjpegpool=8..128) are made inside startMMEngineQueues, the only time the GART bump pointer allows it, and given back in stopMMEngineQueues. Programs reach it through selector 258 of the accelerator's video context; only requests with its own header are taken, the rest go to Apple. The block is powered only while pictures arrive: PowerPlay client 21 and the queue start with the first RUN, and a thread_call gives both back two seconds after the last request (idle_logic.hpp). A timeout or a damaged guard stops the decoder until the next restart. It checks the LC_UUID of AMDRadeonX6000HWLibs and AMDRadeonX6000 (26.7.3, 25G342) and the place and first bytes of the 20 functions it uses, and uses lilu.onKextLoad (no Force call). No sysctl, no root user client. Tests (jpeg/tests/run.sh): the commands, the door with sanitizers and 300000 random requests, the power rule (a 30 fps stream powers the block once and never off between frames), and the Apple and Mesa oracles when the KDK and Mesa are given. tests/run.sh builds the kext twice to the same bytes and compares its table with the running Mac's driver. Nothing has run on a card. --- GPU/build.sh | 12 +- GPU/jpeg/README.md | 81 +++ GPU/jpeg/VERSION | 1 + GPU/jpeg/build.sh | 75 +++ GPU/jpeg/kext/Info.plist | 57 ++ GPU/jpeg/kext/apps_handler.hpp | 247 ++++++++ GPU/jpeg/kext/decode_accept.hpp | 26 + GPU/jpeg/kext/hwlibs_expect.hpp | 131 ++++ GPU/jpeg/kext/idle_logic.hpp | 49 ++ GPU/jpeg/kext/jpeg_cmds.hpp | 460 ++++++++++++++ GPU/jpeg/kext/jpeg_layout.hpp | 149 +++++ GPU/jpeg/kext/jpeg_power.hpp | 142 +++++ GPU/jpeg/kext/jpeg_proto.hpp | 87 +++ GPU/jpeg/kext/kern_start.cpp | 990 ++++++++++++++++++++++++++++++ GPU/jpeg/tests/apps_test.cpp | 664 ++++++++++++++++++++ GPU/jpeg/tests/cmds_test.cpp | 322 ++++++++++ GPU/jpeg/tests/gen_mesa_oracle.py | 144 +++++ GPU/jpeg/tests/hwlibs_oracle.c | 119 ++++ GPU/jpeg/tests/jpeg_normalize.hpp | 149 +++++ GPU/jpeg/tests/run.sh | 162 +++++ GPU/jpeg/tests/x6000_oracle.c | 181 ++++++ GPU/jpeg/tools/gen_expect.py | 145 +++++ GPU/tests/run.sh | 63 +- GPU/tools/format.sh | 5 +- 24 files changed, 4451 insertions(+), 10 deletions(-) create mode 100644 GPU/jpeg/README.md create mode 100644 GPU/jpeg/VERSION create mode 100755 GPU/jpeg/build.sh create mode 100644 GPU/jpeg/kext/Info.plist create mode 100644 GPU/jpeg/kext/apps_handler.hpp create mode 100644 GPU/jpeg/kext/decode_accept.hpp create mode 100644 GPU/jpeg/kext/hwlibs_expect.hpp create mode 100644 GPU/jpeg/kext/idle_logic.hpp create mode 100644 GPU/jpeg/kext/jpeg_cmds.hpp create mode 100644 GPU/jpeg/kext/jpeg_layout.hpp create mode 100644 GPU/jpeg/kext/jpeg_power.hpp create mode 100644 GPU/jpeg/kext/jpeg_proto.hpp create mode 100644 GPU/jpeg/kext/kern_start.cpp create mode 100644 GPU/jpeg/tests/apps_test.cpp create mode 100644 GPU/jpeg/tests/cmds_test.cpp create mode 100644 GPU/jpeg/tests/gen_mesa_oracle.py create mode 100644 GPU/jpeg/tests/hwlibs_oracle.c create mode 100644 GPU/jpeg/tests/jpeg_normalize.hpp create mode 100755 GPU/jpeg/tests/run.sh create mode 100644 GPU/jpeg/tests/x6000_oracle.c create mode 100644 GPU/jpeg/tools/gen_expect.py 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/jpeg/README.md b/GPU/jpeg/README.md new file mode 100644 index 00000000..5d491b6b --- /dev/null +++ b/GPU/jpeg/README.md @@ -0,0 +1,81 @@ +# JPEG decoder + +`VCNJpeg.kext` decodes JPEG and Motion JPEG on the JPEG block of the VCN of a Navi 21 card +(RX 6800, 6800 XT, 6900 XT). Apple's driver carries the code that runs this block but never +starts it. The VideoToolbox plug-in `JPEGVCNDecoder.bundle` (`decode/jpeg/`) hands pictures +to the kext. Apps that play or read Motion JPEG through VideoToolbox (`jpeg` and `dmb1`: +webcam recordings, some cameras' clips) then decode on the GPU instead of the CPU. + +It is optional, off by default, and for **macOS 26.7.3 (25G342) only**. On any other build the +kext does nothing, and VideoToolbox uses Apple's software decoder as before. + +Still pictures opened by Preview, Photos or Safari do not go through VideoToolbox. They are +not changed. + +## How it works + +- When the driver starts its video queues, the kext creates the JPEG queue next to them and + takes one block of buffers (128 MiB by default) from the same allocator. Both have to + happen then: memory taken from it later lands on addresses the accelerator already uses. +- A program reaches the kext through the accelerator's video context: the connection every + program that decodes video may open. The kext answers only its own requests there, and + checks every size and every JPEG before the block sees it. +- The block is powered only while pictures arrive. The first one asks PowerPlay for it the + way the driver asks for a VCN session, and starts the queue. Two seconds after the last + picture the kext stops the queue and gives the power back. +- A picture that does not finish within 3 s, or that writes past its buffer, stops the + decoder until the next restart. New sessions then go to Apple's software decoder. +- When the driver loads, the kext checks the UUID of `AMDRadeonX6000HWLibs` and of + `AMDRadeonX6000` and the start of every function it uses. If anything differs, it stays + off. + +The state is on IOResources: + +```bash +ioreg -rd1 -c IOResources | grep VCNJpeg +``` + +`State` is `ready, block off` when it is waiting for pictures, `decoding, block on` while it +works, and `off: ` or `stuck: ...` when it does not decode. `Jobs`, `PowerOns` and +`Failures` count since boot. + +## Install + +```bash +install/jpeg.sh check # changes nothing +sudo install/install.sh --with-jpeg # the kext on the EFI, the plug-in on the system volume +``` + +Or part by part: `sudo install/jpeg.sh install` and `sudo install/decoders.sh install --jpeg`. +Then reboot. + +Boot arguments: +- `-vcnjpegoff` turns the kext off. +- `vcnjpegpool=` sizes the block of buffers, from 8 to 128. The default, 128, holds a + 48-megapixel 4:2:0 picture. A 4K 4:2:2 frame needs about 24. + +## What it takes + +Baseline JPEG, 8 bits, three components, 4:2:0 or 4:2:2, up to 16384 x 16384 (within the +buffer). Motion JPEG without Huffman tables of its own gets the standard ones. + +Progressive JPEG, 4:4:4, grey and CMYK are refused. VideoToolbox then uses Apple's software +decoder. + +## Build and test + +```bash +jpeg/build.sh tests # the kext and the host tests (needs tools/bootstrap.sh once) +jpeg/tests/run.sh # the tests: commands, the door, when the block is powered +``` + +`jpeg/tests/run.sh` also compares the decode job with the commands of Apple's own driver +code and of Mesa when it has them: `KDK=` points at the KDK of 26.7.3, `MESA_DIR=` at a +copy of Mesa. Without them, those parts are skipped. + +The GPU test is `decode/tests/gpu/vtjpegtest`: it decodes Motion JPEG clips through +VideoToolbox and compares every frame with FFmpeg's. + +`kext/hwlibs_expect.hpp` (the functions the kext checks at load) comes from the KDK +through `tools/gen_expect.py`. A new macOS build gets its own table only after the code +that uses each function was read again; see [docs/macos-updates.md](../docs/macos-updates.md). diff --git a/GPU/jpeg/VERSION b/GPU/jpeg/VERSION new file mode 100644 index 00000000..3eefcb9d --- /dev/null +++ b/GPU/jpeg/VERSION @@ -0,0 +1 @@ +1.0.0 diff --git a/GPU/jpeg/build.sh b/GPU/jpeg/build.sh new file mode 100755 index 00000000..40d5fcfc --- /dev/null +++ b/GPU/jpeg/build.sh @@ -0,0 +1,75 @@ +#!/bin/zsh +# build.sh - builds VCNJpeg.kext, the Lilu plug-in that decodes JPEG on the JPEG block of the +# VCN (see jpeg/README.md), into jpeg/build/. It installs nothing. +# +# jpeg/build.sh the kext +# jpeg/build.sh tests also the host tests (jpeg/tests/run.sh runs them) +# +# The kext needs the Command Line Tools, Lilu.kext (DEBUG build) and MacKernelSDK: +# tools/bootstrap.sh fetches pinned copies into deps/; to use your own, export LILU_KEXT and +# MACKERNELSDK. The tests only need the Command Line Tools. +# +# kext/hwlibs_expect.hpp (the functions the kext checks at load) is generated from the KDK of +# the studied macOS build by tools/gen_expect.py and committed; the build does not need the KDK. +# +# The kext carries its build date (Lilu's version string), taken from SOURCE_DATE_EPOCH, +# which defaults to the date of the last commit: the same commit gives the same kext. +emulate -L zsh +setopt err_exit no_unset pipe_fail +HERE=${0:A:h} +ROOT=${HERE:h} +NAME=VCNJpeg +VERSION=$(<$HERE/VERSION) +export SOURCE_DATE_EPOCH=${SOURCE_DATE_EPOCH:-$(git -C $ROOT log -1 --format=%ct 2>/dev/null || date +%s)} +LILU=${LILU_KEXT:-$ROOT/deps/Lilu.kext} +MKSDK=${MACKERNELSDK:-$ROOT/deps/MacKernelSDK} +B=$HERE/build +OBJ=$B/obj +FINAL=$B/$NAME.kext +OUT=$OBJ/$NAME.kext # assembled here; it replaces $FINAL only when everything worked +[[ -f $LILU/Contents/Resources/Library/plugin_start.cpp && -f $MKSDK/Library/x86_64/libkmod.a ]] || { + print "Lilu.kext (DEBUG) and MacKernelSDK not found: run tools/bootstrap.sh, or set LILU_KEXT and MACKERNELSDK"; exit 1; } +rm -rf $OBJ && mkdir -p $OBJ $OUT/Contents/MacOS + +if [[ ${1:-} == tests ]]; then + T=$B/tests + mkdir -p $T + TF=(-std=c++17 -arch x86_64 -O1 -g -Wall -Wextra -Werror -fsanitize=address,undefined + -fno-sanitize-recover=undefined -I$HERE/kext -I$HERE/tools -I$ROOT/decode/jpeg) + xcrun clang++ $TF $HERE/tests/cmds_test.cpp -o $T/cmds_test + xcrun clang++ $TF -DJC_MAX_DIM=16384 $HERE/tests/apps_test.cpp -o $T/apps_test + xcrun clang -arch x86_64 -O1 -Wall -Wextra -Werror $HERE/tests/hwlibs_oracle.c -o $T/hwlibs_oracle + xcrun clang -arch x86_64 -O1 -Wall -Wextra -Werror $HERE/tests/x6000_oracle.c -o $T/x6000_oracle + print "built the test programs in jpeg/build/tests" +fi + +KFLAGS=(-std=c++17 -target x86_64-apple-macos10.15 -fapple-kext -mkernel -nostdlib -nostdinc++ + -DMODULE_VERSION=$VERSION -DPRODUCT_NAME=$NAME -DJC_MAX_DIM=16384 + -I$HERE/kext -I$ROOT/decode/jpeg -isystem "$LILU/Contents/Resources" -I"$MKSDK/Headers" + -Oz -flto=thin -fno-exceptions -fno-rtti -Wall -Wno-unused-parameter) +objs=() +for src in $HERE/kext/kern_start.cpp "$LILU/Contents/Resources/Library/plugin_start.cpp"; do + o=$OBJ/${src:t:r}.o + xcrun clang++ $KFLAGS -c $src -o $o + objs+=($o) +done +# A manual clang/ld build has to emit kmod_info itself, or the kext loads but never runs. +print -r -- '#include +#include +extern kern_return_t '$NAME'_kern_start(kmod_info_t *, void *); +extern kern_return_t '$NAME'_kern_stop(kmod_info_t *, void *); +extern kern_return_t _start(kmod_info_t *, void *); +extern kern_return_t _stop(kmod_info_t *, void *); +KMOD_EXPLICIT_DECL(com.droga.'$NAME', "'$VERSION'", _start, _stop) +__private_extern__ kmod_start_func_t *_realmain = '$NAME'_kern_start; +__private_extern__ kmod_stop_func_t *_antimain = '$NAME'_kern_stop;' > $OBJ/kmod_info.c +xcrun clang -target x86_64-apple-macos10.15 -mkernel -nostdlib -I"$MKSDK/Headers" -Oz \ + -c $OBJ/kmod_info.c -o $OBJ/kmod_info.o +xcrun ld -kext -arch x86_64 -platform_version macos 10.15 10.15 -L"$MKSDK/Library/x86_64" -lkmod \ + $objs $OBJ/kmod_info.o -o $OUT/Contents/MacOS/$NAME +sed "s/__VERSION__/$VERSION/g" $HERE/kext/Info.plist > $OUT/Contents/Info.plist +plutil -lint -s $OUT/Contents/Info.plist +codesign -f -s - $OUT 2>/dev/null +[[ "$(nm $OUT/Contents/MacOS/$NAME)" == *' D _kmod_info'* ]] || { print "kmod_info missing"; exit 1; } +rm -rf $FINAL && mv $OUT $FINAL +print "built jpeg/build/$NAME.kext ($VERSION)" diff --git a/GPU/jpeg/kext/Info.plist b/GPU/jpeg/kext/Info.plist new file mode 100644 index 00000000..312f6251 --- /dev/null +++ b/GPU/jpeg/kext/Info.plist @@ -0,0 +1,57 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + VCNJpeg + CFBundleIdentifier + com.droga.VCNJpeg + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + VCNJpeg + CFBundlePackageType + KEXT + CFBundleShortVersionString + __VERSION__ + CFBundleSignature + ???? + CFBundleVersion + __VERSION__ + IOKitPersonalities + + VCNJpeg + + CFBundleIdentifier + com.droga.VCNJpeg + IOClass + VCNJpeg + IOMatchCategory + VCNJpeg + IOProviderClass + IOResources + IOResourceMatch + IOKit + + + OSBundleLibraries + + as.vit9696.Lilu + 1.7.0 + com.apple.kpi.bsd + 8.0.0 + com.apple.kpi.iokit + 8.0.0 + com.apple.kpi.libkern + 8.0.0 + com.apple.kpi.mach + 8.0.0 + com.apple.kpi.unsupported + 8.0.0 + + OSBundleRequired + Root + + diff --git a/GPU/jpeg/kext/apps_handler.hpp b/GPU/jpeg/kext/apps_handler.hpp new file mode 100644 index 00000000..f07e552f --- /dev/null +++ b/GPU/jpeg/kext/apps_handler.hpp @@ -0,0 +1,247 @@ +// +// apps_handler.hpp - what VCNJpeg does with one request of jpeg_app.h, and the +// layout of its block of buffers. No kernel call in here: kern_start.cpp +// includes it in the kext and tests/apps_test.cpp on the host, with +// sanitizers, because this is the code any process can reach. Needs: +// appCopyIn(kernel dst, user src, bytes) and appCopyOut(user dst, kernel src, +// bytes), true on success (copyin/copyout in the kext); appTouch() (a request +// of a client arrived: the idle timer starts over) and appBlockOn() (power the +// block and start its queue if it is not yet; false = it cannot be); and the +// decoder's globals and functions (gPool, gP, gLayout, gStream, gResult, +// gDecoded, gLoadedBytes, gLoadPos, gJobs, gDecodeResolved, gCreated, nowMs, +// decodeState, decodeAccept, decodeRun, logResult). +// +#include "jpeg_app.h" + +// copyin/copyout refuse a single transfer above copysize_limit_panic (64 MiB in +// the 25G342 kernel, read from the KDK); a 48-megapixel NV12 picture is ~71 +// MiB. Seen on hardware 2026-11-24: READ_USER of the 8064x6048 picture came +// back as BAD_ADDRESS. So both directions go in pieces of 16 MiB. +static constexpr uint32_t kAppCopyChunk = 16u << 20; +static bool appCopyInChunks(uint8_t* dst, uint64_t src, uint32_t bytes) { + for (uint32_t off = 0; off < bytes; off += kAppCopyChunk) { + uint32_t n = bytes - off < kAppCopyChunk ? bytes - off : kAppCopyChunk; + if (!appCopyIn(dst + off, src + off, n)) return false; + } + return true; +} +static bool appCopyOutChunks(uint64_t dst, const uint8_t* src, uint32_t bytes) { + for (uint32_t off = 0; off < bytes; off += kAppCopyChunk) { + uint32_t n = bytes - off < kAppCopyChunk ? bytes - off : kAppCopyChunk; + if (!appCopyOut(dst + off, src + off, n)) return false; + } + return true; +} + +static void* gAppOwner = nullptr; // the video context that holds the buffers +static uint64_t gAppDeadline = 0; // ms; the owner loses them after this +static uint32_t gAppRequests = 0; +static constexpr uint64_t kAppHoldMs = 2000; + +// Ends the current ownership: nothing of the picture may be left to read. +static void appDrop() { + if (gPool != nullptr && gDecoded) + memset(gPool + gP.surface, 0, gLayout.bytes); + gDecoded = false; + gLoadedBytes = gLoadPos = 0; + gAppOwner = nullptr; +} + +// True when `self` holds the buffers now, or can take them (take = a LOAD at +// offset 0). +static bool appOwns(void* self, bool take) { + uint64_t now = nowMs(); + if (gAppOwner != nullptr && gAppOwner != self && now >= gAppDeadline) + appDrop(); + if (gAppOwner == nullptr && take) gAppOwner = self; + if (gAppOwner != self) return false; + gAppDeadline = now + kAppHoldMs; + return true; +} + +// One request. `in` holds inSize bytes and starts with a checked ja_request; +// `out` has room for `cap` bytes. Returns the bytes written to out. +static uint32_t appHandle(void* self, const uint8_t* in, uint32_t inSize, + uint8_t* out, uint32_t cap) { + ja_request rq; + memcpy(&rq, in, sizeof(rq)); + ja_reply rp{}; + rp.magic = JA_REPLY_MAGIC; + uint8_t* data = out + sizeof(rp); + uint32_t room = cap - static_cast(sizeof(rp)); + auto done = [&](uint32_t status, uint32_t detail, uint32_t bytes) { + rp.status = status; + rp.detail = detail; + rp.dataBytes = bytes; + memcpy(out, &rp, sizeof(rp)); + return static_cast(sizeof(rp)) + bytes; + }; + if (rq.protocol != JA_PROTOCOL) return done(JA_BAD_REQUEST, 0, 0); + gAppRequests++; + if (rq.op == JA_OP_INFO) { + rp.v[0] = decodeState(); + rp.v[1] = gP.bitstreamCap - 128; + rp.v[2] = gP.surfaceCap; + rp.v[3] = gJobs; + return done(JA_OK, 0, 0); + } + if (!gDecodeResolved || gPool == nullptr || !gCreated) + return done(JA_NOT_READY, 0, 0); + // Every request of a client keeps the block powered for another while. + appTouch(); + switch (rq.op) { + case JA_OP_LOAD: { + uint32_t piece = inSize - static_cast(sizeof(rq)); + if (!appOwns(self, rq.arg0 == 0)) return done(JA_BUSY, 0, 0); + if (rq.arg0 == 0) { + gLoadedBytes = gLoadPos = 0; + gDecoded = false; + } + if (piece == 0 || piece > JA_LOAD_PIECE || rq.arg1 == 0 || + rq.arg1 > gP.bitstreamCap - 128 || rq.arg0 != gLoadPos || + rq.arg0 + piece > rq.arg1) { + appDrop(); + return done(JA_BAD_REQUEST, 0, 0); + } + memcpy(gPool + gP.bitstream + rq.arg0, in + sizeof(rq), piece); + gLoadPos += piece; + if (gLoadPos != rq.arg1) return done(JA_MORE, 0, 0); + jc::Stream st = decodeAccept(gLoadPos); + gLoadPos = 0; + if (st != jc::Stream::Ok) { + appDrop(); + return done(JA_BAD_STREAM, static_cast(st), 0); + } + rp.v[0] = gStream.width; + rp.v[1] = gStream.height; + return done(JA_OK, 0, 0); + } + case JA_OP_LOAD_USER: { + if (!appOwns(self, true)) return done(JA_BUSY, 0, 0); + gLoadedBytes = gLoadPos = 0; + gDecoded = false; + if (rq.arg0 == 0 || rq.arg1 == 0 || rq.arg1 > gP.bitstreamCap - 128) { + appDrop(); + return done(JA_BAD_REQUEST, 0, 0); + } + if (!appCopyInChunks(gPool + gP.bitstream, rq.arg0, + static_cast(rq.arg1))) { + appDrop(); + return done(JA_BAD_ADDRESS, 0, 0); + } + jc::Stream st = decodeAccept(static_cast(rq.arg1)); + if (st != jc::Stream::Ok) { + appDrop(); + return done(JA_BAD_STREAM, static_cast(st), 0); + } + rp.v[0] = gStream.width; + rp.v[1] = gStream.height; + return done(JA_OK, 0, 0); + } + case JA_OP_READ_USER: { + if (!appOwns(self, false) || !gDecoded) return done(JA_NOT_OWNER, 0, 0); + if (rq.arg0 == 0 || rq.arg1 < gLayout.bytes) + return done(JA_BAD_REQUEST, 0, 0); + bool ok = appCopyOutChunks(rq.arg0, gPool + gP.surface, gLayout.bytes); + rp.v[0] = gLayout.bytes; + appDrop(); // read (or failed to): the next client may come + return done(ok ? JA_OK : JA_BAD_ADDRESS, 0, 0); + } + case JA_OP_RUN: { + if (!appOwns(self, false)) return done(JA_NOT_OWNER, 0, 0); + if (room < sizeof(ja_picture)) return done(JA_BAD_REQUEST, 0, 0); + // The only request that needs the block: it is powered here, not before. + if (!appBlockOn()) { + appDrop(); + return done(JA_NOT_READY, 0, 0); + } + // Only the write-pointer flag is the caller's to choose. + uint32_t flags = static_cast(rq.arg0) & jp::kFlagWptrRegister; + decodeRun(jp::kModeDecode, flags, &gResult); + if (gResult.status != static_cast(jp::Status::Ok)) { + uint32_t why = gResult.status; + logResult(&gResult); + appDrop(); + return done(why == static_cast(jp::Status::NotReady) + ? JA_NOT_READY + : JA_FAILED, + why, 0); + } + ja_picture pic{}; + pic.width = gResult.width; + pic.height = gResult.height; + pic.pitch = gResult.pitch; + pic.alignedHeight = gResult.alignedHeight; + pic.chromaOffset = gResult.chromaOffset; + pic.surfaceBytes = gResult.surfaceBytes; + pic.elapsedMs = gResult.elapsedMs; + pic.format = gResult.format; + memcpy(data, &pic, sizeof(pic)); + return done(JA_OK, 0, sizeof(pic)); + } + case JA_OP_READ: { + if (!appOwns(self, false) || !gDecoded) return done(JA_NOT_OWNER, 0, 0); + if (rq.arg0 >= gLayout.bytes) return done(JA_BAD_REQUEST, 0, 0); + uint32_t piece = gLayout.bytes - static_cast(rq.arg0); + if (piece > room) piece = room; + if (piece > JA_READ_PIECE) piece = JA_READ_PIECE; + memcpy(data, gPool + gP.surface + rq.arg0, piece); + rp.v[0] = gLayout.bytes; + bool last = rq.arg0 + piece == gLayout.bytes; + uint32_t n = done(JA_OK, 0, piece); + if (last) appDrop(); // read to the end: the next client may come + return n; + } + case JA_OP_RELEASE: + if (gAppOwner == self) appDrop(); + return done(JA_OK, 0, 0); + default: + return done(JA_BAD_REQUEST, 0, 0); + } +} + +// True when a request of the video context's sendPMCommand carries our header. +// PowerPlay's own requests start with their size too, but none has this code: +// PP_Cwdde serves 0xC08001 and above as tests, and below that the low 16 bits +// up to 0xB0. +static bool appIsOurs(const void* in, uint64_t inSize) { + if (in == nullptr || inSize < sizeof(ja_request) || inSize > JA_MAX_IO) + return false; + ja_request rq; + memcpy(&rq, in, sizeof(rq)); + return rq.size == JA_HEADER_SIZE && rq.code == JA_CODE; +} + +// One request that appIsOurs accepted. False = bad arguments, nothing written. +static bool appEntry(void* self, const void* in, uint64_t inSize, void* out, + uint64_t* outSize) { + if (out == nullptr || outSize == nullptr || *outSize < sizeof(ja_reply)) + return false; + uint32_t cap = + *outSize > JA_MAX_IO ? JA_MAX_IO : static_cast(*outSize); + *outSize = + appHandle(self, static_cast(in), + static_cast(inSize), static_cast(out), cap); + return true; +} + +// The block for `mib` MiB (clamped to kPoolMinMiB..kPoolMaxMiB): a quarter for +// the JPEG, never less than a megabyte, the rest for the picture, then the +// guard. +static constexpr uint32_t kPoolMinMiB = 8, kPoolMaxMiB = 128, + kPoolDefaultMiB = 128; +static void appPoolFor(uint32_t mib, Pool* p) { + if (mib < kPoolMinMiB) mib = kPoolMinMiB; + if (mib > kPoolMaxMiB) mib = kPoolMaxMiB; + uint32_t bytes = mib << 20; + uint32_t bs = (bytes / 4) & ~0xFFFu; + // the picture keeps at least the fixed block's room, the JPEG too + uint32_t most = bytes - p->guardBytes - p->bitstream - jl::kSurfaceCap; + if (bs > most) bs = most; + if (bs < jl::kBitstreamCap) bs = jl::kBitstreamCap; + p->bytes = bytes; + p->bitstreamCap = bs; + p->surface = p->bitstream + bs; + p->guard = bytes - p->guardBytes; + p->surfaceCap = p->guard - p->surface; +} diff --git a/GPU/jpeg/kext/decode_accept.hpp b/GPU/jpeg/kext/decode_accept.hpp new file mode 100644 index 00000000..54fe97e4 --- /dev/null +++ b/GPU/jpeg/kext/decode_accept.hpp @@ -0,0 +1,26 @@ +// +// decode_accept.hpp - the check every JPEG passes before anything counts as +// loaded. Included by kern_start.cpp, and by tests/apps_test.cpp so that the +// host test of the apps door runs this exact code. +// Needs: gPool, gP, gLoadedBytes, gDecoded, gStream, gLayout. +// +// Checks the JPEG that was just copied into the bitstream buffer, reads its +// size from it and pads it. Nothing counts as loaded unless this returns Ok. +static jc::Stream decodeAccept(size_t size) { + gLoadedBytes = 0; + gDecoded = false; + uint8_t* bs = gPool + gP.bitstream; + jc::StreamInfo info; + jc::Stream st = jc::parseStream(bs, size, &info); + if (st != jc::Stream::Ok) return st; + jc::Layout layout{}; + if (!jc::outputLayout(info.width, info.height, gP.surfaceCap, &layout, + info.chroma)) + return jc::Stream::BadFrame; + uint32_t padded = jc::alignUp(static_cast(size), 128); + memset(bs + size, 0, padded - size); + gStream = info; + gLayout = layout; + gLoadedBytes = padded; + return jc::Stream::Ok; +} diff --git a/GPU/jpeg/kext/hwlibs_expect.hpp b/GPU/jpeg/kext/hwlibs_expect.hpp new file mode 100644 index 00000000..6def2acb --- /dev/null +++ b/GPU/jpeg/kext/hwlibs_expect.hpp @@ -0,0 +1,131 @@ +// Generated by tools/gen_expect.py from the KDK AMDRadeonX6000HWLibs of 26.7.3 (25G342). Do not edit. +#pragma once +#include +#include + +namespace hwx { + +constexpr const char* kBuild = "26.7.3 (25G342)"; +// LC_UUID 5CD4BC0C-C225-365F-A872-C885575B9A19 +constexpr uint8_t kUuid[16]{0x5c, 0xd4, 0xbc, 0x0c, 0xc2, 0x25, 0x36, 0x5f, 0xa8, 0x72, 0xc8, 0x85, 0x57, 0x5b, 0x9a, 0x19}; + +enum Index : size_t { + kStartMM, + kCreateEngine, + kNotifyEngine, + kQueryState, + kStopMM, + kStopEngineQueue, + kTtlGetIpi, + kIpiGetJpegContext, + kJpegReadRegister, + kJpegCreateQueue, + kJpegStartQueue, + kJpegStopQueue, + kJpegQueryQueueStatus, + kCount +}; + +struct Function { + const char* symbol; + size_t offset; // from the image header + uint8_t head[16]; // the function's first bytes +}; +constexpr Function kFunctions[kCount]{ + {"__ZN14AmdTtlServices19startMMEngineQueuesEv", + 0xaf5e0, + {0x55, 0x48, 0x89, 0xe5, 0x41, 0x57, 0x41, 0x56, 0x41, 0x55, 0x41, 0x54, 0x53, 0x48, 0x83, 0xec}}, + {"__ZN14AmdTtlServices12createEngineE19AMD_SWIP_QUEUE_TYPEjP21_TtlCreateEngineInput", + 0xb1610, + {0x55, 0x48, 0x89, 0xe5, 0x41, 0x57, 0x41, 0x56, 0x41, 0x54, 0x53, 0x48, 0x83, 0xec, 0x20, 0x49}}, + {"__ZN14AmdTtlServices12notifyEngineE19AMD_SWIP_QUEUE_TYPEj20AMD_TTL_ENGINE_EVENT", + 0xb1530, + {0x55, 0x48, 0x89, 0xe5, 0x41, 0x57, 0x41, 0x56, 0x53, 0x50, 0x48, 0x89, 0xfb, 0x48, 0x8b, 0x7f}}, + {"__ZN14AmdTtlServices21queryEngineQueueStateE19AMD_SWIP_QUEUE_TYPEjP21AMD_SWIP_ENGINE_STATE", + 0xb1db0, + {0x55, 0x48, 0x89, 0xe5, 0x41, 0x57, 0x41, 0x56, 0x41, 0x54, 0x53, 0x48, 0x83, 0xec, 0x10, 0x48}}, + {"__ZN14AmdTtlServices18stopMMEngineQueuesEv", + 0xaf9b0, + {0x55, 0x48, 0x89, 0xe5, 0x41, 0x57, 0x41, 0x56, 0x53, 0x50, 0x48, 0x89, 0xfb, 0xc7, 0x45, 0xe4}}, + {"__ZN14AmdTtlServices15stopEngineQueueE19AMD_SWIP_QUEUE_TYPEj", + 0xb1c80, + {0x55, 0x48, 0x89, 0xe5, 0x41, 0x57, 0x41, 0x56, 0x41, 0x54, 0x53, 0x48, 0x89, 0xf8, 0x48, 0x8b}}, + {"_ttlGetIpi", + 0x90fd2, + {0x48, 0x85, 0xff, 0x74, 0x17, 0x55, 0x48, 0x89, 0xe5, 0x48, 0x8b, 0x3f, 0x48, 0x85, 0xff, 0x5d}}, + {"_IpiGetJpegContext", + 0xa6ea5, + {0x55, 0x48, 0x89, 0xe5, 0xbe, 0x0f, 0x00, 0x00, 0x00, 0x5d, 0xe9, 0xf4, 0x20, 0xff, 0xff, 0x55}}, + {"_jpeg_internal_cgs_read_register", + 0x3c211, + {0x55, 0x48, 0x89, 0xe5, 0x48, 0x8b, 0x07, 0x48, 0x8b, 0x4f, 0x10, 0x89, 0xf6, 0x03, 0x54, 0xb1}}, + {"_jpeg_create_queue", + 0x3c760, + {0x55, 0x48, 0x89, 0xe5, 0x41, 0x57, 0x41, 0x56, 0x41, 0x55, 0x41, 0x54, 0x53, 0x50, 0x44, 0x8b}}, + {"_jpeg_start_queue", + 0x3cb38, + {0x55, 0x48, 0x89, 0xe5, 0x41, 0x56, 0x53, 0x48, 0x89, 0xf3, 0x41, 0xbe, 0x02, 0x00, 0x00, 0x00}}, + {"_jpeg_stop_queue", + 0x3cbcc, + {0x55, 0x48, 0x89, 0xe5, 0x41, 0x56, 0x53, 0xb8, 0x02, 0x00, 0x00, 0x00, 0x48, 0x85, 0xff, 0x74}}, + {"_jpeg_query_queue_status", + 0x3cd98, + {0x55, 0x48, 0x89, 0xe5, 0xb8, 0x02, 0x00, 0x00, 0x00, 0x48, 0x85, 0xff, 0x74, 0x47, 0x48, 0x89}}, +}; + +// the decode job +enum DecodeIndex : size_t { + kSubmitFrame, + kJpegAllocMemory, + kJpegReleaseMemory, + kQueueSubmitFrame, + kJpegSubmitFrame, + kDecodeCount +}; + +constexpr Function kDecodeFunctions[kDecodeCount]{ + {"__ZN14AmdTtlServices11submitFrameE19AMD_SWIP_QUEUE_TYPEjPv", + 0xb0840, + {0x55, 0x48, 0x89, 0xe5, 0x41, 0x56, 0x53, 0xbb, 0xbc, 0x02, 0x00, 0xe0, 0x48, 0x85, 0xc9, 0x0f}}, + {"_jpeg_internal_cgs_alloc_memory", + 0x3c117, + {0x55, 0x48, 0x89, 0xe5, 0x41, 0x57, 0x41, 0x56, 0x53, 0x48, 0x83, 0xec, 0x48, 0x4c, 0x89, 0xcb}}, + {"_jpeg_internal_cgs_release_memory", + 0x3c1a8, + {0x55, 0x48, 0x89, 0xe5, 0x48, 0x83, 0xec, 0x30, 0x48, 0x89, 0xf8, 0x4c, 0x8d, 0x55, 0xd8, 0x49}}, + {"_queue_jpeg_decode_2_0_submit_frame", + 0x3dc10, + {0x55, 0x48, 0x89, 0xe5, 0x41, 0x56, 0x53, 0x48, 0x89, 0xfb, 0x4c, 0x8b, 0x77, 0x08, 0x8b, 0x57}}, + {"_jpeg_submit_frame", + 0x3ca68, + {0x55, 0x48, 0x89, 0xe5, 0xb8, 0x02, 0x00, 0x00, 0x00, 0x48, 0x85, 0xff, 0x74, 0x52, 0x48, 0x85}}, +}; + +// the power request: AMDRadeonX6000 of the same macOS build +// LC_UUID 1540D089-EE2D-3339-B5A8-2024F9E38581 +constexpr uint8_t kX6000Uuid[16]{0x15, 0x40, 0xd0, 0x89, 0xee, 0x2d, 0x33, 0x39, 0xb5, 0xa8, 0x20, 0x24, 0xf9, 0xe3, 0x85, 0x81}; + +enum PowerIndex : size_t { + kSendPMCommand, + kPowerCount +}; + +constexpr Function kPowerFunctions[kPowerCount]{ + {"__ZN37AMDRadeonX6000_AMDGraphicsAccelerator13sendPMCommandEPv", + 0x656c, + {0x55, 0x48, 0x89, 0xe5, 0x41, 0x57, 0x41, 0x56, 0x53, 0x50, 0x41, 0xbe, 0xd7, 0x02, 0x00, 0xe0}}, +}; + +// the door for apps: also in AMDRadeonX6000 +enum AppsIndex : size_t { + kVideoSendPM, + kAppsCount +}; + +constexpr Function kAppsFunctions[kAppsCount]{ + {"__ZN35AMDRadeonX6000_AMDAccelVideoContext13sendPMCommandEPvS0_yPy", + 0x280f2, + {0x55, 0x48, 0x89, 0xe5, 0x41, 0x57, 0x41, 0x56, 0x41, 0x55, 0x41, 0x54, 0x53, 0x48, 0x83, 0xec}}, +}; + +} // namespace hwx diff --git a/GPU/jpeg/kext/idle_logic.hpp b/GPU/jpeg/kext/idle_logic.hpp new file mode 100644 index 00000000..0287c6da --- /dev/null +++ b/GPU/jpeg/kext/idle_logic.hpp @@ -0,0 +1,49 @@ +// +// idle_logic.hpp - when VCNJpeg gives the JPEG block's power back. No kernel +// parts: kern_start.cpp drives it with the clock and a thread_call, and +// tests/apps_test.cpp with a made-up clock. +// +// The block is powered (PowerPlay client 21 + the queue started) only while +// some client sends requests. Every request of a client is a touch; the block +// goes off once kIdleMs pass without one. The timer is armed by the first +// touch and, when it fires early because touches came meanwhile, armed again +// for what is left: a stream of frames arms it once per kIdleMs, never per +// frame, and never sees the block go off between two frames. +// +#pragma once +#include + +namespace jidle { + +constexpr uint64_t kIdleMs = 2000; + +struct Idle { + bool on = false; // the block is powered and its queue started + bool armed = false; // the timer is pending + uint64_t last = 0; // ms of the last touch +}; + +// A request of a client at `now`. Returns the delay in ms to arm the timer +// with, or 0 when it is armed already. +inline uint64_t touch(Idle& s, uint64_t now) { + s.last = now; + if (s.armed) return 0; + s.armed = true; + return kIdleMs; +} + +enum class Tick { Nothing, PowerOff, Rearm }; + +// The timer fired at `now`. PowerOff: give the power back now. Rearm: arm the +// timer again with *delayMs. +inline Tick tick(Idle& s, uint64_t now, uint64_t* delayMs) { + s.armed = false; + if (!s.on) return Tick::Nothing; + uint64_t idle = now >= s.last ? now - s.last : 0; + if (idle >= kIdleMs) return Tick::PowerOff; + *delayMs = kIdleMs - idle; + s.armed = true; + return Tick::Rearm; +} + +} // namespace jidle diff --git a/GPU/jpeg/kext/jpeg_cmds.hpp b/GPU/jpeg/kext/jpeg_cmds.hpp new file mode 100644 index 00000000..57c5fcd9 --- /dev/null +++ b/GPU/jpeg/kext/jpeg_cmds.hpp @@ -0,0 +1,460 @@ +// +// jpeg_cmds.hpp - the words a JPEG decode job is made of. No kernel parts: the +// kext and the host tests include this one file. +// +// Two levels, as on Linux: +// +// * the ring frame, 64 words copied into the JRBC ring by Apple's +// queue_jpeg_decode_2_0_submit_frame: start marker, "run this IB", fence, +// end marker, padding. The words are those Apple's own +// queue_jpeg_decode_2_0_build_command (KDK 0x3d7d4) writes for the commands +// 0x20007, 0x20002, 0x20003, 0x20008 and 0x20001; tests/hwlibs_oracle.c +// runs that function from the KDK binary and compares. +// +// * the IB, the per-picture register writes. HWLibs has no code for it. It is +// Mesa's vcn_jpeg_build_decode_cmd (src/amd/common/ac_vcn_dec.c) for the +// register layout Mesa uses on VCN 2.0 to 4.0 (RDECODE_JPEG_VER_2), with a +// linear NV12 target; tests/mesa_oracle.c compiles Mesa's function itself +// and compares. +// +// It also holds the checks that keep the block inside its buffers: the size +// of the picture is read here from the stream itself (parseStream), because +// the hardware writes as many rows as the stream says, whatever the caller +// believes. +// +#pragma once +#include +#include + +namespace jc { + +// PACKETJ(reg, r, cond, type) of Linux jpeg_v2_0.h; r is always 0. +constexpr uint32_t pktj(uint32_t reg, uint32_t cond, uint32_t type) { + return (reg & 0x3FFFF) | ((cond & 0xF) << 24) | ((type & 0xF) << 28); +} +constexpr uint32_t kNop = 0x60000000; // PACKETJ(0, 0, 0, TYPE6) + +// Register numbers as the ring and the IB name them ("internal offsets"). +// For the JPEG registers of vcn_3_0_0_offset.h (BASE_IDX 1) the internal +// number is the header's offset + 0x3f80; each one was checked against it. +namespace reg { +// ring level (Linux jpeg_v2_0.h) +constexpr uint32_t kGpcomCmd = 0x4029; // mmUVD_JPEG_GPCOM_CMD +constexpr uint32_t kGpcomData0 = 0x402a; +constexpr uint32_t kGpcomData1 = 0x402b; +constexpr uint32_t kIbSize = 0x4082; // mmUVD_JRBC_IB_SIZE +constexpr uint32_t kRbRefData = 0x4084; // mmUVD_JRBC_RB_REF_DATA +constexpr uint32_t kRbCondRdTimer = 0x4085; // mmUVD_JRBC_RB_COND_RD_TIMER +constexpr uint32_t kJrbcStatus = 0x4089; // mmUVD_JRBC_STATUS +constexpr uint32_t kIbVmid = 0x40cf; // mmUVD_LMI_JRBC_IB_VMID +constexpr uint32_t kJpegVmid = 0x40d1; // mmUVD_LMI_JPEG_VMID +constexpr uint32_t kIbBarLow = 0x40e8; // mmUVD_LMI_JRBC_IB_64BIT_BAR_LOW +constexpr uint32_t kIbBarHigh = 0x40e9; +constexpr uint32_t kMemWrBarLow = + 0x40ea; // mmUVD_LMI_JRBC_RB_MEM_WR_64BIT_BAR_LOW +constexpr uint32_t kMemWrBarHigh = 0x40eb; +constexpr uint32_t kMemRdBarLow = + 0x40ec; // mmUVD_LMI_JRBC_RB_MEM_RD_64BIT_BAR_LOW +constexpr uint32_t kMemRdBarHigh = 0x40ed; +constexpr uint32_t kExternalReg = + 0x1bfff; // mmUVD_JRBC_EXTERNAL_REG_INTERNAL_OFFSET +constexpr uint32_t kExternalWrite = + 0x18000; // JRBC_DEC_EXTERNAL_REG_WRITE_ADDR +// IB level (Mesa ac_vcn_dec.h, vcnip*) +constexpr uint32_t kJpegCntl = 0x4000; // mmUVD_JPEG_CNTL +constexpr uint32_t kRbBase = 0x4001; // mmUVD_JPEG_RB_BASE +constexpr uint32_t kRbWptr = 0x4002; +constexpr uint32_t kRbRptr = 0x4003; +constexpr uint32_t kRbSize = 0x4004; +constexpr uint32_t kIntEn = 0x400a; // mmUVD_JPEG_INT_EN +constexpr uint32_t kTierCntl2 = 0x400f; +constexpr uint32_t kOutbufCntl = 0x401c; +constexpr uint32_t kOutbufWptr = 0x401d; +constexpr uint32_t kOutbufRptr = 0x401e; +constexpr uint32_t kPitch = 0x401f; // mmUVD_JPEG_PITCH +constexpr uint32_t kUvPitch = 0x4020; +constexpr uint32_t kYTiling = 0x4024; // mmJPEG_DEC_Y_GFX10_TILING_SURFACE +constexpr uint32_t kUvTiling = 0x4025; +constexpr uint32_t kAddrMode = 0x4027; // mmJPEG_DEC_ADDR_MODE +constexpr uint32_t kIndex = 0x402c; // mmUVD_JPEG_INDEX +constexpr uint32_t kData = 0x402d; +constexpr uint32_t kSoftRst = 0x402f; // mmUVD_JPEG_DEC_SOFT_RST +constexpr uint32_t kIbCondRdTimer = 0x408e; // mmUVD_JRBC_IB_COND_RD_TIMER +constexpr uint32_t kIbRefData = 0x408f; +constexpr uint32_t kReadBarLow = 0x40e0; // mmUVD_LMI_JPEG_READ_64BIT_BAR_LOW +constexpr uint32_t kReadBarHigh = 0x40e1; +constexpr uint32_t kWriteBarLow = 0x40e2; // mmUVD_LMI_JPEG_WRITE_64BIT_BAR_LOW +constexpr uint32_t kWriteBarHigh = 0x40e3; +} // namespace reg + +constexpr uint32_t kFrameWords = + 64; // the queue is created with 256-byte frames +constexpr uint32_t kIbMaxWords = 128; // Mesa's max_decode_cmd_dw +constexpr uint32_t kRingTestValue = + 0xABADCAFE; // Linux amdgpu_jpeg_dec_ring_test_ring +constexpr uint32_t kRingTestOther = + 0xCAFEDEAD; // used when the register already holds the first one +constexpr uint32_t kIbTestValue = + 0xDEADBEEF; // Linux amdgpu_jpeg_dec_ring_test_ib + +// A bounded word writer: once full it stops writing and reports failure. +struct Words { + uint32_t* p; + uint32_t cap; + uint32_t n = 0; + bool ok = true; + constexpr Words(uint32_t* buffer, uint32_t capacity) + : p(buffer), cap(capacity) {} + constexpr void put(uint32_t header, uint32_t value) { + if (n + 2 > cap) { + ok = false; + return; + } + p[n++] = header; + p[n++] = value; + } + constexpr void set(uint32_t r, uint32_t cond, uint32_t type, uint32_t value) { + put(pktj(r, cond, type), value); + } + constexpr void padTo(uint32_t multiple) { + while (ok && (n % multiple) != 0) put(kNop, 0); + } +}; + +// ---- ring frame +// ----------------------------------------------------------------- + +// command 0x20007 / 0x20008 +constexpr void putStart(Words& w) { + w.put(reg::kExternalReg, 0x68e04); + w.put(reg::kExternalWrite, 0x80010000); +} +constexpr void putEnd(Words& w) { + w.put(reg::kExternalReg, 0x68e04); + w.put(reg::kExternalWrite, 0x00010000); +} +// command 0x20002: run the IB at ibGpu (ibWords long) with the given VMID. +constexpr void putIb(Words& w, uint32_t vmid, uint64_t ibGpu, uint32_t ibWords, + uint64_t ringGpu) { + uint32_t v = vmid | (vmid << 4); + w.put(reg::kIbVmid, v); + w.put(reg::kJpegVmid, v); + w.put(reg::kIbBarHigh, static_cast(ibGpu >> 32)); + w.put(reg::kIbBarLow, static_cast(ibGpu)); + w.put(reg::kIbSize, ibWords); + w.put(reg::kMemRdBarLow, static_cast(ringGpu)); + w.put(reg::kMemRdBarHigh, static_cast(ringGpu >> 32)); + w.put(pktj(0, 0, 2), 0); + w.put(reg::kRbCondRdTimer, 0x01400200); + w.put(reg::kRbRefData, 2); + w.put(pktj(reg::kJrbcStatus, 3, 3), 2); +} +// command 0x20003: write seq to the memory at fenceGpu, then read it back. +constexpr void putFence(Words& w, uint32_t seq, uint64_t fenceGpu) { + uint32_t lo = static_cast(fenceGpu); + uint32_t hi = static_cast(fenceGpu >> 32); + w.put(reg::kGpcomData0, seq); + w.put(reg::kGpcomData1, seq); + w.put(reg::kMemWrBarLow, lo); + w.put(reg::kMemWrBarHigh, hi); + w.put(reg::kGpcomCmd, 8); + w.put(pktj(reg::kGpcomCmd, 0, 4), 0); + w.put(reg::kRbCondRdTimer, 0x01400200); + w.put(reg::kRbRefData, seq); + w.put(reg::kMemRdBarLow, lo); + w.put(reg::kMemRdBarHigh, hi); + w.put(pktj(0, 3, 2), 0xFFFFFFFF); + w.put(reg::kExternalReg, 0x3fbc); + w.put(reg::kExternalWrite, 1); +} + +// The frame of a job: start, IB, fence, end, padding. No trap command +// (0x20004): macOS has nobody listening for the JPEG interrupt, the caller +// polls the fence. +constexpr bool buildJobFrame(uint32_t frame[kFrameWords], uint64_t ringGpu, + uint64_t ibGpu, uint32_t ibWords, uint32_t seq, + uint64_t fenceGpu) { + Words w(frame, kFrameWords); + putStart(w); + putIb(w, 0, ibGpu, ibWords, ringGpu); + putFence(w, seq, fenceGpu); + putEnd(w); + w.padTo(kFrameWords); + return w.ok && w.n == kFrameWords; +} + +// Linux's ring test: one register write straight in the ring, no IB, no fence. +constexpr bool buildRingTestFrame(uint32_t frame[kFrameWords], uint32_t value) { + Words w(frame, kFrameWords); + w.set(reg::kPitch, 0, 0, value); + w.padTo(kFrameWords); + return w.ok && w.n == kFrameWords; +} + +// ---- IBs +// -------------------------------------------------------------------------- + +// Linux's IB test (amdgpu_jpeg_dec_set_reg): one register write and padding. +constexpr uint32_t buildTestIb(uint32_t* ib, uint32_t cap, uint32_t value) { + Words w(ib, cap); + w.set(reg::kPitch, 0, 0, value); + w.padTo(16); + return w.ok ? w.n : 0; +} + +struct DecodeParams { + uint64_t bitstreamGpu; + uint32_t bitstreamBytes; // padded to 128, the padding zeroed + uint64_t targetGpu; // start of the surface + uint32_t pitch; // Mesa's dt_pitch[0]: pixels per row (= bytes for NV12 luma) + uint32_t uvPitch; // Mesa's dt_pitch[1]: chroma row (bytes for NV12, 0 for + // one plane) + uint32_t lumaOffset; // from targetGpu + uint32_t chromaOffset; // from targetGpu (0 for one plane) +}; + +// Mesa's vcn_jpeg_build_decode_cmd for RDECODE_JPEG_VER_2, a linear surface +// (RDECODE_TILE_LINEAR, ADDR_SW_LINEAR, both 0), no crop and no colour +// conversion, then the padding Mesa's winsys adds (to 16 words). +constexpr uint32_t buildDecodeIb(uint32_t* ib, uint32_t cap, + const DecodeParams& d) { + constexpr uint32_t kTileLinear = 0, kSwizzleLinear = 0; + Words w(ib, cap); + // jpeg soft reset, and wait until it shows in the SCLK domain + w.set(reg::kSoftRst, 0, 0, 1); + w.set(reg::kIbCondRdTimer, 0, 0, 0x01400200); + w.set(reg::kIbRefData, 0, 0, 0x1 << 0x10); + w.set(reg::kSoftRst, 3, 3, 0x1 << 0x10); + w.set(reg::kSoftRst, 0, 0, 0); + w.set(reg::kIbRefData, 0, 0, 0 << 0x10); + w.set(reg::kSoftRst, 3, 3, 0x1 << 0x10); + // bitstream + w.set(reg::kReadBarHigh, 0, 0, static_cast(d.bitstreamGpu >> 32)); + w.set(reg::kReadBarLow, 0, 0, static_cast(d.bitstreamGpu)); + w.set(reg::kRbBase, 0, 0, 0); + w.set(reg::kRbSize, 0, 0, 0xfffffff0); + w.set(reg::kRbWptr, 0, 0, d.bitstreamBytes >> 2); + // target + w.set(reg::kPitch, 0, 0, d.pitch >> 4); + w.set(reg::kUvPitch, 0, 0, d.uvPitch >> 4); + w.set(reg::kAddrMode, 0, 0, kTileLinear | (kTileLinear << 2)); + w.set(reg::kYTiling, 0, 0, kSwizzleLinear); + w.set(reg::kUvTiling, 0, 0, kSwizzleLinear); + w.set(reg::kWriteBarHigh, 0, 0, static_cast(d.targetGpu >> 32)); + w.set(reg::kWriteBarLow, 0, 0, static_cast(d.targetGpu)); + w.set(reg::kIndex, 0, 0, 0); + w.set(reg::kData, 0, 0, d.lumaOffset); + w.set(reg::kIndex, 0, 0, 1); + w.set(reg::kData, 0, 0, d.chromaOffset); + w.set(reg::kIndex, 0, 0, 2); + w.set(reg::kData, 0, 0, 0); + w.set(reg::kTierCntl2, 0, 0, 0); + w.set(reg::kOutbufRptr, 0, 0, 0); + w.set(reg::kOutbufCntl, 0, 0, + (0x00001587 & ~0x00000180u) | (0x1 << 0x7) | (0x1 << 0x6)); + // error interrupts, start + w.set(reg::kIntEn, 0, 0, 0xfffffffe); + w.set(reg::kJpegCntl, 0, 0, 0x6); + // wait until the whole bitstream was fetched, then until the output is idle + w.set(reg::kIbRefData, 0, 0, d.bitstreamBytes >> 2); + w.set(reg::kIbCondRdTimer, 0, 0, 0x01400200); + w.set(reg::kRbRptr, 3, 3, 0xffffffff); + w.set(reg::kIbRefData, 0, 0, 0xffffffff); + w.set(reg::kOutbufWptr, 3, 3, 0x00000001); + // stop + w.set(reg::kJpegCntl, 0, 0, 0x4); + w.padTo(16); + return w.ok ? w.n : 0; +} + +// ---- where the picture goes +// ---------------------------------------------------------- + +// What the block writes depends on the JPEG itself: JPEG 2.0 has no +// output-format register, the sampling factors in the frame header decide. Mesa +// offers NV12 for 4:2:0 and YUYV (PIPE_FORMAT_YUYV, one packed plane) for 4:2:2 +// on this block (si_vid_is_format_supported, PIPE_VIDEO_PROFILE_JPEG_BASELINE); +// no NV16. +enum class Chroma : uint32_t { k420 = 0, k422 = 1 }; +struct Layout { + uint32_t + pitch; // bytes per row (NV12: luma and chroma alike; YUYV: 2 per pixel) + uint32_t alignedHeight; // rows the block writes + uint32_t chromaOffset; // NV12: pitch * alignedHeight; YUYV: 0 + uint32_t bytes; // all the block may write + Chroma chroma = Chroma::k420; + uint32_t regPitch = 0; // Mesa's dt_pitch[0]: pixels per row + uint32_t regUvPitch = 0; // Mesa's dt_pitch[1] +}; +// 4096 unless the build says otherwise: nothing larger has run. Linux's limit +// for this block on Navi 21 is 16384 x 16384 (nv.c, sc_video_codecs_decode). +#ifndef JC_MAX_DIM +#define JC_MAX_DIM 4096 +#endif +constexpr uint32_t kMaxWidth = JC_MAX_DIM, kMaxHeight = JC_MAX_DIM; +constexpr uint32_t alignUp(uint32_t v, uint32_t a) { + return (v + a - 1) / a * a; +} + +// The block writes whole MCUs, so rows and columns are counted rounded up to +// 16; the row is rounded to 256 bytes as Mesa's linear surfaces are on this GPU +// family. 4:2:0 -> NV12 (two planes). 4:2:2 -> YUYV (one plane, 2 bytes per +// pixel; Mesa's YUYV surface has blk_w 2 and bpe 4, so dt_pitch[0] counts +// pixels). +constexpr bool outputLayout(uint32_t width, uint32_t height, uint32_t capacity, + Layout* out, Chroma chroma = Chroma::k420) { + if (width == 0 || height == 0 || width > kMaxWidth || height > kMaxHeight) + return false; + uint32_t rows = alignUp(height, 16); + if (chroma == Chroma::k422) { + uint32_t pitch = alignUp(alignUp(width, 16) * 2, 256); + uint64_t bytes = static_cast(pitch) * rows; + if (bytes > capacity) return false; + out->pitch = pitch; + out->alignedHeight = rows; + out->chromaOffset = 0; + out->bytes = static_cast(bytes); + out->chroma = chroma; + out->regPitch = pitch / 2; + out->regUvPitch = 0; + return true; + } + uint32_t pitch = alignUp(alignUp(width, 16), 256); + uint64_t bytes = static_cast(pitch) * rows * 3 / 2; + if (bytes > capacity) return false; + out->pitch = pitch; + out->alignedHeight = rows; + out->chromaOffset = pitch * rows; + out->bytes = static_cast(bytes); + out->chroma = Chroma::k420; + out->regPitch = pitch; + out->regUvPitch = pitch; + return true; +} + +// The IB parameters for a surface laid out by outputLayout. +constexpr DecodeParams decodeParams(const Layout& l, uint64_t bitstreamGpu, + uint32_t bitstreamBytes, + uint64_t targetGpu) { + DecodeParams d{}; + d.bitstreamGpu = bitstreamGpu; + d.bitstreamBytes = bitstreamBytes; + d.targetGpu = targetGpu; + d.pitch = l.regPitch; + d.uvPitch = l.regUvPitch; + d.lumaOffset = 0; + d.chromaOffset = l.chromaOffset; + return d; +} + +// ---- the stream +// ------------------------------------------------------------------------ + +enum class Stream : uint32_t { + Ok = 0, + TooShort, // not even SOI + EOI + NoSoi, + BadSegment, // a marker or length that does not fit + Unsupported, // a frame type other than baseline (SOF0) + BadFrame, // SOF0 that is not 8-bit, 3 components, 4:2:0 or 4:2:2 + TwoFrames, + NoTables, // DQT or DHT missing before the scan + NoFrame, // SOS before SOF0 + NoScan, + NoEoi, +}; + +struct StreamInfo { + uint32_t width = 0; + uint32_t height = 0; + uint32_t scanOffset = 0; // first byte after the SOS header + uint32_t restartInterval = 0; + Chroma chroma = Chroma::k420; +}; + +// Walks the markers up to the scan and reads the picture size from SOF0. +// Accepts baseline, 8 bits, three components sampled for NV12 (4:2:0) or YUYV +// (4:2:2: webcams' 2x1/1x1/1x1 and ffmpeg's 2x2/1x2/1x2), with its own DQT and +// DHT. +constexpr Stream parseStream(const uint8_t* d, size_t n, StreamInfo* out) { + if (n < 4) return Stream::TooShort; + if (d[0] != 0xff || d[1] != 0xd8) return Stream::NoSoi; + if (d[n - 2] != 0xff || d[n - 1] != 0xd9) return Stream::NoEoi; + bool frame = false, dqt = false, dht = false; + StreamInfo info; + size_t i = 2; + while (true) { + if (i + 4 > n) return Stream::NoScan; + if (d[i] != 0xff) return Stream::BadSegment; + uint8_t m = d[i + 1]; + size_t len = (static_cast(d[i + 2]) << 8) | d[i + 3]; + if (len < 2 || i + 2 + len > n) return Stream::BadSegment; + const uint8_t* s = d + i + 4; // segment body, len - 2 bytes + if (m == 0xc0) { + if (frame) return Stream::TwoFrames; + if (len != 17 || s[0] != 8 || s[5] != 3) return Stream::BadFrame; + info.height = (static_cast(s[1]) << 8) | s[2]; + info.width = (static_cast(s[3]) << 8) | s[4]; + // the sampling factors as Mesa's radeon_dec_jpeg_check_format reads them + // (Y, Cb, Cr): 0x221111 -> NV12; 0x211111, 0x221212, 0x222121 -> YUYV + uint32_t sf = (static_cast(s[7]) << 16) | + (static_cast(s[10]) << 8) | s[13]; + if (sf == 0x221111) + info.chroma = Chroma::k420; + else if (sf == 0x211111 || sf == 0x221212 || sf == 0x222121) + info.chroma = Chroma::k422; + else + return Stream::BadFrame; + if (info.width == 0 || info.height == 0) return Stream::BadFrame; + frame = true; + } else if (m == 0xdb) { + dqt = true; + } else if (m == 0xc4) { + dht = true; + } else if (m == 0xdd) { + if (len != 4) return Stream::BadSegment; + info.restartInterval = (static_cast(s[0]) << 8) | s[1]; + } else if (m == 0xda) { + if (!frame) return Stream::NoFrame; + if (!dqt || !dht) return Stream::NoTables; + info.scanOffset = static_cast(i + 2 + len); + *out = info; + return Stream::Ok; + } else if ((m >= 0xe0 && m <= 0xef) || m == 0xfe) { + // APPn and COM carry nothing the decoder needs + } else { + return Stream::Unsupported; + } + i += 2 + len; + } +} + +constexpr const char* streamText(Stream s) { + switch (s) { + case Stream::Ok: + return "ok"; + case Stream::TooShort: + return "too short"; + case Stream::NoSoi: + return "does not start with SOI"; + case Stream::BadSegment: + return "a segment does not fit"; + case Stream::Unsupported: + return "not a baseline JPEG"; + case Stream::BadFrame: + return "frame header is not 8-bit 4:2:0 or 4:2:2 with 3 components"; + case Stream::TwoFrames: + return "more than one frame header"; + case Stream::NoTables: + return "quantisation or Huffman tables missing"; + case Stream::NoFrame: + return "scan before the frame header"; + case Stream::NoScan: + return "no scan"; + case Stream::NoEoi: + return "does not end with EOI"; + } + return "?"; +} + +} // namespace jc diff --git a/GPU/jpeg/kext/jpeg_layout.hpp b/GPU/jpeg/kext/jpeg_layout.hpp new file mode 100644 index 00000000..1281c30a --- /dev/null +++ b/GPU/jpeg/kext/jpeg_layout.hpp @@ -0,0 +1,149 @@ +// +// jpeg_layout.hpp - offsets inside AMDRadeonX6000HWLibs' objects (25G342). +// +// Each offset names the function whose Hex-Rays output shows it; addresses are +// those of the KDK binary. The maintainer's static check compares this file +// with the output of Hex-Rays (IDA) for the same functions. +// +#pragma once +#include +#include + +// clang-format off: a table, one offset per line with the function that shows it + +namespace jl { + +// AmdTtlServices (C++ object) +constexpr size_t kTtlHandle = 56; // ttl_initialize(.., this + 56) initialize 0xaeac0 +constexpr size_t kTtlQueueSlots = 2424; // this + 2424 + 32*type + 8*index createEngine 0xb1610 +constexpr size_t kTtlGartInfo = 1256; // qwords 157..160 getNonLocalMemoryInfo 0xabc30 +constexpr size_t queueSlot(unsigned type, unsigned index) { + return kTtlQueueSlots + 32 * type + 8 * index; +} + +// AMD_SWIP_QUEUE_TYPE 5 -> TTL engine type 2 = JPEG decode (table 0x509e90) +constexpr int kQueueTypeJpegDecode = 5; +// AMD_TTL_ENGINE_EVENT TtlRtsNotifyEngine 0x91dd0 +constexpr uint32_t kEventStart = 0; +constexpr uint32_t kEventStop = 1; +// _TtlCreateEngineInput {frame bytes, frame count}; Apple's decode queue uses +// {0x100, 0x100} startMMEngineQueues 0xaf5e0 +constexpr uint32_t kFrameBytes = 256; +constexpr uint32_t kFrameCount = 256; + +// ipi JPEG context (232 bytes) ipiJpegCreateContext 0xa6ed5 +constexpr size_t kIpiJpegCtx = 40; // jpeg module context ipiJpegCreateQueue 0xa71ed +constexpr size_t kIpiCreateQueue = 56; // jpeg_create_queue ipiJpegCreateQueue 0xa71ed +constexpr size_t kIpiStartQueue = 72; // jpeg_start_queue ipiJpegStartQueue 0xa7317 +constexpr size_t kIpiStopQueue = 80; // jpeg_stop_queue ipiJpegStopQueue 0xa7338 +constexpr size_t kIpiQueryStatus = 96; // jpeg_query_queue_status ipiJpegQueryEngineState 0xa737a + +// jpeg module context (64 bytes) jpeg_sw_init 0x3be36 +constexpr size_t kCtxCgs = 0; +constexpr size_t kCtxEngine = 16; +constexpr size_t kCtxQueueMgr = 24; + +// jpeg engine (680 bytes) jpeg_engine_sw_init 0x3cea8 +constexpr size_t kEngInit = 0; // jpeg_start_queue 0x3cb38 +constexpr size_t kEngCfgPG = 4; // PP_EnableJPEGPG +constexpr size_t kEngCfgDPG = 8; // EnableJPEGDPG +constexpr size_t kEngCfgCG = 12; // EnableJPEGCG +constexpr size_t kEngCfgSecureLoad = 16; // EnableJPEGSecureLoad +constexpr size_t kEngCfgDoorbell = 20; // EnableJPEGDOORBELL +constexpr size_t kEngRegBase0 = 68; // jpeg_internal_cgs_read_register 0x3c211 +constexpr size_t kEngRegBase1 = 72; +constexpr size_t kEngVersion = 632; // jpeg_get_ip_version 0x3c4db +constexpr size_t kEngTiling = 636; // jpeg_engine_hw_init 0x3d042 +constexpr uint32_t kVersionVcn30 = 0x30000; + +// jpeg queue manager (48 bytes) jpeg_queue_manager_2_0_initialize 0x3e214 +constexpr size_t kMgrActive = 0; // jpeg_start_queue 0x3cb38 +constexpr size_t kMgrDecodeOk = 4; +constexpr size_t kMgrDecodeQueue = 16; // jpeg_create_queue 0x3c760 + +// jpeg queue (208 bytes) jpeg_create_queue 0x3c760 +constexpr size_t kQFlags = 0; // bit 0 started, bit 1 page fault +constexpr size_t kQType = 16; +constexpr size_t kQRingSize = 24; // queue_jpeg_decode_2_0_init_ring 0x3d634 +constexpr size_t kQGpuAddr = 40; +constexpr size_t kQCur = 72; // queue_jpeg_decode_2_0_submit_frame 0x3dc10 +constexpr size_t kQFrameCount = 76; +constexpr size_t kQFrameBytes = 80; + +// Registers, as (set, offset) of jpeg_internal_cgs_read_register. The set is +// the register's BASE_IDX in Linux's vcn_3_0_0_offset.h, where the names come +// from (name, offset and BASE_IDX of every entry were checked against it). +struct Reg { + const char* name; + uint32_t set; + uint32_t offset; +}; +constexpr Reg kPowerRegs[]{ + {"UVD_PGFSM_STATUS", 1, 0x001}, + {"UVD_JPEG_POWER_STATUS", 1, 0x00a}, +}; +constexpr Reg kRingRegs[]{ + {"UVD_JRBC_RB_WPTR", 0, 0x100}, + {"UVD_JRBC_RB_CNTL", 0, 0x101}, + {"UVD_JRBC_STATUS", 0, 0x109}, + {"UVD_JRBC_RB_RPTR", 0, 0x10a}, + {"UVD_JRBC_RB_SIZE", 0, 0x113}, + {"UVD_LMI_JRBC_RB_64BIT_BAR_LOW", 0, 0x166}, + {"UVD_LMI_JRBC_RB_64BIT_BAR_HIGH", 0, 0x167}, + {"UVD_JMI_CNTL", 0, 0x192}, + {"JPEG_SYS_INT_EN", 0, 0x1c1}, + {"JPEG_CGC_GATE", 0, 0x1e0}, + {"JPEG_CGC_CTRL", 0, 0x1e1}, + {"JPEG_DEC_GFX10_ADDR_CONFIG", 0, 0x0a6}, +}; + +// ---- the decode job (kern_start.cpp) --------------------------------------------- +// ipi JPEG context +constexpr size_t kIpiSubmitFrame = 136; // jpeg_submit_frame ipiJpegSubmitFrame 0xa7542 +// jpeg module context +constexpr size_t kCtxDoorbell = 40; // pointer the write pointer is stored through queue_jpeg_decode_2_0_submit_frame 0x3dc10 +// jpeg queue +constexpr size_t kQMemType = 48; // queue_jpeg_decode_2_0_init_ring 0x3d634 +constexpr size_t kQRingCpu = 56; +constexpr size_t kQHandle = 64; +constexpr size_t kQSubmit = 144; // jpeg_submit_frame 0x3ca68 +// jpeg_internal_cgs_alloc_memory(cgs, size, align, type, &gpu, &handle, flag) 0x3c117 +constexpr uint32_t kMemTypeRing = 2; // the type and alignment the ring itself is allocated with +constexpr int32_t kMemAlign = 256; + +// One allocation, made right after the queue (see kern_start.cpp for why then), +// and only if at least kGartSpare bytes of the GART are still unused by then +// (AMDHWGart::setParameters wants total > used; this Mac's GART is 0x40200000). +constexpr uint64_t kGartSpare = 0x10000000; +constexpr uint32_t kPoolBytes = 0x500000; +constexpr uint32_t kPoolIb = 0x000000; // 4 KiB +constexpr uint32_t kPoolFence = 0x001000; // 4 KiB +constexpr uint32_t kPoolBitstream = 0x010000; +constexpr uint32_t kBitstreamCap = 0x100000; +constexpr uint32_t kPoolSurface = 0x110000; +constexpr uint32_t kSurfaceCap = 0x3E0000; +constexpr uint32_t kPoolGuard = 0x4F0000; // filled with kGuardByte, checked after every decode +constexpr uint32_t kGuardBytes = 0x010000; +constexpr uint8_t kGuardByte = 0xA5; +constexpr uint8_t kSurfaceFill = 0xEE; // what the surface holds before the block writes + +// The register the ring and IB tests write (Linux uses the same one). +constexpr Reg kTestReg{"UVD_JPEG_PITCH", 0, 0x09f}; +// Read after every job; same order as jp::kRegNames (jpeg_proto.hpp). +constexpr Reg kJobRegs[]{ + {"UVD_JRBC_RB_WPTR", 0, 0x100}, + {"UVD_JRBC_RB_RPTR", 0, 0x10a}, + {"UVD_JRBC_STATUS", 0, 0x109}, + {"UVD_JPEG_CNTL", 0, 0x080}, + {"UVD_JPEG_RB_WPTR", 0, 0x082}, + {"UVD_JPEG_RB_RPTR", 0, 0x083}, + {"UVD_JPEG_INT_EN", 0, 0x08a}, + {"UVD_JPEG_INT_STAT", 0, 0x08b}, + {"UVD_JPEG_OUTBUF_WPTR", 0, 0x09d}, + {"UVD_JPEG_PITCH", 0, 0x09f}, + {"UVD_JPEG_UV_PITCH", 0, 0x0a0}, + {"UVD_JPEG_POWER_STATUS", 1, 0x00a}, +}; + +} // namespace jl +// clang-format on diff --git a/GPU/jpeg/kext/jpeg_power.hpp b/GPU/jpeg/kext/jpeg_power.hpp new file mode 100644 index 00000000..0c6bc7f3 --- /dev/null +++ b/GPU/jpeg/kext/jpeg_power.hpp @@ -0,0 +1,142 @@ +// +// jpeg_power.hpp - the PowerPlay requests of VCNJpeg. No kernel parts. +// +// Apple's driver never asks PowerPlay for the JPEG block. It does ask for the +// VCN, from the kernel, in two calls of AMDRadeonX6000 that VCNJpeg +// copies with the JPEG client type (21) in place of the VCN one (28): +// +// AMDAccelVCNContext::setClocks (0x47afc) escape 0x53, +// PEM_CWDDEPM_PMRequest: +// creates the session's power client (PSM_CreateNewInstanceCtx) +// AMDAccelVideoContext::notifyPMContext (0x2824a) escape 0x34, +// PEM_CWDDEPM_ActivateClient: +// activates it, or deactivates it (which also frees it), and +// re-arbitrates +// +// With a JPEG client active, PEM_ClockChange case 21 has put a 1 in setting 42 +// of its request; PSM_ReArbit (0xf988a) merges that into the state manager's +// +1540 and calls PHM_PowerGateJPEG -> Phw_SwSmu_PowerGateJpeg -> +// smu_11_0_7_disable_power_gating case 1 (SMU message 44, PowerUpJpeg, only +// when the SMU feature 0x400000 = MM_DPM_PG is on and the block is not marked +// up; smu_query_feature_enabled returns 0 when the feature IS on). With no +// client left it calls the same chain to gate it (message 45). +// +// Both go out as Apple's do: +// AMDGraphicsAccelerator::sendPMCommand(accelerator, {in, in size, out, &out +// size}), which hands them to the framebuffer and on to +// AtiPowerPlayServices::ppCWDDE. +// +// Layouts are those of the two Apple functions and of the handlers in +// HWLibs; each field was checked against Hex-Rays, and tests/run.sh runs +// Apple's two functions from the KDK and compares what they build with ours. +// +#pragma once +#include +#include + +namespace jw { + +constexpr uint32_t kEscapeCode = 0x00C00000; // escape = this | table index +constexpr uint32_t kEscIsGPUAccessible = 0x2a; // in 0, out 12 +constexpr uint32_t kEscActivateClient = 0x34; // in 32, out 0 +constexpr uint32_t kEscPMRequest = 0x53; // in 112, out 72 +constexpr uint32_t kClientJpeg = 21; // PEM_ClockChange case 21 +constexpr uint32_t kClientVcn0 = 28; // what Apple sends, for reference +constexpr uint32_t kRequestClocks = 1; // reqID Apple's setClocks sends +constexpr uint32_t kPmFlags = 1; // setClocks: 1, or 4 for one kind of session; + // bit 0x20 would ask for JPEG DPG mode +constexpr uint32_t kPmRequestTag = 0x5c; // setClocks: payload +4 + +struct Header { // 16 bytes in front of every escape + uint32_t size; // 16 + uint32_t code; // kEscapeCode | index + uint64_t reserved; // 0 +}; + +struct PmRequestIn { // escape 0x53: header + 112 + Header header; + uint32_t size; // +0 112 + uint32_t tag; // +4 0x5c + uint64_t context; // +8 the client's handle: any value nobody else uses + uint32_t clientType; // +16 + uint32_t requestId; // +20 + uint32_t pmFlags; // +24 + uint32_t clocks[21]; // +28..+111: minSclk, minMclk, floors and ceilings; all + // 0 here +}; +struct PmRequestOut { // 72 bytes + uint32_t size; // +0 72 + uint32_t valid; // +4 1 + uint32_t unused8; + uint32_t resultSize; // +12 56 + uint32_t + result; // +16 0 = accepted, 20 = clocks refused, 21 = no client slot + uint32_t words[13]; +}; + +struct ActivateIn { // escape 0x34: header + 32 + Header header; + uint32_t size; // +0 32 + uint32_t clientType; // +4 + uint32_t contextId; // +8 only used when the handle is 0 + uint32_t activate; // +12 1 or 0 + uint32_t flags; // +16 0: a deactivated client is freed + uint32_t contextLow; // +20 the handle, not aligned + uint32_t contextHigh; // +24 + uint32_t pad; // +28 +}; + +struct AccessOut { // escape 0x2a: 12 bytes + uint32_t size; // 12 + uint32_t accessible; // 1: the GPU is up + uint32_t unused; +}; + +// What AMDGraphicsAccelerator::sendPMCommand takes. +struct Args { + const void* in; + uint64_t inSize; + void* out; + uint64_t* outSize; +}; + +static_assert(sizeof(Header) == 16, "header"); +static_assert(sizeof(PmRequestIn) == 128 && + offsetof(PmRequestIn, context) == 24 && + offsetof(PmRequestIn, clientType) == 32, + "PMRequest input"); +static_assert(sizeof(PmRequestOut) == 72, "PMRequest output"); +static_assert(sizeof(ActivateIn) == 48 && + offsetof(ActivateIn, contextLow) == 36, + "ActivateClient input"); +static_assert(sizeof(AccessOut) == 12, "IsGPUAccessible output"); +static_assert(sizeof(Args) == 32, "sendPMCommand arguments"); + +constexpr Header header(uint32_t index) { + return Header{16, kEscapeCode | index, 0}; +} + +constexpr PmRequestIn pmRequest(uint64_t context) { + PmRequestIn r{}; + r.header = header(kEscPMRequest); + r.size = 112; + r.tag = kPmRequestTag; + r.context = context; + r.clientType = kClientJpeg; + r.requestId = kRequestClocks; + r.pmFlags = kPmFlags; + return r; +} + +constexpr ActivateIn activate(uint64_t context, bool on) { + ActivateIn a{}; + a.header = header(kEscActivateClient); + a.size = 32; + a.clientType = kClientJpeg; + a.activate = on ? 1 : 0; + a.contextLow = static_cast(context); + a.contextHigh = static_cast(context >> 32); + return a; +} + +} // namespace jw diff --git a/GPU/jpeg/kext/jpeg_proto.hpp b/GPU/jpeg/kext/jpeg_proto.hpp new file mode 100644 index 00000000..03d8c533 --- /dev/null +++ b/GPU/jpeg/kext/jpeg_proto.hpp @@ -0,0 +1,87 @@ +// +// jpeg_proto.hpp - the state bits, job modes and the result of one job of +// VCNJpeg. No kernel parts: the kext, the host tests and the test tools share +// it. The state bits are the ones the door's INFO answers with (jpeg_app.h +// JA_STATE_*). +// +#pragma once +#include + +namespace jp { + +constexpr uint32_t kProtocol = 1; + +enum State : uint32_t { + kStatePool = 1 << 0, // buffers were allocated when the driver started + kStateCreated = 1 << 1, // the JPEG queue exists + kStateStarted = 1 << 2, // the queue is started (block powered) + kStateStuck = + 1 << 3, // a job timed out or wrote too far: no more jobs until a restart + kStateLoaded = 1 << 4, // a JPEG is loaded + kStateDecoded = 1 << 5, // the surface holds the result of a decode +}; + +enum Mode : uint32_t { + kModeRingTest = 1, // one register write straight in the ring + kModeIbTest = 2, // the same write through an IB, with a fence + kModeDecode = 3, // decode the loaded JPEG +}; + +enum Flags : uint32_t { + kFlagDryRun = 1 << 0, // build everything, submit nothing + kFlagWptrRegister = + 1 + << 1, // publish the write pointer through the register, not the doorbell +}; + +enum class Status : uint32_t { + Ok = 0, + BuiltOnly, // dry run: frame and IB are in the result, nothing was sent + NotReady, // no buffers, no queue, queue not started, or stuck + NothingLoaded, + BadArgument, + CheckFailed, // the driver's tables are not the expected ones any more + SubmitFailed, + Timeout, // the job did not finish; the queue is now marked stuck + WrongValue, // the test register does not hold the value written + GuardDamaged, // the block wrote past the surface +}; + +constexpr uint32_t kResultMagic = 0x4a504752; // "JPGR" +constexpr uint32_t kRegCount = 12; + +// Registers read after each job, by index into Result::regs (the kext's list +// in jpeg_layout.hpp is in the same order). +constexpr const char* kRegNames[kRegCount] = { + "UVD_JRBC_RB_WPTR", "UVD_JRBC_RB_RPTR", "UVD_JRBC_STATUS", + "UVD_JPEG_CNTL", "UVD_JPEG_RB_WPTR", "UVD_JPEG_RB_RPTR", + "UVD_JPEG_INT_EN", "UVD_JPEG_INT_STAT", "UVD_JPEG_OUTBUF_WPTR", + "UVD_JPEG_PITCH", "UVD_JPEG_UV_PITCH", "UVD_JPEG_POWER_STATUS", +}; + +struct Result { + uint32_t magic; + uint32_t protocol; + uint32_t mode; + uint32_t flags; + uint32_t status; // Status + uint32_t submitReturn; // what AmdTtlServices::submitFrame returned + uint32_t elapsedMs; // from submit to completion (or to giving up) + uint32_t seq; // fence value asked for + uint32_t fenceValue; // fence memory at the end + uint32_t testBefore; // UVD_JPEG_PITCH before a ring or IB test + uint32_t testAfter; // and after it + uint32_t width, height; + uint32_t pitch, alignedHeight, chromaOffset, surfaceBytes; + uint32_t bitstreamBytes; + uint32_t ibWords; + uint32_t regs[kRegCount]; + uint32_t testWanted; // value the ring or IB test writes + uint32_t format; // surface written: 0 NV12 (4:2:0), 1 YUYV (4:2:2) + uint64_t ringGpu, ibGpu, fenceGpu, bitstreamGpu, surfaceGpu; + uint32_t frame[64]; + uint32_t ib[128]; +}; +static_assert(sizeof(Result) == 944, "Result layout"); + +} // namespace jp diff --git a/GPU/jpeg/kext/kern_start.cpp b/GPU/jpeg/kext/kern_start.cpp new file mode 100644 index 00000000..c99eabc5 --- /dev/null +++ b/GPU/jpeg/kext/kern_start.cpp @@ -0,0 +1,990 @@ +// +// kern_start.cpp - VCNJpeg, a Lilu plugin: JPEG and Motion JPEG decoding on +// the JPEG block of the VCN of an AMD Radeon RX 6800 / 6800 XT / 6900 XT +// (Navi 21), for the VideoToolbox plug-in in decode/jpeg. +// +// Apple's AMDRadeonX6000HWLibs carries the driver of the JPEG block (its ring, +// JRBC, and the queue code) but never creates its queue. This plugin does, and +// lets any process decode through it: +// +// 1. When AMDRadeonX6000HWLibs loads it checks the image's LC_UUID against the +// one build that was read in IDA (macOS 26.7.3, 25G342), resolves the +// functions it needs by symbol and compares each one's place in the image +// and its first 16 bytes with the values of that build (hwlibs_expect.hpp, +// generated from the KDK by tools/gen_expect.py). The same for the two +// functions of AMDRadeonX6000 it uses. Anything different: it does nothing. +// +// 2. It routes AmdTtlServices::startMMEngineQueues(), where the driver creates +// its VCN queues while it starts. After the original it creates the JPEG +// decode queue the same way (createEngine(this, 5, 0, {256, 256})) and +// takes one block of buffers from the JPEG module's own allocator: IB, +// fence, bitstream, picture and a guard area. Both have to happen there and +// not later: the queue's ring and the block get GART addresses from a bump +// pointer that the accelerator reads only once, afterwards, before it hands +// out the rest of the GART itself. Memory taken later sits on addresses the +// accelerator owns; resizing the block after start hung the GPU (SDMA0) on +// 2026-11-24. Creating the queue touches no JPEG register. +// AmdTtlServices::stopMMEngineQueues (routed too) stops and destroys the +// queue and gives the block back before Apple's queues go. +// +// 3. The door: it routes AMDRadeonX6000_AMDAccelVideoContext::sendPMCommand, +// selector 258 of the accelerator's video context, which every process +// that decodes video may open, and answers the requests that carry the +// header of decode/jpeg/jpeg_app.h (apps_handler.hpp). Every other request +// goes to Apple's function untouched. +// +// 4. Power only while decoding: the first picture a client asks to decode +// powers the block (PowerPlay client 21, jpeg_power.hpp, as Apple's kernel +// asks for a VCN session) and starts its queue (notifyEngine start, which +// powers it up and programs the ring). Two seconds without a request of any +// client (idle_logic.hpp, a thread_call) stop the queue and give the power +// back; the next picture starts both again. +// +// A job that does not finish (timeout) or writes past its picture marks the +// decoder stuck until the next restart: INFO says so, the plug-in refuses new +// sessions and VideoToolbox uses Apple's software decoder. +// +// It never sends anything to the VCN decode queue. +// +// State: the dictionary "VCNJpeg" on IOResources (ioreg -rd1 -c IOResources | +// grep -A12 VCNJpeg): State, Version, Build, PoolBytes, Powered, Stuck, Jobs, +// PowerOns, Failures. +// +// Boot args: -vcnjpegoff disables the plugin; vcnjpegpool= sizes the +// block (8 to 128, default 128: a 48-megapixel 4:2:0 picture fits; a 4K 4:2:2 +// frame needs about 24); -vcnjpegdbg / -vcnjpegbeta are Lilu's usual switches. +// +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wshadow" +#include +#include +#include +#include +#pragma clang diagnostic pop + +#include "hwlibs_expect.hpp" +#include "idle_logic.hpp" +#include "jpeg_app.h" +#include "jpeg_cmds.hpp" +#include "jpeg_layout.hpp" +#include "jpeg_power.hpp" +#include "jpeg_proto.hpp" + +static_assert(jp::kStatePool == JA_STATE_POOL && + jp::kStateCreated == JA_STATE_CREATED && + jp::kStateStarted == JA_STATE_STARTED && + jp::kStateStuck == JA_STATE_STUCK, + "the door's state bits"); + +// ---- functions of AMDRadeonX6000HWLibs, by their Hex-Rays prototypes -------- +// uint32 AmdTtlServices::startMMEngineQueues(this) 0xaf5e0 +using t_startMM = uint32_t (*)(void* ttlServices); +// IOReturn AmdTtlServices::createEngine(this, AMD_SWIP_QUEUE_TYPE, +// uint index, _TtlCreateEngineInput*) +// 0xb1610 +using t_createEngine = uint32_t (*)(void* ttlServices, int queueType, + uint32_t index, const uint32_t* input); +// IOReturn AmdTtlServices::notifyEngine(this, AMD_SWIP_QUEUE_TYPE, uint index, +// AMD_TTL_ENGINE_EVENT) 0xb1530 +using t_notifyEngine = uint32_t (*)(void* ttlServices, uint32_t queueType, + uint32_t index, uint32_t event); +// uint32 AmdTtlServices::stopMMEngineQueues(this) 0xaf9b0 +using t_stopMM = uint32_t (*)(void* ttlServices); +// IOReturn AmdTtlServices::stopEngineQueue(this, AMD_SWIP_QUEUE_TYPE, +// uint index) 0xb1c80 +using t_stopEngineQueue = uint32_t (*)(void* ttlServices, int queueType, + uint32_t index); +// void* ttlGetIpi(ttl handle) 0x90fd2 +using t_ttlGetIpi = void* (*)(void* ttlHandle); +// void* IpiGetJpegContext(ipi) 0xa6ea5 +using t_getJpegContext = void* (*)(void* ipi); +// uint32 jpeg_internal_cgs_read_register(jpeg ctx, uint set, int offset) +// 0x3c211 +using t_readReg = uint64_t (*)(void* jpegCtx, uint32_t set, int32_t offset); +// IOReturn AmdTtlServices::submitFrame(this, AMD_SWIP_QUEUE_TYPE, uint index, +// void* frame) 0xb0840 +using t_submitFrame = uint32_t (*)(void* ttlServices, uint32_t queueType, + uint32_t index, void* frame); +// void* jpeg_internal_cgs_alloc_memory(cgs, size, align, type, &gpuAddress, +// &handle, flag) 0x3c117 +using t_allocMem = void* (*)(void* cgs, uint64_t size, int32_t align, + uint32_t type, uint64_t* gpuAddress, + uint64_t* handle, char flag); +// jpeg_internal_cgs_release_memory(cgs, cpu, size, type, gpuAddress, handle) +// 0x3c1a8 +using t_releaseMem = uint64_t (*)(void* cgs, void* cpu, uint64_t size, + uint32_t type, uint64_t gpuAddress, + uint64_t handle); +// ---- and of AMDRadeonX6000 +// ---------------------------------------------------- IOReturn +// AMDRadeonX6000_AMDGraphicsAccelerator::sendPMCommand(this, void* args) 0x656c +using t_sendPM = uint32_t (*)(void* accelerator, void* args); +// IOReturn AMDRadeonX6000_AMDAccelVideoContext::sendPMCommand(this, void* in, +// void* out, unsigned long long inSize, unsigned long long* outSize) +// 0x280f2 +using t_videoPM = IOReturn (*)(void* self, void* in, void* out, uint64_t inSize, + uint64_t* outSize); + +static t_startMM orgStartMM = nullptr; +static t_stopMM orgStopMM = nullptr; +static t_videoPM orgVideoPM = nullptr; +static t_stopEngineQueue fnStopEngineQueue = nullptr; +static t_createEngine fnCreateEngine = nullptr; +static t_notifyEngine fnNotifyEngine = nullptr; +static t_ttlGetIpi fnTtlGetIpi = nullptr; +static t_getJpegContext fnGetJpegContext = nullptr; +static t_readReg fnReadReg = nullptr; +static t_submitFrame fnSubmitFrame = nullptr; +static t_allocMem fnAllocMem = nullptr; +static t_releaseMem fnReleaseMem = nullptr; +static t_sendPM fnSendPM = nullptr; +// the jpeg_* functions the module's own tables must point to +static mach_vm_address_t adrJpegCreateQueue = 0, adrJpegStartQueue = 0, + adrJpegStopQueue = 0, adrJpegQueryStatus = 0, + adrQueueSubmit = 0, adrJpegSubmit = 0; + +static bool gResolved = false; // every HWLibs function found and checked +static bool gPowerResolved = false; // and both of AMDRadeonX6000 +static bool gDoorRouted = false; +static IOLock* gLock = nullptr; // guards everything below +static void* gTtl = nullptr; // the live AmdTtlServices (one AMD GPU only) +static void* gJpegCtx = nullptr; // jpeg module context (argument of jpeg_*) +static int gHookCalls = 0; +static bool gCreated = false; // createEngine returned 0 +static bool gStarted = false; // the queue is started (notifyEngine start) +static bool gGone = false; // the driver went away while the lock was held: + // never touch it again +static const char* gStateText = "starting"; +static uint32_t gPowerOns = 0, gFailures = 0; +static int gLogs = 0; +static constexpr int kMaxLogs = 64; // lines about failed jobs, so that a + // broken stream cannot flood the log + +__printflike(1, 2) static void say(const char* fmt, ...) { + char line[300]; + va_list ap; + va_start(ap, fmt); + vsnprintf(line, sizeof(line), fmt, ap); + va_end(ap); + SYSLOG("vcnjpeg", "%s", line); +} + +template +static inline T rd(const void* base, size_t off) { + T v; + memcpy(&v, static_cast(base) + off, sizeof(v)); + return v; +} + +static uint64_t nowMs() { + uint64_t t = 0, ns = 0; + clock_get_uptime(&t); + absolutetime_to_nanoseconds(t, &ns); + return ns / 1000000; +} + +// ---- buffers and the decode job +// ------------------------------------------------ +struct Pool { + uint32_t bytes, ib, fence, bitstream, bitstreamCap, surface, surfaceCap, + guard, guardBytes; +}; +static Pool gP{jl::kPoolBytes, jl::kPoolIb, jl::kPoolFence, + jl::kPoolBitstream, jl::kBitstreamCap, jl::kPoolSurface, + jl::kSurfaceCap, jl::kPoolGuard, jl::kGuardBytes}; +static bool gDecodeResolved = false; +static uint8_t* gPool = nullptr; // CPU address of the block +static uint64_t gPoolGpu = 0; +static uint64_t gPoolHandle = 0; +static bool gStuck = false; +static uint32_t gSeq = 0; +static uint32_t gJobs = 0; +static uint32_t gLoadedBytes = 0; // padded size of the loaded JPEG +static uint32_t gLoadPos = 0; // bytes of a JPEG received so far +static jc::StreamInfo gStream; +static jc::Layout gLayout; +static bool gDecoded = false; +static jp::Result gResult; // scratch of the door; the lock guards it +static jidle::Idle gIdle; +static thread_call_t gIdleCall = nullptr; + +static void publish(const char* state) { + if (state != nullptr) gStateText = state; + IOService* res = IOService::getResourceService(); + OSDictionary* d = OSDictionary::withCapacity(9); + if (res == nullptr || d == nullptr) { + if (d != nullptr) d->release(); + return; + } + auto str = [d](const char* key, const char* value) { + OSString* s = OSString::withCString(value); + if (s != nullptr) { + d->setObject(key, s); + s->release(); + } + }; + auto num = [d](const char* key, uint64_t value) { + OSNumber* n = OSNumber::withNumber(value, 64); + if (n != nullptr) { + d->setObject(key, n); + n->release(); + } + }; + str("State", gStateText); + str("Version", xStringify(MODULE_VERSION)); + str("Build", hwx::kBuild); + num("PoolBytes", gPool != nullptr ? gP.bytes : 0); + d->setObject("Powered", gIdle.on ? kOSBooleanTrue : kOSBooleanFalse); + d->setObject("Stuck", gStuck ? kOSBooleanTrue : kOSBooleanFalse); + num("Jobs", gJobs); + num("PowerOns", gPowerOns); + num("Failures", gFailures); + res->setProperty("VCNJpeg", d); + d->release(); +} + +// Returns true when the Mach-O image at `address` has the LC_UUID `want`. +static bool imageHasUuid(mach_vm_address_t address, size_t size, + const uint8_t want[16]) { + if (address == 0 || size < sizeof(mach_header_64)) return false; + auto mh = reinterpret_cast(address); + if (mh->magic != MH_MAGIC_64 || + mh->sizeofcmds > size - sizeof(mach_header_64)) + return false; + auto p = reinterpret_cast(mh + 1); + auto end = p + mh->sizeofcmds; + for (uint32_t i = 0; i < mh->ncmds && p + sizeof(load_command) <= end; i++) { + auto lc = reinterpret_cast(p); + if (lc->cmdsize < sizeof(load_command) || p + lc->cmdsize > end) + return false; + if (lc->cmd == LC_UUID && lc->cmdsize >= sizeof(uuid_command)) + return memcmp(reinterpret_cast(lc)->uuid, want, + 16) == 0; + p += lc->cmdsize; + } + return false; +} + +// ---- the JPEG module's tables, read from memory +// ------------------------------- Fills gJpegCtx. Every pointer is checked +// before it is followed, and the module's function table has to point at the +// jpeg_* functions resolved by symbol, which proves the layout before anything +// is called through it. +static bool findJpegModule(void* ttl, bool quiet) { + void* handle = rd(ttl, jl::kTtlHandle); + void* ipi = handle != nullptr ? fnTtlGetIpi(handle) : nullptr; + void* ipiJpeg = ipi != nullptr ? fnGetJpegContext(ipi) : nullptr; + if (ipiJpeg == nullptr) { + if (!quiet) say("check: no JPEG module on this device"); + return false; + } + if (rd(ipiJpeg, jl::kIpiCreateQueue) != + adrJpegCreateQueue || + rd(ipiJpeg, jl::kIpiStartQueue) != adrJpegStartQueue || + rd(ipiJpeg, jl::kIpiStopQueue) != adrJpegStopQueue || + rd(ipiJpeg, jl::kIpiQueryStatus) != + adrJpegQueryStatus) { + if (!quiet) + say("check: the JPEG module's function table is not the studied one"); + return false; + } + void* ctx = rd(ipiJpeg, jl::kIpiJpegCtx); + if (ctx == nullptr || rd(ctx, jl::kCtxCgs) == nullptr || + rd(ctx, jl::kCtxEngine) == nullptr || + rd(ctx, jl::kCtxQueueMgr) == nullptr) { + if (!quiet) say("check: JPEG context incomplete"); + return false; + } + gJpegCtx = ctx; + return true; +} + +static uint32_t readReg(const jl::Reg& r) { + return static_cast( + fnReadReg(gJpegCtx, r.set, static_cast(r.offset))); +} + +// Takes the block of buffers right after the queue was created (lock held). +static void poolTake(void* ttl) { + // The accelerator sizes its part of the GART from these two numbers later and + // refuses to start unless something is left: take the block only when it + // leaves at least kGartSpare free on top of it. + uint64_t gartSize = rd(ttl, jl::kTtlGartInfo + 8); + uint64_t gartUsed = rd(ttl, jl::kTtlGartInfo + 24); + if (gartUsed > gartSize || gartSize - gartUsed < jl::kGartSpare + gP.bytes) { + say("GART has 0x%llx of 0x%llx in use, too little left for 0x%x bytes of " + "buffers: decoder off", + gartUsed, gartSize, gP.bytes); + return; + } + void* cgs = rd(gJpegCtx, jl::kCtxCgs); + uint64_t gpu = 0, handle = 0; + void* cpu = fnAllocMem(cgs, gP.bytes, jl::kMemAlign, jl::kMemTypeRing, &gpu, + &handle, 0); + if (cpu == nullptr || gpu == 0) { + say("buffer allocation failed (cpu %d gpu 0x%llx): decoder off", + cpu != nullptr, gpu); + return; + } + gPool = static_cast(cpu); + gPoolGpu = gpu; + gPoolHandle = handle; + memset(gPool, 0, gP.bytes); + memset(gPool + gP.guard, jl::kGuardByte, gP.guardBytes); + say("0x%x bytes of buffers at GPU address 0x%llx (JPEG up to 0x%x, picture " + "up to 0x%x); GART 0x%llx of 0x%llx in use before", + gP.bytes, gpu, gP.bitstreamCap - 128, gP.surfaceCap, gartUsed, gartSize); +} + +static uint32_t decodeState() { + uint32_t s = 0; + if (gPool != nullptr) s |= jp::kStatePool; + if (gCreated) s |= jp::kStateCreated; + if (gStarted) s |= jp::kStateStarted; + if (gStuck) s |= jp::kStateStuck; + if (gLoadedBytes != 0) s |= jp::kStateLoaded; + if (gDecoded) s |= jp::kStateDecoded; + return s; +} + +#include "decode_accept.hpp" + +// The queue as it is now, or null when anything about it or about the path a +// frame takes to it (AmdTtlServices::submitFrame -> ipi -> jpeg_submit_frame -> +// the queue's own submit function) is not what was studied. +static void* decodeQueue() { + void* ipiJpeg = + fnGetJpegContext(fnTtlGetIpi(rd(gTtl, jl::kTtlHandle))); + if (ipiJpeg == nullptr || + rd(ipiJpeg, jl::kIpiSubmitFrame) != adrJpegSubmit) + return nullptr; + void* mgr = rd(gJpegCtx, jl::kCtxQueueMgr); + void* queue = rd(mgr, jl::kMgrDecodeQueue); + if (queue == nullptr) return nullptr; + if ((rd(queue, jl::kQFlags) & 1) == 0) return nullptr; + if (rd(queue, jl::kQSubmit) != adrQueueSubmit) + return nullptr; + if (rd(queue, jl::kQFrameBytes) != jc::kFrameWords * 4) + return nullptr; + if (rd(queue, jl::kQRingCpu) == nullptr) return nullptr; + if (rd(gTtl, jl::queueSlot(jl::kQueueTypeJpegDecode, 0)) == nullptr) + return nullptr; + return queue; +} + +static const char* statusText(uint32_t s) { + switch (static_cast(s)) { + case jp::Status::Ok: + return "ok"; + case jp::Status::BuiltOnly: + return "built only"; + case jp::Status::NotReady: + return "not ready"; + case jp::Status::NothingLoaded: + return "no JPEG loaded"; + case jp::Status::BadArgument: + return "bad argument"; + case jp::Status::CheckFailed: + return "driver tables not as expected"; + case jp::Status::SubmitFailed: + return "submitFrame failed"; + case jp::Status::Timeout: + return "timeout, decoder stuck"; + case jp::Status::WrongValue: + return "wrong value"; + case jp::Status::GuardDamaged: + return "guard area damaged, decoder stuck"; + } + return "?"; +} + +// A job that did not succeed: counted, and the first kMaxLogs logged with the +// block's registers. +static void logResult(const jp::Result* r) { + gFailures++; + if (gLogs >= kMaxLogs) return; + gLogs++; + say("job %u: %s; submit 0x%x, %u ms, fence %u; JRBC wptr 0x%x rptr 0x%x " + "status 0x%x; JPEG cntl 0x%x int_stat 0x%x power 0x%x", + r->seq, statusText(r->status), r->submitReturn, r->elapsedMs, + r->fenceValue, r->regs[0], r->regs[1], r->regs[2], r->regs[3], r->regs[7], + r->regs[11]); +} + +// Builds and submits the decode of the loaded JPEG and waits for it. Lock held. +// The frame and the IB are those of the test kext (jpeg_cmds.hpp), checked +// against Apple's own command builder and against Mesa's (tests/run.sh). +static void decodeRun(uint32_t mode, uint32_t flags, jp::Result* r) { + memset(r, 0, sizeof(*r)); + r->magic = jp::kResultMagic; + r->protocol = jp::kProtocol; + r->mode = mode; + r->flags = flags; + auto finish = [r](jp::Status s) { r->status = static_cast(s); }; + if (mode != jp::kModeDecode) return finish(jp::Status::BadArgument); + if (!gDecodeResolved || gPool == nullptr || gTtl == nullptr || + gJpegCtx == nullptr || !gCreated || !gStarted || gStuck) + return finish(jp::Status::NotReady); + if (gLoadedBytes == 0) return finish(jp::Status::NothingLoaded); + + void* mgr = rd(gJpegCtx, jl::kCtxQueueMgr); + void* anyQueue = rd(mgr, jl::kMgrDecodeQueue); + r->ringGpu = anyQueue ? rd(anyQueue, jl::kQGpuAddr) : 0; + r->ibGpu = gPoolGpu + gP.ib; + r->fenceGpu = gPoolGpu + gP.fence; + r->bitstreamGpu = gPoolGpu + gP.bitstream; + r->surfaceGpu = gPoolGpu + gP.surface; + uint32_t seq = gSeq + 1; + r->seq = seq; + + jc::DecodeParams d = + jc::decodeParams(gLayout, r->bitstreamGpu, gLoadedBytes, r->surfaceGpu); + r->ibWords = jc::buildDecodeIb(r->ib, jc::kIbMaxWords, d); + r->width = gStream.width; + r->height = gStream.height; + r->pitch = gLayout.pitch; + r->alignedHeight = gLayout.alignedHeight; + r->chromaOffset = gLayout.chromaOffset; + r->surfaceBytes = gLayout.bytes; + r->format = static_cast(gLayout.chroma); + r->bitstreamBytes = gLoadedBytes; + if (r->ibWords == 0 || r->ringGpu == 0 || + !jc::buildJobFrame(r->frame, r->ringGpu, r->ibGpu, r->ibWords, seq, + r->fenceGpu)) + return finish(jp::Status::BadArgument); + + if (!findJpegModule(gTtl, true)) return finish(jp::Status::CheckFailed); + void* queue = decodeQueue(); + if (queue == nullptr) return finish(jp::Status::CheckFailed); + gSeq = seq; + gJobs++; + volatile uint32_t* fence = + reinterpret_cast(gPool + gP.fence); + memcpy(gPool + gP.ib, r->ib, r->ibWords * 4); + fence[0] = 0; + fence[1] = 0; + memset(gPool + gP.surface, jl::kSurfaceFill, gLayout.bytes); + gDecoded = false; + // With the flag the write pointer goes through the register: the driver + // reads its own EnableJPEGDOORBELL setting at every submit, so it is cleared + // for this one call and put back. + void* engine = rd(gJpegCtx, jl::kCtxEngine); + uint32_t* doorbell = reinterpret_cast( + static_cast(engine) + jl::kEngCfgDoorbell); + uint32_t doorbellSaved = *doorbell; + if ((flags & jp::kFlagWptrRegister) != 0) *doorbell = 0; + uint64_t t0 = nowMs(); + uint32_t rc = fnSubmitFrame(gTtl, jl::kQueueTypeJpegDecode, 0, r->frame); + *doorbell = doorbellSaved; + r->submitReturn = rc; + if (rc != 0) return finish(jp::Status::SubmitFailed); + + // Completion is polled on the fence: nothing answers the block's interrupt. + bool done = false; + while (true) { + if (fence[0] == seq) { + done = true; + break; + } + if (nowMs() - t0 >= 3000) break; + IOSleep(1); + } + r->elapsedMs = static_cast(nowMs() - t0); + r->fenceValue = fence[0]; + if (!done) { + for (size_t i = 0; i < jp::kRegCount; i++) + r->regs[i] = readReg(jl::kJobRegs[i]); + gStuck = true; + return finish(jp::Status::Timeout); + } + const uint8_t* guard = gPool + gP.guard; + for (uint32_t i = 0; i < gP.guardBytes; i++) { + if (guard[i] != jl::kGuardByte) { + gStuck = true; // nothing more through this queue until the next restart + return finish(jp::Status::GuardDamaged); + } + } + gDecoded = true; + finish(jp::Status::Ok); +} + +// ---- power: PowerPlay client 21, as Apple's kernel asks for a VCN session +// ---- +static uint64_t gPowerContext = + 0; // the client's handle: the address of this variable +static bool gPowerCreated = false; // PMRequest was accepted: a client exists + +// The accelerator, retained, when the registry holds exactly one. +static IOService* powerCopyAccelerator() { + OSDictionary* match = + IOService::serviceMatching("AMDRadeonX6000_AMDGraphicsAccelerator"); + if (match == nullptr) return nullptr; + OSIterator* it = IOService::getMatchingServices(match); + match->release(); + if (it == nullptr) return nullptr; + IOService* found = nullptr; + unsigned count = 0; + while (OSObject* o = it->getNextObject()) { + count++; + if (found == nullptr) found = OSDynamicCast(IOService, o); + } + if (count != 1 || found == nullptr || + found->metaCast("AMDRadeonX6000_AMDGraphicsAccelerator") == nullptr) { + it->release(); + say("power: %u accelerator(s) found, need exactly one", count); + return nullptr; + } + found->retain(); + it->release(); + return found; +} + +static uint32_t powerSend(IOService* accel, const void* in, uint64_t inSize, + void* out, uint64_t* outSize) { + jw::Args args{in, inSize, out, outSize}; + return fnSendPM(accel, &args); +} + +// Creates and activates the client. False when PowerPlay did not take it; a +// client it created is given back by powerGiveBack. +static bool powerAsk() { + IOService* accel = powerCopyAccelerator(); + if (accel == nullptr) return false; + bool ok = false; + jw::Header q = jw::header(jw::kEscIsGPUAccessible); + jw::AccessOut a{sizeof(jw::AccessOut), 0, 0}; + uint64_t aSize = sizeof(a); + uint32_t rc = powerSend(accel, &q, sizeof(q), &a, &aSize); + if (rc == 0 && a.accessible != 1) { + say("power: the GPU is not accessible now, nothing asked"); + } else { + jw::PmRequestIn in = jw::pmRequest(gPowerContext); + jw::PmRequestOut out{}; + uint64_t outSize = sizeof(out); + rc = powerSend(accel, &in, sizeof(in), &out, &outSize); + if (rc != 0 || out.result != 0) { + say("power: PMRequest(client %u) returned 0x%x, result %u: not taken", + jw::kClientJpeg, rc, out.result); + } else { + gPowerCreated = true; + jw::ActivateIn on = jw::activate(gPowerContext, true); + uint64_t none = 0; + rc = powerSend(accel, &on, sizeof(on), nullptr, &none); + if (rc != 0) say("power: ActivateClient(1) returned 0x%x", rc); + ok = rc == 0; + } + } + accel->release(); + return ok; +} + +// Deactivates the client; PowerPlay frees it. Safe to repeat. +static void powerGiveBack(const char* why) { + if (!gPowerCreated) return; + IOService* accel = powerCopyAccelerator(); + if (accel == nullptr) return; + jw::ActivateIn off = jw::activate(gPowerContext, false); + uint64_t none = 0; + uint32_t rc = powerSend(accel, &off, sizeof(off), nullptr, &none); + accel->release(); + if (rc != 0) { + say("%s: ActivateClient(0) returned 0x%x", why, rc); + return; + } + gPowerCreated = false; +} + +// ---- the block on and off +// ----------------------------------------------------- +static void idleArm(uint64_t delayMs) { + if (gIdleCall == nullptr || delayMs == 0) return; + uint64_t deadline = 0; + clock_interval_to_deadline(static_cast(delayMs), kMillisecondScale, + &deadline); + thread_call_enter_delayed(gIdleCall, deadline); +} + +// Stops the queue, then gives the power back (Linux's order); both are tried +// whatever the other returned. Lock held. +static void blockOff(const char* why) { + if (!gIdle.on) return; + gIdle.on = false; + if (gStarted) { + uint32_t rc = + findJpegModule(gTtl, true) + ? fnNotifyEngine(gTtl, jl::kQueueTypeJpegDecode, 0, jl::kEventStop) + : 0xffffffffu; + if (rc != 0) say("%s: queue stop returned 0x%x", why, rc); + gStarted = false; + } + powerGiveBack(why); + publish(gStuck ? "stuck: no more jobs until the next restart" + : "ready, block off"); +} + +// Powers the block and starts its queue, unless it is on already. Lock held. +static bool blockOn() { + if (gIdle.on) return true; + if (gGone || gStuck || !gPowerResolved || !gCreated || gTtl == nullptr || + !findJpegModule(gTtl, true)) + return false; + if (!powerAsk()) { + powerGiveBack("power request failed"); + gFailures++; + return false; + } + uint32_t rc = + fnNotifyEngine(gTtl, jl::kQueueTypeJpegDecode, 0, jl::kEventStart); + gStarted = true; // even on failure, so that blockOff sends the stop + gIdle.on = true; + gPowerOns++; + if (rc != 0) { + say("queue start returned 0x%x: decoder stuck until the next restart", rc); + gStuck = true; + blockOff("failed start"); + return false; + } + publish("decoding, block on"); + return true; +} + +static void idleFired(thread_call_param_t, thread_call_param_t) { + IOLockLock(gLock); + if (gGone) { // the driver went away while busy: leave it alone + IOLockUnlock(gLock); + return; + } + uint64_t delay = 0; + switch (jidle::tick(gIdle, nowMs(), &delay)) { + case jidle::Tick::PowerOff: + blockOff("idle"); + break; + case jidle::Tick::Rearm: + idleArm(delay); + break; + case jidle::Tick::Nothing: + break; + } + IOLockUnlock(gLock); +} + +// ---- the door +// ----------------------------------------------------------------- +static bool appCopyIn(uint8_t* dst, uint64_t src, uint32_t bytes) { + return copyin(static_cast(src), dst, bytes) == 0; +} +static bool appCopyOut(uint64_t dst, const uint8_t* src, uint32_t bytes) { + return copyout(src, static_cast(dst), bytes) == 0; +} +static void appTouch() { idleArm(jidle::touch(gIdle, nowMs())); } +static bool appBlockOn() { return blockOn(); } +#include "apps_handler.hpp" + +static IOReturn wrapVideoPM(void* self, void* in, void* out, uint64_t inSize, + uint64_t* outSize) { + if (!appIsOurs(in, inSize)) return orgVideoPM(self, in, out, inSize, outSize); + // Ours. It never reaches PowerPlay, whatever is wrong with it. + if (gLock == nullptr) return kIOReturnBadArgument; + IOLockLock(gLock); + bool ok = !gGone && appEntry(self, in, inSize, out, outSize); + IOLockUnlock(gLock); + return ok ? kIOReturnSuccess : kIOReturnBadArgument; +} + +// ---- driver start and stop +// ---------------------------------------------------- Runs inside +// AmdTtlServices::startMMEngineQueues, right after Apple's own queues were +// created (once per driver start; again if the driver tears down and starts +// over). Lock held. +static void onTtlReady(void* ttl, uint32_t result) { + int call = ++gHookCalls; + if (gTtl != nullptr || gGone) { + say("startMMEngineQueues call %d ignored: another AmdTtlServices is in " + "use, or the last one went away while busy (one AMD GPU only)", + call); + return; + } + if (ttl == nullptr || result != 0) { + publish("off: Apple's video queues failed to start"); + return; + } + gTtl = ttl; + if (!findJpegModule(ttl, false)) { + publish("off: JPEG module check failed"); + return; + } + void* engine = rd(gJpegCtx, jl::kCtxEngine); + void* mgr = rd(gJpegCtx, jl::kCtxQueueMgr); + uint32_t version = rd(engine, jl::kEngVersion); + if (version != jl::kVersionVcn30) { + say("JPEG IP version 0x%x is not the studied one (0x%x)", version, + jl::kVersionVcn30); + publish("off: JPEG IP version not validated"); + return; + } + if (rd(mgr, jl::kMgrDecodeOk) != 1 || + rd(mgr, jl::kMgrDecodeQueue) != nullptr || + rd(ttl, jl::queueSlot(jl::kQueueTypeJpegDecode, 0)) != nullptr) { + publish("off: JPEG queue state unexpected"); + return; + } + const uint32_t input[2]{jl::kFrameBytes, jl::kFrameCount}; + uint32_t rc = fnCreateEngine(ttl, jl::kQueueTypeJpegDecode, 0, input); + if (rc != 0) { + say("createEngine(JPEG decode) returned 0x%x", rc); + publish("off: createEngine failed"); + return; + } + gCreated = true; + if (gDecodeResolved) poolTake(ttl); + publish(gPool == nullptr ? "off: no buffers" : "ready, block off"); +} + +static uint32_t wrapStartMM(void* ttl) { + uint32_t result = orgStartMM(ttl); + IOLockLock(gLock); + onTtlReady(ttl, result); + IOLockUnlock(gLock); + return result; +} + +// AmdTtlServices::stopMMEngineQueues is where the driver destroys its own video +// queues when it shuts the device down. The JPEG queue goes the same way just +// before: stopped if started, its buffers given back, then destroyed with the +// call Apple uses for its queues. After that nothing here points into the +// driver any more. +static uint32_t wrapStopMM(void* ttl) { + // A job can hold the lock for up to 3 s (its timeout). If it is still held + // after that, something is stuck inside the driver: the shutdown must not + // wait for it. The JPEG queue is then left as it is, and the plugin never + // touches the driver again (gGone). + bool locked = false; + for (int i = 0; i < 400 && !(locked = IOLockTryLock(gLock)); i++) IOSleep(10); + if (!locked) { + __atomic_store_n(&gGone, true, __ATOMIC_SEQ_CST); + SYSLOG("vcnjpeg", "teardown: the decoder is still busy, JPEG queue left"); + return orgStopMM(ttl); + } + if (ttl != nullptr && ttl == gTtl) { + if (gIdleCall != nullptr) thread_call_cancel(gIdleCall); + gIdle.armed = false; + if (gCreated) { + if (gStarted) { + uint32_t rc = + fnNotifyEngine(ttl, jl::kQueueTypeJpegDecode, 0, jl::kEventStop); + if (rc != 0) say("teardown: queue stop returned 0x%x", rc); + gStarted = false; + } + if (gPool != nullptr && gJpegCtx != nullptr) { + void* cgs = rd(gJpegCtx, jl::kCtxCgs); + fnReleaseMem(cgs, gPool, gP.bytes, jl::kMemTypeRing, gPoolGpu, + gPoolHandle); + } + uint32_t rc = fnStopEngineQueue(ttl, jl::kQueueTypeJpegDecode, 0); + if (rc != 0) say("teardown: JPEG queue destroy returned 0x%x", rc); + gCreated = false; + } + // PowerPlay goes away with the device: the client is forgotten, not + // released. + gPowerCreated = false; + gIdle.on = false; + gPool = nullptr; + gPoolGpu = gPoolHandle = 0; + gLoadedBytes = gLoadPos = 0; + gDecoded = false; + gAppOwner = nullptr; + gStuck = false; + gTtl = nullptr; + gJpegCtx = nullptr; + publish("driver stopped its video queues"); + } + IOLockUnlock(gLock); + return orgStopMM(ttl); +} + +// ---- load +// --------------------------------------------------------------------- +static const char* kHWLibsPaths[]{ + "/System/Library/Extensions/AMDRadeonX6000HWServices.kext/Contents/PlugIns/" + "AMDRadeonX6000HWLibs.kext/Contents/MacOS/AMDRadeonX6000HWLibs"}; +static const char* kX6000Paths[]{ + "/System/Library/Extensions/AMDRadeonX6000.kext/Contents/MacOS/" + "AMDRadeonX6000"}; +static KernelPatcher::KextInfo kKexts[]{ + {"com.apple.kext.AMDRadeonX6000HWLibs", + kHWLibsPaths, + arrsize(kHWLibsPaths), + {}, + {}, + KernelPatcher::KextInfo::Unloaded}, + {"com.apple.kext.AMDRadeonX6000", + kX6000Paths, + arrsize(kX6000Paths), + {}, + {}, + KernelPatcher::KextInfo::Unloaded}, +}; + +// Finds one function by symbol and checks it against the studied build. +static mach_vm_address_t resolve(KernelPatcher& patcher, size_t index, + mach_vm_address_t address, size_t size, + const hwx::Function& want) { + mach_vm_address_t found = + patcher.solveSymbol(index, want.symbol, address, size); + if (found == 0) { + patcher.clearError(); + say("%s: symbol not found", want.symbol); + return 0; + } + if (found != address + want.offset) { + say("%s: at +0x%llx, expected +0x%llx", want.symbol, found - address, + static_cast(want.offset)); + return 0; + } + if (want.offset + sizeof(want.head) > size || + memcmp(reinterpret_cast(found), want.head, + sizeof(want.head)) != 0) { + say("%s: first bytes differ from the studied build", want.symbol); + return 0; + } + return found; +} + +static void onX6000Load(KernelPatcher& patcher, size_t index, + mach_vm_address_t address, size_t size) { + if (!imageHasUuid(address, size, hwx::kX6000Uuid)) { + publish("off: AMDRadeonX6000 build not validated"); + return; + } + mach_vm_address_t send = resolve(patcher, index, address, size, + hwx::kPowerFunctions[hwx::kSendPMCommand]); + mach_vm_address_t door = resolve(patcher, index, address, size, + hwx::kAppsFunctions[hwx::kVideoSendPM]); + if (send == 0 || door == 0) { + publish("off: an AMDRadeonX6000 function did not match the studied build"); + return; + } + fnSendPM = reinterpret_cast(send); + gPowerContext = reinterpret_cast(&gPowerContext); + gPowerResolved = true; + KernelPatcher::RouteRequest requests[]{ + {hwx::kAppsFunctions[hwx::kVideoSendPM].symbol, wrapVideoPM, orgVideoPM}}; + if (patcher.routeMultiple(index, requests, address, size) && + orgVideoPM != nullptr) { + gDoorRouted = true; + } else { + say("route of the video context failed (%d): no door for apps", + patcher.getError()); + patcher.clearError(); + publish("off: route failed"); + } +} + +static void onHWLibsLoad(KernelPatcher& patcher, size_t index, + mach_vm_address_t address, size_t size) { + if (!imageHasUuid(address, size, hwx::kUuid)) { + publish("off: AMDRadeonX6000HWLibs build not validated"); + return; + } + mach_vm_address_t a[hwx::kCount]{}; + for (size_t i = 0; i < hwx::kCount; i++) { + a[i] = resolve(patcher, index, address, size, hwx::kFunctions[i]); + if (a[i] == 0) { + publish("off: a HWLibs function did not match the studied build"); + return; + } + } + mach_vm_address_t b[hwx::kDecodeCount]{}; + for (size_t i = 0; i < hwx::kDecodeCount; i++) { + b[i] = resolve(patcher, index, address, size, hwx::kDecodeFunctions[i]); + if (b[i] == 0) { + publish("off: a HWLibs function did not match the studied build"); + return; + } + } + fnCreateEngine = reinterpret_cast(a[hwx::kCreateEngine]); + fnNotifyEngine = reinterpret_cast(a[hwx::kNotifyEngine]); + fnTtlGetIpi = reinterpret_cast(a[hwx::kTtlGetIpi]); + fnGetJpegContext = + reinterpret_cast(a[hwx::kIpiGetJpegContext]); + fnReadReg = reinterpret_cast(a[hwx::kJpegReadRegister]); + fnStopEngineQueue = + reinterpret_cast(a[hwx::kStopEngineQueue]); + adrJpegCreateQueue = a[hwx::kJpegCreateQueue]; + adrJpegStartQueue = a[hwx::kJpegStartQueue]; + adrJpegStopQueue = a[hwx::kJpegStopQueue]; + adrJpegQueryStatus = a[hwx::kJpegQueryQueueStatus]; + fnSubmitFrame = reinterpret_cast(b[hwx::kSubmitFrame]); + fnAllocMem = reinterpret_cast(b[hwx::kJpegAllocMemory]); + fnReleaseMem = reinterpret_cast(b[hwx::kJpegReleaseMemory]); + adrQueueSubmit = b[hwx::kQueueSubmitFrame]; + adrJpegSubmit = b[hwx::kJpegSubmitFrame]; + gResolved = gDecodeResolved = true; + + KernelPatcher::RouteRequest requests[]{ + {hwx::kFunctions[hwx::kStartMM].symbol, wrapStartMM, orgStartMM}, + {hwx::kFunctions[hwx::kStopMM].symbol, wrapStopMM, orgStopMM}, + }; + if (patcher.routeMultiple(index, requests, address, size)) { + publish("waiting for the driver to create its video queues"); + } else { + say("route of startMMEngineQueues failed (%d), driver left as it is", + patcher.getError()); + patcher.clearError(); + gResolved = gDecodeResolved = false; + publish("off: route failed"); + } +} + +static void onKextLoad(void*, KernelPatcher& patcher, size_t index, + mach_vm_address_t address, size_t size) { + IOLockLock(gLock); + if (kKexts[0].loadIndex == index) onHWLibsLoad(patcher, index, address, size); + if (kKexts[1].loadIndex == index) onX6000Load(patcher, index, address, size); + IOLockUnlock(gLock); +} + +static const char* bootargOff[]{"-vcnjpegoff"}; +static const char* bootargDebug[]{"-vcnjpegdbg"}; +static const char* bootargBeta[]{"-vcnjpegbeta"}; + +PluginConfiguration ADDPR(config){ + xStringify(PRODUCT_NAME), + parseModuleVersion(xStringify(MODULE_VERSION)), + LiluAPI::AllowNormal, + bootargOff, + arrsize(bootargOff), + bootargDebug, + arrsize(bootargDebug), + bootargBeta, + arrsize(bootargBeta), + KernelVersion::Tahoe, // libraries checked: 26.7.3 only + KernelVersion::Tahoe, + []() { + uint32_t mib = kPoolDefaultMiB; + if (!PE_parse_boot_argn("vcnjpegpool", &mib, sizeof(mib)) || mib == 0) + mib = kPoolDefaultMiB; + appPoolFor(mib, &gP); + gLock = IOLockAlloc(); + gIdleCall = thread_call_allocate(idleFired, nullptr); + if (gLock == nullptr || gIdleCall == nullptr) { + publish("off: out of memory"); + return; + } + publish("waiting for AMDRadeonX6000HWLibs"); + if (lilu.onKextLoad(kKexts, arrsize(kKexts), onKextLoad, nullptr) != + LiluAPI::Error::NoError) + publish("off: Lilu refused the kext load callback"); + }}; diff --git a/GPU/jpeg/tests/apps_test.cpp b/GPU/jpeg/tests/apps_test.cpp new file mode 100644 index 00000000..1ea26f21 --- /dev/null +++ b/GPU/jpeg/tests/apps_test.cpp @@ -0,0 +1,664 @@ +// +// apps_test - host checks of VCNJpeg's door (kext/apps_handler.hpp) and of +// when it powers the block (kext/idle_logic.hpp), built with the address and +// undefined-behaviour sanitizers by jpeg/build.sh. The handler, the stream +// check and the idle logic are the kext's own files; what stands in for the +// kernel here is the clock, the idle timer (a thread_call in the kext), the +// power request, the block of buffers and the decode itself, which writes a +// known pattern instead of asking the GPU. +// +// apps_test +// +#include +#include +#include +#include + +#include "idle_logic.hpp" +#include "jpeg_app_client.h" +#include "jpeg_cmds.hpp" +#include "jpeg_layout.hpp" +#include "jpeg_normalize.hpp" +#include "jpeg_proto.hpp" + +// ---- what kern_start.cpp gives the handler in the kext ---- +struct Pool { + uint32_t bytes, ib, fence, bitstream, bitstreamCap, surface, surfaceCap, + guard, guardBytes; +}; +static Pool gP{jl::kPoolBytes, jl::kPoolIb, jl::kPoolFence, + jl::kPoolBitstream, jl::kBitstreamCap, jl::kPoolSurface, + jl::kSurfaceCap, jl::kPoolGuard, jl::kGuardBytes}; +static uint8_t* gPool = nullptr; +static bool gDecodeResolved = true, gCreated = true, gDecoded = false; +static uint32_t gJobs = 0, gLoadedBytes = 0, gLoadPos = 0; +static jc::StreamInfo gStream; +static jc::Layout gLayout; +static jp::Result gResult; +static uint64_t gNow = 1000; +static uint64_t nowMs() { return gNow; } +static uint32_t decodeState() { return gPool != nullptr ? jp::kStatePool : 0; } +static void logResult(const jp::Result*) {} +#include "decode_accept.hpp" +static uint32_t gRunStatus = static_cast(jp::Status::Ok); +static uint32_t gRunFlags = 0xffffffff; +static uint8_t patternAt(uint32_t i) { return static_cast(i * 7 + 3); } +static void decodeRun(uint32_t mode, uint32_t flags, jp::Result* r) { + memset(r, 0, sizeof(*r)); + gRunFlags = flags; + gJobs++; + r->status = mode == jp::kModeDecode && gLoadedBytes != 0 + ? gRunStatus + : static_cast(jp::Status::NotReady); + if (r->status != static_cast(jp::Status::Ok)) return; + for (uint32_t i = 0; i < gLayout.bytes; i++) + gPool[gP.surface + i] = patternAt(i); + r->width = gStream.width; + r->height = gStream.height; + r->pitch = gLayout.pitch; + r->alignedHeight = gLayout.alignedHeight; + r->chromaOffset = gLayout.chromaOffset; + r->surfaceBytes = gLayout.bytes; + r->elapsedMs = 7; + gDecoded = true; +} +// copyin/copyout refuse an address the caller does not own; here only the +// test's own buffers are owned. +static bool gCopyFails = false; +static std::vector> gOwned; +static bool owned(uint64_t a, uint32_t n) { + for (auto& o : gOwned) + if (a >= o.first && a <= o.first + o.second && n <= o.first + o.second - a) + return true; + return false; +} +static bool appCopyIn(uint8_t* dst, uint64_t src, uint32_t bytes) { + if (gCopyFails || !owned(src, bytes)) return false; + memcpy(dst, reinterpret_cast(src), bytes); + return true; +} +static bool appCopyOut(uint64_t dst, const uint8_t* src, uint32_t bytes) { + if (gCopyFails || !owned(dst, bytes)) return false; + memcpy(reinterpret_cast(dst), src, bytes); + return true; +} +// ---- the block's power and the idle timer, as kern_start.cpp drives them ---- +static jidle::Idle gIdle; +static bool gTimerPending = false, gBlockRefuses = false; +static uint64_t gTimerAt = 0; +static int gPowerOns = 0, gPowerOffs = 0, gArms = 0; +static void idleArm(uint64_t delayMs) { // thread_call_enter_delayed + if (delayMs == 0) return; + gTimerPending = true; + gTimerAt = gNow + delayMs; + gArms++; +} +static void appTouch() { idleArm(jidle::touch(gIdle, gNow)); } +static bool appBlockOn() { + if (gIdle.on) return true; + if (gBlockRefuses) return false; + gIdle.on = true; + gPowerOns++; + return true; +} +// Time goes by `ms`; the timer fires when its moment comes, as the thread_call +// would. +static void advance(uint64_t ms) { + uint64_t end = gNow + ms; + while (gTimerPending && gTimerAt <= end) { + if (gTimerAt > gNow) + gNow = gTimerAt; // the random checks move the clock without the timer + gTimerPending = false; + uint64_t delay = 0; + switch (jidle::tick(gIdle, gNow, &delay)) { + case jidle::Tick::PowerOff: + gIdle.on = false; + gPowerOffs++; + break; + case jidle::Tick::Rearm: + idleArm(delay); + break; + case jidle::Tick::Nothing: + break; + } + } + gNow = end; +} +#include "apps_handler.hpp" + +static int fails = 0; +#define CHECK(cond, text) \ + do { \ + bool ok_ = (cond); \ + if (!ok_) fails++; \ + printf("%s %s\n", ok_ ? "ok " : "FAIL", text); \ + } while (0) + +// One call through the door, with exact-size heap buffers so that a byte too +// far is caught. +struct Reply { + bool ours = false, ok = false; + ja_reply head{}; + std::vector data; + uint64_t outSize = 0; +}; +static Reply call(void* self, const std::vector& in, uint64_t outCap) { + Reply r; + std::vector inCopy(in); + r.ours = appIsOurs(inCopy.empty() ? nullptr : inCopy.data(), inCopy.size()); + if (!r.ours) return r; + std::vector out(outCap, 0xCC); + r.outSize = outCap; + r.ok = appEntry(self, inCopy.data(), inCopy.size(), + outCap != 0 ? out.data() : nullptr, &r.outSize); + if (!r.ok) return r; + if (r.outSize < sizeof(ja_reply) || r.outSize > outCap) { + printf("FAIL reply of %llu bytes for a buffer of %llu\n", + static_cast(r.outSize), + static_cast(outCap)); + exit(1); + } + memcpy(&r.head, out.data(), sizeof(r.head)); + if (r.head.magic != JA_REPLY_MAGIC || + sizeof(ja_reply) + r.head.dataBytes != r.outSize) { + printf("FAIL reply header does not describe the reply\n"); + exit(1); + } + r.data.assign(out.begin() + sizeof(ja_reply), + out.begin() + static_cast(r.outSize)); + return r; +} +static std::vector request(uint32_t op, uint64_t a0 = 0, + uint64_t a1 = 0, + const uint8_t* data = nullptr, + size_t n = 0) { + ja_request rq{JA_HEADER_SIZE, JA_CODE, JA_PROTOCOL, op, a0, a1}; + std::vector v(sizeof(rq) + n); + memcpy(v.data(), &rq, sizeof(rq)); + if (n != 0) memcpy(v.data() + sizeof(rq), data, n); + return v; +} +static uint32_t load(void* self, const std::vector& jpeg, + Reply* last = nullptr) { + uint32_t status = JA_BAD_REQUEST; + for (size_t off = 0; off < jpeg.size();) { + size_t n = + jpeg.size() - off < JA_LOAD_PIECE ? jpeg.size() - off : JA_LOAD_PIECE; + Reply r = + call(self, request(JA_OP_LOAD, off, jpeg.size(), jpeg.data() + off, n), + JA_MAX_IO); + status = r.ok ? r.head.status : 99; + if (last != nullptr) *last = r; + if (status != JA_MORE) break; + off += n; + } + return status; +} +static bool surfaceClean() { + for (uint32_t i = 0; i < gP.surfaceCap; i++) + if (gPool[gP.surface + i] != 0) return false; + return true; +} + +int main(int argc, char** argv) { + if (argc != 2) return 2; + std::vector file, jpeg; + FILE* f = fopen(argv[1], "rb"); + if (f == nullptr) return 2; + uint8_t buf[65536]; + size_t n; + while ((n = fread(buf, 1, sizeof(buf), f)) > 0) + file.insert(file.end(), buf, buf + n); + fclose(f); + if (!jnorm::normalize(file, &jpeg).empty()) return 2; + gPool = static_cast(calloc(1, gP.bytes)); + int a = 0, b = 0; + void *A = &a, *B = &b; + + // ---- what is ours and what goes on to PowerPlay ---- + std::vector pm(112, 0); + uint32_t pmHead[2] = {16, 0x00C00053}; + memcpy(pm.data(), pmHead, 8); + CHECK(!call(A, pm, 72).ours, + "a PowerPlay request (PMRequest, 112 bytes) is not taken"); + CHECK(!call(A, {}, 72).ours, "an empty request is not taken"); + std::vector shortRq = request(JA_OP_INFO); + shortRq.resize(sizeof(ja_request) - 1); + CHECK(!call(A, shortRq, 72).ours, + "a request one byte short of our header is not taken"); + std::vector big = request(JA_OP_INFO); + big.resize(JA_MAX_IO + 1); + CHECK(!call(A, big, 72).ours, "a request above 4096 bytes is not taken"); + Reply r = call(A, request(JA_OP_INFO), sizeof(ja_reply) - 1); + CHECK(r.ours && !r.ok, + "our request with room for less than a reply header is refused, " + "nothing written"); + r = call(A, request(JA_OP_INFO), sizeof(ja_reply)); + CHECK(r.ok && r.head.status == JA_OK && + r.head.v[1] == gP.bitstreamCap - 128 && + r.head.v[2] == gP.surfaceCap, + "INFO answers with the room for the JPEG and for the picture"); + std::vector wrongProto = request(JA_OP_INFO); + wrongProto[8] = 2; + r = call(A, wrongProto, JA_MAX_IO); + CHECK(r.ok && r.head.status == JA_BAD_REQUEST, + "another protocol number is a bad request"); + r = call(A, request(77), JA_MAX_IO); + CHECK(r.ok && r.head.status == JA_BAD_REQUEST, + "an unknown operation is a bad request"); + + // ---- one whole decode ---- + CHECK(call(A, request(JA_OP_RUN), JA_MAX_IO).head.status == JA_NOT_OWNER, + "RUN before any LOAD: not the owner"); + CHECK(call(A, request(JA_OP_READ), JA_MAX_IO).head.status == JA_NOT_OWNER, + "READ before any LOAD: not the owner"); + Reply last; + CHECK(load(A, jpeg, &last) == JA_OK && last.head.v[0] == 640 && + last.head.v[1] == 480, + "the sample loads in pieces and its size comes back (640x480)"); + r = call(A, request(JA_OP_RUN, 0xffffffffffffffffull), JA_MAX_IO); + ja_picture pic{}; + if (r.data.size() == sizeof(pic)) memcpy(&pic, r.data.data(), sizeof(pic)); + CHECK(r.head.status == JA_OK && pic.width == 640 && pic.height == 480 && + pic.pitch == 768 && pic.surfaceBytes == 768 * 480 * 3 / 2 && + pic.chromaOffset == 768 * 480, + "RUN answers with the picture's layout"); + CHECK(gRunFlags == jp::kFlagWptrRegister, + "of the caller's flags only the write-pointer one reaches the decode"); + CHECK(call(B, request(JA_OP_READ, 0), JA_MAX_IO).head.status == JA_NOT_OWNER, + "another client cannot read the picture"); + CHECK(call(B, request(JA_OP_RUN), JA_MAX_IO).head.status == JA_NOT_OWNER, + "another client cannot run"); + CHECK(load(B, jpeg) == JA_BUSY, "another client's LOAD is told to wait"); + r = call(B, request(JA_OP_RELEASE), JA_MAX_IO); + CHECK(r.head.status == JA_OK && gAppOwner == A, + "another client's RELEASE changes nothing"); + bool same = true; + uint32_t got = 0, calls = 0; + while (got < pic.surfaceBytes) { + uint64_t cap = calls % 3 == 0 ? JA_MAX_IO + : calls % 3 == 1 ? sizeof(ja_reply) + 1 + : 1000; + r = call(A, request(JA_OP_READ, got), cap); + if (!r.ok || r.head.status != JA_OK || r.data.empty()) break; + for (size_t i = 0; i < r.data.size(); i++) + same = same && r.data[i] == patternAt(got + static_cast(i)); + got += static_cast(r.data.size()); + calls++; + } + CHECK(got == pic.surfaceBytes && same, + "the picture reads back whole, with reply buffers of three sizes"); + CHECK(gAppOwner == nullptr && surfaceClean(), + "after the last piece the buffers are free and the picture is wiped"); + CHECK(call(A, request(JA_OP_READ, 0), JA_MAX_IO).head.status == JA_NOT_OWNER, + "it cannot be read twice"); + + // ---- the same through the caller's own memory ---- + gOwned.push_back({reinterpret_cast(jpeg.data()), jpeg.size()}); + r = call(A, + request(JA_OP_LOAD_USER, reinterpret_cast(jpeg.data()), + jpeg.size()), + JA_MAX_IO); + CHECK(r.head.status == JA_OK && r.head.v[0] == 640 && r.head.v[1] == 480, + "LOAD_USER takes the whole JPEG in one call"); + CHECK(load(B, jpeg) == JA_BUSY, + "and holds the buffers against another client"); + call(A, request(JA_OP_RUN), JA_MAX_IO); + std::vector whole(pic.surfaceBytes - 1); + gOwned.push_back({reinterpret_cast(whole.data()), whole.size()}); + r = call(A, + request(JA_OP_READ_USER, reinterpret_cast(whole.data()), + whole.size()), + JA_MAX_IO); + CHECK(r.head.status == JA_BAD_REQUEST && gAppOwner == A, + "READ_USER into a buffer one byte short is refused"); + gOwned.pop_back(); + whole.resize(pic.surfaceBytes); + gOwned.push_back({reinterpret_cast(whole.data()), whole.size()}); + r = call(A, + request(JA_OP_READ_USER, reinterpret_cast(whole.data()), + whole.size()), + JA_MAX_IO); + same = r.head.status == JA_OK && r.head.v[0] == pic.surfaceBytes; + for (uint32_t i = 0; same && i < pic.surfaceBytes; i++) + same = whole[i] == patternAt(i); + CHECK(same && gAppOwner == nullptr && surfaceClean(), + "READ_USER copies the whole picture, then frees and wipes"); + gCopyFails = true; + r = call(A, + request(JA_OP_LOAD_USER, reinterpret_cast(jpeg.data()), + jpeg.size()), + JA_MAX_IO); + CHECK(r.head.status == JA_BAD_ADDRESS && gAppOwner == nullptr, + "an address copyin refuses: bad address, buffers free"); + gCopyFails = false; + r = call(A, + request(JA_OP_LOAD_USER, reinterpret_cast(jpeg.data()) + 1, + jpeg.size()), + JA_MAX_IO); + CHECK(r.head.status == JA_BAD_ADDRESS && gAppOwner == nullptr, + "a JPEG one byte past the caller's buffer: bad address"); + CHECK( + call(A, request(JA_OP_LOAD_USER, 0, jpeg.size()), JA_MAX_IO) + .head.status == JA_BAD_REQUEST && + call(A, request(JA_OP_LOAD_USER, 0x1000, gP.bitstreamCap), JA_MAX_IO) + .head.status == JA_BAD_REQUEST && + call(A, request(JA_OP_LOAD_USER, 0x1000, 0), JA_MAX_IO).head.status == + JA_BAD_REQUEST, + "LOAD_USER with address 0, size 0 or a size above the room is a bad " + "request (nothing copied)"); + load(A, jpeg); + call(A, request(JA_OP_RUN), JA_MAX_IO); + gCopyFails = true; + r = call(A, request(JA_OP_READ_USER, 0x1000, pic.surfaceBytes), JA_MAX_IO); + gCopyFails = false; + CHECK( + r.head.status == JA_BAD_ADDRESS && gAppOwner == nullptr && surfaceClean(), + "an address copyout refuses: bad address, buffers free and wiped"); + + // ---- the caller's side (tools/jpeg_app_client.h) against this handler ---- + { + struct Fake { + void* self; + int calls; + bool dropReplies; + }; + auto transport = [](void* ctx, const void* in, size_t inSize, void* out, + size_t* outSize) -> int { + Fake* f = static_cast(ctx); + f->calls++; + if (!appIsOurs(in, inSize)) + return 0x2c2; // what PowerPlay's refusal would look like: an error + uint64_t o = *outSize; + if (!appEntry(f->self, in, inSize, out, &o)) return 0x2c2; + *outSize = f->dropReplies ? 0 : static_cast(o); + return 0; + }; + Fake fa{A, 0, false}; + std::vector surf(pic.surfaceBytes, 0); + gOwned.push_back({reinterpret_cast(surf.data()), surf.size()}); + ja_picture p2{}; + ja_reply last{}; + int s = ja_decode(transport, &fa, jpeg.data(), jpeg.size(), surf.data(), + surf.size(), 0, 100, &p2, &last); + bool good = s == JA_OK && fa.calls == 3 && p2.width == 640 && + p2.surfaceBytes == pic.surfaceBytes; + for (uint32_t i = 0; good && i < p2.surfaceBytes; i++) + good = surf[i] == patternAt(i); + CHECK(good && gAppOwner == nullptr, + "ja_decode: one picture in three calls (LOAD_USER, RUN, READ_USER), " + "buffers free after"); + uint64_t st = 0, jcap = 0, scap = 0; + CHECK(ja_info(transport, &fa, &st, &jcap, &scap) == JA_OK && + jcap == gP.bitstreamCap - 128 && scap == gP.surfaceCap, + "ja_info reads the room for the JPEG and the picture"); + load(B, jpeg); // another client holds the decoder + Fake fw{A, 0, false}; + uint64_t t0 = gNow; + s = ja_decode(transport, &fw, jpeg.data(), jpeg.size(), surf.data(), + surf.size(), 0, 30, &p2, &last); + CHECK(s == JA_BUSY && gAppOwner == B && gNow == t0, + "ja_decode waits while another client holds it, then says busy"); + call(B, request(JA_OP_RELEASE), JA_MAX_IO); + Fake fd{A, 0, true}; + CHECK(ja_decode(transport, &fd, jpeg.data(), jpeg.size(), surf.data(), + surf.size(), 0, 0, &p2, &last) == -1, + "a reply that is not one of ours counts as no door"); + call(A, request(JA_OP_RELEASE), JA_MAX_IO); + std::vector small(pic.surfaceBytes - 1); + gOwned.push_back({reinterpret_cast(small.data()), small.size()}); + s = ja_decode(transport, &fa, jpeg.data(), jpeg.size(), small.data(), + small.size(), 0, 0, &p2, &last); + CHECK(s == JA_BAD_REQUEST && gAppOwner == nullptr, + "a surface buffer too small: refused, and the decoder is given back"); + auto none = [](void*, const void*, size_t, void*, size_t*) -> int { + return 0x2c2; + }; + CHECK(ja_info(none, nullptr, nullptr, nullptr, nullptr) == -1, + "without the kext (PowerPlay refuses) ja_info says no door"); + } + + // ---- ownership ends by release, by silence, by error ---- + load(A, jpeg); + call(A, request(JA_OP_RUN), JA_MAX_IO); + r = call(A, request(JA_OP_READ, pic.surfaceBytes), JA_MAX_IO); + CHECK(r.head.status == JA_BAD_REQUEST, + "READ at the end of the picture is a bad request"); + r = call(A, request(JA_OP_READ, 0x100000000ull), JA_MAX_IO); + CHECK(r.head.status == JA_BAD_REQUEST, + "READ at an offset above 32 bits is a bad request"); + call(A, request(JA_OP_RELEASE), JA_MAX_IO); + CHECK(gAppOwner == nullptr && surfaceClean(), + "RELEASE frees the buffers and wipes the picture"); + load(A, jpeg); + call(A, request(JA_OP_RUN), JA_MAX_IO); + gNow += kAppHoldMs - 1; + CHECK(load(B, jpeg) == JA_BUSY, + "just before two seconds of silence the owner still holds the buffers"); + gNow += kAppHoldMs; + CHECK(load(B, jpeg) == JA_OK && gAppOwner == B, + "after two seconds of silence another client takes them"); + CHECK(call(A, request(JA_OP_READ, 0), JA_MAX_IO).head.status == JA_NOT_OWNER, + "the client that lost them cannot read the new owner's picture"); + call(B, request(JA_OP_RELEASE), JA_MAX_IO); + gRunStatus = static_cast(jp::Status::Timeout); + load(A, jpeg); + r = call(A, request(JA_OP_RUN), JA_MAX_IO); + CHECK(r.head.status == JA_FAILED && + r.head.detail == static_cast(jp::Status::Timeout) && + gAppOwner == nullptr, + "a decode that fails says why and frees the buffers"); + gRunStatus = static_cast(jp::Status::Ok); + load(A, jpeg); + r = call(A, request(JA_OP_RUN), sizeof(ja_reply) + sizeof(ja_picture) - 1); + CHECK(r.head.status == JA_BAD_REQUEST, + "RUN without room for the layout is a bad request"); + call(A, request(JA_OP_RELEASE), JA_MAX_IO); + + // ---- LOAD arguments ---- + auto piece = [&](uint64_t off, uint64_t total, size_t bytes) { + std::vector d(bytes, 0xff); + Reply x = + call(A, request(JA_OP_LOAD, off, total, d.data(), d.size()), JA_MAX_IO); + return x.ok ? x.head.status : 99u; + }; + CHECK(piece(0, 100, 0) == JA_BAD_REQUEST, + "LOAD with no data is a bad request"); + CHECK(piece(0, 0, 10) == JA_BAD_REQUEST, + "LOAD of a JPEG of 0 bytes is a bad request"); + CHECK(piece(0, gP.bitstreamCap - 127, 10) == JA_BAD_REQUEST, + "LOAD of a JPEG one byte above the room is a bad request"); + CHECK(piece(0, 5, 10) == JA_BAD_REQUEST, + "LOAD of more bytes than the JPEG has is a bad request"); + CHECK(piece(0, 10000, 100) == JA_MORE && + piece(200, 10000, 100) == JA_BAD_REQUEST && gAppOwner == nullptr, + "LOAD pieces out of order are a bad request and free the buffers"); + CHECK(piece(100, 10000, 100) == JA_BUSY, + "a LOAD that does not start at 0 cannot take the buffers"); + CHECK(piece(0xffffffff00000000ull, 10000, 100) == JA_BUSY && + piece(0, 0xffffffffffffffffull, 100) == JA_BAD_REQUEST, + "64-bit offsets and sizes do not wrap"); + CHECK(piece(0, 64, 64) == JA_BAD_STREAM && gAppOwner == nullptr, + "64 bytes that are not a JPEG: bad stream, buffers free"); + std::vector bigPicture(jpeg); + for (size_t i = 0; i + 9 < bigPicture.size(); i++) { + if (bigPicture[i] == 0xff && bigPicture[i + 1] == 0xc0) { + bigPicture[i + 5] = 0x10; // height 4096+ + bigPicture[i + 7] = 0x10; // width 4096+ + break; + } + } + CHECK(load(A, bigPicture) == JA_BAD_STREAM && gAppOwner == nullptr, + "a JPEG whose picture does not fit the surface is refused"); + gCreated = false; + CHECK(piece(0, 64, 64) == JA_NOT_READY && + call(A, request(JA_OP_INFO), JA_MAX_IO).head.status == JA_OK, + "without the queue everything but INFO says not ready"); + gCreated = true; + + // ---- the block for a boot argument ---- + bool poolOk = true; + for (uint32_t mib : {0u, 1u, 5u, 7u, 8u, 9u, 64u, 96u, 127u, 128u, 129u, 256u, + 0xffffffffu}) { + Pool p = gP; + appPoolFor(mib, &p); + uint32_t want = (mib < 8 ? 8 : mib > 128 ? 128 : mib) << 20; + poolOk = poolOk && p.bytes == want && p.bitstream == jl::kPoolBitstream && + p.bitstreamCap >= jl::kBitstreamCap && + p.bitstreamCap % 4096 == 0 && + p.surface == p.bitstream + p.bitstreamCap && + p.surface + p.surfaceCap == p.guard && + p.guard + p.guardBytes == p.bytes && p.surface % 4096 == 0 && + p.surfaceCap >= jl::kSurfaceCap; + } + CHECK(poolOk, + "the block for 8..128 MiB keeps every part inside it, page aligned, " + "never smaller than the fixed one"); + CHECK(kPoolDefaultMiB == 128, + "the default block is 128 MiB, the size run on the GPU"); + Pool p128 = gP, p32 = gP; + appPoolFor(128, &p128); + appPoolFor(32, &p32); + jc::Layout l48{}, l12{}; + CHECK(jc::outputLayout(8064, 6048, p128.surfaceCap, &l48) && + p128.bitstreamCap >= 30u << 20, + "128 MiB hold a 48-megapixel picture (8064x6048) and a JPEG of 30 MiB"); + CHECK(jc::outputLayout(4032, 3024, p32.surfaceCap, &l12) && + p32.bitstreamCap >= 7u << 20, + "32 MiB hold a 12-megapixel picture (4032x3024) and a JPEG of 7 MiB"); + + // ---- power only while decoding (idle_logic.hpp) ---- + advance(10 * jidle::kIdleMs); // whatever the checks above left on goes off + CHECK( + !gIdle.on && !gTimerPending, + "after the checks above and a pause the block is off and no timer runs"); + gPowerOns = gPowerOffs = gArms = 0; + for (int i = 0; i < 10; i++) call(A, request(JA_OP_INFO), JA_MAX_IO); + CHECK(!gIdle.on && gArms == 0, + "INFO neither powers the block nor starts the timer"); + r = call(A, + request(JA_OP_LOAD_USER, reinterpret_cast(jpeg.data()), + jpeg.size()), + JA_MAX_IO); + CHECK(r.head.status == JA_OK && !gIdle.on && gPowerOns == 0, + "a LOAD does not power the block: only RUN needs it"); + call(A, request(JA_OP_RELEASE), JA_MAX_IO); + auto frame = [&](void* who) { + Reply l = + call(who, + request(JA_OP_LOAD_USER, reinterpret_cast(jpeg.data()), + jpeg.size()), + JA_MAX_IO); + Reply x = call(who, request(JA_OP_RUN), JA_MAX_IO); + Reply y = + call(who, + request(JA_OP_READ_USER, reinterpret_cast(whole.data()), + whole.size()), + JA_MAX_IO); + return l.head.status == JA_OK && x.head.status == JA_OK && + y.head.status == JA_OK; + }; + // 30 frames a second for ten seconds: one power-on, never off between two + // frames + bool frames = true, onAll = true; + for (int i = 0; i < 300; i++) { + frames = frame(A) && frames; + onAll = onAll && gIdle.on; + advance(33); + onAll = onAll && gIdle.on; + } + CHECK( + frames && onAll && gPowerOns == 1 && gPowerOffs == 0, + "a 30 fps stream of 300 frames: powered once, never off between frames"); + CHECK(gArms <= 300 * 33 / static_cast(jidle::kIdleMs) + 2, + "the idle timer is armed about once per two seconds of stream, not " + "once per frame"); + advance(jidle::kIdleMs - 100); + CHECK(gIdle.on && frame(A) && gPowerOns == 1, + "a pause shorter than two seconds keeps the block on"); + advance(jidle::kIdleMs - 1); + bool stillOn = gIdle.on; + advance(1); + CHECK(stillOn && !gIdle.on && gPowerOffs == 1 && !gTimerPending, + "two seconds after the last request the block goes off, and the timer " + "stops"); + CHECK(frame(A) && gIdle.on && gPowerOns == 2, + "the next picture powers the block again"); + // two clients taking turns, each at 15 fps: still one power-on + frames = true; + for (int i = 0; i < 100; i++) { + frames = frame(i % 2 == 0 ? A : B) && frames; + advance(33); + } + CHECK(frames && gIdle.on && gPowerOns == 2 && gPowerOffs == 1, + "two clients taking turns share one power-on"); + advance(jidle::kIdleMs); + CHECK(!gIdle.on && gPowerOffs == 2, "and the block goes off once both stop"); + gBlockRefuses = true; + r = call(A, + request(JA_OP_LOAD_USER, reinterpret_cast(jpeg.data()), + jpeg.size()), + JA_MAX_IO); + Reply refused = call(A, request(JA_OP_RUN), JA_MAX_IO); + CHECK(r.head.status == JA_OK && refused.head.status == JA_NOT_READY && + gAppOwner == nullptr && surfaceClean() && gPowerOns == 2, + "when the block cannot be powered RUN says not ready and the client " + "loses the buffers"); + gBlockRefuses = false; + advance(jidle::kIdleMs); + + // ---- random requests: nothing may read or write outside its buffers ---- + uint32_t seed = 12345; + auto rnd = [&]() { + seed = seed * 1664525u + 1013904223u; + return seed >> 8; + }; + uint32_t handled = 0; + for (int i = 0; i < 300000; i++) { + void* who = rnd() % 3 == 0 ? B : A; + size_t dataBytes = + rnd() % 4 == 0 ? rnd() % (JA_LOAD_PIECE + 1) : rnd() % 64; + std::vector d(dataBytes); + for (auto& x : d) x = static_cast(rnd()); + uint64_t a0 = rnd() % 5 == 0 ? (static_cast(rnd()) << 24) | rnd() + : rnd() % 5000; + uint64_t a1 = rnd() % 5 == 0 ? (static_cast(rnd()) << 24) | rnd() + : rnd() % 9000; + uint32_t op = rnd() % 9; + if ((op == JA_OP_LOAD_USER || op == JA_OP_READ_USER) && rnd() % 2 == 0) { + a0 = rnd() % 2 == 0 + ? reinterpret_cast( + op == JA_OP_LOAD_USER ? jpeg.data() : whole.data()) + : a0; + a1 = op == JA_OP_LOAD_USER ? jpeg.size() : whole.size(); + } + if (op == JA_OP_LOAD && rnd() % 3 == 0) { + a0 = gLoadPos; + a1 = gLoadPos + dataBytes + rnd() % 3; + } + std::vector rq = request(op, a0, a1, d.data(), d.size()); + if (rnd() % 50 == 0) + rq[rnd() % rq.size()] ^= static_cast(1u << (rnd() % 8)); + uint64_t cap = rnd() % 6 == 0 ? rnd() % 100 + : rnd() % 3 == 0 ? JA_MAX_IO + : rnd() % 5000; + if (rnd() % 400 == 0) load(who, jpeg); + if (rnd() % 1000 == 0) gNow += kAppHoldMs; + Reply x = call(who, rq, cap); + handled += x.ok ? 1 : 0; + gNow += rnd() % 20; + } + CHECK(handled > 100000 && gJobs > 10, + "300000 random requests from two clients, no access outside a buffer"); + uint8_t* guard = gPool + gP.guard; + bool guardOk = true; + for (uint32_t i = 0; i < gP.guardBytes; i++) + guardOk = guardOk && guard[i] == 0; + CHECK(guardOk, "nothing was written after the surface"); + advance(jidle::kIdleMs); + CHECK(!gIdle.on && !gTimerPending, + "after the random requests and a pause the block is off"); + free(gPool); + printf("%s\n", fails == 0 ? "APPS PASSED" : "APPS FAILED"); + return fails == 0 ? 0 : 1; +} diff --git a/GPU/jpeg/tests/cmds_test.cpp b/GPU/jpeg/tests/cmds_test.cpp new file mode 100644 index 00000000..a190cd7c --- /dev/null +++ b/GPU/jpeg/tests/cmds_test.cpp @@ -0,0 +1,322 @@ +// +// cmds_test - host checks of kext/jpeg_cmds.hpp and tools/jpeg_normalize.hpp +// (built with the address and undefined-behaviour sanitizers by tests/run.sh). +// +// cmds_test frame the job frame, +// one word per line cmds_test ib +// the decode IB cmds_test unit everything +// that needs no oracle +// +#include +#include +#include +#include +#include +#include + +#include "jpeg_cmds.hpp" +#include "jpeg_normalize.hpp" +#include "jpeg_power.hpp" +#include "jpeg_proto.hpp" + +static int fails = 0; +#define CHECK(cond, text) \ + do { \ + bool ok_ = (cond); \ + if (!ok_) fails++; \ + printf("%s %s\n", ok_ ? "ok " : "FAIL", text); \ + } while (0) + +static std::vector readFile(const char* path) { + std::vector v; + FILE* f = fopen(path, "rb"); + if (!f) return v; + uint8_t buf[65536]; + size_t n; + while ((n = fread(buf, 1, sizeof(buf), f)) > 0) + v.insert(v.end(), buf, buf + n); + fclose(f); + return v; +} + +// Each parse works on an exact-size heap copy, so that reading one byte too far +// is caught. +static jc::Stream parseCopy(const uint8_t* d, size_t n, jc::StreamInfo* info) { + std::vector copy(d, d + n); + return jc::parseStream(copy.data(), copy.size(), info); +} + +static int unit(const char* samplePath) { + // frames + uint32_t frame[jc::kFrameWords]; + CHECK( + jc::buildJobFrame(frame, 0x8000100000, 0x8000200000, 80, 7, 0x8000201000), + "job frame fills exactly 64 words"); + bool pad = true; + for (int i = 56; i < 64; i += 2) + pad &= frame[i] == 0x60000000 && frame[i + 1] == 0; + CHECK(pad, "job frame: words 56..63 are nop pairs"); + bool noTrap = true; + for (int i = 0; i < 64; i += 2) noTrap &= (frame[i] >> 28) != 7; + CHECK(noTrap, "job frame has no trap packet (type 7)"); + CHECK(jc::buildRingTestFrame(frame, jc::kRingTestValue) && + frame[0] == 0x401f && frame[1] == 0xABADCAFE, + "ring test frame starts with the pitch register write"); + pad = true; + for (int i = 2; i < 64; i += 2) + pad &= frame[i] == 0x60000000 && frame[i + 1] == 0; + CHECK(pad, "ring test frame: the rest is nop pairs"); + // Linux amdgpu_jpeg_dec_set_reg: 16 words, PACKETJ(pitch, 0, 0, TYPE0), + // 0xDEADBEEF, then (TYPE6, 0) pairs + uint32_t ib[jc::kIbMaxWords]; + uint32_t n = jc::buildTestIb(ib, jc::kIbMaxWords, jc::kIbTestValue); + pad = n == 16 && ib[0] == 0x401f && ib[1] == 0xDEADBEEF; + for (uint32_t i = 2; i < 16 && pad; i += 2) + pad &= ib[i] == 0x60000000 && ib[i + 1] == 0; + CHECK(pad, "test IB equals Linux's (16 words)"); + jc::DecodeParams d{0x8000110000, 24704, 0x8000210000, 768, 768, 0, 368640}; + n = jc::buildDecodeIb(ib, jc::kIbMaxWords, d); + CHECK(n == 80, "decode IB is 80 words after padding"); + CHECK(jc::buildDecodeIb(ib, 70, d) == 0, + "decode IB refuses a buffer that is too small"); + bool types = true; + for (uint32_t i = 0; i < n; i += 2) { + uint32_t type = ib[i] >> 28, cond = (ib[i] >> 24) & 15, + res = (ib[i] >> 18) & 63, reg = ib[i] & 0x3ffff; + // what Linux's amdgpu_jpeg_dec_parse_cs lets through: type 0 with cond 0, + // type 3 with cond 3, the nop + types &= res == 0 && + ((type == 0 && cond == 0 && reg >= 0x4000 && reg < 0x4200) || + (type == 3 && cond == 3) || ib[i] == 0x60000000); + } + CHECK(types, + "decode IB: every packet is of a kind Linux's command parser accepts"); + // layout + jc::Layout lay{}; + CHECK(jc::outputLayout(640, 480, 0x3E0000, &lay) && lay.pitch == 768 && + lay.alignedHeight == 480 && lay.chromaOffset == 368640 && + lay.bytes == 552960, + "layout 640x480: pitch 768, 480 rows, chroma at 368640, 552960 bytes"); + CHECK(jc::outputLayout(1920, 1080, 0x3E0000, &lay) && lay.pitch == 2048 && + lay.alignedHeight == 1088 && lay.bytes == 2048u * 1088 * 3 / 2, + "layout 1920x1080: pitch 2048, 1088 rows"); + CHECK(jc::outputLayout(641, 481, 0x3E0000, &lay) && lay.pitch == 768 && + lay.alignedHeight == 496, + "layout 641x481 rounds columns and rows up to 16"); + CHECK(!jc::outputLayout(4096, 4096, 0x3E0000, &lay), + "layout refuses a picture larger than the surface"); + CHECK(!jc::outputLayout(0, 480, 0x3E0000, &lay) && + !jc::outputLayout(5000, 16, 0x7fffffff, &lay), + "layout refuses zero and oversize dimensions"); + // every size the layout accepts fits the surface, at the limits too + bool fits = true; + for (uint32_t w = 1; w <= 4096; w += 37) + for (uint32_t h = 1; h <= 4096; h += 41) + if (jc::outputLayout(w, h, 0x3E0000, &lay)) + fits &= + lay.bytes <= 0x3E0000 && lay.pitch >= jc::alignUp(w, 16) && + lay.pitch % 16 == 0 && + lay.chromaOffset + lay.pitch * (lay.alignedHeight / 2) == lay.bytes; + CHECK(fits, "layout: whatever it accepts fits the surface (sweep)"); + // stream + std::vector file = readFile(samplePath); + CHECK(!file.empty(), "sample read"); + if (file.empty()) return 1; + jc::StreamInfo si; + CHECK(jc::parseStream(file.data(), file.size(), &si) == jc::Stream::Ok && + si.width == 640 && si.height == 480, + "sample as it is: baseline 4:2:0, 640x480"); + std::vector norm; + std::string why = jnorm::normalize(file, &norm); + CHECK(why.empty(), "sample normalises"); + jc::StreamInfo sn; + CHECK(jc::parseStream(norm.data(), norm.size(), &sn) == jc::Stream::Ok && + sn.width == 640 && sn.height == 480, + "normalised sample: same size"); + CHECK(norm.size() >= 4 && norm[0] == 0xff && norm[1] == 0xd8 && + norm[2] == 0xff && norm[3] == 0xdb, + "normalised sample starts with SOI, DQT (the start Mesa looks for)"); + std::vector again; + CHECK(jnorm::normalize(norm, &again).empty() && again == norm, + "normalising twice changes nothing"); + // no prefix, and no single damaged byte in the headers, makes the parser read + // outside its input + size_t accepted = 0; + for (size_t len = 0; len <= norm.size(); len++) { + jc::StreamInfo x; + accepted += parseCopy(norm.data(), len, &x) == jc::Stream::Ok; + } + CHECK(accepted == 1, + "of every prefix of the sample only the whole file is accepted"); + size_t wrongSize = 0; + for (size_t at = 0; at < sn.scanOffset; at++) { + for (int bit = 0; bit < 8; bit++) { + std::vector bad = norm; + bad[at] ^= static_cast(1 << bit); + jc::StreamInfo x; + if (parseCopy(bad.data(), bad.size(), &x) == jc::Stream::Ok) { + jc::Layout l{}; + // an accepted stream with other dimensions must still be checked + // against the surface + if (x.width != 640 || x.height != 480) + wrongSize += + !jc::outputLayout(x.width, x.height, 0x3E0000, &l) ? 0 : 1; + } + std::vector o; + (void)jnorm::normalize(bad, &o); + } + } + printf( + " (%zu single-bit header changes still parse with another size; each " + "goes through the layout check)\n", + wrongSize); + uint8_t progressive[] = {0xff, 0xd8, 0xff, 0xc2, 0x00, 0x11, 8, 0, + 16, 0, 16, 3, 1, 0x22, 0, 2, + 0x11, 0, 3, 0x11, 0, 0xff, 0xd9}; + CHECK(jc::parseStream(progressive, sizeof(progressive), &si) == + jc::Stream::Unsupported, + "progressive JPEG refused"); + std::vector f444 = norm; + for (size_t i = 2; i + 20 < f444.size(); i++) + if (f444[i] == 0xff && f444[i + 1] == 0xc0) { + f444[i + 11] = 0x11; + break; + } + CHECK(jc::parseStream(f444.data(), f444.size(), &si) == jc::Stream::BadFrame, + "4:4:4 frame header refused"); + // 4:2:2: the three sampling forms Mesa writes as YUYV, and its surface + auto withSampling = [&](uint8_t y, uint8_t cb, uint8_t cr) { + std::vector v = norm; + for (size_t i = 2; i + 20 < v.size(); i++) + if (v[i] == 0xff && v[i + 1] == 0xc0) { + v[i + 11] = y; + v[i + 14] = cb; + v[i + 17] = cr; + break; + } + return v; + }; + for (auto sf : {std::array{0x21, 0x11, 0x11}, + std::array{0x22, 0x12, 0x12}, + std::array{0x22, 0x21, 0x21}}) { + std::vector v = withSampling(sf[0], sf[1], sf[2]); + jc::StreamInfo x; + char name[96]; + snprintf(name, sizeof name, "sampling %02x%02x%02x is 4:2:2 (YUYV)", sf[0], + sf[1], sf[2]); + CHECK(parseCopy(v.data(), v.size(), &x) == jc::Stream::Ok && + x.chroma == jc::Chroma::k422 && x.width == 640, + name); + } + { + std::vector v = withSampling(0x12, 0x11, 0x11); + jc::StreamInfo x; + CHECK(parseCopy(v.data(), v.size(), &x) == jc::Stream::BadFrame, + "sampling 121111 (4:4:0) refused"); + CHECK(sn.chroma == jc::Chroma::k420, "the 4:2:0 sample reads as 4:2:0"); + } + jc::Layout l422{}; + CHECK(jc::outputLayout(640, 480, 0x3E0000, &l422, jc::Chroma::k422) && + l422.pitch == 1280 && l422.alignedHeight == 480 && + l422.chromaOffset == 0 && l422.bytes == 614400 && + l422.regPitch == 640 && l422.regUvPitch == 0 && + l422.chroma == jc::Chroma::k422, + "4:2:2 layout 640x480: YUYV, 1280 bytes per row, register pitch 640 " + "pixels, one plane"); + CHECK(jc::outputLayout(641, 481, 0x3E0000, &l422, jc::Chroma::k422) && + l422.pitch == 1536 && l422.alignedHeight == 496, + "4:2:2 layout rounds columns to 16 and rows to 256 bytes"); + CHECK(!jc::outputLayout(1920, 1088, 0x3E0000, &l422, jc::Chroma::k422), + "4:2:2 layout refuses what does not fit"); + { + jc::Layout l{}; + jc::outputLayout(640, 480, 0x3E0000, &l); + jc::DecodeParams d = jc::decodeParams(l, 0x8000110000, 24704, 0x8000210000); + CHECK(d.pitch == 768 && d.uvPitch == 768 && d.chromaOffset == 368640 && + d.lumaOffset == 0, + "decodeParams for NV12 gives what the decode stage always sent"); + } + CHECK(sizeof(jp::Result) == 944, "Result is 944 bytes"); + printf("%s\n", fails == 0 ? "UNIT PASSED" : "UNIT FAILED"); + return fails == 0 ? 0 : 1; +} + +int main(int argc, char** argv) { + if (argc >= 2 && !strcmp(argv[1], "unit") && argc == 3) return unit(argv[2]); + if (argc == 7 && !strcmp(argv[1], "frame")) { + uint32_t frame[jc::kFrameWords]; + if (!jc::buildJobFrame(frame, strtoull(argv[2], nullptr, 0), + strtoull(argv[3], nullptr, 0), + static_cast(strtoul(argv[4], nullptr, 0)), + static_cast(strtoul(argv[5], nullptr, 0)), + strtoull(argv[6], nullptr, 0))) + return 1; + for (uint32_t w : frame) printf("%08x\n", w); + return 0; + } + if (argc == 7 && !strcmp(argv[1], "ib")) { + jc::DecodeParams d{}; + d.bitstreamGpu = strtoull(argv[2], nullptr, 0); + d.bitstreamBytes = static_cast(strtoul(argv[3], nullptr, 0)); + d.targetGpu = strtoull(argv[4], nullptr, 0); + d.pitch = d.uvPitch = static_cast(strtoul(argv[5], nullptr, 0)); + d.chromaOffset = static_cast(strtoul(argv[6], nullptr, 0)); + uint32_t ib[jc::kIbMaxWords]; + uint32_t n = jc::buildDecodeIb(ib, jc::kIbMaxWords, d); + if (n == 0) return 1; + for (uint32_t i = 0; i < n; i++) printf("%08x\n", ib[i]); + return 0; + } + // ibl : the IB the kext builds, going through outputLayout and decodeParams + // as kern_start.cpp does + if (argc == 8 && !strcmp(argv[1], "ibl")) { + jc::Layout lay{}; + if (!jc::outputLayout( + static_cast(strtoul(argv[5], nullptr, 0)), + static_cast(strtoul(argv[6], nullptr, 0)), 0xFFFFFFFFu, + &lay, static_cast(strtoul(argv[7], nullptr, 0)))) + return 1; + jc::DecodeParams d = + jc::decodeParams(lay, strtoull(argv[2], nullptr, 0), + static_cast(strtoul(argv[3], nullptr, 0)), + strtoull(argv[4], nullptr, 0)); + uint32_t ib[jc::kIbMaxWords]; + uint32_t n = jc::buildDecodeIb(ib, jc::kIbMaxWords, d); + if (n == 0) return 1; + for (uint32_t i = 0; i < n; i++) printf("%08x\n", ib[i]); + return 0; + } + // pm request | pm activate <0|1>: the PowerPlay requests, + // in x6000_oracle's format + if (argc >= 4 && !strcmp(argv[1], "pm")) { + uint64_t context = strtoull(argv[3], nullptr, 0); + uint8_t bytes[256]; + size_t n = 0; + uint64_t outSize = 0; + int hasOut = 0; + if (!strcmp(argv[2], "request") && argc == 4) { + jw::PmRequestIn r = jw::pmRequest(context); + n = sizeof(r); + memcpy(bytes, &r, n); + hasOut = 1; + outSize = sizeof(jw::PmRequestOut); + } else if (!strcmp(argv[2], "activate") && argc == 5) { + jw::ActivateIn a = jw::activate(context, atoi(argv[4]) != 0); + n = sizeof(a); + memcpy(bytes, &a, n); + } else { + return 2; + } + printf("insize %zu\nhasout %d\noutsize %llu\n", n, hasOut, outSize); + for (size_t i = 0; i < n; i += 4) { + uint32_t w; + memcpy(&w, bytes + i, 4); + printf("%08x\n", w); + } + return 0; + } + fprintf(stderr, + "usage: cmds_test unit | frame ... | ib ... | pm ...\n"); + return 2; +} diff --git a/GPU/jpeg/tests/gen_mesa_oracle.py b/GPU/jpeg/tests/gen_mesa_oracle.py new file mode 100644 index 00000000..6384e9ba --- /dev/null +++ b/GPU/jpeg/tests/gen_mesa_oracle.py @@ -0,0 +1,144 @@ +#!/usr/bin/env python3 +"""gen_mesa_oracle.py + +Builds a small C program around Mesa's own JPEG decode command builder, so that the IB the kext +writes (kext/jpeg_cmds.hpp, buildDecodeIb) can be compared word for word with what Mesa writes. + +Taken from the Mesa files as they are, by position, never retyped: + ac_vcn_dec.c everything from "#define RDECODE_JPEG_VER_1" to the end of ac_vcn_create_jpeg_decoder + (struct ac_vcn_jpeg_decoder, vcn_jpeg_build_decode_cmd, the register choice per VCN version) + ac_vcn_dec.h the RDECODE_*, vcnip*, COND* and TYPE* macros + amd_family.h enum vcn_version + addrtypes.h the swizzle mode enums +Only the surrounding types (the few fields the function reads) are written here. +The Mesa files are not part of this project: holds copies fetched from Mesa's repository.""" +import re, sys + +mesa, out = sys.argv[1], sys.argv[2] +rd = lambda n: open("%s/%s" % (mesa, n)).read() + +c = rd("ac_vcn_dec.c") +a = c.index("#define RDECODE_JPEG_VER_1") +b = c.index("ac_vcn_create_jpeg_decoder(const struct radeon_info") +b = c.index("\n}\n", b) + 3 +body = c[a:b] +assert "vcn_jpeg_build_decode_cmd" in body and "struct ac_vcn_jpeg_decoder {" in body + +h = rd("ac_vcn_dec.h") +defines = [] +lines = h.split("\n") +i = 0 +while i < len(lines): + if re.match(r"#define (RDECODE_|vcnip|COND\d|TYPE\d)", lines[i]): + j = i + while lines[j].rstrip().endswith("\\"): + j += 1 + defines.append("\n".join(lines[i:j + 1])) + i = j + 1 + else: + i += 1 +assert any("vcnipUVD_JPEG_CNTL" in d for d in defines) and any("RDECODE_PKTJ" in d for d in defines) + +fam = rd("amd_family.h") +m = re.search(r"enum vcn_version\s*\{.*?\};", fam, re.S) +vcn_enum = m.group(0) +addr = rd("addrtypes.h") +sw = re.search(r"typedef enum _AddrSwizzleMode\s*\{.*?\} AddrSwizzleMode;", addr, re.S).group(0) +sw3 = re.search(r"typedef enum _Addr3SwizzleMode\s*\{.*?\} Addr3SwizzleMode;", addr, re.S).group(0) + +shim = r''' +#include +#include +#include +#include +#include +#include + +/* ---- written here: the few surrounding types and helpers the Mesa code uses ---- */ +#define ROUND_DOWN_TO(v, a) ((v) / (a) * (a)) +static inline uint32_t align(uint32_t v, uint32_t a) { return (v + a - 1) / a * a; } +#define CALLOC_STRUCT(T) ((struct T *)calloc(1, sizeof(struct T))) +#define FREE(p) free(p) +#define SOC15_REG_ADDR(reg) 0 /* VCN 1.0 path only, never taken here */ +enum amd_gfx_level { GFX10_3 = 1, GFX11, GFX12 }; +enum amd_ip_type { AMD_IP_VCN_JPEG = 1 }; +enum pipe_format { PIPE_FORMAT_NV12 = 1, PIPE_FORMAT_R8_G8_B8_UNORM, PIPE_FORMAT_R8G8B8A8_UNORM, + PIPE_FORMAT_A8R8G8B8_UNORM, PIPE_FORMAT_YUYV }; +struct radeon_surf { + uint8_t blk_w, bpe; + uint16_t tile_swizzle; + struct { struct { uint64_t surf_offset; uint32_t surf_pitch; uint32_t swizzle_mode; } gfx9; } u; +}; +struct ac_video_surface { + enum pipe_format format; + uint32_t num_planes; + struct { struct radeon_surf *surf; uint64_t va; } planes[3]; +}; +struct ac_video_dec_session_param { int unused; }; +struct ac_video_dec_decode_cmd { + void *cmd_buffer; + uint64_t bitstream_va; + uint32_t bitstream_size; + struct ac_video_surface decode_surface; + struct { struct { uint32_t crop_x, crop_y, crop_width, crop_height; } mjpeg; } codec_param; + struct { uint32_t cmd_dw; } out; +}; +struct ac_video_dec { + enum amd_ip_type ip_type; + struct ac_video_dec_session_param param; + uint32_t max_decode_cmd_dw; + void (*destroy)(struct ac_video_dec *); + int (*build_decode_cmd)(struct ac_video_dec *, struct ac_video_dec_decode_cmd *); +}; +struct ac_cmdbuf { uint32_t *buf; uint32_t cdw, max_dw; }; +#define ac_cmdbuf_begin(cs) struct ac_cmdbuf *__cs = (cs); uint32_t __cs_num = __cs->cdw; uint32_t *__cs_buf = __cs->buf +#define ac_cmdbuf_emit(value) do { __cs_buf[__cs_num++] = (value); } while (0) +#define ac_cmdbuf_end() do { __cs->cdw = __cs_num; assert(__cs->cdw <= __cs->max_dw); __cs = NULL; } while (0) +''' + +main = r''' +/* ---- written here: one linear NV12 target on a VCN 3.0 GPU, as the kext sets it up; or, with "yuyv", + one linear YUYV target (Mesa's surface for 4:2:2 JPEG: blk_w 2, bpe 4, pitch counted in 2-pixel blocks) ---- */ +int main(int argc, char **argv) +{ + if (argc != 6 && !(argc == 7 && !strcmp(argv[6], "yuyv"))) { + fprintf(stderr, "usage: mesa_oracle bitstreamVa bitstreamBytes targetVa pitchBytes chromaOffset [yuyv]\n"); return 2; } + uint64_t bs_va = strtoull(argv[1], NULL, 0), dt_va = strtoull(argv[3], NULL, 0); + uint32_t bs_size = strtoul(argv[2], NULL, 0), pitch = strtoul(argv[4], NULL, 0), chroma = strtoul(argv[5], NULL, 0); + struct radeon_info info = { .gfx_level = GFX10_3, .vcn_ip_version = VCN_3_0_0 }; + struct ac_video_dec_session_param param = { 0 }; + struct ac_video_dec *dec = ac_vcn_create_jpeg_decoder(&info, ¶m); + /* luma: 1 byte per element; chroma: 2 bytes per element, half as many per row */ + struct radeon_surf luma = { .blk_w = 1, .bpe = 1 }, uv = { .blk_w = 1, .bpe = 2 }; + luma.u.gfx9.surf_pitch = pitch; luma.u.gfx9.swizzle_mode = ADDR_SW_LINEAR; luma.u.gfx9.surf_offset = 0; + uv.u.gfx9.surf_pitch = pitch / 2; uv.u.gfx9.swizzle_mode = ADDR_SW_LINEAR; uv.u.gfx9.surf_offset = chroma; + uint32_t words[256] = { 0 }; + struct ac_video_dec_decode_cmd cmd = { 0 }; + cmd.cmd_buffer = words; + cmd.bitstream_va = bs_va; + cmd.bitstream_size = bs_size; + cmd.decode_surface.format = PIPE_FORMAT_NV12; + cmd.decode_surface.num_planes = 2; + cmd.decode_surface.planes[0].surf = &luma; cmd.decode_surface.planes[0].va = dt_va; + cmd.decode_surface.planes[1].surf = &uv; cmd.decode_surface.planes[1].va = dt_va; + struct radeon_surf packed = { .blk_w = 2, .bpe = 4 }; + if (argc == 7) { + packed.u.gfx9.surf_pitch = pitch / 4; packed.u.gfx9.swizzle_mode = ADDR_SW_LINEAR; packed.u.gfx9.surf_offset = 0; + cmd.decode_surface.format = PIPE_FORMAT_YUYV; + cmd.decode_surface.num_planes = 1; + cmd.decode_surface.planes[0].surf = &packed; + cmd.decode_surface.planes[1].surf = NULL; cmd.decode_surface.planes[1].va = 0; + } + if (dec->build_decode_cmd(dec, &cmd) != 0) return 1; + for (uint32_t i = 0; i < cmd.out.cmd_dw; i++) printf("%08x\n", words[i]); + return 0; +} +''' +src = ("/* Generated by tests/gen_mesa_oracle.py. The middle part is Mesa's code (MIT), copied as it is. */\n" + shim + + "\n/* ---- from Mesa amd_family.h ---- */\n" + vcn_enum + + "\nstruct radeon_info { enum amd_gfx_level gfx_level; enum vcn_version vcn_ip_version; };\n" + + "\n/* ---- from Mesa addrtypes.h ---- */\n" + sw + "\n" + sw3 + + "\n/* ---- from Mesa ac_vcn_dec.h ---- */\n" + "\n".join(defines) + + "\n\n/* ---- from Mesa ac_vcn_dec.c ---- */\nstruct ac_video_dec *ac_vcn_create_jpeg_decoder(const struct radeon_info *info, struct ac_video_dec_session_param *param);\n" + body + main) +open(out, "w").write(src) +print("wrote %s (%d lines of Mesa code)" % (out, body.count("\n"))) diff --git a/GPU/jpeg/tests/hwlibs_oracle.c b/GPU/jpeg/tests/hwlibs_oracle.c new file mode 100644 index 00000000..219e2d8b --- /dev/null +++ b/GPU/jpeg/tests/hwlibs_oracle.c @@ -0,0 +1,119 @@ +// +// hwlibs_oracle - runs Apple's queue_jpeg_decode_2_0_build_command, the +// function of AMDRadeonX6000HWLibs that writes the JRBC ring commands, in user +// space and prints what it writes. tests/run.sh compares the output with the +// frame kext/jpeg_cmds.hpp builds. +// +// It maps the segments of the KDK binary into this process at one base and +// calls the function there. The function only computes: it reads the ring +// address from the queue (offset 40) and the command description, and writes +// words to the output buffer. The commands asked for here (start, IB, fence, +// end) call nothing outside the image except two local helpers +// (dmu_get_lo/hi_32bit). No kext is loaded and no device is touched. +// +// usage: hwlibs_oracle +// +// +#include +#include +#include +#include +#include +#include +#include +#include +#include + +// _TtlBuildCommandInfo as the function reads it (JPEG-HWLIBS.md, section B). +struct info { + uint32_t type, pad; + uint32_t flags, a; + uint64_t b, c; +}; +typedef uint64_t (*build_fn)(void* queue, struct info* in, void* out); + +static void emit(const char* name, const uint32_t* w, int n) { + for (int i = 0; i < n; i++) printf("%s %08x\n", name, w[i]); +} + +int main(int argc, char** argv) { + if (argc != 8) { + fprintf(stderr, + "usage: hwlibs_oracle \n"); + return 2; + } + int fd = open(argv[1], O_RDONLY); + struct stat st; + if (fd < 0 || fstat(fd, &st) != 0) return perror(argv[1]), 2; + uint8_t* file = mmap(NULL, (size_t)st.st_size, PROT_READ, MAP_PRIVATE, fd, 0); + if (file == MAP_FAILED) return perror("mmap"), 2; + const struct mach_header_64* mh = (const void*)file; + if (mh->magic != MH_MAGIC_64 || mh->cputype != CPU_TYPE_X86_64) + return fprintf(stderr, "not a thin x86_64 Mach-O\n"), 2; + uint64_t span = 0; + const struct load_command* lc = (const void*)(mh + 1); + for (uint32_t i = 0; i < mh->ncmds; + i++, lc = (const void*)((const uint8_t*)lc + lc->cmdsize)) { + if (lc->cmd != LC_SEGMENT_64) continue; + const struct segment_command_64* sg = (const void*)lc; + if (sg->vmaddr + sg->vmsize > span) span = sg->vmaddr + sg->vmsize; + } + uint8_t* base = + mmap(NULL, span, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON, -1, 0); + if (base == MAP_FAILED) return perror("mmap image"), 2; + lc = (const void*)(mh + 1); + for (uint32_t i = 0; i < mh->ncmds; + i++, lc = (const void*)((const uint8_t*)lc + lc->cmdsize)) { + if (lc->cmd != LC_SEGMENT_64) continue; + const struct segment_command_64* sg = (const void*)lc; + if (sg->filesize != 0) + memcpy(base + sg->vmaddr, file + sg->fileoff, sg->filesize); + } + if (mprotect(base, span, PROT_READ | PROT_EXEC) != 0) + return perror("mprotect"), 2; + build_fn build = (build_fn)(base + strtoull(argv[2], NULL, 0)); + uint64_t ring = strtoull(argv[3], NULL, 0), ib = strtoull(argv[4], NULL, 0), + fence = strtoull(argv[7], NULL, 0); + uint32_t ibBytes = (uint32_t)strtoul(argv[5], NULL, 0), + seq = (uint32_t)strtoul(argv[6], NULL, 0); + + uint8_t queue[208] = {0}; + memcpy(queue + 40, &ring, 8); + uint32_t out[64]; + struct info in; + + memset(out, 0xcc, sizeof(out)); + memset(&in, 0, sizeof(in)); + in.type = 0x20007; + build(queue, &in, out); + emit("start", out, 4); + + memset(out, 0xcc, sizeof(out)); + memset(&in, 0, sizeof(in)); + in.type = 0x20002; + in.flags = 1 | 2 | 4 | 8; // template, vmid, IB address, IB size + in.a = 0; // VMID 0 + in.b = ib; + in.c = ibBytes; + build(queue, &in, out); + emit("ib", out, 22); + + memset(out, 0xcc, sizeof(out)); + memset(&in, 0, sizeof(in)); + in.type = 0x20003; + in.flags = 1 | 4 | 8; // template, sequence number, address + in.b = seq; + in.c = fence; + build(queue, &in, out); + emit("fence", out, 26); + + memset(out, 0xcc, sizeof(out)); + memset(&in, 0, sizeof(in)); + in.type = 0x20008; + build(queue, &in, out); + emit("end", out, 4); + // Every command must have stayed inside the size HWLibs itself gives for it: + // the words after it still hold the fill pattern. + return 0; +} diff --git a/GPU/jpeg/tests/jpeg_normalize.hpp b/GPU/jpeg/tests/jpeg_normalize.hpp new file mode 100644 index 00000000..1f32d301 --- /dev/null +++ b/GPU/jpeg/tests/jpeg_normalize.hpp @@ -0,0 +1,149 @@ +// +// jpeg_normalize.hpp - rewrites a baseline JPEG file into the exact shape Mesa +// hands the VCN JPEG block: SOI, one DQT segment, one DHT segment (DC tables, +// then AC tables), DRI if there is a restart interval, SOF0, SOS, the scan, +// EOI. That is what vlVaGetJpegSliceHeader (src/gallium/frontends/va/ +// picture_mjpeg.c) builds in front of the scan data; APPn and COM segments +// never reach the hardware there, so they are dropped here too. +// User space only (tool and tests). +// +#pragma once +#include +#include +#include + +namespace jnorm { + +struct Tables { + bool haveQ[4] = {}; + uint8_t q[4][64] = {}; + bool haveH[2][2] = {}; // [class 0 DC / 1 AC][id] + std::vector h[2][2]; // 16 counts + values + uint16_t restart = 0; + std::vector sof, sos; // segment bodies, without marker and length + std::vector scan; // entropy-coded data, without EOI +}; + +inline void seg(std::vector& o, uint8_t marker, + const std::vector& body) { + o.push_back(0xff); + o.push_back(marker); + o.push_back(static_cast((body.size() + 2) >> 8)); + o.push_back(static_cast(body.size() + 2)); + o.insert(o.end(), body.begin(), body.end()); +} + +// Returns an empty string and fills `out`, or says why the file is not handled. +inline std::string normalize(const std::vector& in, + std::vector* out) { + const uint8_t* d = in.data(); + size_t n = in.size(); + if (n < 4 || d[0] != 0xff || d[1] != 0xd8) return "not a JPEG (no SOI)"; + Tables t; + size_t i = 2; + bool gotScan = false; + while (!gotScan) { + if (i + 4 > n) return "no scan found"; + if (d[i] != 0xff) return "marker expected at byte " + std::to_string(i); + uint8_t m = d[i + 1]; + size_t len = (static_cast(d[i + 2]) << 8) | d[i + 3]; + if (len < 2 || i + 2 + len > n) + return "segment at byte " + std::to_string(i) + " does not fit"; + 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 "16-bit quantisation table"; + if (tq > 3 || p + 65 > body) return "bad quantisation table"; + t.haveQ[tq] = true; + for (int k = 0; k < 64; k++) t.q[tq][k] = s[p + 1 + k]; + 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 > 1 || p + 17 > body) + return "Huffman table the block is not given by Mesa (class or id " + "above 1)"; + size_t count = 0; + for (int k = 0; k < 16; k++) count += s[p + 1 + k]; + if (count > (tc == 0 ? 12u : 162u) || p + 17 + count > body) + return "bad Huffman table"; + t.haveH[tc][th] = true; + t.h[tc][th].assign(s + p + 1, s + p + 17 + count); + p += 17 + count; + } + } else if (m == 0xdd) { + if (body != 2) return "bad restart interval segment"; + t.restart = static_cast((s[0] << 8) | s[1]); + } else if (m == 0xc0) { + if (!t.sof.empty()) return "more than one frame header"; + t.sof.assign(s, s + body); + } else if (m == 0xda) { + t.sos.assign(s, s + body); + gotScan = true; + } else if ((m >= 0xe0 && m <= 0xef) || m == 0xfe) { + // dropped + } else if (m >= 0xc1 && m <= 0xcf && m != 0xc4 && m != 0xc8 && m != 0xcc) { + return "not a baseline JPEG (frame type 0x" + + std::string(1, "0123456789abcdef"[m >> 4]) + + std::string(1, "0123456789abcdef"[m & 15]) + ")"; + } else { + return "segment the test does not handle at byte " + std::to_string(i); + } + i += 2 + len; + } + if (t.sof.empty()) return "scan before the frame header"; + // The scan runs to the first marker that is neither a stuffed FF00 nor RSTn. + size_t e = i; + while (true) { + if (e + 1 >= n) return "no EOI after the scan"; + if (d[e] == 0xff && d[e + 1] != 0x00 && + !(d[e + 1] >= 0xd0 && d[e + 1] <= 0xd7)) + break; + e++; + } + if (d[e + 1] != 0xd9) return "more than one scan"; + t.scan.assign(d + i, d + e); + bool anyQ = false, anyH = false; + std::vector dqt, dht; + for (int k = 0; k < 4; k++) { + if (!t.haveQ[k]) continue; + anyQ = true; + dqt.push_back(static_cast(k)); + dqt.insert(dqt.end(), t.q[k], t.q[k] + 64); + } + for (int c = 0; c < 2; c++) { + for (int k = 0; k < 2; k++) { + if (!t.haveH[c][k]) continue; + anyH = true; + dht.push_back(static_cast((c << 4) | k)); + dht.insert(dht.end(), t.h[c][k].begin(), t.h[c][k].end()); + } + } + if (!anyQ) return "no quantisation tables"; + if (!anyH) + return "no Huffman tables in the file (a bare MJPEG frame); not handled " + "yet"; + std::vector& o = *out; + o.clear(); + o.push_back(0xff); + o.push_back(0xd8); + seg(o, 0xdb, dqt); + seg(o, 0xc4, dht); + if (t.restart != 0) + seg(o, 0xdd, + {static_cast(t.restart >> 8), + static_cast(t.restart)}); + seg(o, 0xc0, t.sof); + seg(o, 0xda, t.sos); + o.insert(o.end(), t.scan.begin(), t.scan.end()); + o.push_back(0xff); + o.push_back(0xd9); + return ""; +} + +} // namespace jnorm diff --git a/GPU/jpeg/tests/run.sh b/GPU/jpeg/tests/run.sh new file mode 100755 index 00000000..e07470c2 --- /dev/null +++ b/GPU/jpeg/tests/run.sh @@ -0,0 +1,162 @@ +#!/bin/zsh +# jpeg/tests/run.sh - host checks of VCNJpeg. Loads no kext and touches no device. Run +# jpeg/build.sh tests first. +# +# 1. unit checks of kext/jpeg_cmds.hpp (frames, IB, layout, stream check), with sanitizers +# 2. the door (kext/apps_handler.hpp) and when the block is powered (kext/idle_logic.hpp) +# 3. the job frame against Apple's own queue_jpeg_decode_2_0_build_command, run from the KDK +# binary (KDK_HWLIBS) +# 4. the decode IB against Mesa's own vcn_jpeg_build_decode_cmd, compiled from Mesa's source +# (MESA_DIR: ac_vcn_dec.c and the files tests/gen_mesa_oracle.py names) +# 5. the PowerPlay requests against Apple's own setClocks and notifyPMContext, run from the +# KDK binary (KDK_X6000) +# +# 1 and 2 need a baseline JPEG of 640x480 (SAMPLE); without one, it is made with ffmpeg +# (FFMPEG). 3 to 5 need Apple's KDK for macOS 26.7.3 (25G342) and a copy of Mesa: when they are +# missing those parts are skipped, and the result says so. +emulate -L zsh +setopt err_exit no_unset pipe_fail +HERE=${0:A:h}; JPEG=${HERE:h}; B=$JPEG/build/tests +KDK=${KDK:-/Library/Developer/KDKs/KDK_26.7.3_25G342.kdk} +KDK_HWLIBS=${KDK_HWLIBS:-$KDK/System/Library/Extensions/AMDRadeonX6000HWServices.kext/Contents/PlugIns/AMDRadeonX6000HWLibs.kext/Contents/MacOS/AMDRadeonX6000HWLibs} +KDK_X6000=${KDK_X6000:-$KDK/System/Library/Extensions/AMDRadeonX6000.kext/Contents/MacOS/AMDRadeonX6000} +MESA_DIR=${MESA_DIR:-} +FFMPEG=${FFMPEG:-$(command -v ffmpeg || true)} +[[ -x $B/cmds_test && -x $B/apps_test ]] || { print "run jpeg/build.sh tests first"; exit 1; } +fails=0 skips=0 +say() { print -r -- "$1 $2"; [[ $1 == ok ]] || fails=$((fails + 1)); } +skip() { print -r -- "skip $1"; skips=$((skips + 1)); } + +SAMPLE=${SAMPLE:-} +if [[ -z $SAMPLE && -n $FFMPEG ]]; then + SAMPLE=$B/sample-640x480.jpg + $FFMPEG -hide_banner -v error -f lavfi -i testsrc=size=640x480:rate=1 -frames:v 1 -pix_fmt yuvj420p \ + -huffman default -q:v 4 -y $SAMPLE +fi + +print "== 1. unit checks, and 2. the door and the block's power (address and undefined-behaviour sanitizers)" +if [[ -n $SAMPLE && -f $SAMPLE ]]; then + $B/cmds_test unit $SAMPLE > $B/cmds_test.txt || fails=$((fails + 1)) + grep -v '^ok ' $B/cmds_test.txt || true + print "$(grep -c '^ok ' $B/cmds_test.txt) unit checks passed" + $B/apps_test $SAMPLE > $B/apps_test.txt || fails=$((fails + 1)) + grep -v '^ok ' $B/apps_test.txt || true + print "$(grep -c '^ok ' $B/apps_test.txt) door checks passed" +else + say FAIL "no 640x480 baseline JPEG: give SAMPLE, or install ffmpeg" +fi + +print "== 3. job frame against HWLibs' own command builder" +if [[ -f $KDK_HWLIBS ]]; then + addr=0x$(nm $KDK_HWLIBS | awk '$3 == "_queue_jpeg_decode_2_0_build_command" {print $1}') + for args in "0x8000100000 0x8000200000 80 7 0x8000201000" "0xff00123000 0x1234567000 16 4294967295 0xabcdef1000" \ + "0x100000 0x200000 128 1 0x201000"; do + a=(${=args}) + $B/hwlibs_oracle $KDK_HWLIBS $addr $a[1] $a[2] $((a[3] * 4)) $a[4] $a[5] | awk '{print $2}' > $B/frame.hwlibs + $B/cmds_test frame $a[1] $a[2] $a[3] $a[4] $a[5] > $B/frame.ours + # HWLibs' four commands are the first 56 words; ours go on with four nop pairs + if [[ $(wc -l < $B/frame.hwlibs) -eq 56 ]] && cmp -s $B/frame.hwlibs <(head -56 $B/frame.ours) \ + && [[ "$(tail -8 $B/frame.ours | tr '\n' ' ')" == "60000000 00000000 60000000 00000000 60000000 00000000 60000000 00000000 " ]]; then + say ok "frame equals HWLibs' start + IB + fence + end, word for word ($args)" + else + say FAIL "frame differs from HWLibs' ($args)"; diff $B/frame.hwlibs <(head -56 $B/frame.ours) | head -10 || true + fi + done +else + skip "no KDK AMDRadeonX6000HWLibs at $KDK_HWLIBS (set KDK or KDK_HWLIBS)" +fi + +print "== 4. decode IB against Mesa's own builder" +if [[ -n $MESA_DIR && -f $MESA_DIR/ac_vcn_dec.c ]]; then + python3 -I $HERE/gen_mesa_oracle.py $MESA_DIR $B/mesa_oracle.c > /dev/null + xcrun clang -std=c11 -arch x86_64 -O1 -Wall -Wno-unused-function -Wno-unused-variable $B/mesa_oracle.c -o $B/mesa_oracle + for args in "0x8000110000 24704 0x8000210000 768 368640" "0xff12345000 1048448 0xab00110000 2048 2228224" \ + "0x110000 128 0x210000 256 4096"; do + a=(${=args}) + $B/mesa_oracle $a > $B/ib.mesa + $B/cmds_test ib $a > $B/ib.ours + n=$(wc -l < $B/ib.mesa | tr -d ' ') + rest=$(tail -n +$((n + 1)) $B/ib.ours | tr '\n' ' ') + # Mesa's builder stops before the padding its winsys adds: (0x60000000, 0) pairs up to 16 words + if cmp -s $B/ib.mesa <(head -$n $B/ib.ours) && [[ $(( $(wc -l < $B/ib.ours) % 16 )) -eq 0 ]] \ + && [[ -z ${rest//60000000 00000000 /} ]]; then + say ok "IB equals Mesa's $n words, then nop pairs to $(wc -l < $B/ib.ours | tr -d ' ') ($args)" + else + say FAIL "IB differs from Mesa's ($args)"; diff $B/ib.mesa <(head -$n $B/ib.ours) | head -10 || true + fi + done + # through outputLayout + decodeParams, NV12 and YUYV (4:2:2), against Mesa's surface for each + for pair in "0x8000110000 24704 0x8000210000 768 368640|0x8000110000 24704 0x8000210000 640 480 0" \ + "0x8000110000 24704 0x8000210000 1280 0 yuyv|0x8000110000 24704 0x8000210000 640 480 1" \ + "0xff12345000 1048448 0xab00110000 3840 0 yuyv|0xff12345000 1048448 0xab00110000 1920 1080 1"; do + m=(${=pair%%|*}); o=(${=pair##*|}) + $B/mesa_oracle $m > $B/ib.mesa + $B/cmds_test ibl $o > $B/ib.ours + n=$(wc -l < $B/ib.mesa | tr -d ' ') + rest=$(tail -n +$((n + 1)) $B/ib.ours | tr '\n' ' ') + if cmp -s $B/ib.mesa <(head -$n $B/ib.ours) && [[ $(( $(wc -l < $B/ib.ours) % 16 )) -eq 0 ]] \ + && [[ -z ${rest//60000000 00000000 /} ]]; then + say ok "layout IB equals Mesa's $n words (mesa: ${m[*]}; ours: ${o[*]})" + else + say FAIL "layout IB differs from Mesa's (mesa: ${m[*]}; ours: ${o[*]})"; diff $B/ib.mesa <(head -$n $B/ib.ours) | head -10 || true + fi + done +else + skip "no copy of Mesa (set MESA_DIR to a folder holding ac_vcn_dec.c and its headers)" +fi + +print "== 5. PowerPlay requests against Apple's own kernel code" +if [[ -f $KDK_X6000 ]]; then + # address and length of a function, and the external calls inside it as site:stand-in + xfn() { nm -n $KDK_X6000 | python3 -I -c 'import sys +want, start, end = sys.argv[1], None, None +for line in sys.stdin: + f = line.split() + if len(f) != 3 or f[1] not in "TtSs": continue + if start is not None and end is None: end = int(f[0], 16) + if f[2] == want: start = int(f[0], 16) +print("0x%x %d" % (start, end - start))' $1; } + xsites() { otool -rv $KDK_X6000 | python3 -I -c 'import sys +lo, n = int(sys.argv[1], 16), int(sys.argv[2]) +for line in sys.stdin: + f = line.split() + if len(f) >= 7 and f[4] == "BRANCH" and lo <= int(f[0], 16) < lo + n: + kind = {"___bzero": "bzero", "_IOLockLock": "nop", "_IOLockUnlock": "nop"}.get(f[6], "UNKNOWN_" + f[6]) + print("%s:%s" % (f[0], kind))' $1 $2; } + send=0x$(nm $KDK_X6000 | awk '$3 == "__ZN37AMDRadeonX6000_AMDGraphicsAccelerator13sendPMCommandEPv" {print $1}') + sc=($(xfn __ZN33AMDRadeonX6000_AMDAccelVCNContext9setClocksEv)) + nf=($(xfn __ZN35AMDRadeonX6000_AMDAccelVideoContext15notifyPMContextE21_CWDDEPM_SCHEDULER_IDjyjj)) + for ctx in 0xffffff8012345678 0x1122334455667788; do + $B/x6000_oracle $KDK_X6000 $send setclocks $sc[1] $sc[2] 21 $ctx $(xsites $sc[1] $sc[2]) > $B/pm.apple + $B/cmds_test pm request $ctx > $B/pm.ours + if [[ $(wc -l < $B/pm.apple) -eq 35 ]] && cmp -s $B/pm.apple $B/pm.ours; then + say ok "PMRequest equals what AMDAccelVCNContext::setClocks builds for client type 21 (context $ctx)" + else + say FAIL "PMRequest differs from setClocks' ($ctx)"; diff $B/pm.apple $B/pm.ours | head -10 || true + fi + for on in 1 0; do + $B/x6000_oracle $KDK_X6000 $send notify $nf[1] $nf[2] 21 $ctx $on $(xsites $nf[1] $nf[2]) > $B/pm.apple + $B/cmds_test pm activate $ctx $on > $B/pm.ours + if [[ $(wc -l < $B/pm.apple) -eq 15 ]] && cmp -s $B/pm.apple $B/pm.ours; then + say ok "ActivateClient($on) equals what AMDAccelVideoContext::notifyPMContext builds (context $ctx)" + else + say FAIL "ActivateClient($on) differs from notifyPMContext's ($ctx)"; diff $B/pm.apple $B/pm.ours | head -10 || true + fi + done + done + # the same Apple code with the VCN client type differs from ours in that one word only + $B/x6000_oracle $KDK_X6000 $send setclocks $sc[1] $sc[2] 28 0x1122334455667788 $(xsites $sc[1] $sc[2]) > $B/pm.apple + $B/cmds_test pm request 0x1122334455667788 > $B/pm.ours + diff $B/pm.apple $B/pm.ours > $B/pm.diff || true + if [[ $(grep -c '^[<>]' $B/pm.diff) -eq 2 ]] && grep -q '^< 0000001c$' $B/pm.diff && grep -q '^> 00000015$' $B/pm.diff; then + say ok "with Apple's own client type (28) the request differs from ours in the client type word only" + else + say FAIL "unexpected difference against the VCN request" + fi +else + skip "no KDK AMDRadeonX6000 at $KDK_X6000 (set KDK or KDK_X6000)" +fi + +print "" +if (( fails )); then print "$fails TEST(S) FAILED"; exit 1; fi +if (( skips )); then print "TESTS PASSED ($skips part(s) skipped)"; else print "TESTS PASSED"; fi diff --git a/GPU/jpeg/tests/x6000_oracle.c b/GPU/jpeg/tests/x6000_oracle.c new file mode 100644 index 00000000..53f11615 --- /dev/null +++ b/GPU/jpeg/tests/x6000_oracle.c @@ -0,0 +1,181 @@ +// +// x6000_oracle - runs the two functions of Apple's AMDRadeonX6000 that build +// PowerPlay requests in the kernel, in user space, and prints the requests +// they hand to sendPMCommand: +// +// AMDAccelVCNContext::setClocks() the PMRequest (escape 0x53) of +// a video session AMDAccelVideoContext::notifyPMContext() ActivateClient +// (escape 0x34) +// +// tests/run.sh compares them, with the JPEG client type, with what +// kext/jpeg_power.hpp builds. +// +// The KDK binary's segments are mapped into this process. Inside the two +// functions every call is replaced before anything runs: the call to +// AMDGraphicsAccelerator::sendPMCommand goes to capture() below, which copies +// the request; __bzero goes to a local bzero; IOLockLock / IOLockUnlock to a +// function that does nothing. The objects passed as "this" are plain zeroed +// buffers with only the fields the functions read filled in. No kext is loaded +// and no device is touched. +// +// usage: x6000_oracle setclocks +// +// : ... +// x6000_oracle notify +// +// : ... +// A site is the address of the 4-byte operand of an external call, as `otool +// -rv` lists it. +// +#include +#include +#include +#include +#include +#include +#include +#include +#include + +struct args { + const void* in; + uint64_t inSize; + void* out; + uint64_t* outSize; +}; +static uint8_t gIn[512]; +static uint64_t gInSize, gOutSize; +static int gHasOut, gCalls; +static void* gAccelSeen; + +static uint32_t capture(void* accel, struct args* a) { + gCalls++; + gAccelSeen = accel; + gInSize = a->inSize; + if (a->inSize <= sizeof(gIn)) memcpy(gIn, a->in, a->inSize); + gHasOut = a->out != NULL; + gOutSize = a->outSize ? *a->outSize : ~0ull; + return 0; +} +static void my_bzero(void* p, size_t n) { memset(p, 0, n); } +static void nothing(void) {} + +// movabs rax, target; jmp rax +static uint8_t* trampoline(uint8_t* at, void* target) { + at[0] = 0x48; + at[1] = 0xb8; + memcpy(at + 2, &target, 8); + at[10] = 0xff; + at[11] = 0xe0; + return at; +} +static int patch_call(uint8_t* base, uint64_t operand, uint8_t* tramp) { + if (base[operand - 1] != 0xe8) return 0; // must be a call rel32 + int32_t rel = (int32_t)(tramp - (base + operand + 4)); + memcpy(base + operand, &rel, 4); + return 1; +} + +int main(int argc, char** argv) { + if (argc < 8) + return fprintf(stderr, "usage: see the head of x6000_oracle.c\n"), 2; + int notify = !strcmp(argv[3], "notify"); + int fd = open(argv[1], O_RDONLY); + struct stat st; + if (fd < 0 || fstat(fd, &st) != 0) return perror(argv[1]), 2; + uint8_t* file = mmap(NULL, (size_t)st.st_size, PROT_READ, MAP_PRIVATE, fd, 0); + if (file == MAP_FAILED) return perror("mmap"), 2; + const struct mach_header_64* mh = (const void*)file; + if (mh->magic != MH_MAGIC_64 || mh->cputype != CPU_TYPE_X86_64) + return fprintf(stderr, "not a thin x86_64 Mach-O\n"), 2; + uint64_t span = 0; + const struct load_command* lc = (const void*)(mh + 1); + for (uint32_t i = 0; i < mh->ncmds; + i++, lc = (const void*)((const uint8_t*)lc + lc->cmdsize)) { + if (lc->cmd != LC_SEGMENT_64) continue; + const struct segment_command_64* sg = (const void*)lc; + if (sg->vmaddr + sg->vmsize > span) span = sg->vmaddr + sg->vmsize; + } + span = (span + 0xfff) & ~0xfffull; + uint8_t* base = mmap(NULL, span + 0x1000, PROT_READ | PROT_WRITE, + MAP_PRIVATE | MAP_ANON, -1, 0); + if (base == MAP_FAILED) return perror("mmap image"), 2; + lc = (const void*)(mh + 1); + for (uint32_t i = 0; i < mh->ncmds; + i++, lc = (const void*)((const uint8_t*)lc + lc->cmdsize)) { + if (lc->cmd != LC_SEGMENT_64) continue; + const struct segment_command_64* sg = (const void*)lc; + if (sg->filesize != 0) + memcpy(base + sg->vmaddr, file + sg->fileoff, sg->filesize); + } + uint8_t* page = base + span; // trampolines live right after the image + uint8_t* tCapture = trampoline(page, capture); + uint8_t* tBzero = trampoline(page + 16, my_bzero); + uint8_t* tNothing = trampoline(page + 32, nothing); + + uint64_t sendPM = strtoull(argv[2], NULL, 0), fn = strtoull(argv[4], NULL, 0), + len = strtoull(argv[5], NULL, 0); + uint32_t clientType = (uint32_t)strtoul(argv[6], NULL, 0); + uint64_t context = strtoull(argv[7], NULL, 0); + int first = notify ? 9 : 8; + // every call inside the function: to sendPMCommand -> capture; the listed + // external ones -> their stand-in + int toSend = 0, calls = 0, patched = 0; + for (uint64_t a = fn; a + 5 <= fn + len; a++) { + if (base[a] != 0xe8) continue; + int32_t rel; + memcpy(&rel, base + a + 1, 4); + if (a + 5 + (int64_t)rel == sendPM) { + toSend += patch_call(base, a + 1, tCapture); + a += 4; + } + } + for (int i = first; i < argc; i++) { + char* colon = strchr(argv[i], ':'); + if (!colon) return fprintf(stderr, "bad site %s\n", argv[i]), 2; + uint64_t site = strtoull(argv[i], NULL, 16); + if (site < fn || site >= fn + len) + return fprintf(stderr, "site %s is outside the function\n", argv[i]), 2; + calls++; + patched += + patch_call(base, site, !strcmp(colon + 1, "bzero") ? tBzero : tNothing); + } + if (toSend != 1 || patched != calls) + return fprintf(stderr, + "calls not as expected: %d to sendPMCommand, %d of %d " + "external patched\n", + toSend, patched, calls), + 2; + if (mprotect(base, span + 0x1000, PROT_READ | PROT_EXEC) != 0) + return perror("mprotect"), 2; + + static uint8_t accel[8192], self[8192], lock[64]; + if (!notify) { + // AMDAccelVCNContext: +56 accelerator, +104 client type, +112 context + // handle, +128/+136/+140 clock fields (0) + void* p = accel; + memcpy(self + 56, &p, 8); + memcpy(self + 104, &clientType, 4); + memcpy(self + 112, &context, 8); + ((uint64_t (*)(void*))(base + fn))(self); + } else { + // AMDAccelVideoContext: +1448 accelerator, +4552 lock + void* p = accel; + void* l = lock; + memcpy(self + 1448, &p, 8); + memcpy(self + 4552, &l, 8); + uint32_t activate = (uint32_t)strtoul(argv[8], NULL, 0); + ((uint64_t (*)(void*, uint32_t, uint32_t, uint64_t, uint32_t, uint32_t))( + base + fn))(self, clientType, 0, context, activate, 0); + } + if (gCalls != 1 || gAccelSeen != (void*)accel || gInSize > sizeof(gIn)) + return fprintf(stderr, "sendPMCommand was not called once as expected\n"), + 1; + printf("insize %llu\nhasout %d\noutsize %llu\n", gInSize, gHasOut, gOutSize); + for (uint64_t i = 0; i < gInSize; i += 4) { + uint32_t w; + memcpy(&w, gIn + i, 4); + printf("%08x\n", w); + } + return 0; +} diff --git a/GPU/jpeg/tools/gen_expect.py b/GPU/jpeg/tools/gen_expect.py new file mode 100644 index 00000000..e146d556 --- /dev/null +++ b/GPU/jpeg/tools/gen_expect.py @@ -0,0 +1,145 @@ +#!/usr/bin/env python3 +"""gen_expect.py + +Writes the table the kext checks at load: for every function it needs, the +symbol, its offset from the image header and its first 16 bytes, all read from +the KDK binary of the studied build. Run by hand when a build is added; its +output is committed as jpeg/kext/hwlibs_expect.hpp. GPU/tests/run.sh compares +the first bytes with this Mac's kernel collection when it runs that build.""" +import struct, subprocess, sys, uuid + +BUILD = "26.7.3 (25G342)" +# (enum name, symbol) +FUNCS = [ + ("kStartMM", "__ZN14AmdTtlServices19startMMEngineQueuesEv"), + ("kCreateEngine", "__ZN14AmdTtlServices12createEngineE19AMD_SWIP_QUEUE_TYPEjP21_TtlCreateEngineInput"), + ("kNotifyEngine", "__ZN14AmdTtlServices12notifyEngineE19AMD_SWIP_QUEUE_TYPEj20AMD_TTL_ENGINE_EVENT"), + ("kQueryState", "__ZN14AmdTtlServices21queryEngineQueueStateE19AMD_SWIP_QUEUE_TYPEjP21AMD_SWIP_ENGINE_STATE"), + ("kStopMM", "__ZN14AmdTtlServices18stopMMEngineQueuesEv"), + ("kStopEngineQueue", "__ZN14AmdTtlServices15stopEngineQueueE19AMD_SWIP_QUEUE_TYPEj"), + ("kTtlGetIpi", "_ttlGetIpi"), + ("kIpiGetJpegContext", "_IpiGetJpegContext"), + ("kJpegReadRegister", "_jpeg_internal_cgs_read_register"), + ("kJpegCreateQueue", "_jpeg_create_queue"), + ("kJpegStartQueue", "_jpeg_start_queue"), + ("kJpegStopQueue", "_jpeg_stop_queue"), + ("kJpegQueryQueueStatus", "_jpeg_query_queue_status"), +] +# The decode job (kext/kern_start.cpp: decodeRun, poolTake). +DECODE_FUNCS = [ + ("kSubmitFrame", "__ZN14AmdTtlServices11submitFrameE19AMD_SWIP_QUEUE_TYPEjPv"), + ("kJpegAllocMemory", "_jpeg_internal_cgs_alloc_memory"), + ("kJpegReleaseMemory", "_jpeg_internal_cgs_release_memory"), + ("kQueueSubmitFrame", "_queue_jpeg_decode_2_0_submit_frame"), + ("kJpegSubmitFrame", "_jpeg_submit_frame"), +] +# The power request (kext/kern_start.cpp: powerAsk); these are in AMDRadeonX6000, not in HWLibs. +POWER_FUNCS = [ + ("kSendPMCommand", "__ZN37AMDRadeonX6000_AMDGraphicsAccelerator13sendPMCommandEPv"), +] +# The door for apps (kext/kern_start.cpp: wrapVideoPM); also in AMDRadeonX6000. +APPS_FUNCS = [ + ("kVideoSendPM", "__ZN35AMDRadeonX6000_AMDAccelVideoContext13sendPMCommandEPvS0_yPy"), +] +HEAD = 16 + + +def macho_info(path): + """(uuid bytes, __TEXT vmaddr, [(vmaddr, vmsize, fileoff)]) of a thin x86_64 Mach-O.""" + d = open(path, "rb").read() + magic, _, _, _, ncmds, _, _, _ = struct.unpack_from("\n#include \n\nnamespace hwx {\n") + o.append('constexpr const char* kBuild = "%s";' % BUILD) + o.append("// LC_UUID %s" % str(uuid.UUID(bytes=uid)).upper()) + o.append("constexpr uint8_t kUuid[16]{%s};\n" % ", ".join("0x%02x" % b for b in uid)) + o.append("enum Index : size_t {") + for enum, _, _, _ in rows: + o.append(" %s," % enum) + o.append(" kCount\n};\n") + o.append("struct Function {\n const char* symbol;\n size_t offset; // from the image header\n" + " uint8_t head[%d]; // the function's first bytes\n};" % HEAD) + o.append("constexpr Function kFunctions[kCount]{") + for enum, sym, off, head in rows: + o.append(' {"%s",\n 0x%x,\n {%s}},' % (sym, off, ", ".join("0x%02x" % b for b in head))) + o.append("};\n") + _, drows = table(sys.argv[1], DECODE_FUNCS) + o.append("// the decode job") + o.append("enum DecodeIndex : size_t {") + for enum, _, _, _ in drows: + o.append(" %s," % enum) + o.append(" kDecodeCount\n};\n") + o.append("constexpr Function kDecodeFunctions[kDecodeCount]{") + for enum, sym, off, head in drows: + o.append(' {"%s",\n 0x%x,\n {%s}},' % (sym, off, ", ".join("0x%02x" % b for b in head))) + o.append("};\n") + xuid, xrows = table(sys.argv[3], POWER_FUNCS) + o.append("// the power request: AMDRadeonX6000 of the same macOS build") + o.append("// LC_UUID %s" % str(uuid.UUID(bytes=xuid)).upper()) + o.append("constexpr uint8_t kX6000Uuid[16]{%s};\n" % ", ".join("0x%02x" % b for b in xuid)) + o.append("enum PowerIndex : size_t {") + for enum, _, _, _ in xrows: + o.append(" %s," % enum) + o.append(" kPowerCount\n};\n") + o.append("constexpr Function kPowerFunctions[kPowerCount]{") + for enum, sym, off, head in xrows: + o.append(' {"%s",\n 0x%x,\n {%s}},' % (sym, off, ", ".join("0x%02x" % b for b in head))) + o.append("};\n") + _, arows = table(sys.argv[3], APPS_FUNCS) + o.append("// the door for apps: also in AMDRadeonX6000") + o.append("enum AppsIndex : size_t {") + for enum, _, _, _ in arows: + o.append(" %s," % enum) + o.append(" kAppsCount\n};\n") + o.append("constexpr Function kAppsFunctions[kAppsCount]{") + for enum, sym, off, head in arows: + o.append(' {"%s",\n 0x%x,\n {%s}},' % (sym, off, ", ".join("0x%02x" % b for b in head))) + o.append("};\n\n} // namespace hwx") + open(sys.argv[2], "w").write("\n".join(o) + "\n") + print("wrote %s: %d + %d functions, UUID %s" % (sys.argv[2], len(rows), len(drows), str(uuid.UUID(bytes=uid)).upper())) diff --git a/GPU/tests/run.sh b/GPU/tests/run.sh index 80125259..b1dd0182 100755 --- a/GPU/tests/run.sh +++ b/GPU/tests/run.sh @@ -26,6 +26,10 @@ # (on made-up EFI folders), and that it accepts the AMFI functions of this Mac # 5c. the GPU sensors: they build twice to the same bytes, their decisions, and that the # kext accepts the PMLog function of this Mac's driver +# 5d. the JPEG decoder kext: it builds twice to the same bytes, its door and the rule that +# powers the block only while decoding (jpeg/tests/run.sh, with the KDK and Mesa parts +# when they are there), and that this Mac's driver starts each function it uses the way +# its table says # 6. every symbol the kexts import exists in this kernel or in Lilu (tools/kextlinks.sh); # the encoding fix builds and passes its own tests (the wide patch run on the CPU for # each validated build, OpenCore config editing) @@ -69,8 +73,8 @@ fi syntax() { local f - for f in build.sh {decode,encode,sensors}/build.sh decode/loader/build.sh decode/tests/gpu/build.sh tools/*.sh tests/*.sh \ - install/*.sh encode/scripts/*.sh; do + for f in build.sh {decode,encode,sensors,jpeg}/build.sh decode/loader/build.sh decode/tests/gpu/build.sh tools/*.sh tests/*.sh \ + install/*.sh encode/scripts/*.sh jpeg/tests/run.sh; do zsh -n $f || { print "syntax error in $f"; return 1; } done } @@ -137,7 +141,7 @@ jpeg_plugin() { { cat decode/build/tests/plugintest-jpeg.txt; return 1; } decode/build/tests/jpegtest > decode/build/tests/jpegtest.txt || { grep -v ^PASS decode/build/tests/jpegtest.txt; return 1; } } -check "the JPEG plug-in (built only with VCN_JPEG=1): VideoToolbox side, preparer, session against a made-up kext" jpeg_plugin +check "the JPEG plug-in: VideoToolbox side, preparer, session against a made-up kext" jpeg_plugin damaged() {$PD --mutate $rounds tests/media/av1/*.ivf tests/media/vp9/*.ivf > decode/build/tests/damaged.txt; } check "$rounds damaged copies of each stream are survived" damaged @@ -235,9 +239,58 @@ if [[ -f $SKC ]]; then else skip "the sensors kext against this Mac's driver" "no system kernel collection on this machine" fi +step "JPEG decoder kext" +if [[ -f deps/Lilu.kext/Contents/Resources/Library/plugin_start.cpp || -n ${LILU_KEXT:-} ]]; then + jpeg_twice() { + local k=jpeg/build/VCNJpeg.kext/Contents/MacOS/VCNJpeg + jpeg/build.sh tests > /dev/null || return 1 + local first second + first=$(shasum -a 256 < $k) || return 1 + jpeg/build.sh tests > /dev/null || return 1 + second=$(shasum -a 256 < $k) || return 1 + [[ $first == $second ]] || { print "two builds differ"; return 1; } + no_local_paths $k || return 1 + } + check "the JPEG kext builds twice to the same bytes, with no local path inside" jpeg_twice + jpeg_host() { jpeg/tests/run.sh > decode/build/tests/jpeg-host.txt || { cat decode/build/tests/jpeg-host.txt; return 1; }; } + check "the JPEG kext's commands, door and power rule (jpeg/tests/run.sh)" jpeg_host + grep '^skip ' decode/build/tests/jpeg-host.txt 2>/dev/null | while read -r _ why; do skip "part of jpeg/tests/run.sh" "$why"; done + if [[ -f $SKC && $(/usr/bin/sw_vers -buildVersion) == 25G342 ]]; then + # every function of jpeg/kext/hwlibs_expect.hpp starts in this Mac's driver as the table says + jpeg_this_mac() { + /usr/bin/python3 -I - $SKC <<'PY' +import re, subprocess, sys +hpp = open("jpeg/kext/hwlibs_expect.hpp").read() +want = {} +for block, kext in ((hpp.split("kX6000Uuid")[0], "com.apple.kext.AMDRadeonX6000HWLibs"), + (hpp.split("kX6000Uuid")[1], "com.apple.kext.AMDRadeonX6000")): + for sym, head in re.findall(r'\{"(\w+)",\s+0x[0-9a-f]+,\s+\{([^}]*)\}\}', block): + want.setdefault(kext, {})[sym] = bytes(int(x, 16) for x in head.split(",")) +bad = 0 +for kext, syms in want.items(): + out = subprocess.run([sys.executable, "-I", "tools/driver/kcfunc.py", kext, ",".join(syms), "this_mac=" + sys.argv[1]], + capture_output=True, text=True).stdout + got = {f[1]: bytes.fromhex(f[0])[:16] for f in (l.split() for l in out.splitlines()) if len(f) >= 2} + for sym, head in syms.items(): + if got.get(sym) != head: + print("differs or missing in this Mac's driver: %s" % sym) + bad += 1 +print("%d functions checked" % sum(len(s) for s in want.values())) +sys.exit(1 if bad else 0) +PY + } + check "the JPEG kext's functions start in this Mac's driver as its table says" jpeg_this_mac + else + skip "the JPEG kext against this Mac's driver" "not macOS 25G342, or no system kernel collection" + fi +else + print "SKIP: no kext SDK (run tools/bootstrap.sh)" + failed+=("JPEG kext not built") +fi + kext_links() { tools/kextlinks.sh sensors/build/GPUSensors.kext decode/build/VCNVTLoader.kext \ - encode/build/VCNEncodeFloor.kext > decode/build/tests/kextlinks.txt || + encode/build/VCNEncodeFloor.kext jpeg/build/VCNJpeg.kext > decode/build/tests/kextlinks.txt || { cat decode/build/tests/kextlinks.txt; return 1; } } encode_paths() { @@ -249,7 +302,7 @@ step "encoding fix" if [[ -f deps/Lilu.kext/Contents/Resources/Library/plugin_start.cpp || -n ${LILU_KEXT:-} ]]; then check "builds and passes its tests" encode/build.sh check "holds no path of this machine" encode_paths - check "every symbol the three kexts import exists in this kernel or in Lilu" kext_links + check "every symbol the four kexts import exists in this kernel or in Lilu" kext_links else print "SKIP: no kext SDK (run tools/bootstrap.sh)" failed+=("encoding fix not built") diff --git a/GPU/tools/format.sh b/GPU/tools/format.sh index c567c977..653abcc1 100755 --- a/GPU/tools/format.sh +++ b/GPU/tools/format.sh @@ -1,6 +1,7 @@ #!/bin/zsh # format.sh - formats every C, C++ and Objective-C file of the repository with clang-format, -# using .clang-format at the top. The table copied from Mesa keeps its own layout. +# using .clang-format at the top. The table copied from Mesa and the two generated tables +# (jpeg/kext/hwlibs_expect.hpp, decode/tests/jpegsamples.h) keep their own layout. # # tools/format.sh rewrites the files in place # tools/format.sh --check changes nothing; exit status 1 when a file is not formatted @@ -8,7 +9,7 @@ emulate -L zsh setopt err_exit no_unset pipe_fail cd "${0:A:h:h}" files=(${(f)"$(git ls-files -co --exclude-standard -- '*.c' '*.h' '*.cpp' '*.hpp' '*.m' | - grep -v -E '(^|/)ac_vcn_vp9_default\.h$')"}) + grep -v -E '(^|/)(ac_vcn_vp9_default\.h|hwlibs_expect\.hpp|jpegsamples\.h)$')"}) if [[ ${1:-} == --check ]]; then xcrun clang-format --dry-run --Werror $files && print "${#files} files are formatted" else From e4534ad9a359cf73a1c15057ab92d598a5c3aee1 Mon Sep 17 00:00:00 2001 From: DrogaBox Date: Wed, 25 Nov 2026 01:42:16 -0300 Subject: [PATCH 10/35] GPU decode: the JPEG plug-in is always built, and refuses a stuck decoder JPEGVCNDecoder.bundle is no longer behind VCN_JPEG=1; it goes to the VCNJpeg kext (jpeg/). At session start it refuses, so that VideoToolbox picks Apple's software decoder, when the kext's decoder is stuck or has no queue or buffers (the INFO state bits, now JA_STATE_* in jpeg_app.h), and when the session's size does not fit the kext's picture buffer (vcnjpeg_fits). vtjpegtest -system decodes through whatever hardware decoder VideoToolbox picks, the installed plug-in, without asking for our DecoderID. Formatting of decode/jpeg and its tests with tools/format.sh. --- GPU/decode/build.sh | 10 +- GPU/decode/jpeg/JPEGVCNDecoder.c | 24 ++- GPU/decode/jpeg/jpeg_app.h | 68 ++++---- GPU/decode/jpeg/jpeg_app_client.h | 91 +++++++---- GPU/decode/jpeg/jpegprep.c | 51 +++--- GPU/decode/jpeg/jpegprep.h | 8 +- GPU/decode/jpeg/jpegstd.h | 70 +++++---- GPU/decode/jpeg/vcnjpeg.c | 153 ++++++++++++------ GPU/decode/jpeg/vcnjpeg.h | 31 ++-- GPU/decode/loader/build.sh | 4 +- GPU/decode/tests/gpu/README.md | 19 +++ GPU/decode/tests/gpu/build.sh | 3 +- GPU/decode/tests/gpu/mkmjpeg422.c | 124 +++++++++------ GPU/decode/tests/gpu/vtjpegtest.c | 175 ++++++++++++++------- GPU/decode/tests/jpegtest.c | 251 +++++++++++++++++++++--------- GPU/decode/tests/plugintest.c | 15 +- 16 files changed, 732 insertions(+), 365 deletions(-) diff --git a/GPU/decode/build.sh b/GPU/decode/build.sh index 8061ccd7..0bb0e2d0 100755 --- a/GPU/decode/build.sh +++ b/GPU/decode/build.sh @@ -4,8 +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, only with VCN_JPEG=1 (off by default: -# it needs the apps build of the VCNJpegProbe kext, and nothing installs it) +# 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 @@ -59,11 +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 -if [[ ${VCN_JPEG:-0} == 1 ]]; then - build_bundle JPEGVCNDecoder jpeg jpeg/JPEGVCNDecoder.c jpeg/vcnjpeg.c jpeg/jpegprep.c -else - rm -rf $B/JPEGVCNDecoder.bundle -fi +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. diff --git a/GPU/decode/jpeg/JPEGVCNDecoder.c b/GPU/decode/jpeg/JPEGVCNDecoder.c index 1740cdb6..4fe14f84 100644 --- a/GPU/decode/jpeg/JPEGVCNDecoder.c +++ b/GPU/decode/jpeg/JPEGVCNDecoder.c @@ -5,9 +5,8 @@ // with -DTEST_JPEG); see vtav1/AV1VCNDecoder.c for where the private plugin // interface comes from. // -// Not built by default: ./build.sh builds it only with VCN_JPEG=1, and no -// installer puts it anywhere. It needs the apps build of the VCNJpegProbe kext, -// which nothing installs either. +// 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 @@ -358,7 +357,8 @@ static OSStatus start_session(State* s, VTVideoDecoderSession session, // 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) + if (codec != kCMVideoCodecType_JPEG && + codec != kCMVideoCodecType_JPEG_OpenDML) return kVTVideoDecoderUnsupportedDataFormatErr; char err[256] = ""; @@ -368,6 +368,14 @@ static OSStatus start_session(State* s, VTVideoDecoderSession session, 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 = @@ -709,11 +717,13 @@ static const VTVideoDecoderClass kDecoderClass = { static const VTVideoDecoderVTable kVTable = {NULL, &kBaseClass, &kDecoderClass}; -__attribute__((visibility("default"))) OSStatus JPEGVCN_VTDecoder_CreateInstance( - FourCharCode codec, CFAllocatorRef alloc, VTVideoDecoderRef* out) { +__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) + if (codec != kCMVideoCodecType_JPEG && + codec != kCMVideoCodecType_JPEG_OpenDML) return kVTCouldNotFindVideoDecoderErr; CMBaseObjectRef obj = NULL; OSStatus r = diff --git a/GPU/decode/jpeg/jpeg_app.h b/GPU/decode/jpeg/jpeg_app.h index bea75fb7..363b7875 100644 --- a/GPU/decode/jpeg/jpeg_app.h +++ b/GPU/decode/jpeg/jpeg_app.h @@ -1,6 +1,6 @@ /* - * jpeg_app.h - how a program asks the "apps" build of VCNJpegProbe to decode a - * JPEG without a user client of its own: through the AMD accelerator's video + * 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 @@ -28,32 +28,47 @@ #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_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 (jp::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 */ + 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_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 */ + 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 { @@ -67,8 +82,8 @@ struct ja_request { }; struct ja_reply { - uint32_t magic; /* JA_REPLY_MAGIC */ - uint32_t status; /* JA_OK ... */ + 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]; @@ -78,12 +93,13 @@ struct ja_reply { /* 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 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) */ + 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)) diff --git a/GPU/decode/jpeg/jpeg_app_client.h b/GPU/decode/jpeg/jpeg_app_client.h index 5fa57dc0..95059855 100644 --- a/GPU/decode/jpeg/jpeg_app_client.h +++ b/GPU/decode/jpeg/jpeg_app_client.h @@ -1,7 +1,7 @@ /* * jpeg_app_client.h - the caller's side of jpeg_app.h: one picture through the - * apps build of VCNJpegProbe. Plain C, header only; jpegprobe and the - * VideoToolbox plug-in use it (the plug-in keeps a copy of this file). + * 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. @@ -15,14 +15,18 @@ #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); +/* 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) { +/* 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; @@ -32,25 +36,33 @@ static inline int ja_call(ja_transport t, void* ctx, uint32_t op, uint64_t a0, u 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); + 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; } +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 +/* 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) { +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); + 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); @@ -60,7 +72,9 @@ static inline int ja_decode(ja_transport t, void* ctx, const uint8_t* jpeg, size 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_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; @@ -70,8 +84,10 @@ static inline int ja_decode(ja_transport t, void* ctx, const uint8_t* jpeg, size 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) { +/* 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; @@ -85,24 +101,30 @@ static inline int ja_info(ja_transport t, void* ctx, uint64_t* state, uint64_t* #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. */ +/* 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 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. */ +/* 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")); + 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); @@ -136,7 +158,9 @@ static inline io_connect_t ja_iokit_open_why(kern_return_t* why, int* step) { 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); } +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) { @@ -153,7 +177,8 @@ static inline void ja_iokit_close(io_connect_t 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) { +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); } diff --git a/GPU/decode/jpeg/jpegprep.c b/GPU/decode/jpeg/jpegprep.c index 7ae97ebc..ea635c5a 100644 --- a/GPU/decode/jpeg/jpegprep.c +++ b/GPU/decode/jpeg/jpegprep.c @@ -1,9 +1,9 @@ -// jpegprep.c - see jpegprep.h. The same rewrite as VCNJpegProbe's -// tools/jpeg_normalize.hpp (the tool the first GPU tests use). 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. +// 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 @@ -87,7 +87,8 @@ int jpeg_prepare(const uint8_t* d, size_t n, uint8_t** out, size_t* outLen, 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"); + 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; @@ -117,7 +118,8 @@ int jpeg_prepare(const uint8_t* d, size_t n, uint8_t** out, size_t* outLen, 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"); + if (t.sof) + return fail(why, whyLen, JPEG_BAD, "more than one frame header"); t.sof = s; t.sofLen = body; } else if (m == 0xda) { @@ -126,53 +128,60 @@ int jpeg_prepare(const uint8_t* d, size_t n, uint8_t** out, size_t* outLen, 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) { + } 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"); + 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"); + 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 (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"); // 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]; + 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"); + 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"); + return fail(why, whyLen, JPEG_UNSUPPORTED, + "a scan without all three components"); // 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)) + 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++; - if (d[f + 1] != 0xd9) return fail(why, whyLen, JPEG_UNSUPPORTED, "more than one 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; @@ -180,7 +189,8 @@ int jpeg_prepare(const uint8_t* d, size_t n, uint8_t** out, size_t* outLen, 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"); + 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; @@ -198,7 +208,8 @@ int jpeg_prepare(const uint8_t* d, size_t n, uint8_t** out, size_t* outLen, nh += t.hLen[c][k]; } } - size_t cap = 2 + (4 + nq) + (4 + nh) + 6 + (4 + t.sofLen) + (4 + t.sosLen) + t.scanLen + 2; + 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; diff --git a/GPU/decode/jpeg/jpegprep.h b/GPU/decode/jpeg/jpegprep.h index 7e481d74..733f1e56 100644 --- a/GPU/decode/jpeg/jpegprep.h +++ b/GPU/decode/jpeg/jpegprep.h @@ -6,7 +6,7 @@ // 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 (VCNJpegProbe jc::parseStream): baseline, 8 bits, three components, +// 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 @@ -27,9 +27,9 @@ enum { 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) + 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. diff --git a/GPU/decode/jpeg/jpegstd.h b/GPU/decode/jpeg/jpegstd.h index 8b482bcc..7cad5013 100644 --- a/GPU/decode/jpeg/jpegstd.h +++ b/GPU/decode/jpeg/jpegstd.h @@ -1,35 +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. +// 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, + 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 index edf46e74..b2b4b0a1 100644 --- a/GPU/decode/jpeg/vcnjpeg.c +++ b/GPU/decode/jpeg/vcnjpeg.c @@ -23,7 +23,8 @@ static void* iokit_open(void) { } static void iokit_close(void* ctx) { if (!ctx) return; - ja_iokit_close(*(io_connect_t*)ctx); // the video context and its shared client + ja_iokit_close( + *(io_connect_t*)ctx); // the video context and its shared client free(ctx); } ja_transport vcnjpeg_transport = ja_iokit_call; @@ -37,7 +38,9 @@ enum { kBusyWaitMs = 1000 }; struct VcnJpeg { void* conn; uint32_t maxW, maxH; - uint8_t* surface; // what the kext copies the picture into (its layout, see ja_picture) + 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; @@ -56,10 +59,12 @@ static bool put_num(CFMutableDictionaryRef d, CFStringRef k, int32_t v) { // 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); + 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); @@ -69,11 +74,13 @@ static CFDictionaryRef attributes(uint32_t w, uint32_t h, OSType format) { if (format) { ok = put_num(a, kCVPixelBufferPixelFormatTypeKey, (int32_t)format); } else { - int32_t f[2] = {kCVPixelFormatType_420YpCbCr8BiPlanarFullRange, kCVPixelFormatType_422YpCbCr8BiPlanarFullRange}; + 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; + CFArrayRef arr = + n0 && n1 ? CFArrayCreate(NULL, v, 2, &kCFTypeArrayCallBacks) : NULL; if (n0) CFRelease(n0); if (n1) CFRelease(n1); ok = arr != NULL; @@ -94,11 +101,18 @@ static CFDictionaryRef attributes(uint32_t w, uint32_t h, OSType format) { return a; } -CFDictionaryRef vcnjpeg_copy_pixel_buffer_attributes(uint32_t w, uint32_t h, bool ten) { +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) @@ -108,7 +122,8 @@ static int failed(VcnJpeg* d, int failure, const char* what, int status) { return -1; } -VcnJpeg* vcnjpeg_create(uint32_t maxWidth, uint32_t maxHeight, char* err, size_t errLen) { +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; @@ -129,13 +144,29 @@ VcnJpeg* vcnjpeg_create(uint32_t maxWidth, uint32_t maxHeight, char* err, size_t 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 apps build of VCNJpegProbe is not loaded" - : "the JPEG decoder is not ready (status %d)", s); + // -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; } @@ -143,7 +174,8 @@ 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); + 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); @@ -151,7 +183,8 @@ void vcnjpeg_destroy(VcnJpeg* d) { free(d); } -static CVPixelBufferRef new_target(VcnJpeg* d, uint32_t w, uint32_t h, OSType format) { +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; @@ -174,9 +207,9 @@ static CVPixelBufferRef new_target(VcnJpeg* d, uint32_t w, uint32_t h, OSType fo return pb; } -// The kext's surface layout for a picture (VCNJpegProbe 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 +// 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; @@ -185,18 +218,24 @@ static size_t surface_bytes(uint32_t w, uint32_t h, bool yuyv) { 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) { +// 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 (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; + 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 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++) { @@ -217,21 +256,28 @@ static bool copy_yuyv(const uint8_t* src, const struct ja_picture* pic, CVPixelB // 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) { +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) + 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 && + 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); + 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); } @@ -239,8 +285,8 @@ static bool copy_planes(const uint8_t* src, const struct ja_picture* pic, CVPixe return ok; } -int vcnjpeg_decode(VcnJpeg* d, const uint8_t* sample, size_t size, int64_t tag, VcnJpegOutputFn fn, - void* ctx) { +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; @@ -252,7 +298,8 @@ int vcnjpeg_decode(VcnJpeg* d, const uint8_t* sample, size_t size, int64_t tag, 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); + return failed(d, VCNJPEG_FAIL_STREAM, + "picture larger than the session allows", 0); } size_t need = surface_bytes(info.width, info.height, info.yuyv); if (need > d->surfaceCap) { @@ -266,25 +313,35 @@ int vcnjpeg_decode(VcnJpeg* d, const uint8_t* sample, size_t size, int64_t tag, } 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); + 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 (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))) { + 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); + 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, + CVBufferSetAttachment(pb, kCVImageBufferYCbCrMatrixKey, + kCVImageBufferYCbCrMatrix_ITU_R_601_4, kCVAttachmentMode_ShouldPropagate); fn(ctx, pb, NULL, info.width, info.height, tag); CVPixelBufferRelease(pb); diff --git a/GPU/decode/jpeg/vcnjpeg.h b/GPU/decode/jpeg/vcnjpeg.h index fe19f822..1fd5ab17 100644 --- a/GPU/decode/jpeg/vcnjpeg.h +++ b/GPU/decode/jpeg/vcnjpeg.h @@ -1,5 +1,5 @@ // vcnjpeg: one JPEG picture at a time on the JPEG block of the AMD VCN, through -// the apps build of the VCNJpegProbe kext. The kext owns the block, its queue +// 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. @@ -15,8 +15,9 @@ #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); +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; @@ -27,24 +28,34 @@ 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); +// 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); -VcnJpeg* vcnjpeg_create(uint32_t maxWidth, uint32_t maxHeight, char* err, size_t errLen); +// 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_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. +// 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/tests/gpu/README.md b/GPU/decode/tests/gpu/README.md index de6dfa7f..8d1b5f50 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 | @@ -146,6 +148,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 diff --git a/GPU/decode/tests/gpu/build.sh b/GPU/decode/tests/gpu/build.sh index d31c3843..2ef93de2 100755 --- a/GPU/decode/tests/gpu/build.sh +++ b/GPU/decode/tests/gpu/build.sh @@ -12,7 +12,8 @@ # 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, compared with FFmpeg (no switch) +# 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) diff --git a/GPU/decode/tests/gpu/mkmjpeg422.c b/GPU/decode/tests/gpu/mkmjpeg422.c index 8cce9302..4c1679f3 100644 --- a/GPU/decode/tests/gpu/mkmjpeg422.c +++ b/GPU/decode/tests/gpu/mkmjpeg422.c @@ -15,45 +15,62 @@ #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}; +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 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 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 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}; + 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}; + 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]; @@ -122,7 +139,9 @@ static void fdct(const uint8_t* src, int stride, double out[64]) { 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); + 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]; @@ -140,12 +159,13 @@ static void fdct(const uint8_t* src, int stride, double out[64]) { } } -static void block(Out* o, const uint8_t* src, int stride, const uint8_t q[64], int* dcPred, const Huff* dc, - const Huff* ac) { +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]]); + 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); @@ -170,7 +190,8 @@ static void block(Out* o, const uint8_t* src, int stride, const uint8_t q[64], i 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) { +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)); @@ -180,18 +201,24 @@ static void dht(Out* o, int cls, int id, const uint8_t b[16], const uint8_t* v) int main(int argc, char** argv) { if (argc != 5 && argc != 6) { - fprintf(stderr, "usage: mkmjpeg422 in.yuv(yuvj422p) width height out.mjpeg [quality]\n"); + 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"); + 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; + 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); } @@ -246,8 +273,10 @@ int main(int argc, char** argv) { 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); + 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); @@ -258,6 +287,7 @@ int main(int argc, char** argv) { 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); + 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/vtjpegtest.c b/GPU/decode/tests/gpu/vtjpegtest.c index 3ce450a7..0a3f7ac9 100644 --- a/GPU/decode/tests/gpu/vtjpegtest.c +++ b/GPU/decode/tests/gpu/vtjpegtest.c @@ -3,6 +3,11 @@ // // 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 @@ -24,8 +29,8 @@ // 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 apps build -// of VCNJpegProbe is loaded and its JPEG queue is started. +// 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. @@ -45,26 +50,34 @@ static double now_ms(void) { 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); } +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); +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); + 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; + 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; @@ -72,9 +85,11 @@ static int load_bundle(const char* path, FourCharCode codec, const char* fourcc) 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("CMClassImplementationID"), + CFSTR("com.droga.vtjpegtest")); CFDictionarySetValue(info, CFSTR("IsHardwareAccelerated"), kCFBooleanTrue); - CFStringRef name = CFDictionaryGetValue(impl, CFSTR("CMClassImplementationName")); + CFStringRef name = + CFDictionaryGetValue(impl, CFSTR("CMClassImplementationName")); if (name) CFDictionarySetValue(info, CFSTR("CodecName"), name); OSStatus st = reg(codec, info, factory); CFRelease(info); @@ -107,7 +122,8 @@ static uint8_t* read_all(const char* path, size_t* n) { // 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) { +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; @@ -126,7 +142,8 @@ static bool next_picture(const uint8_t* d, size_t n, size_t* at, size_t* start, 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] == 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; @@ -149,8 +166,9 @@ typedef struct { double firstOut; } Ctx; -static void out_cb(void* refcon, void* frameRefcon, OSStatus st, VTDecodeInfoFlags flags, CVImageBufferRef img, - CMTime pts, CMTime dur) { +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; @@ -163,8 +181,9 @@ static void out_cb(void* refcon, void* frameRefcon, OSStatus st, VTDecodeInfoFla 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); + 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) { @@ -179,8 +198,10 @@ static void out_cb(void* refcon, void* frameRefcon, OSStatus st, VTDecodeInfoFla 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 && + 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) { @@ -194,7 +215,8 @@ static void out_cb(void* refcon, void* frameRefcon, OSStatus st, VTDecodeInfoFla 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 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; @@ -204,8 +226,8 @@ static void out_cb(void* refcon, void* frameRefcon, OSStatus st, VTDecodeInfoFla 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); + 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; @@ -217,15 +239,19 @@ static void out_cb(void* refcon, void* frameRefcon, OSStatus st, VTDecodeInfoFla static int usage(void) { fprintf(stderr, - "usage: vtjpegtest -load bundle clip.mjpeg reference.yuv width height 420|422 [-dmb1] [-frames N]\n" - " vtjpegtest -apple clip.mjpeg reference.yuv width height 420|422 [-dmb1] (CPU only)\n" + "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; + bool apple = false, system = false; const char* pos[5]; int npos = 0, maxFrames = INT_MAX; bool dmb1 = false; @@ -234,6 +260,8 @@ int main(int argc, char** argv) { 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) @@ -243,18 +271,23 @@ int main(int argc, char** argv) { else return usage(); } - if (!!bundle == apple || npos != 5 || maxFrames < 1) 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; + 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 (!apple && load_bundle(bundle, codec, fourcc)) return 1; + 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; + 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; @@ -262,32 +295,54 @@ int main(int argc, char** argv) { 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; + 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); + CFDictionaryCreateMutable(NULL, 0, &kCFTypeDictionaryKeyCallBacks, + &kCFTypeDictionaryValueCallBacks); CFMutableDictionaryRef dest = NULL; - if (!apple) { - CFDictionarySetValue(spec, kVTVideoDecoderSpecification_RequireHardwareAcceleratedVideoDecoder, kCFBooleanTrue); - CFStringRef id = CFStringCreateWithFormat(NULL, NULL, CFSTR("com.droga.vtjpegtest.%s"), fourcc); + 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); + 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); + 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"); + 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 + if (dest && + getenv("VTJPEG_NODEST")) { // debugging: Apple's own output format CFRelease(dest); dest = NULL; } @@ -297,8 +352,11 @@ int main(int argc, char** argv) { 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"); + 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; @@ -307,10 +365,13 @@ int main(int argc, char** argv) { 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}; + 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) + st = CMSampleBufferCreateReady(NULL, bb, fmt, 1, 1, &ti, 1, &ss, &sb); if (!st) { VTDecodeInfoFlags info = 0; st = VTDecompressionSessionDecodeFrame(sess, sb, 0, (void*)fed, &info); @@ -326,15 +387,23 @@ int main(int argc, char** argv) { 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"); + 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/jpegtest.c b/GPU/decode/tests/jpegtest.c index 457227f2..095eb4aa 100644 --- a/GPU/decode/tests/jpegtest.c +++ b/GPU/decode/tests/jpegtest.c @@ -6,7 +6,8 @@ // 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 +// 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 @@ -44,7 +45,8 @@ static uint8_t* rgba(const uint8_t* d, size_t n, size_t* w, size_t* h) { *h = CGImageGetHeight(img); px = calloc(*w * *h, 4); CGColorSpaceRef cs = CGColorSpaceCreateWithName(kCGColorSpaceSRGB); - CGContextRef ctx = CGBitmapContextCreate(px, *w, *h, 8, *w * 4, cs, kCGImageAlphaPremultipliedLast); + CGContextRef ctx = CGBitmapContextCreate(px, *w, *h, 8, *w * 4, cs, + kCGImageAlphaPremultipliedLast); CGContextDrawImage(ctx, CGRectMake(0, 0, *w, *h), img); CGContextRelease(ctx); CGColorSpaceRelease(cs); @@ -55,7 +57,8 @@ static uint8_t* rgba(const uint8_t* d, size_t n, size_t* w, size_t* h) { return px; } -static bool same_picture(const uint8_t* a, size_t an, const uint8_t* b, size_t bn) { +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); @@ -76,7 +79,8 @@ static void shape(const uint8_t* d, size_t n, char* out, size_t cap) { i += 2 + len; if (m == 0xda) break; } - if (n >= 2 && d[n - 2] == 0xff && d[n - 1] == 0xd9) snprintf(out + p, cap - p, " d9"); + 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). @@ -99,21 +103,27 @@ static uint8_t* without(const uint8_t* d, size_t n, uint8_t m, size_t* outN) { return o; } -// ---- a made-up kext behind the transport --------------------------------------------- +// ---- 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 + 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 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) { +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; @@ -125,8 +135,9 @@ static int fake_call(void* ctx, const void* in, size_t inSize, void* out, size_t 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] = 1u << 24; + rp.v[2] = K.infoRoom; break; case JA_OP_LOAD_USER: { if (K.busy) { @@ -142,9 +153,11 @@ static int fake_call(void* ctx, const void* in, size_t inSize, void* out, size_t 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)) { + // 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; @@ -153,8 +166,9 @@ static int fake_call(void* ctx, const void* in, size_t inSize, void* out, size_t 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.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; @@ -163,8 +177,14 @@ static int fake_call(void* ctx, const void* in, size_t inSize, void* out, size_t 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}; + 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; @@ -202,7 +222,8 @@ static void fake_close(void* ctx) { 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) { +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); @@ -210,31 +231,43 @@ static void on_picture(void* ctx, CVPixelBufferRef pb, const void* unused, uint3 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; +// 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; + 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); + 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; + 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); + 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); + 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++) @@ -260,7 +293,8 @@ int main(void) { 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)); + 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; @@ -269,16 +303,24 @@ int main(void) { 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; + 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); + 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( + "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 ---- @@ -288,19 +330,22 @@ int main(void) { 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)); + 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}; + 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; @@ -312,13 +357,17 @@ int main(void) { // ---- 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); + 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}}; + 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)); @@ -331,12 +380,16 @@ int main(void) { 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); + 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); + expect( + "sampling 211111 and 222121 are YUYV too; 4:4:4 and 4:4:0 are refused", + all); } bool prefixes = true; for (size_t n = 0; n < sizeof(kJpeg48x32) - 1; n++) { @@ -357,9 +410,11 @@ int main(void) { 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 + 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)); + 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); @@ -370,7 +425,8 @@ int main(void) { free(o); free(copy); } - printf(" (%u of 40000 damaged copies still had the shape of a JPEG)\n", accepted); + 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 ---- @@ -379,69 +435,120 @@ int main(void) { 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); + 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")); + 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); + 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); + 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)); 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; + 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)); + 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; + 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); + 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); + 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) && + 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) && + 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; + 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); + 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); + 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/plugintest.c b/GPU/decode/tests/plugintest.c index f55b70df..f1f667fe 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_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: +// 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; @@ -376,6 +377,10 @@ VcnJpeg* vcnjpeg_create(uint32_t w, uint32_t h, char* err, size_t 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"; @@ -385,12 +390,12 @@ unsigned vcnjpeg_firmware_errors(VcnJpeg* d) { return 0; } CFDictionaryRef vcnjpeg_copy_pixel_buffer_attributes(uint32_t w, uint32_t h, - bool t) { + 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) { + VcnJpegOutputFn fn, void* ctx) { (void)size; fake_decode_begin(d); if (chunk[0] == 5) slow_decode(); From ca15847b57c1d56c76e64223f4d3b7cadea74ca0 Mon Sep 17 00:00:00 2001 From: DrogaBox Date: Wed, 25 Nov 2026 01:42:25 -0300 Subject: [PATCH 11/35] GPU install: the JPEG decoder behind --jpeg and --with-jpeg install/jpeg.sh puts VCNJpeg.kext on the EFI or takes it off (efikext.zsh, like sensors.sh) and checks the macOS build against the new "jpeg" column of validated-builds.json (25G342: untested-on-gpu; check_lists.sh allows a value other than false only for the build of jpeg/kext/hwlibs_expect.hpp). decoders.sh --jpeg (VCNVT_JPEG_DECODER=1) adds the JPEG plug-in, and an install without it takes off one an earlier install left; install.sh --with-jpeg does both. check.sh shows the JPEG kext where it is built or runs; undo.sh takes it off; kextentry knows VCNJpeg (MinKernel 25.0.0). The loader kext lists the JPEG plug-in like the other five. The package carries the plug-in and the kext only with VCNVT_JPEG_DECODER=1 (tools/package.sh, Tools/build-gpu-assets.sh). Docs: jpeg/README.md, install/README.md, macos-updates.md, testing.md, CHANGELOG. --- GPU/CHANGELOG.md | 17 ++ GPU/README.md | 3 + GPU/docs/macos-updates.md | 15 ++ GPU/docs/testing.md | 4 + GPU/install/README.md | 10 +- GPU/install/check.sh | 17 +- GPU/install/check_lists.sh | 15 +- GPU/install/common.zsh | 5 + GPU/install/decoders.sh | 77 ++++++- GPU/install/install.sh | 21 +- GPU/install/jpeg.sh | 287 ++++++++++++++++++++++++ GPU/install/kextentry.c | 25 ++- GPU/install/loader.sh | 13 +- GPU/install/undo.sh | 8 +- GPU/install/validated-builds.json | 8 +- GPU/tests/loader_install.sh | 17 +- GPU/tools/package.sh | 11 + Tests/Suites/GPUInstallerDMGTests.swift | 2 +- Tools/build-gpu-assets.sh | 12 +- 19 files changed, 527 insertions(+), 40 deletions(-) create mode 100755 GPU/install/jpeg.sh diff --git a/GPU/CHANGELOG.md b/GPU/CHANGELOG.md index 24a1cfcd..450904ad 100644 --- a/GPU/CHANGELOG.md +++ b/GPU/CHANGELOG.md @@ -2,6 +2,23 @@ The encoding fix keeps its own history in `encode/CHANGELOG.md`. +## JPEG decoder 1.0.0 (not released; host tests only, not booted) + +- 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 itself has not run yet. + ## 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..bfa82125 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 @@ -38,6 +39,7 @@ Inc. | 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) | +| JPEG decoder kext (`jpeg/`) | 1.0.0 | not run yet; the test kext it comes from decoded through the same plug-in on RX 6800 XT (Tahoe 26.7.3) | 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/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/testing.md b/GPU/docs/testing.md index 7ffb7ada..295a422f 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 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--