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/build.sh b/GPU/build.sh index e3e971cc..adbf35a3 100755 --- a/GPU/build.sh +++ b/GPU/build.sh @@ -1,18 +1,20 @@ #!/bin/zsh # build.sh - builds every part of the repository. Installs nothing. # -# ./build.sh the decoders, their loader kext, the GPU sensors and the encoding fix +# ./build.sh the decoders, their loader kext, the GPU sensors, the encoding fix and +# the JPEG decoder kext # ./build.sh decode only the decoders # ./build.sh loader only the loader kext (needs tools/bootstrap.sh once) # ./build.sh sensors only the GPU sensors (the kext needs tools/bootstrap.sh once) # ./build.sh encode only the encoding fix (needs tools/bootstrap.sh once) +# ./build.sh jpeg only the JPEG decoder kext (needs tools/bootstrap.sh once) emulate -L zsh setopt err_exit no_unset pipe_fail cd "${0:A:h}" what=${1:-all} case $what in - all|decode|loader|sensors|encode) ;; - *) print "usage: ./build.sh [decode|loader|sensors|encode]"; exit 2 ;; + all|decode|loader|sensors|encode|jpeg) ;; + *) print "usage: ./build.sh [decode|loader|sensors|encode|jpeg]"; exit 2 ;; esac if [[ $what == (all|decode) ]]; then print "== decoders" @@ -30,3 +32,7 @@ if [[ $what == (all|encode) ]]; then print "== encoding fix" encode/build.sh fi +if [[ $what == (all|jpeg) ]]; then + print "== JPEG decoder kext" + jpeg/build.sh +fi diff --git a/GPU/decode/build.sh b/GPU/decode/build.sh index 5812415c..55d38dc6 100755 --- a/GPU/decode/build.sh +++ b/GPU/decode/build.sh @@ -4,6 +4,8 @@ # VP9VCNDecoder.bundle vp09 on the same block # MPEG2VCNDecoder.bundle mp2v, VC1VCNDecoder.bundle vc-1/WVC1/WMV3 and # MPEG4VCNDecoder.bundle mp4v on the same block (common/vcnlegacy.c) +# JPEGVCNDecoder.bundle jpeg and dmb1 on the JPEG block of the VCN, through the VCNJpeg kext +# (jpeg/); installed only on request (install/decoders.sh --jpeg) # lvprobe the installer's helper that asks macOS whether it would accept them # kextentry the installers' helper that edits OpenCore's config.plist for the # loader kext and the sensors kext @@ -57,6 +59,7 @@ LEGACY=(common/vcnlegacy.c common/vcndriver.c common/vcnsession.c) build_bundle MPEG2VCNDecoder mpeg2 mpeg2/MPEG2VCNDecoder.c mpeg2/vcnmpeg2.c mpeg2/mpeg2parse.c $LEGACY build_bundle VC1VCNDecoder vc1 vc1/VC1VCNDecoder.c vc1/vcnvc1.c vc1/vc1parse.c $LEGACY build_bundle MPEG4VCNDecoder mpeg4 mpeg4/MPEG4VCNDecoder.c mpeg4/vcnmpeg4.c mpeg4/mpeg4parse.c $LEGACY +build_bundle JPEGVCNDecoder jpeg jpeg/JPEGVCNDecoder.c jpeg/vcnjpeg.c jpeg/jpegprep.c # lvprobe (install/lvprobe.c) asks macOS whether it would accept a plug-in; the installer # runs it. It must carry the library-validation flag, or the kernel says yes to everything. @@ -84,8 +87,8 @@ if [[ ${1:-} == tests ]]; then xcrun clang $TFLAGS -Iav1 -Ivp9 -Icommon tests/colortest.c av1/av1parse.c vp9/vp9parse.c \ -framework CoreFoundation -framework CoreMedia -framework CoreVideo -o $T/colortest xcrun clang $TFLAGS -Ivp9 tests/vp9state.c vp9/vp9parse.c -o $T/vp9state - for c in AV1 VP9; do - xcrun clang $TFLAGS -DTEST_$c -Icommon tests/plugintest.c -framework CoreFoundation -framework CoreMedia \ + for c in AV1 VP9 JPEG; do + xcrun clang $TFLAGS -DTEST_$c -Icommon -Ijpeg tests/plugintest.c -framework CoreFoundation -framework CoreMedia \ -framework CoreVideo -framework VideoToolbox -o $T/plugintest-${(L)c} done for c in MPEG2 VC1 MPEG4; do @@ -117,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..4fe14f84 --- /dev/null +++ b/GPU/decode/jpeg/JPEGVCNDecoder.c @@ -0,0 +1,759 @@ +// VideoToolbox decoder plugin for 'jpeg' (Photo JPEG / Motion JPEG A) and +// 'dmb1' (Open DML Motion JPEG) on the JPEG block of the AMD VCN (macOS +// x86_64), built on vcnjpeg. It is VP9VCNDecoder.c with the VP9 parts taken +// out: the same ABI, the same threading and the same tests (tests/plugintest.c +// with -DTEST_JPEG); see vtav1/AV1VCNDecoder.c for where the private plugin +// interface comes from. +// +// It needs the VCNJpeg kext (GPU/jpeg). Both are installed only on request +// (install/decoders.sh --jpeg, install/jpeg.sh; install.sh --with-jpeg). +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "vcnjpeg.h" + +// ---- private CoreMedia / VideoToolbox plugin SPI +// ------------------------------------------- +typedef const void* CMBaseClassID; +typedef struct OpaqueCMBaseObject* CMBaseObjectRef; +typedef struct OpaqueVTVideoDecoder* VTVideoDecoderRef; +typedef struct OpaqueVTVideoDecoderSession* VTVideoDecoderSession; +typedef struct OpaqueVTVideoDecoderFrame* VTVideoDecoderFrame; + +#pragma pack(push, 4) +typedef struct { + uint32_t version; + size_t derivedStorageSize; + Boolean (*equal)(CMBaseObjectRef, CMBaseObjectRef); + OSStatus (*invalidate)(CMBaseObjectRef); + void (*finalize)(CMBaseObjectRef); + CFStringRef (*copyDebugDescription)(CMBaseObjectRef); + OSStatus (*copyProperty)(CMBaseObjectRef, CFStringRef, CFAllocatorRef, void*); + OSStatus (*setProperty)(CMBaseObjectRef, CFStringRef, CFTypeRef); + OSStatus (*notificationBarrier)(CMBaseObjectRef); + const void* propertyHandlers; +} CMBaseClass; + +typedef struct { + uint32_t version; + OSStatus (*startSession)(VTVideoDecoderRef, VTVideoDecoderSession, + CMVideoFormatDescriptionRef); + OSStatus (*decodeFrame)(VTVideoDecoderRef, VTVideoDecoderFrame, + CMSampleBufferRef, VTDecodeFrameFlags, + VTDecodeInfoFlags*); + OSStatus (*copySupportedPropertyDictionary)(VTVideoDecoderRef, + CFDictionaryRef*); + OSStatus (*setProperties)(VTVideoDecoderRef, CFDictionaryRef); + OSStatus (*copySerializableProperties)(VTVideoDecoderRef, CFAllocatorRef, + CFDictionaryRef*); + Boolean (*canAcceptFormatDescription)(VTVideoDecoderRef, + CMFormatDescriptionRef); + OSStatus (*finishDelayedFrames)(VTVideoDecoderRef); + void* reserved[6]; +} VTVideoDecoderClass; +#pragma pack(pop) + +typedef struct { + void* reserved; + const CMBaseClass* baseClass; + const VTVideoDecoderClass* decoderClass; +} VTVideoDecoderVTable; + +extern OSStatus CMDerivedObjectCreate(CFAllocatorRef, const void* vtable, + CMBaseClassID, CMBaseObjectRef*); +extern void* CMBaseObjectGetDerivedStorage(CMBaseObjectRef); +extern CMBaseClassID VTVideoDecoderGetClassID(void); +extern CMBaseObjectRef VTVideoDecoderGetCMBaseObject(VTVideoDecoderRef); +extern OSStatus VTDecoderSessionSetPixelBufferAttributes(VTVideoDecoderSession, + CFDictionaryRef); +extern OSStatus VTDecoderSessionEmitDecodedFrame(VTVideoDecoderSession, + VTVideoDecoderFrame, OSStatus, + VTDecodeInfoFlags, + CVImageBufferRef); + +// ---- decoder instance +// ---------------------------------------------------------------------- +// What the decode queue and the calls still inside the plug-in use. It lives +// apart from the CoreMedia storage, which CoreMedia frees as soon as finalize +// returns, and it is counted: the storage holds one reference, each queued +// frame one and each call in the plug-in one, and the last to let go frees +// it. finalize can run on the decode queue (a host that lets go of its session +// from inside its output callback), where it may wait for nothing: the frames +// still queued and a call waiting for the queue then find the state alive, +// closed, and emit nothing. +typedef struct { + VTVideoDecoderSession session; + VcnJpeg* vcn; + int32_t width, height; + bool tenBit; // never: kept so the code stays the one of the VP9 plug-in + // Set by invalidate once the queue is drained, and by finalize: nothing is + // emitted any more. + bool invalidated; + CVPixelBufferRef + lastFrame; // retained shown frame of the chunk being decoded + pthread_mutex_t lock; + // What canAcceptFormatDescription reads, under meta. A decode holds lock + // for as long as the GPU takes; meta is never held across a driver call. + pthread_mutex_t meta; + CMVideoFormatDescriptionRef format; // of the running session; NULL: none + bool broken; // the session failed as a device: it decodes nothing more + // Also under meta. closing: invalidate or finalize has begun, frames are + // refused. callers: decodeFrame calls from outside the decode queue that + // are still in the plug-in (waiting for a slot, queuing, or decoding at + // once); idle is signalled when the count drops to 0. + bool closing; + int callers; + pthread_cond_t idle; + dispatch_queue_t + queue; // serial: frames are decoded (and emitted) in submission order + dispatch_semaphore_t slots; // bounds frames queued but not yet decoded + // stats, logged every STATS_EVERY frames: decode = vcnjpeg_decode time, queue + // = enqueue -> start + int st_n, st_over, st_depth_max, depth; + double st_dec_sum, st_dec_max, st_q_sum, st_q_max, st_t0; + // frame time of the stream (ms, 0 until known) and the last sample's time + double st_frame_ms, st_frame_sum; + CMTime st_last_pts; + int refs; // see above; changed with atomics only +} State; + +// The CoreMedia storage of the decoder object. +typedef struct { + State* state; // NULL once finalized +} Storage; + +#define STATS_EVERY 120 + +// Frames that may wait in the queue. The VCN runs one command at a time, the +// queue only lets the caller keep feeding samples while the previous one +// decodes. (The JPEG block, too, runs one picture at a time.) +#define MAX_QUEUED 4 + +// The JPEG block of Navi 21 takes up to 16384 x 16384 (Linux, nv.c). Nothing +// has run on the GPU yet; the kext's buffers set the real limit per picture. +#define MAX_WIDTH 16384 +#define MAX_HEIGHT 16384 + +static os_log_t logger(void) { + static os_log_t l; + static dispatch_once_t once; + dispatch_once(&once, ^{ + l = os_log_create("com.droga.vtjpegvcn", "decoder"); + }); + return l; +} + +// Driver sessions of this plug-in in this process, for the log: a host that +// keeps creating sessions without ending them shows up as a growing "live". +static long g_started, g_ended, g_live; + +// Sets the format canAcceptFormatDescription compares with (NULL: none), for +// a session that starts or ends. Either way the session is not broken. +static void set_format(State* s, CMVideoFormatDescriptionRef fmt) { + pthread_mutex_lock(&s->meta); + CMVideoFormatDescriptionRef old = s->format; + s->format = fmt ? (CMVideoFormatDescriptionRef)CFRetain(fmt) : NULL; + s->broken = false; + pthread_mutex_unlock(&s->meta); + if (old) CFRelease(old); +} + +// Ends the decoder session, if there is one, and logs it with the counts. The +// caller holds s->lock or is the only one left using s. +static void end_session(State* s, const char* why) { + set_format(s, NULL); + if (!s->vcn) return; + vcnjpeg_destroy(s->vcn); + s->vcn = NULL; + long ended = __atomic_add_fetch(&g_ended, 1, __ATOMIC_RELAXED), + live = __atomic_sub_fetch(&g_live, 1, __ATOMIC_RELAXED), + started = __atomic_load_n(&g_started, __ATOMIC_RELAXED); + os_log_info(logger(), + "session %dx%d ended (%{public}s): %ld started, %ld ended, %ld " + "live in this process", + s->width, s->height, why, started, ended, live); +} + +static State* state_retain(State* s) { + __atomic_add_fetch(&s->refs, 1, __ATOMIC_RELAXED); + return s; +} +// The last one frees the state. Nothing is queued and no call is inside the +// plug-in by then: no lock is held, nobody waits on the semaphore and every +// slot has been given back. +static void state_release(State* s) { + if (__atomic_sub_fetch(&s->refs, 1, __ATOMIC_ACQ_REL)) return; + end_session(s, "finalized"); // finalize ended it already: only the format + if (s->lastFrame) CVPixelBufferRelease(s->lastFrame); + if (s->queue) dispatch_release(s->queue); + if (s->slots) dispatch_release(s->slots); + pthread_mutex_destroy(&s->lock); + pthread_mutex_destroy(&s->meta); + pthread_cond_destroy(&s->idle); + free(s); +} + +// The state of a decoder, without a reference: for calls that wait for +// nothing. +static State* state_of(VTVideoDecoderRef dec) { + Storage* st = + CMBaseObjectGetDerivedStorage(VTVideoDecoderGetCMBaseObject(dec)); + return __atomic_load_n(&st->state, __ATOMIC_ACQUIRE); +} +// The same with a reference, for a call that may wait for the decode queue: +// it keeps the state alive until the call lets go, also if the decoder is +// finalized meanwhile. NULL after finalize. +static State* state_enter(VTVideoDecoderRef dec) { + State* s = state_of(dec); + return s ? state_retain(s) : NULL; +} + +// Marks the decode queue. The output callback runs on it, and a call made from +// inside the callback must not wait for the queue, which is busy running it. +static char kQueueKey; +static bool on_queue(State* s) { + return dispatch_get_specific(&kQueueKey) == s; +} +// Waits until every queued frame has been emitted, also those queued from +// inside the callback while it waited. From inside the callback the frames +// queued after the running one cannot be waited for. +static void drain(State* s) { + if (!s->queue || on_queue(s)) return; + do + dispatch_sync(s->queue, ^{ + }); + while (__atomic_load_n(&s->depth, __ATOMIC_RELAXED) > 0); +} + +// A decodeFrame call from outside the decode queue counts itself in callers +// for as long as it runs. Returns false, counting nothing, once invalidate or +// finalize has begun. +static bool enter_call(State* s, bool counted) { + pthread_mutex_lock(&s->meta); + bool open = !s->closing; + if (open && counted) s->callers++; + pthread_mutex_unlock(&s->meta); + return open; +} +static void leave_call(State* s) { + pthread_mutex_lock(&s->meta); + if (--s->callers == 0) pthread_cond_broadcast(&s->idle); + pthread_mutex_unlock(&s->meta); +} +static bool is_closing(State* s) { + pthread_mutex_lock(&s->meta); + bool closing = s->closing; + pthread_mutex_unlock(&s->meta); + return closing; +} +// Refuses frames from now on and waits for the decodeFrame calls still on +// their way in: drain() only sees frames already queued, and a call that +// waits for a slot has not queued its frame yet. From the decode queue (the +// output callback) nothing is waited for: a call waiting for a slot may be +// waiting for the frame whose callback this is. Such a call refuses its frame +// once it gets the slot. Its own reference keeps the state until it has +// left, as each queued frame's own does until the frame has run, also when +// finalize runs on the queue. +static void close_calls(State* s) { + pthread_mutex_lock(&s->meta); + s->closing = true; + if (!on_queue(s)) + while (s->callers > 0) pthread_cond_wait(&s->idle, &s->meta); + pthread_mutex_unlock(&s->meta); +} + +// ---- CMBaseClass +// --------------------------------------------------------------------------- +static OSStatus base_invalidate(CMBaseObjectRef obj) { + Storage* st = CMBaseObjectGetDerivedStorage(obj); + State* s = __atomic_load_n(&st->state, __ATOMIC_ACQUIRE); + if (!s) return noErr; + state_retain(s); + // Frames handed in from now on are refused; the ones already queued are + // still emitted. + close_calls(s); + drain(s); + pthread_mutex_lock(&s->lock); + // None is emitted any more. + __atomic_store_n(&s->invalidated, true, __ATOMIC_RELAXED); + end_session(s, "invalidated"); + pthread_mutex_unlock(&s->lock); + state_release(s); + return noErr; +} + +// Off the decode queue this waits, as invalidate does, for the calls still on +// their way in and for every queued frame. On the queue (the host let go of +// the decoder from inside its output callback) it waits for neither: the +// frames queued behind the running one and a call waiting for the queue on +// another thread still hold the state, run after this returns and emit +// nothing. Either way the session ends here, once, under lock: a decode holds +// lock for as long as the GPU works on its frame, and on the queue the frame +// whose callback this is has finished with the GPU before it emits. +static void base_finalize(CMBaseObjectRef obj) { + Storage* st = CMBaseObjectGetDerivedStorage(obj); + State* s = __atomic_exchange_n(&st->state, NULL, __ATOMIC_ACQ_REL); + if (!s) return; + close_calls(s); + drain(s); + pthread_mutex_lock(&s->lock); + __atomic_store_n(&s->invalidated, true, __ATOMIC_RELAXED); + end_session(s, "finalized"); // releases the format too + pthread_mutex_unlock(&s->lock); + state_release(s); // the storage's reference: the last one frees the state +} + +static CFStringRef base_copy_debug_description(CMBaseObjectRef obj) { + return CFStringCreateWithFormat(NULL, NULL, CFSTR(""), + obj); +} + +static OSStatus base_copy_property(CMBaseObjectRef obj, CFStringRef key, + CFAllocatorRef alloc, void* out) { + if (!key || !out) return kVTParameterErr; + if (CFEqual( + key, + kVTDecompressionPropertyKey_UsingHardwareAcceleratedVideoDecoder)) { + *(CFTypeRef*)out = CFRetain(kCFBooleanTrue); + return noErr; + } + return kVTPropertyNotSupportedErr; +} + +static OSStatus base_set_property(CMBaseObjectRef obj, CFStringRef key, + CFTypeRef value) { + return kVTPropertyNotSupportedErr; +} + +// ---- VTVideoDecoderClass +// ------------------------------------------------------------------- +static OSStatus start_session(State* s, VTVideoDecoderSession session, + CMVideoFormatDescriptionRef fmt) { + if (!fmt) return kVTParameterErr; + CMVideoDimensions dim = CMVideoFormatDescriptionGetDimensions(fmt); + if (dim.width <= 0 || dim.height <= 0) + return kVTVideoDecoderUnsupportedDataFormatErr; + // A second start replaces the decoder of the first one. Ending it drops its + // format too: a start that fails must leave none that + // canAcceptFormatDescription could match. + drain(s); + pthread_mutex_lock(&s->lock); + end_session(s, "replaced by a new start"); + s->session = session; + pthread_mutex_unlock(&s->lock); + int32_t width = dim.width, height = dim.height; + bool tenBit = false; + if (width > MAX_WIDTH || height > MAX_HEIGHT) + return kVTVideoDecoderUnsupportedDataFormatErr; + + // A JPEG format description says nothing about sampling or precision: + // each picture carries its own. 4:2:0 comes out as '420f', 4:2:2 as '422f'; + // vcnjpeg refuses what the block is not given (progressive, 4:4:4, grey). + FourCharCode codec = CMFormatDescriptionGetMediaSubType(fmt); + if (codec != kCMVideoCodecType_JPEG && + codec != kCMVideoCodecType_JPEG_OpenDML) + return kVTVideoDecoderUnsupportedDataFormatErr; + + char err[256] = ""; + __atomic_store_n(&vcnjpeg_gpu_armed, 1, __ATOMIC_RELAXED); + VcnJpeg* vcn = vcnjpeg_create(MAX_WIDTH, MAX_HEIGHT, err, sizeof(err)); + if (!vcn) { + os_log_error(logger(), "vcnjpeg_create: %{public}s", err); + return kVTVideoDecoderNotAvailableNowErr; + } + // A picture the kext's buffers cannot hold goes to Apple's software decoder. + if (!vcnjpeg_fits(vcn, (uint32_t)width, (uint32_t)height)) { + os_log_error(logger(), + "%dx%d does not fit the kext's buffers (vcnjpegpool)", width, + height); + vcnjpeg_destroy(vcn); + return kVTVideoDecoderUnsupportedDataFormatErr; + } + // The new session is set up before anything else can see it: until it is + // published below, neither invalidate nor a decode can reach it. + CFDictionaryRef attrs = + vcnjpeg_copy_pixel_buffer_attributes(width, height, tenBit); + if (!attrs) { // out of memory: no session rather than one with no attributes + vcnjpeg_destroy(vcn); + return kVTAllocationFailedErr; + } + VTDecoderSessionSetPixelBufferAttributes(session, attrs); + CFRelease(attrs); + pthread_mutex_lock(&s->lock); + if (__atomic_load_n(&s->invalidated, __ATOMIC_RELAXED)) { + // Invalidated while the session was being made: nothing may stay open. + pthread_mutex_unlock(&s->lock); + vcnjpeg_destroy(vcn); + return kVTInvalidSessionErr; + } + end_session(s, "replaced by a new start"); // a start that ran alongside + s->vcn = vcn; + s->st_frame_ms = 0; // a new stream: learn its frame time again + s->st_last_pts = kCMTimeInvalid; + s->width = width; + s->height = height; + s->tenBit = tenBit; + long started = __atomic_add_fetch(&g_started, 1, __ATOMIC_RELAXED), + live = __atomic_add_fetch(&g_live, 1, __ATOMIC_RELAXED), + ended = __atomic_load_n(&g_ended, __ATOMIC_RELAXED); + set_format(s, fmt); + pthread_mutex_unlock(&s->lock); + os_log(logger(), + "session %dx%d %{public}s: %ld started, %ld ended, %ld live in this " + "process", + width, height, tenBit ? "10-bit" : "8-bit", started, ended, live); + return noErr; +} +static OSStatus dec_start_session(VTVideoDecoderRef dec, + VTVideoDecoderSession session, + CMVideoFormatDescriptionRef fmt) { + State* s = state_enter(dec); // it waits for the queue + if (!s) return kVTInvalidSessionErr; + OSStatus r = start_session(s, session, fmt); + state_release(s); + return r; +} + +static void on_output(void* ctx, CVPixelBufferRef frame, const void* p, + uint32_t w, uint32_t h, int64_t tag) { + State* s = ctx; + // A chunk has at most one shown frame; keep the last one if a stream breaks + // that rule. + if (s->lastFrame) CVPixelBufferRelease(s->lastFrame); + s->lastFrame = CVPixelBufferRetain(frame); +} + +static double now_ms(void) { + static mach_timebase_info_data_t tb; + if (!tb.denom) mach_timebase_info(&tb); + return (double)mach_absolute_time() * tb.numer / tb.denom / 1e6; +} + +// The stream's frame time: the sample's duration, or the step from the +// previous sample's presentation time when the caller gives none. The last good +// value is kept for samples with no timing; 60 fps is assumed until one is +// known. It is the stream's time, so at 2x playback each frame really has half +// of it. +static double frame_ms(State* s, CMSampleBufferRef sbuf) { + if (!sbuf) return s->st_frame_ms > 0 ? s->st_frame_ms : 1000.0 / 60; + CMTime d = CMSampleBufferGetDuration(sbuf); + CMTime pts = CMSampleBufferGetPresentationTimeStamp(sbuf); + double ms = 0; + if (CMTIME_IS_NUMERIC(d) && d.value > 0) { + ms = CMTimeGetSeconds(d) * 1000; + } else if (CMTIME_IS_NUMERIC(pts) && CMTIME_IS_NUMERIC(s->st_last_pts)) { + // A step longer than 100 ms is a seek, not a frame. + ms = CMTimeGetSeconds(CMTimeSubtract(pts, s->st_last_pts)) * 1000; + if (ms > 100) ms = 0; + } + if (CMTIME_IS_NUMERIC(pts)) s->st_last_pts = pts; + if (ms >= 1 && ms <= 1000) s->st_frame_ms = ms; + return s->st_frame_ms > 0 ? s->st_frame_ms : 1000.0 / 60; +} + +// A frame counts as slow when its decode alone took longer than the stream's +// frame time. Time in the queue is not counted: frames wait there by design, +// up to the queue depth, while the one ahead decodes. +static void stats_add(State* s, double queued, double decode, double frame) { + if (!s->st_n) s->st_t0 = now_ms(); + s->st_n++; + s->st_dec_sum += decode; + if (decode > s->st_dec_max) s->st_dec_max = decode; + s->st_q_sum += queued; + if (queued > s->st_q_max) s->st_q_max = queued; + s->st_frame_sum += frame; + if (decode > frame) s->st_over++; + if (s->st_n >= STATS_EVERY) { + os_log(logger(), + "stats %dx%d: %d frames in %.0f ms, decode avg %.2f max %.2f ms, " + "queue avg %.2f max %.2f ms, " + "decode over frame time (avg %.1f ms) %d, max depth %d, " + "firmware errors %u", + s->width, s->height, s->st_n, now_ms() - s->st_t0, + s->st_dec_sum / s->st_n, s->st_dec_max, s->st_q_sum / s->st_n, + s->st_q_max, s->st_frame_sum / s->st_n, s->st_over, s->st_depth_max, + vcnjpeg_firmware_errors(s->vcn)); + s->st_n = s->st_over = s->st_depth_max = 0; + s->st_dec_sum = s->st_dec_max = s->st_q_sum = s->st_q_max = 0; + s->st_frame_sum = 0; + } +} + +// A sample larger than the JPEG room of the kext's largest block (256 MiB, a +// quarter of it for the JPEG) cannot be decoded: refuse it before copying. +enum { kMaxSampleBytes = 0x4000000 }; + +// What VideoToolbox is told when a sample fails. A broken session (a driver +// call failed, or the GPU did not finish a command) is a malfunction, so that +// the host can fall back to another decoder; bad data is kept for streams +// that cannot be decoded as they are. +static OSStatus decode_status(int failure) { + switch (failure) { + case VCNJPEG_FAIL_DEVICE: + return kVTVideoDecoderMalfunctionErr; + case VCNJPEG_FAIL_MEMORY: + return kVTAllocationFailedErr; + // VideoToolbox's own code for it: FFmpeg goes on with the next frame on + // this one, and makes a new session on any other error. + case VCNJPEG_FAIL_REFERENCE: + return kVTVideoDecoderReferenceMissingErr; + default: + return kVTVideoDecoderBadDataErr; + } +} + +// Decode one chunk and hand its shown frame to VideoToolbox. A chunk with only +// hidden frames is valid: it hands back the last hidden frame's picture (see +// below). +static void decode_and_emit(State* s, VTVideoDecoderFrame frame, + CMSampleBufferRef sbuf, double enqueued) { + double started = now_ms(); + CMBlockBufferRef bb = CMSampleBufferGetDataBuffer(sbuf); + size_t len = bb ? CMBlockBufferGetDataLength(bb) : 0; + OSStatus status = noErr; + uint8_t* copy = NULL; + char* ptr = NULL; + if (!len || len > kMaxSampleBytes) + status = kVTVideoDecoderBadDataErr; + else if (CMBlockBufferIsRangeContiguous(bb, 0, len) && + !CMBlockBufferGetDataPointer(bb, 0, NULL, NULL, &ptr) && ptr) { + } else { + copy = malloc(len); + if (!copy) + status = kVTAllocationFailedErr; + else if (CMBlockBufferCopyDataBytes(bb, 0, len, copy)) + status = kVTVideoDecoderBadDataErr; + ptr = (char*)copy; + } + pthread_mutex_lock(&s->lock); + int depth = __atomic_load_n(&s->depth, __ATOMIC_RELAXED); + if (depth > s->st_depth_max) s->st_depth_max = depth; + bool invalidated = s->invalidated; + if (!status && !s->vcn) status = kVTInvalidSessionErr; + if (!status && + vcnjpeg_decode(s->vcn, (const uint8_t*)ptr, len, 0, on_output, s)) { + os_log_error(logger(), "decode: %{public}s", vcnjpeg_last_error(s->vcn)); + int failure = vcnjpeg_failure(s->vcn); + status = decode_status(failure); + // The session takes no more frames: canAcceptFormatDescription says no + // from now on, so VideoToolbox makes a new decoder. + if (failure == VCNJPEG_FAIL_DEVICE) { + pthread_mutex_lock(&s->meta); + s->broken = true; + pthread_mutex_unlock(&s->meta); + } + } + CVPixelBufferRef out = s->lastFrame; + s->lastFrame = NULL; + // A sample that holds only a hidden frame (a caller that sends frames one by + // one, as FFmpeg does) hands back that frame's picture. FFmpeg makes a new + // session whenever a decode returns no picture, and the new session has + // lost the references. A temporal unit or superframe always shows one frame, + // so Safari and Chrome never get here. + bool shown = out != NULL; + if (!status && !out && s->vcn) { + CVPixelBufferRef hidden = vcnjpeg_hidden_picture(s->vcn); + if (hidden) out = CVPixelBufferRetain(hidden); + } + double decode = now_ms() - started; + // A sample with only a hidden frame carries another frame's time: it is + // measured against the known frame time and does not change it. + stats_add(s, started - enqueued, decode, frame_ms(s, shown ? sbuf : NULL)); + pthread_mutex_unlock(&s->lock); + free(copy); + // A sample that failed hands back no picture, even one it showed before. + if (status && out) { + CVPixelBufferRelease(out); + out = NULL; + } + if (!invalidated) + VTDecoderSessionEmitDecodedFrame(s->session, frame, status, + out ? 0 : kVTDecodeInfo_FrameDropped, out); + if (out) CVPixelBufferRelease(out); +} + +// The caller holds a reference to s for as long as this runs. +static OSStatus decode_frame(State* s, VTVideoDecoderFrame frame, + CMSampleBufferRef sbuf, VTDecodeFrameFlags flags, + VTDecodeInfoFlags* infoOut) { + if (!sbuf) return kVTParameterErr; + // From inside the output callback the queue is already running this code, + // and invalidate run from there waits for no call (see close_calls). + bool counted = !on_queue(s); + if (!enter_call(s, counted)) return kVTInvalidSessionErr; + if (!(flags & kVTDecodeFrame_EnableAsynchronousDecompression)) { + double t = now_ms(); + if (!counted) + decode_and_emit(s, frame, sbuf, t); + else + dispatch_sync(s->queue, ^{ + decode_and_emit(s, frame, sbuf, t); + }); // keeps order with queued work + if (counted) leave_call(s); + return noErr; + } + // From inside the output callback the running frame still holds its slot, + // so waiting for one could wait for ever: queue the frame without one. + if (counted) { + dispatch_semaphore_wait(s->slots, DISPATCH_TIME_FOREVER); + // An invalidate that began during the wait refuses the frame. + if (is_closing(s)) { + dispatch_semaphore_signal(s->slots); + leave_call(s); + return kVTInvalidSessionErr; + } + } + CFRetain(sbuf); + double t = now_ms(); + __atomic_add_fetch(&s->depth, 1, __ATOMIC_RELAXED); + state_retain(s); // the frame's own reference, let go of last + dispatch_async(s->queue, ^{ + decode_and_emit(s, frame, sbuf, t); + __atomic_sub_fetch(&s->depth, 1, __ATOMIC_RELAXED); + CFRelease(sbuf); + if (counted) dispatch_semaphore_signal(s->slots); + state_release(s); + }); + if (infoOut) *infoOut = kVTDecodeInfo_Asynchronous; + // Queued and counted in depth: from here on drain() waits for the frame. + // Until then the call is counted in callers, so an invalidate or finalize + // off the queue, which waits for callers before it drains, cannot miss it. + // On the queue they wait for no frame queued behind the running one. + if (counted) leave_call(s); + return noErr; +} +static OSStatus dec_decode_frame(VTVideoDecoderRef dec, + VTVideoDecoderFrame frame, + CMSampleBufferRef sbuf, + VTDecodeFrameFlags flags, + VTDecodeInfoFlags* infoOut) { + if (infoOut) *infoOut = 0; + State* s = state_enter(dec); + if (!s) return kVTInvalidSessionErr; + OSStatus r = decode_frame(s, frame, sbuf, flags, infoOut); + state_release(s); + return r; +} + +static OSStatus dec_copy_supported_properties(VTVideoDecoderRef dec, + CFDictionaryRef* out) { + if (!out) return kVTParameterErr; + *out = NULL; + const void* k[] = {kVTPropertyTypeKey, kVTPropertyReadWriteStatusKey}; + const void* v[] = {kVTPropertyType_Boolean, + kVTPropertyReadWriteStatus_ReadOnly}; + CFDictionaryRef hw = + CFDictionaryCreate(NULL, k, v, 2, &kCFTypeDictionaryKeyCallBacks, + &kCFTypeDictionaryValueCallBacks); + if (!hw) return kVTAllocationFailedErr; + const void* keys[] = { + kVTDecompressionPropertyKey_UsingHardwareAcceleratedVideoDecoder}; + const void* vals[] = {hw}; + *out = CFDictionaryCreate(NULL, keys, vals, 1, &kCFTypeDictionaryKeyCallBacks, + &kCFTypeDictionaryValueCallBacks); + CFRelease(hw); + return *out ? noErr : kVTAllocationFailedErr; +} + +// A new size or configuration gets a new session. Size changes inside the +// stream don't come through here, the format description stays the same for +// those. +static Boolean dec_can_accept_format(VTVideoDecoderRef dec, + CMFormatDescriptionRef fmt) { + State* s = state_of(dec); + if (!s || !fmt) return false; + // A decoder whose start failed, whose session broke or whose invalidate has + // begun takes no format: VideoToolbox must make a new one. Read under meta, + // not lock: a decode holds lock while the GPU works on its frame. + pthread_mutex_lock(&s->meta); + CMFormatDescriptionRef cur = + s->format && !s->broken && !s->closing ? CFRetain(s->format) : NULL; + pthread_mutex_unlock(&s->meta); + if (!cur) return false; + Boolean same = false; + CMVideoDimensions a = CMVideoFormatDescriptionGetDimensions(cur), + b = CMVideoFormatDescriptionGetDimensions(fmt); + if (CMFormatDescriptionGetMediaSubType(fmt) == + CMFormatDescriptionGetMediaSubType(cur) && + a.width == b.width && a.height == b.height) + same = true; + CFRelease(cur); + return same; +} + +static OSStatus dec_finish_delayed_frames(VTVideoDecoderRef dec) { + State* s = state_enter(dec); + if (!s) return noErr; + drain(s); // every queued frame has been emitted when this returns + state_release(s); + return noErr; +} + +static const CMBaseClass kBaseClass = { + .version = 1, + .derivedStorageSize = sizeof(Storage), + .invalidate = base_invalidate, + .finalize = base_finalize, + .copyDebugDescription = base_copy_debug_description, + .copyProperty = base_copy_property, + .setProperty = base_set_property, +}; + +static const VTVideoDecoderClass kDecoderClass = { + .version = 3, + .startSession = dec_start_session, + .decodeFrame = dec_decode_frame, + .copySupportedPropertyDictionary = dec_copy_supported_properties, + .canAcceptFormatDescription = dec_can_accept_format, + .finishDelayedFrames = dec_finish_delayed_frames, +}; + +static const VTVideoDecoderVTable kVTable = {NULL, &kBaseClass, &kDecoderClass}; + +__attribute__((visibility("default"))) OSStatus +JPEGVCN_VTDecoder_CreateInstance(FourCharCode codec, CFAllocatorRef alloc, + VTVideoDecoderRef* out) { + if (!out) return kVTParameterErr; + *out = NULL; + if (codec != kCMVideoCodecType_JPEG && + codec != kCMVideoCodecType_JPEG_OpenDML) + return kVTCouldNotFindVideoDecoderErr; + CMBaseObjectRef obj = NULL; + OSStatus r = + CMDerivedObjectCreate(alloc, &kVTable, VTVideoDecoderGetClassID(), &obj); + if (r || !obj) return r ? r : kVTAllocationFailedErr; + Storage* st = CMBaseObjectGetDerivedStorage(obj); + memset(st, 0, sizeof(*st)); + State* s = calloc(1, sizeof(*s)); + if (!s) { + CFRelease(obj); + return kVTAllocationFailedErr; + } + s->refs = 1; // the storage's + pthread_mutex_init(&s->lock, NULL); + pthread_mutex_init(&s->meta, NULL); + pthread_cond_init(&s->idle, NULL); + s->queue = dispatch_queue_create( + "com.droga.vtjpegvcn.decode", + dispatch_queue_attr_make_with_qos_class(DISPATCH_QUEUE_SERIAL, + QOS_CLASS_USER_INTERACTIVE, 0)); + s->slots = dispatch_semaphore_create(MAX_QUEUED); + if (!s->queue || !s->slots) { + state_release(s); // the only reference: frees what was made + CFRelease(obj); // finalize finds no state + return kVTAllocationFailedErr; + } + dispatch_queue_set_specific(s->queue, &kQueueKey, s, NULL); + // Published with release once it is set up; from here on finalize frees + // it. + __atomic_store_n(&st->state, s, __ATOMIC_RELEASE); + *out = (VTVideoDecoderRef)obj; + return noErr; +} diff --git a/GPU/decode/jpeg/jpeg_app.h b/GPU/decode/jpeg/jpeg_app.h new file mode 100644 index 00000000..363b7875 --- /dev/null +++ b/GPU/decode/jpeg/jpeg_app.h @@ -0,0 +1,108 @@ +/* + * jpeg_app.h - how a program asks the VCNJpeg kext (GPU/jpeg) to decode a JPEG + * without a user client of its own: through the AMD accelerator's video + * context, the connection every sandboxed process may open. + * + * IOServiceOpen(accelerator, task, 3, &conn) type 3 = video context + * IOConnectCallStructMethod(conn, 258, in, inSize, out, &outSize) + * + * Selector 258 is AMDRadeonX6000_AMDAccelVideoContext::sendPMCommand(in, out, + * inSize, &outSize), declared with variable-size structs both ways and meant + * for PowerPlay escapes. The kext routes that function and takes the requests + * that start with the header below; everything else goes on to the original. + * Without the kext such a request reaches PowerPlay, whose PP_Cwdde refuses it + * (low 16 bits of the code above 0xB0, code below 0xC08001) and changes + * nothing: the caller gets an error and knows there is no decoder. + * + * Plain C: the kext, the tool and the VideoToolbox plug-in share this file. + * Struct data is at most 4096 bytes each way. LOAD and READ move a JPEG and + * the picture in pieces of that size; LOAD_USER and READ_USER instead give the + * address of a buffer in the caller's own memory, which the kext reads or + * fills with copyin/copyout in one go (a 48-megapixel picture is 74 MB: about + * 18000 calls in pieces). + */ +#ifndef JPEG_APP_H +#define JPEG_APP_H +#include + +#define JA_PROTOCOL 1u +#define JA_VIDEO_CONTEXT_TYPE 3u /* IOServiceOpen type */ +#define JA_SELECTOR 258u +#define JA_HEADER_SIZE 16u /* what a PowerPlay escape header says too */ +#define JA_CODE 0x004A5047u /* never a PowerPlay escape, see above */ +#define JA_REPLY_MAGIC 0x4a504741u /* "JPGA" */ +#define JA_MAX_IO 4096u + +enum { + JA_OP_INFO = 1, /* reply v: state bits (JA_STATE_*), JPEG capacity, surface + capacity, jobs */ + JA_OP_LOAD = + 2, /* arg0 offset, arg1 size of the whole JPEG; data: the next piece */ + JA_OP_RUN = 3, /* arg0 flags (jp::Flags); reply data: ja_picture */ + JA_OP_READ = 4, /* arg0 offset into the surface; reply data: the next piece */ + JA_OP_RELEASE = 5, /* gives the decoder back to whoever comes next */ + JA_OP_LOAD_USER = 6, /* arg0 address of the whole JPEG in the caller's memory, + arg1 its size */ + JA_OP_READ_USER = + 7, /* arg0 address of a buffer in the caller's memory, arg1 its size: the + whole surface is copied there; reply v[0] = bytes */ +}; + +/* INFO reply v[0]: the decoder's state (the kext's jp::State) */ +enum { + JA_STATE_POOL = 1 << 0, /* the buffers were taken when the driver started */ + JA_STATE_CREATED = 1 << 1, /* the JPEG queue exists */ + JA_STATE_STARTED = 1 << 2, /* the block is powered and its queue started (only + while decoding) */ + JA_STATE_STUCK = 1 << 3, /* a job failed in a way that stops the decoder until + the next restart */ +}; + +enum { + JA_OK = 0, + JA_MORE = 1, /* LOAD: piece taken, more expected */ + JA_BUSY = 2, /* another client holds the decoder: try again */ + JA_NOT_READY = 3, /* no buffers, queue not started, or stuck */ + JA_BAD_REQUEST = 4, + JA_NOT_OWNER = 5, /* RUN or READ without a LOAD of this client */ + JA_BAD_STREAM = 6, /* detail: jc::Stream */ + JA_FAILED = 7, /* the job did not succeed; detail: jp::Status */ + JA_BAD_ADDRESS = + 8, /* LOAD_USER / READ_USER: the buffer could not be read or written */ +}; + +struct ja_request { + uint32_t size; /* JA_HEADER_SIZE */ + uint32_t code; /* JA_CODE */ + uint32_t protocol; /* JA_PROTOCOL */ + uint32_t op; + uint64_t arg0; + uint64_t arg1; + /* data follows */ +}; + +struct ja_reply { + uint32_t magic; /* JA_REPLY_MAGIC */ + uint32_t status; /* JA_OK ... */ + uint32_t detail; + uint32_t dataBytes; /* bytes of data after this struct */ + uint64_t v[4]; + /* data follows */ +}; + +/* What RUN returns about the picture; the surface is NV12 with this layout. */ +struct ja_picture { + uint32_t width, height; + uint32_t pitch; /* bytes per row, luma and chroma */ + uint32_t alignedHeight; /* luma rows in the surface */ + uint32_t chromaOffset; /* from the start of the surface */ + uint32_t surfaceBytes; + uint32_t elapsedMs; /* submit to completion, in the kernel */ + uint32_t format; /* 0 NV12 (4:2:0: luma, then UV at chromaOffset), 1 YUYV + (4:2:2, one plane) */ +}; + +#define JA_LOAD_PIECE (JA_MAX_IO - (uint32_t)sizeof(struct ja_request)) +#define JA_READ_PIECE (JA_MAX_IO - (uint32_t)sizeof(struct ja_reply)) + +#endif diff --git a/GPU/decode/jpeg/jpeg_app_client.h b/GPU/decode/jpeg/jpeg_app_client.h new file mode 100644 index 00000000..95059855 --- /dev/null +++ b/GPU/decode/jpeg/jpeg_app_client.h @@ -0,0 +1,187 @@ +/* + * jpeg_app_client.h - the caller's side of jpeg_app.h: one picture through the + * VCNJpeg kext. Plain C, header only; the VideoToolbox plug-in and the + * kext's host tests (jpeg/tests/apps_test.cpp) use it. + * + * The transport is a function, so tests can put a fake behind it; the real one + * (ja_iokit_*) calls selector 258 of a video context of the AMD accelerator. + */ +#ifndef JPEG_APP_CLIENT_H +#define JPEG_APP_CLIENT_H +#include +#include +#include +#include + +#include "jpeg_app.h" + +/* One struct call: in -> out, *outSize is the room on entry and the bytes + written on return. 0 = the call went through (kern_return_t KERN_SUCCESS for + the real one). */ +typedef int (*ja_transport)(void* ctx, const void* in, size_t inSize, void* out, + size_t* outSize); + +/* Sends one request; fills *rp. Returns the reply's status, or -1 when the call + itself failed or the reply is not one of ours (no kext: PowerPlay refuses the + request). */ +static inline int ja_call(ja_transport t, void* ctx, uint32_t op, uint64_t a0, + uint64_t a1, const void* data, size_t dataBytes, + struct ja_reply* rp, void* outData, size_t outCap) { + uint8_t in[JA_MAX_IO], out[JA_MAX_IO]; + struct ja_request rq = {JA_HEADER_SIZE, JA_CODE, JA_PROTOCOL, op, a0, a1}; + if (dataBytes > JA_LOAD_PIECE) return -1; + memcpy(in, &rq, sizeof(rq)); + if (dataBytes != 0) memcpy(in + sizeof(rq), data, dataBytes); + size_t outSize = sizeof(out); + if (t(ctx, in, sizeof(rq) + dataBytes, out, &outSize) != 0) return -1; + if (outSize < sizeof(*rp) || outSize > sizeof(out)) return -1; + memcpy(rp, out, sizeof(*rp)); + if (rp->magic != JA_REPLY_MAGIC || sizeof(*rp) + rp->dataBytes != outSize) + return -1; + if (outData != NULL) + memcpy(outData, out + sizeof(*rp), + rp->dataBytes <= outCap ? rp->dataBytes : outCap); + return (int)rp->status; +} + +static inline uint64_t ja_now_ms(void) { + return clock_gettime_nsec_np(CLOCK_UPTIME_RAW) / 1000000u; +} + +/* Decodes one JPEG (already in the shape the block takes) into `surface` (NV12, + layout in *pic). Waits up to waitMs while another client holds the decoder. + Returns JA_OK or the failing status + (-1: transport). */ +static inline int ja_decode(ja_transport t, void* ctx, const uint8_t* jpeg, + size_t jpegBytes, uint8_t* surface, + size_t surfaceCap, uint32_t flags, unsigned waitMs, + struct ja_picture* pic, struct ja_reply* last) { + struct ja_reply rp; + memset(&rp, 0, sizeof(rp)); + uint64_t until = ja_now_ms() + waitMs; + int s; + while (1) { + s = ja_call(t, ctx, JA_OP_LOAD_USER, (uint64_t)(uintptr_t)jpeg, jpegBytes, + NULL, 0, &rp, NULL, 0); + if (s != JA_BUSY || ja_now_ms() >= until) break; + struct timespec ts = {0, 2000000}; + nanosleep(&ts, NULL); + } + if (s == JA_OK) { + memset(pic, 0, sizeof(*pic)); + s = ja_call(t, ctx, JA_OP_RUN, flags, 0, NULL, 0, &rp, pic, sizeof(*pic)); + if (s == JA_OK && rp.dataBytes != sizeof(*pic)) s = -1; + if (s == JA_OK && pic->surfaceBytes > surfaceCap) s = JA_BAD_REQUEST; + if (s == JA_OK) + s = ja_call(t, ctx, JA_OP_READ_USER, (uint64_t)(uintptr_t)surface, + surfaceCap, NULL, 0, &rp, NULL, 0); + } + if (s != JA_OK && s != JA_BUSY && s != -1) { + struct ja_reply ignored; + ja_call(t, ctx, JA_OP_RELEASE, 0, 0, NULL, 0, &ignored, NULL, 0); + } + if (last != NULL) *last = rp; + return s; +} + +/* Room the kext has now: JPEG bytes and surface bytes (0 when there is no + * door). */ +static inline int ja_info(ja_transport t, void* ctx, uint64_t* state, + uint64_t* jpegCap, uint64_t* surfaceCap) { + struct ja_reply rp; + int s = ja_call(t, ctx, JA_OP_INFO, 0, 0, NULL, 0, &rp, NULL, 0); + if (s != JA_OK) return s; + if (state) *state = rp.v[0]; + if (jpegCap) *jpegCap = rp.v[1]; + if (surfaceCap) *surfaceCap = rp.v[2]; + return JA_OK; +} + +#ifdef __APPLE__ +#include +#include + +/* A video context only answers once it is connected to a shared user client + (type 6) of the same task: IOConnectAddClient(video, shared) -> + IOAccelContext2::connectClient -> contextStart, which sets the method table. + Before that every selector returns kIOReturnNotReady + (IOAccelContext2::externalMethod checks the started flag at +1688). Seen on + hardware 2026-11-24: type 3 alone gave 0xE00002D8. The shared client stays + open as long as the video context: ja_iokit_close closes both. */ +#define JA_SHARED_TYPE 6u +#define JA_MAX_PAIRS 16 +static struct { + io_connect_t video, shared; +} ja_pairs[JA_MAX_PAIRS]; +static os_unfair_lock ja_pairs_lock = OS_UNFAIR_LOCK_INIT; + +/* Opens shared (6) + video (3) on the AMD accelerator and connects them: what + any process that decodes video does. Returns the video context, or + IO_OBJECT_NULL; *why (optional) gets the failing step's code. */ +static inline io_connect_t ja_iokit_open_why(kern_return_t* why, int* step) { + kern_return_t kr = kIOReturnNotFound; + int at = 0; + io_connect_t video = IO_OBJECT_NULL, shared = IO_OBJECT_NULL; + io_service_t s = IOServiceGetMatchingService( + kIOMainPortDefault, + IOServiceMatching("AMDRadeonX6000_AMDGraphicsAccelerator")); + if (s != IO_OBJECT_NULL) { + at = 1; + kr = IOServiceOpen(s, mach_task_self(), JA_SHARED_TYPE, &shared); + if (kr == KERN_SUCCESS) { + at = 2; + kr = IOServiceOpen(s, mach_task_self(), JA_VIDEO_CONTEXT_TYPE, &video); + } + if (kr == KERN_SUCCESS) { + at = 3; + kr = IOConnectAddClient(video, shared); + } + IOObjectRelease(s); + } + if (kr == KERN_SUCCESS) { + at = 4; + kr = kIOReturnNoResources; + os_unfair_lock_lock(&ja_pairs_lock); + for (int i = 0; i < JA_MAX_PAIRS; i++) + if (ja_pairs[i].video == IO_OBJECT_NULL) { + ja_pairs[i].video = video; + ja_pairs[i].shared = shared; + kr = KERN_SUCCESS; + break; + } + os_unfair_lock_unlock(&ja_pairs_lock); + } + if (why) *why = kr; + if (step) *step = at; + if (kr == KERN_SUCCESS) return video; + if (video != IO_OBJECT_NULL) IOServiceClose(video); + if (shared != IO_OBJECT_NULL) IOServiceClose(shared); + return IO_OBJECT_NULL; +} +static inline io_connect_t ja_iokit_open(void) { + return ja_iokit_open_why(NULL, NULL); +} + +/* Closes a video context from ja_iokit_open and its shared client. */ +static inline void ja_iokit_close(io_connect_t video) { + io_connect_t shared = IO_OBJECT_NULL; + os_unfair_lock_lock(&ja_pairs_lock); + for (int i = 0; i < JA_MAX_PAIRS; i++) + if (ja_pairs[i].video == video && video != IO_OBJECT_NULL) { + shared = ja_pairs[i].shared; + ja_pairs[i].video = ja_pairs[i].shared = IO_OBJECT_NULL; + break; + } + os_unfair_lock_unlock(&ja_pairs_lock); + if (video != IO_OBJECT_NULL) IOServiceClose(video); + if (shared != IO_OBJECT_NULL) IOServiceClose(shared); +} + +static inline int ja_iokit_call(void* ctx, const void* in, size_t inSize, + void* out, size_t* outSize) { + io_connect_t c = *(io_connect_t*)ctx; + return IOConnectCallStructMethod(c, JA_SELECTOR, in, inSize, out, outSize); +} +#endif + +#endif diff --git a/GPU/decode/jpeg/jpegprep.c b/GPU/decode/jpeg/jpegprep.c new file mode 100644 index 00000000..7f672f53 --- /dev/null +++ b/GPU/decode/jpeg/jpegprep.c @@ -0,0 +1,247 @@ +// jpegprep.c - see jpegprep.h. The same rewrite as +// jpeg/tests/jpeg_normalize.hpp (from the tool the first GPU tests used). On +// 2026-11-24 both gave the same bytes for six files (photos of 12 and 48 MP, a +// 640x480 MJPEG frame, the samples of tests/jpegsamples.h); tests/jpegtest.c +// checks the shape and the picture. This one also takes fill bytes and adds +// Annex K's tables where the kext's tool refuses. +#include "jpegprep.h" + +#include +#include +#include +#include + +#include "jpegstd.h" + +typedef struct { + bool haveQ[4]; + uint8_t q[4][64]; + bool haveH[2][2]; // [class 0 DC / 1 AC][id] + const uint8_t* h[2][2]; // 16 counts + values, inside the input + size_t hLen[2][2]; + uint16_t restart; + const uint8_t* sof; + size_t sofLen; + const uint8_t* sos; + size_t sosLen; + const uint8_t* scan; + size_t scanLen; +} Tables; + +static int fail(char* why, size_t whyLen, int code, const char* text) { + if (why && whyLen) snprintf(why, whyLen, "%s", text); + return code; +} + +static void put_seg(uint8_t* o, size_t* p, uint8_t marker, const uint8_t* body, + size_t len) { + o[(*p)++] = 0xff; + o[(*p)++] = marker; + o[(*p)++] = (uint8_t)((len + 2) >> 8); + o[(*p)++] = (uint8_t)(len + 2); + memcpy(o + *p, body, len); + *p += len; +} + +// Reads the standard tables out of jpegstd.h for the ones the picture lacks. +static void std_tables(Tables* t, bool* added) { + size_t p = 0; + while (p < sizeof(kJpegStdDht)) { + uint8_t tc = kJpegStdDht[p] >> 4, th = kJpegStdDht[p] & 15; + size_t count = 0; + for (int k = 0; k < 16; k++) count += kJpegStdDht[p + 1 + k]; + if (!t->haveH[tc][th]) { + t->haveH[tc][th] = true; + t->h[tc][th] = kJpegStdDht + p + 1; + t->hLen[tc][th] = 16 + count; + *added = true; + } + p += 17 + count; + } +} + +int jpeg_prepare(const uint8_t* d, size_t n, uint8_t** out, size_t* outLen, + JpegInfo* info, char* why, size_t whyLen) { + *out = NULL; + *outLen = 0; + memset(info, 0, sizeof(*info)); + if (!d || n < 4 || d[0] != 0xff || d[1] != 0xd8) + return fail(why, whyLen, JPEG_BAD, "not a JPEG (no SOI)"); + Tables t; + memset(&t, 0, sizeof(t)); + size_t i = 2; + bool gotScan = false; + while (!gotScan) { + // fill bytes (0xFF repeated) may come before a marker + while (i + 1 < n && d[i] == 0xff && d[i + 1] == 0xff) i++; + if (i + 4 > n) return fail(why, whyLen, JPEG_BAD, "no scan found"); + if (d[i] != 0xff) return fail(why, whyLen, JPEG_BAD, "marker expected"); + uint8_t m = d[i + 1]; + size_t len = ((size_t)d[i + 2] << 8) | d[i + 3]; + if (len < 2 || len > n - i - 2) + return fail(why, whyLen, JPEG_BAD, "a segment does not fit the file"); + const uint8_t* s = d + i + 4; + size_t body = len - 2; + if (m == 0xdb) { + size_t p = 0; + while (p < body) { + uint8_t pq = s[p] >> 4, tq = s[p] & 15; + if (pq != 0) + return fail(why, whyLen, JPEG_UNSUPPORTED, + "16-bit quantisation table"); + if (tq > 3 || body - p < 65) + return fail(why, whyLen, JPEG_BAD, "bad quantisation table"); + t.haveQ[tq] = true; + memcpy(t.q[tq], s + p + 1, 64); + p += 65; + } + } else if (m == 0xc4) { + size_t p = 0; + while (p < body) { + uint8_t tc = s[p] >> 4, th = s[p] & 15; + if (tc > 1 || th > 3 || body - p < 17) + return fail(why, whyLen, JPEG_BAD, "bad Huffman table"); + if (th > 1) + return fail(why, whyLen, JPEG_UNSUPPORTED, + "Huffman table id above 1 (Mesa gives the block two)"); + size_t count = 0; + for (int k = 0; k < 16; k++) count += s[p + 1 + k]; + if (count > (tc == 0 ? 12u : 162u) || body - p - 17 < count) + return fail(why, whyLen, JPEG_BAD, "bad Huffman table"); + t.haveH[tc][th] = true; + t.h[tc][th] = s + p + 1; + t.hLen[tc][th] = 16 + count; + p += 17 + count; + } + } else if (m == 0xdd) { + if (body != 2) + return fail(why, whyLen, JPEG_BAD, "bad restart interval segment"); + t.restart = (uint16_t)((s[0] << 8) | s[1]); + } else if (m == 0xc0) { + if (t.sof) + return fail(why, whyLen, JPEG_BAD, "more than one frame header"); + t.sof = s; + t.sofLen = body; + } else if (m == 0xda) { + t.sos = s; + t.sosLen = body; + gotScan = true; + } else if ((m >= 0xe0 && m <= 0xef) || m == 0xfe) { + // dropped, as Mesa does + } else if (m >= 0xc1 && m <= 0xcf && m != 0xc4 && m != 0xc8 && m != 0xcc) { + return fail(why, whyLen, JPEG_UNSUPPORTED, + "not a baseline JPEG (progressive, lossless or arithmetic)"); + } else { + return fail(why, whyLen, JPEG_UNSUPPORTED, + "a segment this decoder does not handle"); + } + i += 2 + len; + } + if (!t.sof) + return fail(why, whyLen, JPEG_BAD, "scan before the frame header"); + // frame header: P, Y, X, Nf, then Nf x (C, HV, Tq) + if (t.sofLen < 6 || t.sofLen != 6 + 3u * t.sof[5]) + return fail(why, whyLen, JPEG_BAD, "bad frame header"); + uint32_t height = ((uint32_t)t.sof[1] << 8) | t.sof[2]; + uint32_t width = ((uint32_t)t.sof[3] << 8) | t.sof[4]; + if (t.sof[0] != 8) + return fail(why, whyLen, JPEG_UNSUPPORTED, "not 8 bits per sample"); + if (width == 0 || height == 0) + return fail(why, whyLen, JPEG_UNSUPPORTED, "no size in the frame header"); + if (t.sof[5] != 3) + return fail(why, whyLen, JPEG_UNSUPPORTED, "not three components"); + if (t.sof[6] == t.sof[9] || t.sof[6] == t.sof[12] || t.sof[9] == t.sof[12]) + return fail(why, whyLen, JPEG_BAD, "two components with the same id"); + // sampling (Y, Cb, Cr) as Mesa's radeon_dec_jpeg_check_format: NV12 or YUYV + uint32_t sf = + ((uint32_t)t.sof[7] << 16) | ((uint32_t)t.sof[10] << 8) | t.sof[13]; + bool yuyv = sf == 0x211111 || sf == 0x221212 || sf == 0x222121; + if (sf != 0x221111 && !yuyv) + return fail(why, whyLen, JPEG_UNSUPPORTED, "not 4:2:0 or 4:2:2"); + for (int c = 0; c < 3; c++) { + uint8_t tq = t.sof[8 + 3 * c]; + if (tq > 3 || !t.haveQ[tq]) + return fail(why, whyLen, JPEG_BAD, + "a component's quantisation table is missing"); + } + // scan header: Ns, Ns x (C, Td/Ta), Ss, Se, Ah/Al + if (t.sosLen < 1 || t.sosLen != 4 + 2u * t.sos[0]) + return fail(why, whyLen, JPEG_BAD, "bad scan header"); + if (t.sos[0] != 3) + return fail(why, whyLen, JPEG_UNSUPPORTED, + "a scan without all three components"); + // the scan names the frame's components in the frame's order (T.81 B.2.3) + for (int c = 0; c < 3; c++) + if (t.sos[1 + 2 * c] != t.sof[6 + 3 * c]) + return fail(why, whyLen, JPEG_BAD, + "the scan names other components than the frame"); + // The scan runs to the first marker that is neither a stuffed FF00 nor RSTn. + size_t e = i; + while (1) { + if (e + 1 >= n) return fail(why, whyLen, JPEG_BAD, "no EOI after the scan"); + if (d[e] == 0xff && d[e + 1] != 0x00 && + !(d[e + 1] >= 0xd0 && d[e + 1] <= 0xd7)) + break; + e++; + } + // fill bytes before EOI belong to no segment + size_t f = e; + while (f + 1 < n && d[f + 1] == 0xff) f++; + // a sample that ends in fill bytes has no EOI after them + if (f + 1 >= n) return fail(why, whyLen, JPEG_BAD, "no EOI after the scan"); + if (d[f + 1] != 0xd9) + return fail(why, whyLen, JPEG_UNSUPPORTED, "more than one scan"); + t.scan = d + i; + t.scanLen = e - i; + bool added = false; + std_tables(&t, &added); + for (int c = 0; c < 3; c++) { + uint8_t td = t.sos[2 + 2 * c] >> 4, ta = t.sos[2 + 2 * c] & 15; + if (td > 1 || ta > 1 || !t.haveH[0][td] || !t.haveH[1][ta]) + return fail(why, whyLen, JPEG_BAD, + "a component's Huffman table is missing"); + } + uint8_t dqt[4 * 65], dht[4 * 179]; + size_t nq = 0, nh = 0; + for (int k = 0; k < 4; k++) { + if (!t.haveQ[k]) continue; + dqt[nq++] = (uint8_t)k; + memcpy(dqt + nq, t.q[k], 64); + nq += 64; + } + for (int c = 0; c < 2; c++) { + for (int k = 0; k < 2; k++) { + if (!t.haveH[c][k]) continue; + dht[nh++] = (uint8_t)((c << 4) | k); + memcpy(dht + nh, t.h[c][k], t.hLen[c][k]); + nh += t.hLen[c][k]; + } + } + size_t cap = 2 + (4 + nq) + (4 + nh) + 6 + (4 + t.sofLen) + (4 + t.sosLen) + + t.scanLen + 2; + uint8_t* o = malloc(cap); + if (!o) return fail(why, whyLen, JPEG_NO_MEMORY, "out of memory"); + size_t p = 0; + o[p++] = 0xff; + o[p++] = 0xd8; + put_seg(o, &p, 0xdb, dqt, nq); + put_seg(o, &p, 0xc4, dht, nh); + if (t.restart) { + uint8_t r[2] = {(uint8_t)(t.restart >> 8), (uint8_t)t.restart}; + put_seg(o, &p, 0xdd, r, 2); + } + put_seg(o, &p, 0xc0, t.sof, t.sofLen); + put_seg(o, &p, 0xda, t.sos, t.sosLen); + memcpy(o + p, t.scan, t.scanLen); + p += t.scanLen; + o[p++] = 0xff; + o[p++] = 0xd9; + *out = o; + *outLen = p; + info->width = width; + info->height = height; + info->restart = t.restart; + info->stdTables = added; + info->yuyv = yuyv; + return JPEG_OK; +} diff --git a/GPU/decode/jpeg/jpegprep.h b/GPU/decode/jpeg/jpegprep.h new file mode 100644 index 00000000..733f1e56 --- /dev/null +++ b/GPU/decode/jpeg/jpegprep.h @@ -0,0 +1,41 @@ +// jpegprep: turns one JPEG picture (a 'jpeg' or 'dmb1' sample) into the exact +// shape the VCN JPEG block is given on Linux by Mesa (vlVaGetJpegSliceHeader, +// src/gallium/frontends/va/picture_mjpeg.c): SOI, one DQT segment, one DHT +// segment (DC tables, then AC tables), DRI if there is a restart interval, +// SOF0, SOS, the scan, EOI. APPn and COM segments are dropped; a picture +// without Huffman tables (Motion JPEG) gets the standard ones of Annex K. +// +// What the block is given here is what the kext checks again before it takes +// the JPEG (VCNJpeg jc::parseStream): baseline, 8 bits, three components, +// one scan with all three, sampled as Mesa's radeon_dec_jpeg_check_format +// takes them on this block: 0x221111 (4:2:0, written as NV12) or 0x211111, +// 0x221212, 0x222121 (4:2:2, written as YUYV). Anything else is +// JPEG_UNSUPPORTED: progressive, 4:4:4, 4:4:0, grey. +// +// Pure code: no system call, no allocation but the output buffer. +#pragma once +#include +#include +#include + +enum { + JPEG_OK = 0, + JPEG_BAD = 1, // not a JPEG, or one that breaks the standard + JPEG_UNSUPPORTED = 2, // a valid JPEG the block is not given (see above) + JPEG_NO_MEMORY = 3, +}; + +typedef struct { + uint32_t width, height; + uint16_t restart; // restart interval, 0 = none + bool stdTables; // the Huffman tables of Annex K were added + bool yuyv; // 4:2:2: the block writes YUYV (else NV12) +} JpegInfo; + +// The output is at most the input plus kJpegPrepExtra bytes. +enum { kJpegPrepExtra = 1024 }; + +// Fills out (malloc'ed, free it) and *info. On failure *out is NULL and why +// holds a short reason. +int jpeg_prepare(const uint8_t* in, size_t n, uint8_t** out, size_t* outLen, + JpegInfo* info, char* why, size_t whyLen); diff --git a/GPU/decode/jpeg/jpegstd.h b/GPU/decode/jpeg/jpegstd.h new file mode 100644 index 00000000..7cad5013 --- /dev/null +++ b/GPU/decode/jpeg/jpegstd.h @@ -0,0 +1,45 @@ +// jpegstd.h - the four Huffman tables of ITU-T T.81 Annex K (K.3 to K.6), as +// one DHT segment body: DC luminance (class 0 id 0), DC chrominance (0/1), AC +// luminance (1/0), AC chrominance (1/1). Motion JPEG from cameras ('dmb1', AVI +// MJPEG) leaves the DHT out and means these tables. Copied byte for byte from a +// JPEG that FFmpeg wrote with -huffman default. +#pragma once +#include + +static const uint8_t kJpegStdDht[416] = { + 0x00, 0x00, 0x01, 0x05, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, + 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x01, 0x00, 0x03, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, + 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x10, 0x00, + 0x02, 0x01, 0x03, 0x03, 0x02, 0x04, 0x03, 0x05, 0x05, 0x04, 0x04, 0x00, + 0x00, 0x01, 0x7d, 0x01, 0x02, 0x03, 0x00, 0x04, 0x11, 0x05, 0x12, 0x21, + 0x31, 0x41, 0x06, 0x13, 0x51, 0x61, 0x07, 0x22, 0x71, 0x14, 0x32, 0x81, + 0x91, 0xa1, 0x08, 0x23, 0x42, 0xb1, 0xc1, 0x15, 0x52, 0xd1, 0xf0, 0x24, + 0x33, 0x62, 0x72, 0x82, 0x09, 0x0a, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x25, + 0x26, 0x27, 0x28, 0x29, 0x2a, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, + 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x53, 0x54, 0x55, 0x56, + 0x57, 0x58, 0x59, 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, + 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x83, 0x84, 0x85, 0x86, + 0x87, 0x88, 0x89, 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, + 0x9a, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, + 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, + 0xc7, 0xc8, 0xc9, 0xca, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, + 0xda, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xf1, + 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0x11, 0x00, 0x02, + 0x01, 0x02, 0x04, 0x04, 0x03, 0x04, 0x07, 0x05, 0x04, 0x04, 0x00, 0x01, + 0x02, 0x77, 0x00, 0x01, 0x02, 0x03, 0x11, 0x04, 0x05, 0x21, 0x31, 0x06, + 0x12, 0x41, 0x51, 0x07, 0x61, 0x71, 0x13, 0x22, 0x32, 0x81, 0x08, 0x14, + 0x42, 0x91, 0xa1, 0xb1, 0xc1, 0x09, 0x23, 0x33, 0x52, 0xf0, 0x15, 0x62, + 0x72, 0xd1, 0x0a, 0x16, 0x24, 0x34, 0xe1, 0x25, 0xf1, 0x17, 0x18, 0x19, + 0x1a, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, + 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x53, 0x54, 0x55, 0x56, + 0x57, 0x58, 0x59, 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, + 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x82, 0x83, 0x84, 0x85, + 0x86, 0x87, 0x88, 0x89, 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, + 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xb2, + 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3, 0xc4, 0xc5, + 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, + 0xd9, 0xda, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xf2, + 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, +}; diff --git a/GPU/decode/jpeg/vcnjpeg.c b/GPU/decode/jpeg/vcnjpeg.c new file mode 100644 index 00000000..a27ce5c3 --- /dev/null +++ b/GPU/decode/jpeg/vcnjpeg.c @@ -0,0 +1,368 @@ +// vcnjpeg.c - see vcnjpeg.h. +#include "vcnjpeg.h" + +#include +#include +#include +#include + +#include "jpegprep.h" + +int vcnjpeg_gpu_armed = 0; + +static void* iokit_open(void) { + io_connect_t c = ja_iokit_open(); + if (c == IO_OBJECT_NULL) return NULL; + io_connect_t* p = malloc(sizeof(*p)); + if (!p) { + ja_iokit_close(c); + return NULL; + } + *p = c; + return p; +} +static void iokit_close(void* ctx) { + if (!ctx) return; + ja_iokit_close( + *(io_connect_t*)ctx); // the video context and its shared client + free(ctx); +} +ja_transport vcnjpeg_transport = ja_iokit_call; +void* (*vcnjpeg_transport_open)(void) = iokit_open; +void (*vcnjpeg_transport_close)(void* ctx) = iokit_close; + +// How long a frame waits while another process holds the block before the +// session counts as broken: a picture of 48 MP takes the block well under that. +enum { kBusyWaitMs = 1000 }; + +struct VcnJpeg { + void* conn; + uint32_t maxW, maxH; + uint64_t surfaceRoom; // what the kext's picture buffer holds (INFO) + uint8_t* surface; // what the kext copies the picture into (its layout, see + // ja_picture) + size_t surfaceCap; + CVPixelBufferPoolRef pool; + uint32_t poolW, poolH; + OSType poolFormat; + int failure; + char err[160]; +}; + +static bool put_num(CFMutableDictionaryRef d, CFStringRef k, int32_t v) { + CFNumberRef n = CFNumberCreate(NULL, kCFNumberSInt32Type, &v); + if (!n) return false; + CFDictionarySetValue(d, k, n); + CFRelease(n); + return true; +} + +// formats: one OSType, or (format == 0) the session's two. +static CFDictionaryRef attributes(uint32_t w, uint32_t h, OSType format) { + CFMutableDictionaryRef a = + CFDictionaryCreateMutable(NULL, 0, &kCFTypeDictionaryKeyCallBacks, + &kCFTypeDictionaryValueCallBacks); + CFMutableDictionaryRef io = + CFDictionaryCreateMutable(NULL, 0, &kCFTypeDictionaryKeyCallBacks, + &kCFTypeDictionaryValueCallBacks); + if (!a || !io) { + if (a) CFRelease(a); + if (io) CFRelease(io); + return NULL; + } + bool ok = true; + if (format) { + ok = put_num(a, kCVPixelBufferPixelFormatTypeKey, (int32_t)format); + } else { + int32_t f[2] = {kCVPixelFormatType_420YpCbCr8BiPlanarFullRange, + kCVPixelFormatType_422YpCbCr8BiPlanarFullRange}; + CFNumberRef n0 = CFNumberCreate(NULL, kCFNumberSInt32Type, &f[0]); + CFNumberRef n1 = CFNumberCreate(NULL, kCFNumberSInt32Type, &f[1]); + CFTypeRef v[2] = {n0, n1}; + CFArrayRef arr = + n0 && n1 ? CFArrayCreate(NULL, v, 2, &kCFTypeArrayCallBacks) : NULL; + if (n0) CFRelease(n0); + if (n1) CFRelease(n1); + ok = arr != NULL; + if (arr) { + CFDictionarySetValue(a, kCVPixelBufferPixelFormatTypeKey, arr); + CFRelease(arr); + } + } + ok = put_num(a, kCVPixelBufferWidthKey, (int32_t)w) && ok; + ok = put_num(a, kCVPixelBufferHeightKey, (int32_t)h) && ok; + CFDictionarySetValue(a, kCVPixelBufferIOSurfacePropertiesKey, io); + CFDictionarySetValue(a, kCVPixelBufferMetalCompatibilityKey, kCFBooleanTrue); + CFRelease(io); + if (!ok) { + CFRelease(a); + return NULL; + } + return a; +} + +CFDictionaryRef vcnjpeg_copy_pixel_buffer_attributes(uint32_t w, uint32_t h, + bool ten) { + (void)ten; + return attributes(w, h, 0); +} + +static size_t surface_bytes(uint32_t w, uint32_t h, bool yuyv); +bool vcnjpeg_fits(VcnJpeg* d, uint32_t w, uint32_t h) { + size_t a = surface_bytes(w, h, false), b = surface_bytes(w, h, true); + return (a > b ? a : b) <= d->surfaceRoom; +} + +static int failed(VcnJpeg* d, int failure, const char* what, int status) { + d->failure = failure; + if (status == 0) + snprintf(d->err, sizeof(d->err), "%s", what); + else + snprintf(d->err, sizeof(d->err), "%s (status %d)", what, status); + return -1; +} + +VcnJpeg* vcnjpeg_create(uint32_t maxWidth, uint32_t maxHeight, char* err, + size_t errLen) { + if (!__atomic_load_n(&vcnjpeg_gpu_armed, __ATOMIC_RELAXED)) { + snprintf(err, errLen, "not armed"); + return NULL; + } + VcnJpeg* d = calloc(1, sizeof(*d)); + if (!d) { + snprintf(err, errLen, "out of memory"); + return NULL; + } + d->maxW = maxWidth; + d->maxH = maxHeight; + d->conn = vcnjpeg_transport_open(); + if (!d->conn) { + snprintf(err, errLen, "cannot open a video context on the AMD accelerator"); + free(d); + return NULL; + } + uint64_t state = 0, jcap = 0, scap = 0; + int s = ja_info(vcnjpeg_transport, d->conn, &state, &jcap, &scap); + if (s != JA_OK) { + // -1: the request went on to PowerPlay, which refused it: no kext with the + // door + snprintf(err, errLen, + s == -1 ? "no JPEG decoder: the VCNJpeg kext is not loaded" + : "the JPEG decoder is not ready (status %d)", + s); + vcnjpeg_transport_close(d->conn); + free(d); + return NULL; + } + if ((state & JA_STATE_STUCK) || !(state & JA_STATE_POOL) || + !(state & JA_STATE_CREATED)) { + snprintf(err, errLen, + (state & JA_STATE_STUCK) + ? "the JPEG decoder is stuck until the next restart" + : "the JPEG decoder has no queue or no buffers (state 0x%llx)", + (unsigned long long)state); + vcnjpeg_transport_close(d->conn); + free(d); + return NULL; + } + d->surfaceRoom = scap; + (void)jcap; + return d; +} + +void vcnjpeg_destroy(VcnJpeg* d) { + if (!d) return; + if (d->conn) { + struct ja_reply rp; + ja_call(vcnjpeg_transport, d->conn, JA_OP_RELEASE, 0, 0, NULL, 0, &rp, NULL, + 0); + vcnjpeg_transport_close(d->conn); + } + if (d->pool) CVPixelBufferPoolRelease(d->pool); + free(d->surface); + free(d); +} + +static CVPixelBufferRef new_target(VcnJpeg* d, uint32_t w, uint32_t h, + OSType format) { + if (d->pool && (d->poolW != w || d->poolH != h || d->poolFormat != format)) { + CVPixelBufferPoolRelease(d->pool); + d->pool = NULL; + } + if (!d->pool) { + CFDictionaryRef a = attributes(w, h, format); + if (!a) return NULL; + CVReturn r = CVPixelBufferPoolCreate(NULL, NULL, a, &d->pool); + CFRelease(a); + if (r) { + d->pool = NULL; + return NULL; + } + d->poolW = w; + d->poolH = h; + d->poolFormat = format; + } + CVPixelBufferRef pb = NULL; + if (CVPixelBufferPoolCreatePixelBuffer(NULL, d->pool, &pb)) return NULL; + return pb; +} + +// The kext's surface layout for a picture (VCNJpeg jc::outputLayout): +// NV12: rows of alignUp(alignUp(width, 16), 256) bytes, alignUp(height, 16) +// luma rows, then the interleaved chroma. YUYV (4:2:2): one plane, rows of +// alignUp(alignUp(width, 16) * 2, 256) bytes. +static size_t surface_bytes(uint32_t w, uint32_t h, bool yuyv) { + size_t rows = ((size_t)h + 15) / 16 * 16; + if (yuyv) return (((size_t)w + 15) / 16 * 16 * 2 + 255) / 256 * 256 * rows; + size_t pitch = (((size_t)w + 15) / 16 * 16 + 255) / 256 * 256; + return pitch * rows * 3 / 2; +} + +// YUYV rows (Y0 Cb Y1 Cr) into '422f': the Ys to plane 0, each Cb Cr pair to +// plane 1. +static bool copy_yuyv(const uint8_t* src, const struct ja_picture* pic, + CVPixelBufferRef pb) { + uint32_t w = pic->width, h = pic->height; + size_t row = ((size_t)w + 1) / 2 * 4; + if (pic->pitch < row || (size_t)pic->pitch * h > pic->surfaceBytes) + return false; + if (CVPixelBufferLockBaseAddress(pb, 0)) return false; + bool ok = CVPixelBufferGetPlaneCount(pb) == 2 && + CVPixelBufferGetWidthOfPlane(pb, 0) == w && + CVPixelBufferGetHeightOfPlane(pb, 0) == h && + CVPixelBufferGetHeightOfPlane(pb, 1) == h; + if (ok) { + uint8_t* y = CVPixelBufferGetBaseAddressOfPlane(pb, 0); + uint8_t* uv = CVPixelBufferGetBaseAddressOfPlane(pb, 1); + size_t ys = CVPixelBufferGetBytesPerRowOfPlane(pb, 0), + uvs = CVPixelBufferGetBytesPerRowOfPlane(pb, 1); + size_t pairs = ((size_t)w + 1) / 2; + ok = y && uv && ys >= w && uvs >= pairs * 2; + for (uint32_t r = 0; ok && r < h; r++) { + const uint8_t* s = src + (size_t)r * pic->pitch; + uint8_t* yr = y + r * ys; + uint8_t* cr = uv + r * uvs; + for (size_t p = 0; p < pairs; p++) { + yr[2 * p] = s[4 * p]; + if (2 * p + 1 < w) yr[2 * p + 1] = s[4 * p + 2]; + cr[2 * p] = s[4 * p + 1]; + cr[2 * p + 1] = s[4 * p + 3]; + } + } + } + CVPixelBufferUnlockBaseAddress(pb, 0); + return ok; +} + +// Copies the kext's surface into the planes of pb; false if the layout the kext +// reported does not fit the picture. +static bool copy_planes(const uint8_t* src, const struct ja_picture* pic, + CVPixelBufferRef pb) { + uint32_t w = pic->width, h = pic->height; + if (pic->pitch < w || (size_t)pic->pitch * h > pic->chromaOffset || + pic->chromaOffset + (size_t)pic->pitch * ((h + 1) / 2) > + pic->surfaceBytes) + return false; + if (CVPixelBufferLockBaseAddress(pb, 0)) return false; + bool ok = CVPixelBufferGetPlaneCount(pb) == 2 && + CVPixelBufferGetWidthOfPlane(pb, 0) == w && + CVPixelBufferGetHeightOfPlane(pb, 0) == h; + if (ok) { + uint8_t* y = CVPixelBufferGetBaseAddressOfPlane(pb, 0); + uint8_t* uv = CVPixelBufferGetBaseAddressOfPlane(pb, 1); + size_t ys = CVPixelBufferGetBytesPerRowOfPlane(pb, 0), + uvs = CVPixelBufferGetBytesPerRowOfPlane(pb, 1); + size_t cw = ((size_t)w + 1) / 2 * 2, + ch = CVPixelBufferGetHeightOfPlane(pb, 1); + ok = y && uv && ys >= w && uvs >= cw && ch == (h + 1) / 2 && + cw <= pic->pitch; + for (uint32_t r = 0; ok && r < h; r++) + memcpy(y + r * ys, src + (size_t)r * pic->pitch, w); + for (size_t r = 0; ok && r < ch; r++) + memcpy(uv + r * uvs, src + pic->chromaOffset + r * pic->pitch, cw); + } + CVPixelBufferUnlockBaseAddress(pb, 0); + return ok; +} + +int vcnjpeg_decode(VcnJpeg* d, const uint8_t* sample, size_t size, int64_t tag, + VcnJpegOutputFn fn, void* ctx) { + d->failure = VCNJPEG_FAIL_STREAM; + d->err[0] = 0; + uint8_t* jpeg = NULL; + size_t jpegLen = 0; + JpegInfo info; + char why[96]; + int p = jpeg_prepare(sample, size, &jpeg, &jpegLen, &info, why, sizeof(why)); + if (p == JPEG_NO_MEMORY) return failed(d, VCNJPEG_FAIL_MEMORY, why, 0); + if (p != JPEG_OK) return failed(d, VCNJPEG_FAIL_STREAM, why, 0); + if (info.width > d->maxW || info.height > d->maxH) { + free(jpeg); + return failed(d, VCNJPEG_FAIL_STREAM, + "picture larger than the session allows", 0); + } + size_t need = surface_bytes(info.width, info.height, info.yuyv); + // The size comes from the picture's own header, before the kext has seen it: + // a picture the kext cannot hold is refused here, so that a few bytes of SOF + // cannot make this process allocate hundreds of megabytes. + if (need > d->surfaceRoom) { + free(jpeg); + return failed(d, VCNJPEG_FAIL_STREAM, + "picture larger than the kext's buffer", 0); + } + if (need > d->surfaceCap) { + free(d->surface); + d->surface = malloc(need); + d->surfaceCap = d->surface ? need : 0; + if (!d->surface) { + free(jpeg); + return failed(d, VCNJPEG_FAIL_MEMORY, "out of memory", 0); + } + } + struct ja_picture pic; + struct ja_reply rp; + int s = ja_decode(vcnjpeg_transport, d->conn, jpeg, jpegLen, d->surface, + d->surfaceCap, 0, kBusyWaitMs, &pic, &rp); + free(jpeg); + if (s == JA_BAD_STREAM) + return failed(d, VCNJPEG_FAIL_STREAM, "the kext refused the picture", + (int)rp.detail); + if (s == JA_BAD_REQUEST) + return failed(d, VCNJPEG_FAIL_STREAM, + "the picture does not fit the kext's buffers", s); + if (s != JA_OK) + return failed(d, VCNJPEG_FAIL_DEVICE, "the JPEG decoder failed", s); + if (pic.width != info.width || pic.height != info.height || + pic.surfaceBytes > d->surfaceCap || pic.format != (info.yuyv ? 1u : 0u)) + return failed(d, VCNJPEG_FAIL_DEVICE, + "the kext's picture is not the one sent", 0); + CVPixelBufferRef pb = + new_target(d, info.width, info.height, + info.yuyv ? kCVPixelFormatType_422YpCbCr8BiPlanarFullRange + : kCVPixelFormatType_420YpCbCr8BiPlanarFullRange); + if (!pb) return failed(d, VCNJPEG_FAIL_MEMORY, "no pixel buffer", 0); + if (!(info.yuyv ? copy_yuyv(d->surface, &pic, pb) + : copy_planes(d->surface, &pic, pb))) { + CVPixelBufferRelease(pb); + return failed(d, VCNJPEG_FAIL_DEVICE, + "the kext's layout does not fit the picture", 0); + } + // JFIF: BT.601 matrix, full range (the pixel format says the range) + CVBufferSetAttachment(pb, kCVImageBufferYCbCrMatrixKey, + kCVImageBufferYCbCrMatrix_ITU_R_601_4, + kCVAttachmentMode_ShouldPropagate); + fn(ctx, pb, NULL, info.width, info.height, tag); + CVPixelBufferRelease(pb); + return 0; +} + +const char* vcnjpeg_last_error(VcnJpeg* d) { return d->err; } +int vcnjpeg_failure(VcnJpeg* d) { return d->failure; } +CVPixelBufferRef vcnjpeg_hidden_picture(VcnJpeg* d) { + (void)d; + return NULL; +} +unsigned vcnjpeg_firmware_errors(VcnJpeg* d) { + (void)d; + return 0; +} diff --git a/GPU/decode/jpeg/vcnjpeg.h b/GPU/decode/jpeg/vcnjpeg.h new file mode 100644 index 00000000..1fd5ab17 --- /dev/null +++ b/GPU/decode/jpeg/vcnjpeg.h @@ -0,0 +1,61 @@ +// vcnjpeg: one JPEG picture at a time on the JPEG block of the AMD VCN, through +// the VCNJpeg kext (GPU/jpeg). The kext owns the block, its queue +// and its buffers; a process reaches it through the accelerator's video context +// (selector 258, see jpeg_app.h), the connection any process that decodes +// video may open. Without that kext there is no decoder: vcnjpeg_create fails. +// +// The interface is the one of vcnvp9.h, so that the VideoToolbox side +// (JPEGVCNDecoder.c) and its tests (tests/plugintest.c) are the same code. +#pragma once +#include +#include +#include +#include + +#include "jpeg_app_client.h" + +typedef struct VcnJpeg VcnJpeg; +typedef void (*VcnJpegOutputFn)(void* ctx, CVPixelBufferRef pb, + const void* unused, uint32_t width, + uint32_t height, int64_t tag); + +// The plug-in sets this; nothing is sent to the kernel before it is set. +extern int vcnjpeg_gpu_armed; + +// The transport to the kext: the real one by default, a stand-in in the tests. +extern ja_transport vcnjpeg_transport; +extern void* (*vcnjpeg_transport_open)(void); +extern void (*vcnjpeg_transport_close)(void* ctx); + +// What the session may get, full range (a JPEG's samples are 0..255), IOSurface +// backed: NV12 ('420f') for 4:2:0 pictures, '422f' (Y plane + CbCr plane at +// full height) for 4:2:2 ones, which the block writes as YUYV and vcnjpeg +// splits. +CFDictionaryRef vcnjpeg_copy_pixel_buffer_attributes(uint32_t w, uint32_t h, + bool tenBit); + +// Fails when there is no kext with the door, or its decoder is not ready or is +// stuck (a job failed in a way that stops it until the next restart). +VcnJpeg* vcnjpeg_create(uint32_t maxWidth, uint32_t maxHeight, char* err, + size_t errLen); +// True when a picture of w x h, 4:2:0 or 4:2:2, fits the kext's buffers. +bool vcnjpeg_fits(VcnJpeg* d, uint32_t w, uint32_t h); +void vcnjpeg_destroy(VcnJpeg* d); +// Decodes one picture and calls fn with it. +int vcnjpeg_decode(VcnJpeg* d, const uint8_t* sample, size_t size, int64_t tag, + VcnJpegOutputFn fn, void* ctx); +const char* vcnjpeg_last_error(VcnJpeg* d); +enum { + VCNJPEG_FAIL_STREAM = + 0, // the picture cannot be decoded as it is (or not by the block) + VCNJPEG_FAIL_DEVICE = + 1, // the kext is gone, refused, timed out, or stays busy + VCNJPEG_FAIL_MEMORY = 2, + VCNJPEG_FAIL_REFERENCE = 3, // never: a JPEG needs no other picture +}; +int vcnjpeg_failure(VcnJpeg* d); +// A JPEG has no hidden pictures: always NULL. +CVPixelBufferRef vcnjpeg_hidden_picture(VcnJpeg* d); +// Pictures the block decoded but the kext reported as wrong: none can be told +// apart yet, always 0. +unsigned vcnjpeg_firmware_errors(VcnJpeg* d); diff --git a/GPU/decode/loader/build.sh b/GPU/decode/loader/build.sh index ebe3fe76..90520938 100755 --- a/GPU/decode/loader/build.sh +++ b/GPU/decode/loader/build.sh @@ -7,7 +7,7 @@ # # The kext only lets through the exact plug-in builds listed in it. The list is made here, # from three places: -# 1. the five plug-in bundles of decode/build/ (AV1, VP9, MPEG-2, VC-1, MPEG-4; built +# 1. the six plug-in bundles of decode/build/ (AV1, VP9, MPEG-2, VC-1, MPEG-4, JPEG; built # first if one is missing) # 2. released-builds.txt in this folder: the builds of published releases # 3. any bundle given on the command line @@ -38,7 +38,7 @@ OBJ=$B/loader FINAL=$B/$NAME.kext OUT=$OBJ/$NAME.kext # assembled here; it replaces $FINAL only when everything worked # Every plug-in decode/build.sh makes; a kext that lists only some would refuse the others. -PLUGINS=(AV1VCNDecoder VP9VCNDecoder MPEG2VCNDecoder VC1VCNDecoder MPEG4VCNDecoder) +PLUGINS=(AV1VCNDecoder VP9VCNDecoder MPEG2VCNDecoder VC1VCNDecoder MPEG4VCNDecoder JPEGVCNDecoder) for p in $PLUGINS; do [[ -d $B/$p.bundle ]] || { $DECODE/build.sh; break; } done diff --git a/GPU/decode/tests/gpu/README.md b/GPU/decode/tests/gpu/README.md index 4ff98ea4..9a64e07d 100644 --- a/GPU/decode/tests/gpu/README.md +++ b/GPU/decode/tests/gpu/README.md @@ -24,6 +24,8 @@ Mac has to be reset. Before any run marked "can hang" below: | `vtlegacytest` | yes, through VideoToolbox | **yes** | `VCNLEGACY_ALLOW_GPU=yes-i-know-it-can-hang` (without it, it only cuts the stream into samples) | | `vtav1test` | yes, through VideoToolbox | **yes** | none: a decode run is armed | | `vtvp9test` | yes, through VideoToolbox | **yes** | none: a decode run is armed | +| `vtjpegtest` | yes, through VideoToolbox and the VCNJpeg kext | **yes** | none: a decode run is armed (`-apple` runs on the CPU only) | +| `mkmjpeg422` | no | no | none | | `vtchurn` | yes, through VideoToolbox | **yes** | none: every session decodes | | `probe_ctx` | yes | low risk: it opens a session, it decodes nothing | none | | `tools/driver/dryrun.py`, `dryrun_vp9.py` | yes, under lldb | the driver's own setup goes out; our commands do not | the scripts arm the program themselves | @@ -147,6 +149,23 @@ VCNVP9_SESSION=vp9 VCNVP9_ALLOW_GPU=yes-i-know-it-can-hang \ A pass: one line per frame ending in `OK`, then `N frames, 0 mismatches`, and exit status 0. +## vtjpegtest + +Motion JPEG through VideoToolbox, every frame compared with FFmpeg's decode (within 2: the +block's IDCT rounds a little differently). It needs `VCNJpeg.kext` running +([jpeg/README.md](../../../jpeg/README.md)). + +```bash +ffmpeg -f lavfi -i testsrc2=size=1280x720:rate=30 -frames:v 30 -pix_fmt yuvj420p -c:v mjpeg -q:v 3 -f mjpeg c420.mjpeg +ffmpeg -i c420.mjpeg -f rawvideo -pix_fmt yuvj420p r420.yuv +decode/build/gpu/vtjpegtest -apple c420.mjpeg r420.yuv 1280 720 420 # CPU only: checks the clip +decode/build/gpu/vtjpegtest -load decode/build/JPEGVCNDecoder.bundle c420.mjpeg r420.yuv 1280 720 420 +decode/build/gpu/vtjpegtest -system c420.mjpeg r420.yuv 1280 720 420 # the installed plug-in +``` + +`-dmb1` sends the same pictures as OpenDML. `mkmjpeg422` writes the 4:2:2 sampling webcams +use (luma 2x1), which FFmpeg does not write. + ## vtav1test and vtvp9test They decode through the public VideoToolbox API, the way Safari does. They test the plug-in diff --git a/GPU/decode/tests/gpu/build.sh b/GPU/decode/tests/gpu/build.sh index 713a8235..2ef93de2 100755 --- a/GPU/decode/tests/gpu/build.sh +++ b/GPU/decode/tests/gpu/build.sh @@ -12,6 +12,9 @@ # test's own process, nothing installed (armed by VCNLEGACY_ALLOW_GPU) # vtav1test AV1 through VideoToolbox, as Safari does (no switch: see README.md) # vtvp9test VP9 through VideoToolbox, as Safari does (no switch: see README.md) +# vtjpegtest Motion JPEG through VideoToolbox, our decoder only (loaded in the process, or the +# installed one with -system), compared with FFmpeg (no switch) +# mkmjpeg422 writes Motion JPEG sampled as webcams do (4:2:2, luma 2x1); CPU only # vtchurn many sessions in one process, counts ports and IOKit connections (no switch) # probe_ctx asks the driver for one decode context (no switch: see README.md) # driveruuid prints the build identifier of the installed driver @@ -79,6 +82,8 @@ build vtlegacytest -Impeg2 -Ivc1 -Impeg4 $T/vtlegacytest.c mpeg2/MPEG2VCNDecoder build vtav1test $T/vtav1test.c av1/av1parse.c $CF $VT build vtvp9test $T/vtvp9test.c vp9/vp9parse.c $CF $VT +build vtjpegtest $T/vtjpegtest.c $CF $VT +build mkmjpeg422 $T/mkmjpeg422.c build vtchurn $T/vtchurn.c $CF $VT build probe_ctx $T/probe_ctx.c common/vcndriver.c $CF $IOKIT build driveruuid $T/driveruuid.c common/vcndriver.c $CF $IOKIT diff --git a/GPU/decode/tests/gpu/mkmjpeg422.c b/GPU/decode/tests/gpu/mkmjpeg422.c new file mode 100644 index 00000000..4c1679f3 --- /dev/null +++ b/GPU/decode/tests/gpu/mkmjpeg422.c @@ -0,0 +1,293 @@ +// mkmjpeg422: writes a Motion JPEG stream sampled the way webcams do it +// (4:2:2 as luma 2x1, chroma 1x1, 1x1), which FFmpeg's encoder cannot write +// (it writes 4:2:2 as 2x2, 1x2, 1x2) and Apple's encoder neither (4:2:0 only). +// +// mkmjpeg422 in.yuv width height out.mjpeg [quality] +// +// in.yuv: planar 4:2:2 frames (FFmpeg's yuvj422p), width a multiple of 16, +// height a multiple of 8. Each frame becomes one baseline JPEG: standard +// quantisation tables of Annex K scaled as libjpeg does for the quality (90 by +// default), the standard Huffman tables of Annex K, one interleaved scan. +// Runs on the CPU only. +#include +#include +#include +#include +#include + +static const uint8_t kZigzag[64] = { + 0, 1, 8, 16, 9, 2, 3, 10, 17, 24, 32, 25, 18, 11, 4, 5, + 12, 19, 26, 33, 40, 48, 41, 34, 27, 20, 13, 6, 7, 14, 21, 28, + 35, 42, 49, 56, 57, 50, 43, 36, 29, 22, 15, 23, 30, 37, 44, 51, + 58, 59, 52, 45, 38, 31, 39, 46, 53, 60, 61, 54, 47, 55, 62, 63}; +static const uint8_t kStdLuma[64] = { + 16, 11, 10, 16, 24, 40, 51, 61, 12, 12, 14, 19, 26, 58, 60, 55, + 14, 13, 16, 24, 40, 57, 69, 56, 14, 17, 22, 29, 51, 87, 80, 62, + 18, 22, 37, 56, 68, 109, 103, 77, 24, 35, 55, 64, 81, 104, 113, 92, + 49, 64, 78, 87, 103, 121, 120, 101, 72, 92, 95, 98, 112, 100, 103, 99}; +static const uint8_t kStdChroma[64] = { + 17, 18, 24, 47, 99, 99, 99, 99, 18, 21, 26, 66, 99, 99, 99, 99, + 24, 26, 56, 99, 99, 99, 99, 99, 47, 66, 99, 99, 99, 99, 99, 99, + 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, + 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}; +// Annex K.3: bits (count of codes of each length 1..16) and values +static const uint8_t kDcLumaBits[16] = {0, 1, 5, 1, 1, 1, 1, 1, + 1, 0, 0, 0, 0, 0, 0, 0}; +static const uint8_t kDcLumaVals[12] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11}; +static const uint8_t kDcChromaBits[16] = {0, 3, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 0, 0, 0, 0, 0}; +static const uint8_t kDcChromaVals[12] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11}; +static const uint8_t kAcLumaBits[16] = {0, 2, 1, 3, 3, 2, 4, 3, + 5, 5, 4, 4, 0, 0, 1, 0x7d}; +static const uint8_t kAcLumaVals[162] = { + 0x01, 0x02, 0x03, 0x00, 0x04, 0x11, 0x05, 0x12, 0x21, 0x31, 0x41, 0x06, + 0x13, 0x51, 0x61, 0x07, 0x22, 0x71, 0x14, 0x32, 0x81, 0x91, 0xa1, 0x08, + 0x23, 0x42, 0xb1, 0xc1, 0x15, 0x52, 0xd1, 0xf0, 0x24, 0x33, 0x62, 0x72, + 0x82, 0x09, 0x0a, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x25, 0x26, 0x27, 0x28, + 0x29, 0x2a, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x43, 0x44, 0x45, + 0x46, 0x47, 0x48, 0x49, 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, + 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x73, 0x74, 0x75, + 0x76, 0x77, 0x78, 0x79, 0x7a, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, + 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0xa2, 0xa3, + 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, + 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, + 0xca, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xe1, 0xe2, + 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xf1, 0xf2, 0xf3, 0xf4, + 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa}; +static const uint8_t kAcChromaBits[16] = {0, 2, 1, 2, 4, 4, 3, 4, + 7, 5, 4, 4, 0, 1, 2, 0x77}; +static const uint8_t kAcChromaVals[162] = { + 0x00, 0x01, 0x02, 0x03, 0x11, 0x04, 0x05, 0x21, 0x31, 0x06, 0x12, 0x41, + 0x51, 0x07, 0x61, 0x71, 0x13, 0x22, 0x32, 0x81, 0x08, 0x14, 0x42, 0x91, + 0xa1, 0xb1, 0xc1, 0x09, 0x23, 0x33, 0x52, 0xf0, 0x15, 0x62, 0x72, 0xd1, + 0x0a, 0x16, 0x24, 0x34, 0xe1, 0x25, 0xf1, 0x17, 0x18, 0x19, 0x1a, 0x26, + 0x27, 0x28, 0x29, 0x2a, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x43, 0x44, + 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, + 0x59, 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x73, 0x74, + 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, + 0x88, 0x89, 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, + 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4, + 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, + 0xc8, 0xc9, 0xca, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, + 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xf2, 0xf3, 0xf4, + 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa}; + +typedef struct { + uint16_t code[256]; + uint8_t len[256]; +} Huff; +static void build_huff(Huff* h, const uint8_t bits[16], const uint8_t* vals) { + memset(h, 0, sizeof(*h)); + uint16_t code = 0; + int k = 0; + for (int l = 1; l <= 16; l++) { + for (int i = 0; i < bits[l - 1]; i++) { + h->code[vals[k]] = code++; + h->len[vals[k]] = (uint8_t)l; + k++; + } + code <<= 1; + } +} + +typedef struct { + uint8_t* d; + size_t n, cap; + uint32_t acc; + int nbits; +} Out; +static void put(Out* o, uint8_t b) { + if (o->n == o->cap) { + o->cap = o->cap ? o->cap * 2 : 1 << 20; + o->d = realloc(o->d, o->cap); + if (!o->d) exit(3); + } + o->d[o->n++] = b; +} +static void put16(Out* o, int v) { + put(o, (uint8_t)(v >> 8)); + put(o, (uint8_t)v); +} +static void bits(Out* o, uint32_t v, int n) { + for (int i = n - 1; i >= 0; i--) { + o->acc = (o->acc << 1) | ((v >> i) & 1); + if (++o->nbits == 8) { + put(o, (uint8_t)o->acc); + if ((uint8_t)o->acc == 0xff) put(o, 0); // byte stuffing + o->acc = 0; + o->nbits = 0; + } + } +} +static void flush_bits(Out* o) { + while (o->nbits) bits(o, 1, 1); // pad with ones +} +static int magnitude(int v) { + int a = v < 0 ? -v : v, n = 0; + while (a) { + n++; + a >>= 1; + } + return n; +} +static void put_value(Out* o, int v, int n) { + if (n) bits(o, (uint32_t)(v < 0 ? v + (1 << n) - 1 : v), n); +} + +static void fdct(const uint8_t* src, int stride, double out[64]) { + static double c[8][8]; + static int init; + if (!init) { + for (int u = 0; u < 8; u++) + for (int x = 0; x < 8; x++) + c[u][x] = (u ? sqrt(2.0 / 8) : sqrt(1.0 / 8)) * + cos((2 * x + 1) * u * M_PI / 16); + init = 1; + } + double tmp[64]; + for (int y = 0; y < 8; y++) + for (int u = 0; u < 8; u++) { + double s = 0; + for (int x = 0; x < 8; x++) s += c[u][x] * (src[y * stride + x] - 128.0); + tmp[y * 8 + u] = s; + } + for (int u = 0; u < 8; u++) + for (int v = 0; v < 8; v++) { + double s = 0; + for (int y = 0; y < 8; y++) s += c[v][y] * tmp[y * 8 + u]; + out[v * 8 + u] = s; + } +} + +static void block(Out* o, const uint8_t* src, int stride, const uint8_t q[64], + int* dcPred, const Huff* dc, const Huff* ac) { + double f[64]; + fdct(src, stride, f); + int z[64]; + for (int i = 0; i < 64; i++) + z[i] = (int)lround(f[kZigzag[i]] / q[kZigzag[i]]); + int diff = z[0] - *dcPred; + *dcPred = z[0]; + int n = magnitude(diff); + bits(o, dc->code[n], dc->len[n]); + put_value(o, diff, n); + int run = 0; + for (int i = 1; i < 64; i++) { + if (!z[i]) { + run++; + continue; + } + while (run > 15) { + bits(o, ac->code[0xf0], ac->len[0xf0]); + run -= 16; + } + n = magnitude(z[i]); + int sym = (run << 4) | n; + bits(o, ac->code[sym], ac->len[sym]); + put_value(o, z[i], n); + run = 0; + } + if (run) bits(o, ac->code[0], ac->len[0]); +} + +static void dht(Out* o, int cls, int id, const uint8_t b[16], + const uint8_t* v) { + int n = 0; + for (int i = 0; i < 16; i++) n += b[i]; + put(o, (uint8_t)((cls << 4) | id)); + for (int i = 0; i < 16; i++) put(o, b[i]); + for (int i = 0; i < n; i++) put(o, v[i]); +} + +int main(int argc, char** argv) { + if (argc != 5 && argc != 6) { + fprintf(stderr, + "usage: mkmjpeg422 in.yuv(yuvj422p) width height out.mjpeg " + "[quality]\n"); + return 1; + } + int w = atoi(argv[2]), h = atoi(argv[3]), + quality = argc == 6 ? atoi(argv[5]) : 90; + if (w < 16 || h < 8 || w % 16 || h % 8 || w > 8192 || h > 8192 || + quality < 1 || quality > 100) { + fprintf(stderr, + "width must be a multiple of 16, height of 8, quality 1..100\n"); + return 1; + } + int scale = quality < 50 ? 5000 / quality : 200 - quality * 2; + uint8_t ql[64], qc[64]; + for (int i = 0; i < 64; i++) { + int a = (kStdLuma[i] * scale + 50) / 100, + b = (kStdChroma[i] * scale + 50) / 100; + ql[i] = (uint8_t)(a < 1 ? 1 : a > 255 ? 255 : a); + qc[i] = (uint8_t)(b < 1 ? 1 : b > 255 ? 255 : b); + } + Huff dcl, dcc, acl, acc; + build_huff(&dcl, kDcLumaBits, kDcLumaVals); + build_huff(&dcc, kDcChromaBits, kDcChromaVals); + build_huff(&acl, kAcLumaBits, kAcLumaVals); + build_huff(&acc, kAcChromaBits, kAcChromaVals); + FILE* in = fopen(argv[1], "rb"); + FILE* out = fopen(argv[4], "wb"); + if (!in || !out) { + fprintf(stderr, "cannot open the files\n"); + return 1; + } + size_t frameBytes = (size_t)w * h * 2; + uint8_t* f = malloc(frameBytes); + int frames = 0; + while (f && fread(f, 1, frameBytes, in) == frameBytes) { + const uint8_t *Y = f, *U = f + (size_t)w * h, *V = U + (size_t)w / 2 * h; + Out o = {0}; + put16(&o, 0xffd8); + put16(&o, 0xffdb); // DQT: two 8-bit tables, zigzag order + put16(&o, 2 + 2 * 65); + put(&o, 0); + for (int i = 0; i < 64; i++) put(&o, ql[kZigzag[i]]); + put(&o, 1); + for (int i = 0; i < 64; i++) put(&o, qc[kZigzag[i]]); + put16(&o, 0xffc0); // SOF0: 8 bits, three components, Y 2x1, Cb 1x1, Cr 1x1 + put16(&o, 17); + put(&o, 8); + put16(&o, h); + put16(&o, w); + put(&o, 3); + put(&o, 1), put(&o, 0x21), put(&o, 0); + put(&o, 2), put(&o, 0x11), put(&o, 1); + put(&o, 3), put(&o, 0x11), put(&o, 1); + put16(&o, 0xffc4); // DHT: the four standard tables + put16(&o, 2 + 4 * 17 + 12 + 12 + 162 + 162); + dht(&o, 0, 0, kDcLumaBits, kDcLumaVals); + dht(&o, 1, 0, kAcLumaBits, kAcLumaVals); + dht(&o, 0, 1, kDcChromaBits, kDcChromaVals); + dht(&o, 1, 1, kAcChromaBits, kAcChromaVals); + put16(&o, 0xffda); // SOS + put16(&o, 12); + put(&o, 3); + put(&o, 1), put(&o, 0x00); + put(&o, 2), put(&o, 0x11); + put(&o, 3), put(&o, 0x11); + put(&o, 0), put(&o, 63), put(&o, 0); + int py = 0, pu = 0, pv = 0; + for (int my = 0; my < h; my += 8) + for (int mx = 0; mx < w; mx += 16) { + block(&o, Y + (size_t)my * w + mx, w, ql, &py, &dcl, &acl); + block(&o, Y + (size_t)my * w + mx + 8, w, ql, &py, &dcl, &acl); + block(&o, U + (size_t)my * (w / 2) + mx / 2, w / 2, qc, &pu, &dcc, + &acc); + block(&o, V + (size_t)my * (w / 2) + mx / 2, w / 2, qc, &pv, &dcc, + &acc); + } + flush_bits(&o); + put16(&o, 0xffd9); + fwrite(o.d, 1, o.n, out); + free(o.d); + frames++; + } + free(f); + fclose(in); + fclose(out); + printf("wrote %d frames of %dx%d, 4:2:2 sampled 2x1/1x1/1x1, quality %d\n", + frames, w, h, quality); + return frames ? 0 : 2; +} diff --git a/GPU/decode/tests/gpu/vtjpegtest.c b/GPU/decode/tests/gpu/vtjpegtest.c new file mode 100644 index 00000000..0a3f7ac9 --- /dev/null +++ b/GPU/decode/tests/gpu/vtjpegtest.c @@ -0,0 +1,410 @@ +// vtjpegtest: drives our Motion JPEG decoder through the public VideoToolbox +// API and compares every frame with FFmpeg's decode of the same file. +// +// vtjpegtest -load bundle clip.mjpeg reference.yuv width height 420|422 +// [-dmb1] [-frames N] +// vtjpegtest -system clip.mjpeg reference.yuv width height 420|422 +// [-dmb1] [-frames N] +// the decoder VideoToolbox picks for a hardware decoder, as an app gets +// it: the installed JPEGVCNDecoder.bundle when it is in place (fails when +// it is not, or when its kext is not ready) +// vtjpegtest -apple clip.mjpeg reference.yuv width height 420|422 [-dmb1] +// the same with Apple's own software decoder, asked for the same pixel +// format: runs on the CPU only, checks the clip, the reference and this +// program's comparison without the GPU +// +// clip.mjpeg is a raw Motion JPEG stream (JPEG pictures one after the other, as +// `ffmpeg -c:v mjpeg -f mjpeg` writes it). reference.yuv holds the same frames +// as FFmpeg decodes them, planar and full range: yuvj420p for 420, yuvj422p for +// 422 (`ffmpeg -i clip.mjpeg -f rawvideo -pix_fmt yuvj4xxp reference.yuv`). +// +// -load registers the bundle in this process only, under the ID +// com.droga.vtjpegtest (VideoToolbox lists it as com.droga.vtjpegtest.jpeg or +// .dmb1), and the session asks for exactly that decoder: an installed plug-in +// or Apple's software decoders cannot serve it. Nothing is installed. +// -dmb1 uses the OpenDML codec type instead of 'jpeg'. -frames stops early. +// +// Checks, per frame: decoded without error, the pixel format is the one our +// decoder gives for the sampling ('420f' for 4:2:0, '422f' for 4:2:2), and +// every sample is within 2 of FFmpeg's (the block's IDCT rounds differently, +// a difference of 1 was seen on hardware). +// +// There is no switch to arm: a run goes to the GPU as soon as the VCNJpeg +// kext is loaded (it starts the block for the first picture). +// +// Exit status: 0 = every frame decoded and matched, 2 = a frame failed, +// differs or is missing, 1 = anything else. +#include +#include +#include +#include +#include +#include +#include +#include +#include + +static double now_ms(void) { + static mach_timebase_info_data_t tb; + if (!tb.denom) mach_timebase_info(&tb); + return (double)mach_absolute_time() * tb.numer / tb.denom / 1e6; +} + +static void copy_kv(const void* k, const void* v, void* dict) { + CFDictionarySetValue(dict, k, v); +} + +// Registers the bundle's decoder for one codec in this process only, under our +// own ID. Fails when nothing was registered. +static int load_bundle(const char* path, FourCharCode codec, + const char* fourcc) { + CFURLRef url = CFURLCreateFromFileSystemRepresentation( + NULL, (const UInt8*)path, (CFIndex)strlen(path), true); + CFBundleRef b = url ? CFBundleCreate(NULL, url) : NULL; + if (url) CFRelease(url); + if (!b || !CFBundleLoadExecutable(b)) { + fprintf(stderr, "cannot load %s\n", path); + return -1; + } + CFArrayRef impls = + CFBundleGetValueForInfoDictionaryKey(b, CFSTR("CMClassImplementations")); + OSStatus (*reg)(FourCharCode, CFDictionaryRef, void*) = + dlsym(RTLD_DEFAULT, "VTRegisterVideoDecoderWithInfo"); + CFStringRef want = + CFStringCreateWithCString(NULL, fourcc, kCFStringEncodingASCII); + int registered = 0; + for (CFIndex i = 0; impls && reg && want && i < CFArrayGetCount(impls); i++) { + CFDictionaryRef impl = CFArrayGetValueAtIndex(impls, i); + CFDictionaryRef match = CFDictionaryGetValue(impl, CFSTR("CMMatchingInfo")); + CFStringRef type = + match ? CFDictionaryGetValue(match, CFSTR("VTCodecType")) : NULL; + if (!type || !CFEqual(type, want)) continue; + CFStringRef fn = CFDictionaryGetValue(impl, CFSTR("CMFactoryFunction")); + void* factory = fn ? CFBundleGetFunctionPointerForName(b, fn) : NULL; + if (!factory) continue; + CFMutableDictionaryRef info = CFDictionaryCreateMutableCopy(NULL, 0, impl); + // dynamic registration ignores CMMatchingInfo: lift its keys to the top + CFDictionaryApplyFunction(match, copy_kv, info); + CFDictionarySetValue(info, CFSTR("CMClassImplementationID"), + CFSTR("com.droga.vtjpegtest")); + CFDictionarySetValue(info, CFSTR("IsHardwareAccelerated"), kCFBooleanTrue); + CFStringRef name = + CFDictionaryGetValue(impl, CFSTR("CMClassImplementationName")); + if (name) CFDictionarySetValue(info, CFSTR("CodecName"), name); + OSStatus st = reg(codec, info, factory); + CFRelease(info); + printf("registered %s from %s -> %d\n", fourcc, path, (int)st); + if (!st) registered++; + } + if (want) CFRelease(want); + if (!registered) { + fprintf(stderr, "no %s decoder of %s could be registered\n", fourcc, path); + return -1; + } + return 0; +} + +static uint8_t* read_all(const char* path, size_t* n) { + FILE* f = fopen(path, "rb"); + if (!f) return NULL; + fseek(f, 0, SEEK_END); + long len = ftell(f); + fseek(f, 0, SEEK_SET); + uint8_t* d = len > 0 ? malloc((size_t)len) : NULL; + if (d && fread(d, 1, (size_t)len, f) != (size_t)len) { + free(d); + d = NULL; + } + fclose(f); + *n = d ? (size_t)len : 0; + return d; +} + +// The next JPEG picture of a raw Motion JPEG stream: SOI, segments up to the +// scan, the scan (where FF is always stuffed or a restart marker), EOI. +static bool next_picture(const uint8_t* d, size_t n, size_t* at, size_t* start, + size_t* len) { + size_t i = *at; + while (i + 1 < n && !(d[i] == 0xff && d[i + 1] == 0xd8)) i++; + if (i + 1 >= n) return false; + size_t s = i; + i += 2; + while (1) { + if (i + 4 > n || d[i] != 0xff) return false; + uint8_t m = d[i + 1]; + if (m == 0xff) { // fill byte + i++; + continue; + } + size_t l = ((size_t)d[i + 2] << 8) | d[i + 3]; + if (l < 2 || i + 2 + l > n) return false; + i += 2 + l; + if (m == 0xda) break; + } + while (i + 1 < n) { + if (d[i] == 0xff && d[i + 1] != 0x00 && + !(d[i + 1] >= 0xd0 && d[i + 1] <= 0xd7)) { + if (d[i + 1] != 0xd9) return false; + *start = s; + *len = i + 2 - s; + *at = i + 2; + return true; + } + i++; + } + return false; +} + +typedef struct { + const uint8_t* ref; // reference frames, planar + size_t refFrames, frameBytes; + int w, h, chromaRows; + OSType wantFormat; + int frames, errors, wrongFormat, mismatches, missing; + int maxDiff; + double sqErr, samples; + double firstOut; +} Ctx; + +static void out_cb(void* refcon, void* frameRefcon, OSStatus st, + VTDecodeInfoFlags flags, CVImageBufferRef img, CMTime pts, + CMTime dur) { + (void)pts, (void)dur; + Ctx* c = refcon; + long idx = (long)frameRefcon; + if (st || !img) { + c->errors++; + printf("frame %ld: error %d flags %x\n", idx, (int)st, flags); + return; + } + c->frames++; + OSType f = CVPixelBufferGetPixelFormatType(img); + if (f != c->wantFormat) { + c->wrongFormat++; + printf( + "frame %ld: pixel format '%c%c%c%c', not the one our decoder gives\n", + idx, (char)(f >> 24), (char)(f >> 16), (char)(f >> 8), (char)f); + return; + } + if ((size_t)idx >= c->refFrames) { + c->missing++; + printf("frame %ld: no reference frame for it\n", idx); + return; + } + const uint8_t* ry = c->ref + (size_t)idx * c->frameBytes; + int cw = (c->w + 1) / 2; + const uint8_t* ru = ry + (size_t)c->w * c->h; + const uint8_t* rv = ru + (size_t)cw * c->chromaRows; + CVPixelBufferLockBaseAddress(img, kCVPixelBufferLock_ReadOnly); + const uint8_t* y = CVPixelBufferGetBaseAddressOfPlane(img, 0); + const uint8_t* uv = CVPixelBufferGetBaseAddressOfPlane(img, 1); + size_t ys = CVPixelBufferGetBytesPerRowOfPlane(img, 0), + uvs = CVPixelBufferGetBytesPerRowOfPlane(img, 1); + bool sizes = (int)CVPixelBufferGetWidth(img) == c->w && + (int)CVPixelBufferGetHeight(img) == c->h && + (int)CVPixelBufferGetHeightOfPlane(img, 1) == c->chromaRows; + int frameMax = 0; + if (sizes) { + for (int r = 0; r < c->h; r++) + for (int x = 0; x < c->w; x++) { + int dd = abs((int)y[r * ys + x] - (int)ry[(size_t)r * c->w + x]); + if (dd > frameMax) frameMax = dd; + c->sqErr += (double)dd * dd; + c->samples++; + } + for (int r = 0; r < c->chromaRows; r++) + for (int x = 0; x < cw; x++) { + int du = abs((int)uv[r * uvs + 2 * x] - (int)ru[(size_t)r * cw + x]); + int dv = + abs((int)uv[r * uvs + 2 * x + 1] - (int)rv[(size_t)r * cw + x]); + int dd = du > dv ? du : dv; + if (dd > frameMax) frameMax = dd; + c->sqErr += (double)du * du + (double)dv * dv; + c->samples += 2; + } + } + CVPixelBufferUnlockBaseAddress(img, kCVPixelBufferLock_ReadOnly); + if (!sizes) { + c->mismatches++; + printf("frame %ld: %zux%zu, not %dx%d\n", idx, CVPixelBufferGetWidth(img), + CVPixelBufferGetHeight(img), c->w, c->h); + return; + } + if (frameMax > c->maxDiff) c->maxDiff = frameMax; + if (frameMax > 2) { + c->mismatches++; + printf("frame %ld: differs from FFmpeg by up to %d\n", idx, frameMax); + } +} + +static int usage(void) { + fprintf(stderr, + "usage: vtjpegtest -load bundle clip.mjpeg reference.yuv width " + "height 420|422 [-dmb1] [-frames N]\n" + " vtjpegtest -system clip.mjpeg reference.yuv width height " + "420|422 [-dmb1] [-frames N] (the installed plug-in)\n" + " vtjpegtest -apple clip.mjpeg reference.yuv width height " + "420|422 [-dmb1] (CPU only)\n" + "A run goes to the GPU: there is no switch to arm.\n"); + return 1; +} + +int main(int argc, char** argv) { + const char* bundle = NULL; + bool apple = false, system = false; + const char* pos[5]; + int npos = 0, maxFrames = INT_MAX; + bool dmb1 = false; + for (int i = 1; i < argc; i++) { + if (!strcmp(argv[i], "-load") && i + 1 < argc) + bundle = argv[++i]; + else if (!strcmp(argv[i], "-apple")) + apple = true; + else if (!strcmp(argv[i], "-system")) + system = true; + else if (!strcmp(argv[i], "-dmb1")) + dmb1 = true; + else if (!strcmp(argv[i], "-frames") && i + 1 < argc) + maxFrames = atoi(argv[++i]); + else if (npos < 5) + pos[npos++] = argv[i]; + else + return usage(); + } + if ((!!bundle + apple + system) != 1 || npos != 5 || maxFrames < 1) + return usage(); + int w = atoi(pos[2]), h = atoi(pos[3]); + bool s422 = !strcmp(pos[4], "422"); + if (w < 1 || h < 1 || w > 16384 || h > 16384 || + (!s422 && strcmp(pos[4], "420"))) + return usage(); + FourCharCode codec = + dmb1 ? kCMVideoCodecType_JPEG_OpenDML : kCMVideoCodecType_JPEG; + const char* fourcc = dmb1 ? "dmb1" : "jpeg"; + if (bundle && load_bundle(bundle, codec, fourcc)) return 1; + + size_t clipLen = 0, refLen = 0; + uint8_t* clip = read_all(pos[0], &clipLen); + uint8_t* ref = read_all(pos[1], &refLen); + if (!clip || !ref) + return fprintf(stderr, "cannot read %s or %s\n", pos[0], pos[1]), 1; + Ctx c = {0}; + c.ref = ref; + c.w = w; + c.h = h; + c.chromaRows = s422 ? h : (h + 1) / 2; + c.frameBytes = (size_t)w * h + 2 * (size_t)((w + 1) / 2) * c.chromaRows; + c.refFrames = refLen / c.frameBytes; + c.wantFormat = s422 ? kCVPixelFormatType_422YpCbCr8BiPlanarFullRange + : kCVPixelFormatType_420YpCbCr8BiPlanarFullRange; + + CMVideoFormatDescriptionRef fmt = NULL; + OSStatus st = CMVideoFormatDescriptionCreate(NULL, codec, w, h, NULL, &fmt); + if (st) return fprintf(stderr, "format description %d\n", (int)st), 1; + CFMutableDictionaryRef spec = + CFDictionaryCreateMutable(NULL, 0, &kCFTypeDictionaryKeyCallBacks, + &kCFTypeDictionaryValueCallBacks); + CFMutableDictionaryRef dest = NULL; + if (system) { + // Apple's JPEG decoders are software ones: a hardware decoder for 'jpeg' + // or 'dmb1' on this Mac can only be ours. + CFDictionarySetValue( + spec, + kVTVideoDecoderSpecification_RequireHardwareAcceleratedVideoDecoder, + kCFBooleanTrue); + printf( + "asking VideoToolbox for any hardware decoder (the installed one)\n"); + } else if (!apple) { + CFDictionarySetValue( + spec, + kVTVideoDecoderSpecification_RequireHardwareAcceleratedVideoDecoder, + kCFBooleanTrue); + CFStringRef id = CFStringCreateWithFormat( + NULL, NULL, CFSTR("com.droga.vtjpegtest.%s"), fourcc); + CFDictionarySetValue(spec, CFSTR("DecoderID"), id); + printf( + "asking for decoder com.droga.vtjpegtest.%s (ours, loaded in this " + "process)\n", + fourcc); + CFRelease(id); + } else { + // Apple's decoder, converted by VideoToolbox to the format ours gives + dest = CFDictionaryCreateMutable(NULL, 0, &kCFTypeDictionaryKeyCallBacks, + &kCFTypeDictionaryValueCallBacks); + int32_t pf = (int32_t)c.wantFormat; + CFNumberRef n = CFNumberCreate(NULL, kCFNumberSInt32Type, &pf); + CFDictionarySetValue(dest, kCVPixelBufferPixelFormatTypeKey, n); + CFRelease(n); + printf( + "Apple's software decoder (no -load), output asked as the format ours " + "gives\n"); + } + VTDecompressionOutputCallbackRecord cb = {out_cb, &c}; + VTDecompressionSessionRef sess = NULL; + if (dest && + getenv("VTJPEG_NODEST")) { // debugging: Apple's own output format + CFRelease(dest); + dest = NULL; + } + st = VTDecompressionSessionCreate(NULL, fmt, spec, dest, &cb, &sess); + CFRelease(spec); + if (dest) CFRelease(dest); + printf("VTDecompressionSessionCreate = %d\n", (int)st); + if (st || !sess) return 1; + CFBooleanRef hw = NULL; + VTSessionCopyProperty( + sess, kVTDecompressionPropertyKey_UsingHardwareAcceleratedVideoDecoder, + NULL, &hw); + printf("UsingHardwareAcceleratedVideoDecoder = %s\n", + hw == kCFBooleanTrue ? "yes" : "no"); + if (hw) CFRelease(hw); + + size_t at = 0, start = 0, len = 0; + long fed = 0; + double t0 = now_ms(); + while (fed < maxFrames && next_picture(clip, clipLen, &at, &start, &len)) { + CMBlockBufferRef bb = NULL; + CMSampleBufferRef sb = NULL; + st = CMBlockBufferCreateWithMemoryBlock( + NULL, clip + start, len, kCFAllocatorNull, NULL, 0, len, 0, &bb); + CMSampleTimingInfo ti = {CMTimeMake(1, 30), CMTimeMake(fed, 30), + kCMTimeInvalid}; + size_t ss = len; + if (!st) + st = CMSampleBufferCreateReady(NULL, bb, fmt, 1, 1, &ti, 1, &ss, &sb); + if (!st) { + VTDecodeInfoFlags info = 0; + st = VTDecompressionSessionDecodeFrame(sess, sb, 0, (void*)fed, &info); + if (st) printf("DecodeFrame %ld -> %d\n", fed, (int)st); + } + if (sb) CFRelease(sb); + if (bb) CFRelease(bb); + if (st) c.errors++; + fed++; + } + VTDecompressionSessionWaitForAsynchronousFrames(sess); + double ms = now_ms() - t0; + VTDecompressionSessionInvalidate(sess); + CFRelease(sess); + CFRelease(fmt); + double psnr = + c.sqErr > 0 ? 10 * log10(255.0 * 255.0 * c.samples / c.sqErr) : INFINITY; + printf( + "fed %ld pictures (%s %s %dx%d), got %d frames in %.1f ms (%.2f ms " + "each)\n", + fed, fourcc, s422 ? "4:2:2" : "4:2:0", w, h, c.frames, ms, + fed ? ms / (double)fed : 0.0); + printf( + "errors %d, wrong pixel format %d, differ %d, no reference %d; max " + "difference %d, PSNR %.2f dB\n", + c.errors, c.wrongFormat, c.mismatches, c.missing, c.maxDiff, psnr); + bool ok = fed > 0 && c.frames == fed && !c.errors && !c.wrongFormat && + !c.mismatches && !c.missing; + printf("%s\n", + ok ? (apple ? "PASS: every frame from Apple's decoder, matching FFmpeg" + : "PASS: every frame from our decoder, matching FFmpeg") + : "FAIL"); + free(clip); + free(ref); + return ok ? 0 : 2; +} diff --git a/GPU/decode/tests/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, 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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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b, 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, 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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, 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0x3f, 0x70, 0x7a, 0x63, 0xd7, 0xbd, 0x53, 0xf0, 0x6e, 0xa3, 0x7f, + 0xa3, 0xc3, 0x73, 0x2d, 0xbe, 0x97, 0x73, 0xa8, 0x0b, 0x9f, 0x27, 0xfd, 0x50, 0x90, 0x04, 0xf2, + 0x8c, 0x83, 0xaa, 0x43, 0x2e, 0x72, 0x58, 0x8e, 0xd8, 0xdb, 0x5f, 0x9e, 0xf0, 0x6d, 0x59, 0x42, + 0x32, 0x8a, 0xda, 0xa4, 0x79, 0x5f, 0xca, 0x72, 0x92, 0xfc, 0x8f, 0xaf, 0xca, 0x78, 0x5f, 0x2d, + 0xcb, 0xb0, 0x7f, 0x58, 0xc3, 0x67, 0xb8, 0x4c, 0xc2, 0x71, 0x8b, 0x93, 0xa3, 0x45, 0x52, 0xe6, + 0x5a, 0xc9, 0x6b, 0xc9, 0x8a, 0xaa, 0xd6, 0xb2, 0xb7, 0xc3, 0xb9, 0x18, 0x0c, 0x05, 0x2c, 0x56, + 0x23, 0x88, 0xeb, 0xcd, 0x2e, 0x7c, 0x15, 0x6c, 0xa2, 0xb5, 0x39, 0x5b, 0x5b, 0xd4, 0xc3, 0xd7, + 0xa1, 0x28, 0xa7, 0x75, 0x64, 0xd5, 0x5b, 0xbd, 0xd3, 0xe5, 0x5a, 0x5e, 0xcd, 0x77, 0x70, 0x9c, + 0xe8, 0xe3, 0x23, 0x9d, 0x7d, 0x6a, 0xb5, 0x3c, 0xbe, 0x79, 0x8b, 0xcb, 0xa1, 0x2a, 0x75, 0xa5, + 0x15, 0x2c, 0x3c, 0xe8, 0x42, 0x73, 0x8c, 0x1a, 0x9b, 0xa4, 0xe5, 0x2a, 0xb0, 0x8c, 0xe7, 0x14, + 0xd4, 0x1f, 0x2c, 0x24, 0xd5, 0xd2, 0x67, 0xff, 0xd9, +}; diff --git a/GPU/decode/tests/jpegtest.c b/GPU/decode/tests/jpegtest.c new file mode 100644 index 00000000..ca151265 --- /dev/null +++ b/GPU/decode/tests/jpegtest.c @@ -0,0 +1,610 @@ +// jpegtest: the JPEG plug-in below its VideoToolbox side, with nothing sent to +// the GPU or the kernel. It checks: +// +// 1. jpeg/jpegprep.c gives the block the shape Mesa gives it (SOI, DQT, DHT, +// SOF0, SOS, scan, EOI) and the same picture: ImageIO decodes the +// original and the rewritten file to the same pixels; +// 2. a picture without Huffman tables (Motion JPEG) gets those of Annex K, +// and APPn/COM segments and fill bytes change nothing; +// 3. 4:2:2 is taken (as YUYV), what the block is not given (4:4:4, grey) is +// refused, and no +// prefix or damaged copy of a sample is read outside its buffer (the +// address sanitizer stops the program if one is); +// 4. jpeg/vcnjpeg.c against a made-up kext behind the transport: the +// session needs the plug-in armed and the kext's door; a picture comes +// back in an NV12 full-range buffer with the kext's pixels in place; a +// refused picture, a failed job, a decoder that stays busy and a reply +// that does not match are reported as the right kind of failure. +// +// usage: jpegtest (exit status 0 = pass) +#include +#include +#include +#include +#include +#include + +#include "jpegprep.h" +#include "jpegsamples.h" +#include "vcnjpeg.h" + +static int failures; +static void expect(const char* what, bool ok) { + printf("%s %s\n", ok ? "PASS" : "FAIL", what); + if (!ok) failures++; +} + +// RGBA pixels as ImageIO decodes them; NULL if it cannot. +static uint8_t* rgba(const uint8_t* d, size_t n, size_t* w, size_t* h) { + CFDataRef data = CFDataCreate(NULL, d, (CFIndex)n); + CGImageSourceRef src = CGImageSourceCreateWithData(data, NULL); + CGImageRef img = src ? CGImageSourceCreateImageAtIndex(src, 0, NULL) : NULL; + uint8_t* px = NULL; + if (img) { + *w = CGImageGetWidth(img); + *h = CGImageGetHeight(img); + px = calloc(*w * *h, 4); + CGColorSpaceRef cs = CGColorSpaceCreateWithName(kCGColorSpaceSRGB); + CGContextRef ctx = CGBitmapContextCreate(px, *w, *h, 8, *w * 4, cs, + kCGImageAlphaPremultipliedLast); + CGContextDrawImage(ctx, CGRectMake(0, 0, *w, *h), img); + CGContextRelease(ctx); + CGColorSpaceRelease(cs); + CGImageRelease(img); + } + if (src) CFRelease(src); + CFRelease(data); + return px; +} + +static bool same_picture(const uint8_t* a, size_t an, const uint8_t* b, + size_t bn) { + size_t aw = 0, ah = 0, bw = 0, bh = 0; + uint8_t* x = rgba(a, an, &aw, &ah); + uint8_t* y = rgba(b, bn, &bw, &bh); + bool ok = x && y && aw == bw && ah == bh && !memcmp(x, y, aw * ah * 4); + free(x); + free(y); + return ok; +} + +// The markers of a prepared file, in order, as text ("d8 db c4 c0 da d9"). +static void shape(const uint8_t* d, size_t n, char* out, size_t cap) { + size_t i = 2, p = 0; + p += snprintf(out + p, cap - p, "d8"); + while (i + 4 <= n && p + 8 < cap) { + uint8_t m = d[i + 1]; + p += snprintf(out + p, cap - p, " %02x", m); + size_t len = ((size_t)d[i + 2] << 8) | d[i + 3]; + i += 2 + len; + if (m == 0xda) break; + } + if (n >= 2 && d[n - 2] == 0xff && d[n - 1] == 0xd9) + snprintf(out + p, cap - p, " d9"); +} + +// A copy of a sample with one segment of marker `m` cut out (all of them). +static uint8_t* without(const uint8_t* d, size_t n, uint8_t m, size_t* outN) { + uint8_t* o = malloc(n); + size_t i = 2, p = 2; + memcpy(o, d, 2); + while (i + 4 <= n) { + uint8_t mk = d[i + 1]; + size_t len = ((size_t)d[i + 2] << 8) | d[i + 3]; + if (mk == 0xda) break; + if (mk != m) { + memcpy(o + p, d + i, 2 + len); + p += 2 + len; + } + i += 2 + len; + } + memcpy(o + p, d + i, n - i); + *outN = p + n - i; + return o; +} + +// ---- a made-up kext behind the transport +// --------------------------------------------- +static struct { + int calls, opens, closes; + int infoStatus; // what INFO answers (-1: no door) + uint32_t infoState; // the state bits INFO gives (JA_STATE_*) + uint64_t infoRoom; // and the room of the picture buffer + int runStatus; // what RUN answers + bool busy; // LOAD_USER says busy, always + int widthOff; // added to the width RUN reports + uint8_t jpeg[1 << 16]; // what LOAD_USER copied + size_t jpegLen; + uint32_t w, h, pitch, rows; + bool yuyv; // the picture is 4:2:2: one YUYV plane +} K; +static size_t k_bytes(void) { + return K.yuyv ? (size_t)K.pitch * K.rows : (size_t)K.pitch * K.rows * 3 / 2; +} +static uint8_t pattern(size_t i) { return (uint8_t)(i * 13 + 5); } +static int fake_call(void* ctx, const void* in, size_t inSize, void* out, + size_t* outSize) { + (void)ctx; + K.calls++; + struct ja_request rq; + memcpy(&rq, in, sizeof(rq)); + if (inSize < sizeof(rq) || rq.code != JA_CODE) return 0x2c2; + if (K.infoStatus == -1) return 0x2c2; // PowerPlay's refusal: no door + struct ja_reply rp = {JA_REPLY_MAGIC, JA_OK, 0, 0, {0}}; + uint8_t* data = (uint8_t*)out + sizeof(rp); + switch (rq.op) { + case JA_OP_INFO: + rp.status = (uint32_t)K.infoStatus; + rp.v[0] = K.infoState; + rp.v[1] = sizeof(K.jpeg); + rp.v[2] = K.infoRoom; + break; + case JA_OP_LOAD_USER: { + if (K.busy) { + rp.status = JA_BUSY; + break; + } + if (rq.arg1 > sizeof(K.jpeg)) { + rp.status = JA_BAD_REQUEST; + break; + } + memcpy(K.jpeg, (const void*)(uintptr_t)rq.arg0, rq.arg1); + K.jpegLen = rq.arg1; + JpegInfo info; + uint8_t* again = NULL; + size_t againLen = 0; + // the kext checks the stream again; a prepared file must come out + // unchanged + if (jpeg_prepare(K.jpeg, K.jpegLen, &again, &againLen, &info, NULL, 0) != + JPEG_OK || + againLen != K.jpegLen || memcmp(again, K.jpeg, againLen)) { + free(again); + rp.status = JA_BAD_STREAM; + break; + } + free(again); + K.w = info.width; + K.h = info.height; + K.yuyv = info.yuyv; + K.pitch = K.yuyv + ? (uint32_t)(((K.w + 15) / 16 * 16 * 2 + 255) / 256 * 256) + : (uint32_t)(((K.w + 15) / 16 * 16 + 255) / 256 * 256); + K.rows = (K.h + 15) / 16 * 16; + rp.v[0] = K.w; + rp.v[1] = K.h; + break; + } + case JA_OP_RUN: { + rp.status = (uint32_t)K.runStatus; + if (K.runStatus != JA_OK) break; + struct ja_picture pic = {K.w + (uint32_t)K.widthOff, + K.h, + K.pitch, + K.rows, + K.yuyv ? 0 : K.pitch * K.rows, + (uint32_t)k_bytes(), + 3, + K.yuyv ? 1u : 0u}; + memcpy(data, &pic, sizeof(pic)); + rp.dataBytes = sizeof(pic); + break; + } + case JA_OP_READ_USER: { + size_t bytes = k_bytes(); + if (rq.arg1 < bytes) { + rp.status = JA_BAD_REQUEST; + break; + } + uint8_t* dst = (uint8_t*)(uintptr_t)rq.arg0; + for (size_t i = 0; i < bytes; i++) dst[i] = pattern(i); + rp.v[0] = bytes; + break; + } + case JA_OP_RELEASE: + break; + default: + rp.status = JA_BAD_REQUEST; + } + memcpy(out, &rp, sizeof(rp)); + *outSize = sizeof(rp) + rp.dataBytes; + return 0; +} +static bool openFails; +static int dummyConn; +static void* fake_open(void) { + K.opens++; + return openFails ? NULL : &dummyConn; +} +static void fake_close(void* ctx) { + (void)ctx; + K.closes++; +} + +static CVPixelBufferRef got; +static uint32_t gotW, gotH; +static void on_picture(void* ctx, CVPixelBufferRef pb, const void* unused, + uint32_t w, uint32_t h, int64_t tag) { + (void)ctx, (void)unused, (void)tag; + if (got) CVPixelBufferRelease(got); + got = CVPixelBufferRetain(pb); + gotW = w; + gotH = h; +} + +// The kext's pattern is where the plug-in put it: luma row r at r * pitch, +// chroma after the luma rows. '422f' from the YUYV the made-up kext wrote: Y +// from the even bytes, Cb Cr from the odd ones. +static bool planes_hold_pattern_422(CVPixelBufferRef pb, uint32_t w, + uint32_t h) { + if (CVPixelBufferGetPixelFormatType(pb) != + kCVPixelFormatType_422YpCbCr8BiPlanarFullRange) + return false; + CVPixelBufferLockBaseAddress(pb, kCVPixelBufferLock_ReadOnly); + const uint8_t* y = CVPixelBufferGetBaseAddressOfPlane(pb, 0); + const uint8_t* uv = CVPixelBufferGetBaseAddressOfPlane(pb, 1); + size_t ys = CVPixelBufferGetBytesPerRowOfPlane(pb, 0), + uvs = CVPixelBufferGetBytesPerRowOfPlane(pb, 1); + bool ok = CVPixelBufferGetWidth(pb) == w && CVPixelBufferGetHeight(pb) == h && + CVPixelBufferGetHeightOfPlane(pb, 1) == h; + for (uint32_t r = 0; ok && r < h; r++) { + for (uint32_t c = 0; ok && c < w; c++) + ok = y[r * ys + c] == pattern((size_t)r * K.pitch + 2 * c); + for (uint32_t c = 0; ok && c < (w + 1) / 2 * 2; c++) + ok = uv[r * uvs + c] == pattern((size_t)r * K.pitch + 2 * c + 1); + } + CVPixelBufferUnlockBaseAddress(pb, kCVPixelBufferLock_ReadOnly); + return ok; +} +static bool planes_hold_pattern(CVPixelBufferRef pb, uint32_t w, uint32_t h) { + if (CVPixelBufferGetPixelFormatType(pb) != + kCVPixelFormatType_420YpCbCr8BiPlanarFullRange) + return false; + CVPixelBufferLockBaseAddress(pb, kCVPixelBufferLock_ReadOnly); + const uint8_t* y = CVPixelBufferGetBaseAddressOfPlane(pb, 0); + const uint8_t* uv = CVPixelBufferGetBaseAddressOfPlane(pb, 1); + size_t ys = CVPixelBufferGetBytesPerRowOfPlane(pb, 0), + uvs = CVPixelBufferGetBytesPerRowOfPlane(pb, 1); + bool ok = CVPixelBufferGetWidth(pb) == w && CVPixelBufferGetHeight(pb) == h; + for (uint32_t r = 0; ok && r < h; r++) + for (uint32_t c = 0; ok && c < w; c++) + ok = y[r * ys + c] == pattern((size_t)r * K.pitch + c); + size_t chromaAt = (size_t)K.pitch * K.rows; + for (uint32_t r = 0; ok && r < (h + 1) / 2; r++) + for (uint32_t c = 0; ok && c < (w + 1) / 2 * 2; c++) + ok = uv[r * uvs + c] == pattern(chromaAt + (size_t)r * K.pitch + c); + CVPixelBufferUnlockBaseAddress(pb, kCVPixelBufferLock_ReadOnly); + return ok; +} + +int main(void) { + setvbuf(stdout, NULL, _IOLBF, 0); + struct { + const uint8_t* d; + size_t n; + uint32_t w, h; + } ok420[] = {{kJpeg16x16, sizeof(kJpeg16x16), 16, 16}, + {kJpeg48x32, sizeof(kJpeg48x32), 48, 32}, + {kJpeg50x30, sizeof(kJpeg50x30), 50, 30}}; + char why[96], text[64]; + + // ---- 1. shape and picture ---- + bool shapes = true, pictures = true, sizes = true; + for (size_t k = 0; k < 3; k++) { + uint8_t* o = NULL; + size_t on = 0; + JpegInfo info; + int r = + jpeg_prepare(ok420[k].d, ok420[k].n, &o, &on, &info, why, sizeof(why)); + if (r != JPEG_OK) { + printf(" %s\n", why); + shapes = pictures = sizes = false; + continue; + } + shape(o, on, text, sizeof(text)); + shapes = shapes && !strcmp(text, "d8 db c4 c0 da d9"); + pictures = pictures && same_picture(ok420[k].d, ok420[k].n, o, on); + sizes = sizes && info.width == ok420[k].w && info.height == ok420[k].h && + on <= ok420[k].n + kJpegPrepExtra; + // what comes out goes in again unchanged (the kext checks it again) + uint8_t* o2 = NULL; + size_t on2 = 0; + shapes = shapes && + jpeg_prepare(o, on, &o2, &on2, &info, NULL, 0) == JPEG_OK && + on2 == on && !memcmp(o, o2, on); + free(o2); + free(o); + } + expect( + "16x16, 48x32 and 50x30: SOI, DQT, DHT, SOF0, SOS, scan, EOI, and " + "nothing else", + shapes); + expect( + "ImageIO decodes the original and the rewritten file to the same pixels", + pictures); + expect("the size comes from the frame header", sizes); + + // ---- 2. Motion JPEG without tables; segments that are dropped ---- + uint8_t *base = NULL, *o = NULL; + size_t baseN = 0, on = 0, cutN = 0; + JpegInfo info; + jpeg_prepare(kJpeg48x32, sizeof(kJpeg48x32), &base, &baseN, &info, NULL, 0); + uint8_t* cut = without(kJpeg48x32, sizeof(kJpeg48x32), 0xc4, &cutN); + int r = jpeg_prepare(cut, cutN, &o, &on, &info, why, sizeof(why)); + expect( + "without its DHT the picture gets Annex K's tables, byte for byte what " + "FFmpeg wrote", + r == JPEG_OK && info.stdTables && on == baseN && !memcmp(o, base, on)); + expect("and ImageIO, given the result, decodes the original picture", + r == JPEG_OK && same_picture(kJpeg48x32, sizeof(kJpeg48x32), o, on)); + free(o); + free(cut); + // APP1 + COM + fill bytes in front of SOF0 + size_t extraN = sizeof(kJpeg48x32) + 32; + uint8_t* extra = malloc(extraN); + memcpy(extra, kJpeg48x32, 2); + static const uint8_t junk[] = {0xff, 0xe1, 0x00, 0x08, 'E', 'x', 'i', 'f', + 0, 0, 0xff, 0xfe, 0x00, 0x06, 'h', 'e', + 'l', 'l', 0xff, 0xff, 0xff, 0xe2, 0x00, 0x0a, + 1, 2, 3, 4, 5, 6, 7, 8}; + memcpy(extra + 2, junk, sizeof(junk)); + memcpy(extra + 2 + sizeof(junk), kJpeg48x32 + 2, sizeof(kJpeg48x32) - 2); + o = NULL; + r = jpeg_prepare(extra, extraN, &o, &on, &info, why, sizeof(why)); + expect("APP1, COM and fill bytes are dropped: the same bytes as without them", + r == JPEG_OK && on == baseN && !memcmp(o, base, on)); + free(o); + free(extra); + + // ---- 3. refused, cut and damaged ---- + o = NULL; + r = jpeg_prepare(kJpeg422, sizeof(kJpeg422), &o, &on, &info, why, + sizeof(why)); + expect("4:2:2 (ffmpeg's 2x2/1x2/1x2) is taken, as YUYV", + r == JPEG_OK && o && info.yuyv && info.width == 32); + free(o); + { + // the other sampling forms Mesa takes or refuses on this block + static const uint8_t forms[][4] = {{0x21, 0x11, 0x11, JPEG_OK}, + {0x22, 0x21, 0x21, JPEG_OK}, + {0x11, 0x11, 0x11, JPEG_UNSUPPORTED}, + {0x12, 0x11, 0x11, JPEG_UNSUPPORTED}}; + bool all = true; + for (size_t f = 0; f < sizeof(forms) / sizeof(forms[0]); f++) { + uint8_t* c = malloc(sizeof(kJpeg48x32)); + memcpy(c, kJpeg48x32, sizeof(kJpeg48x32)); + for (size_t i = 2; i + 20 < sizeof(kJpeg48x32); i++) + if (c[i] == 0xff && c[i + 1] == 0xc0) { + c[i + 11] = forms[f][0]; + c[i + 14] = forms[f][1]; + c[i + 17] = forms[f][2]; + break; + } + o = NULL; + int rr = + jpeg_prepare(c, sizeof(kJpeg48x32), &o, &on, &info, why, sizeof(why)); + all = all && rr == forms[f][3] && (rr != JPEG_OK || info.yuyv) && + (rr == JPEG_OK || !o); + free(o); + free(c); + } + expect( + "sampling 211111 and 222121 are YUYV too; 4:4:4 and 4:4:0 are refused", + all); + } + { + // EOI replaced by fill bytes: the sample ends in 0xff 0xff. The copy has + // the exact size, so a read past its end is caught by the sanitizer. + size_t n = sizeof(kJpeg48x32); + uint8_t* c = malloc(n); + memcpy(c, kJpeg48x32, n); + c[n - 1] = 0xff; + o = NULL; + r = jpeg_prepare(c, n, &o, &on, &info, why, sizeof(why)); + expect( + "a sample that ends in fill bytes instead of EOI is refused, nothing " + "read past it", + r != JPEG_OK && !o); + free(o); + free(c); + } + { + // a scan that names another component than the frame: refused here, and + // by the kext again + uint8_t* c = malloc(sizeof(kJpeg48x32)); + memcpy(c, kJpeg48x32, sizeof(kJpeg48x32)); + bool found = false; + for (size_t i = 2; i + 6 < sizeof(kJpeg48x32); i++) + if (c[i] == 0xff && c[i + 1] == 0xda) { + c[i + 5] ^= 0x40; + found = true; + break; + } + o = NULL; + r = jpeg_prepare(c, sizeof(kJpeg48x32), &o, &on, &info, why, sizeof(why)); + expect("a scan that names other components than the frame is refused", + found && r == JPEG_BAD && !o); + free(o); + free(c); + } + bool prefixes = true; + for (size_t n = 0; n < sizeof(kJpeg48x32) - 1; n++) { + uint8_t* copy = malloc(n ? n : 1); + memcpy(copy, kJpeg48x32, n); + o = NULL; + r = jpeg_prepare(copy, n, &o, &on, &info, NULL, 0); + // a prefix that ends inside the scan has no EOI: refused + prefixes = prefixes && r != JPEG_OK && !o; + free(copy); + } + expect("every prefix of a sample is refused, nothing read past it", prefixes); + uint32_t seed = 1, accepted = 0; + for (int k = 0; k < 40000; k++) { + size_t n = ok420[k % 3].n; + uint8_t* copy = malloc(n); + memcpy(copy, ok420[k % 3].d, n); + int flips = 1 + k % 8; + for (int f = 0; f < flips; f++) { + seed = seed * 1664525u + 1013904223u; + size_t at = + (seed >> 8) % (k % 2 ? 200 : n); // half of them in the headers + seed = seed * 1664525u + 1013904223u; + copy[at] = k % 5 == 0 ? (uint8_t)(seed >> 24) + : copy[at] ^ (uint8_t)(1u << ((seed >> 8) % 8)); + } + o = NULL; + r = jpeg_prepare(copy, n, &o, &on, &info, NULL, 0); + if (r == JPEG_OK) { + accepted++; + if (on > n + kJpegPrepExtra) prefixes = false; + } + free(o); + free(copy); + } + printf(" (%u of 40000 damaged copies still had the shape of a JPEG)\n", + accepted); + expect("40000 damaged copies are read without a fault", prefixes); + + // ---- 4. the session against a made-up kext ---- + vcnjpeg_transport = fake_call; + vcnjpeg_transport_open = fake_open; + vcnjpeg_transport_close = fake_close; + char err[160] = ""; + VcnJpeg* d = vcnjpeg_create(16384, 16384, err, sizeof(err)); + expect("no session before the plug-in arms it, and nothing is opened", + !d && K.opens == 0); + vcnjpeg_gpu_armed = 1; + K.infoStatus = -1; + d = vcnjpeg_create(16384, 16384, err, sizeof(err)); + expect( + "no session without the kext's door (PowerPlay refuses the request), and " + "the connection is closed", + !d && K.opens == 1 && K.closes == 1 && strstr(err, "not loaded")); + K.infoStatus = JA_NOT_READY; + d = vcnjpeg_create(16384, 16384, err, sizeof(err)); + expect("no session while the kext's decoder is not ready", + !d && K.closes == 2); + openFails = true; + d = vcnjpeg_create(16384, 16384, err, sizeof(err)); + expect("no session when the accelerator cannot be opened", + !d && K.closes == 2); + openFails = false; + K.infoStatus = JA_OK; + K.infoRoom = 1u << 24; + K.infoState = JA_STATE_POOL | JA_STATE_CREATED | JA_STATE_STUCK; + int closesBefore = K.closes; + d = vcnjpeg_create(16384, 16384, err, sizeof(err)); + expect( + "no session while the kext's decoder is stuck, and the connection is " + "closed", + !d && K.closes == closesBefore + 1 && strstr(err, "stuck")); + K.infoState = JA_STATE_CREATED; + d = vcnjpeg_create(16384, 16384, err, sizeof(err)); + expect("no session when the kext has no buffers", + !d && K.closes == closesBefore + 2); + K.infoState = JA_STATE_POOL | JA_STATE_CREATED; + K.runStatus = JA_OK; + d = vcnjpeg_create(16384, 16384, err, sizeof(err)); + expect("a session with the door open", d != NULL); + // 16 MiB of room: 2048x2048 fits in both layouts, 4:2:2 at 2896x2896 does not + expect( + "the size check: 1920x1080 and 2048x2048 fit 16 MiB, 2896x2896 and " + "16384x16384 do not", + d && vcnjpeg_fits(d, 1920, 1080) && vcnjpeg_fits(d, 2048, 2048) && + !vcnjpeg_fits(d, 2896, 2896) && !vcnjpeg_fits(d, 16384, 16384)); + { + // A small frame whose SOF says 4096x4096: more than the kext's 16 MiB. It + // must be refused before anything is allocated for it or sent. + uint8_t* big = malloc(sizeof(kJpeg16x16)); + memcpy(big, kJpeg16x16, sizeof(kJpeg16x16)); + for (size_t i = 2; i + 9 < sizeof(kJpeg16x16); i++) + if (big[i] == 0xff && big[i + 1] == 0xc0) { + big[i + 5] = 0x10, big[i + 6] = 0x00; // height 4096 + big[i + 7] = 0x10, big[i + 8] = 0x00; // width 4096 + break; + } + int before = K.calls; + expect( + "a frame whose header asks for more than the kext's buffer is refused " + "as the stream's, nothing sent", + d && vcnjpeg_decode(d, big, sizeof(kJpeg16x16), 0, on_picture, NULL) && + vcnjpeg_failure(d) == VCNJPEG_FAIL_STREAM && K.calls == before && + strstr(vcnjpeg_last_error(d), "kext's buffer")); + free(big); + } + bool pics = d != NULL; + for (size_t k = 0; pics && k < 3; k++) { + int calls = K.calls; + pics = !vcnjpeg_decode(d, ok420[k].d, ok420[k].n, 0, on_picture, NULL) && + got && gotW == ok420[k].w && gotH == ok420[k].h && + planes_hold_pattern(got, ok420[k].w, ok420[k].h) && + K.calls == calls + 3; + if (!pics) printf(" %s\n", vcnjpeg_last_error(d)); + } + expect( + "16x16, 48x32 and 50x30 come back in NV12 full range, the kext's pixels " + "in place, in three calls", + pics); + CFTypeRef matrix = + got ? CVBufferCopyAttachment(got, kCVImageBufferYCbCrMatrixKey, NULL) + : NULL; + expect("the picture says BT.601 (JFIF)", + matrix && CFEqual(matrix, kCVImageBufferYCbCrMatrix_ITU_R_601_4)); + if (matrix) CFRelease(matrix); + int calls = K.calls; + bool p422 = + d && + !vcnjpeg_decode(d, kJpeg422, sizeof(kJpeg422), 0, on_picture, NULL) && + got && gotW == 32 && gotH == 16 && planes_hold_pattern_422(got, 32, 16) && + K.calls == calls + 3; + if (!p422 && d) printf(" %s\n", vcnjpeg_last_error(d)); + expect( + "a 4:2:2 picture comes back as '422f', the kext's YUYV split into its " + "planes, in three calls", + p422); + if (d) { + vcnjpeg_destroy(d); + d = vcnjpeg_create(32, 32, err, sizeof(err)); + } + calls = K.calls; + expect( + "a picture larger than the session allows fails as the stream's, nothing " + "sent", + d && + vcnjpeg_decode(d, kJpeg48x32, sizeof(kJpeg48x32), 0, on_picture, + NULL) && + vcnjpeg_failure(d) == VCNJPEG_FAIL_STREAM && K.calls == calls); + vcnjpeg_destroy(d); + d = vcnjpeg_create(16384, 16384, err, sizeof(err)); + K.runStatus = JA_FAILED; + expect("a job that fails in the kext is a device failure", + d && + vcnjpeg_decode(d, kJpeg16x16, sizeof(kJpeg16x16), 0, on_picture, + NULL) && + vcnjpeg_failure(d) == VCNJPEG_FAIL_DEVICE); + K.runStatus = JA_OK; + K.widthOff = 16; + expect("a picture of another size than the one sent is a device failure", + d && + vcnjpeg_decode(d, kJpeg16x16, sizeof(kJpeg16x16), 0, on_picture, + NULL) && + vcnjpeg_failure(d) == VCNJPEG_FAIL_DEVICE); + K.widthOff = 0; + K.busy = true; + CFAbsoluteTime t0 = CFAbsoluteTimeGetCurrent(); + bool busy = + d && + vcnjpeg_decode(d, kJpeg16x16, sizeof(kJpeg16x16), 0, on_picture, NULL) && + vcnjpeg_failure(d) == VCNJPEG_FAIL_DEVICE; + double waited = CFAbsoluteTimeGetCurrent() - t0; + expect( + "a decoder another process keeps busy for a second is a device failure", + busy && waited >= 0.9 && waited < 3); + K.busy = false; + int closes = K.closes; + vcnjpeg_destroy(d); + expect("destroy gives the decoder back and closes the connection", + K.closes == closes + 1); + if (got) CVPixelBufferRelease(got); + free(base); + return failures ? 1 : 0; +} diff --git a/GPU/decode/tests/plugintest.c b/GPU/decode/tests/plugintest.c index 16709908..d6a69f54 100644 --- a/GPU/decode/tests/plugintest.c +++ b/GPU/decode/tests/plugintest.c @@ -1,8 +1,9 @@ // plugintest: the VideoToolbox side of a decoder plug-in, with the decoder // session replaced by a stand-in (nothing opens the GPU or the driver). Built -// once for each plug-in, with -DTEST_AV1, -DTEST_VP9, -DTEST_MPEG2, -DTEST_VC1 -// or -DTEST_MPEG4 (the last three share common/vtlegacy.h and have no hidden -// frames: their sample 6 is one more shown frame). It checks: +// once for each plug-in, with -DTEST_AV1, -DTEST_VP9, -DTEST_JPEG, +// -DTEST_MPEG2, -DTEST_VC1 or -DTEST_MPEG4 (the last three share +// common/vtlegacy.h and have no hidden frames: their sample 6 is one more shown +// frame). It checks: // // 1. the factory refuses a NULL result pointer; // 2. a second session start replaces the decoder of the first; @@ -76,6 +77,12 @@ typedef VcnAV1OutputFn OutputFn; #define CREATE VP9VCN_VTDecoder_CreateInstance typedef VcnVP9 Vcn; typedef VcnVP9OutputFn OutputFn; +#elif defined(TEST_JPEG) +#include "../jpeg/JPEGVCNDecoder.c" +#define CODEC kCMVideoCodecType_JPEG +#define CREATE JPEGVCN_VTDecoder_CreateInstance +typedef VcnJpeg Vcn; +typedef VcnJpegOutputFn OutputFn; #elif defined(TEST_MPEG2) || defined(TEST_VC1) || defined(TEST_MPEG4) #define TEST_LEGACY 1 #if defined(TEST_MPEG2) @@ -98,7 +105,7 @@ typedef void Vcn; typedef VcnLegacyOutputFn OutputFn; #else #error \ - "build with -DTEST_AV1, -DTEST_VP9, -DTEST_MPEG2, -DTEST_VC1 or -DTEST_MPEG4" + "build with -DTEST_AV1, -DTEST_VP9, -DTEST_JPEG, -DTEST_MPEG2, -DTEST_VC1 or -DTEST_MPEG4" #endif #undef dispatch_semaphore_wait #undef dispatch_sync @@ -333,7 +340,7 @@ const VcnLegacyCodec FAKE_CODEC = {.name = "stand-in", .last_error = legacy_last_error, .failure = legacy_failure, .firmware_errors = legacy_firmware_errors}; -#else +#elif defined(TEST_VP9) int vcnvp9_gpu_armed; VcnVP9* vcnvp9_create(uint32_t w, uint32_t h, char* err, size_t n) { (void)w, (void)h, (void)err, (void)n; @@ -378,6 +385,50 @@ void vcnvp9_color(VcnVP9* d, VcnColor* c) { (void)d; *c = streamColor; } +#else +int vcnjpeg_gpu_armed; +VcnJpeg* vcnjpeg_create(uint32_t w, uint32_t h, char* err, size_t n) { + (void)w, (void)h, (void)err, (void)n; + return fake_create(); +} +void vcnjpeg_destroy(VcnJpeg* d) { fake_destroy(d); } +bool vcnjpeg_fits(VcnJpeg* d, uint32_t w, uint32_t h) { + (void)d, (void)w, (void)h; + return true; +} +const char* vcnjpeg_last_error(VcnJpeg* d) { + (void)d; + return "stand-in"; +} +unsigned vcnjpeg_firmware_errors(VcnJpeg* d) { + (void)d; + return 0; +} +CFDictionaryRef vcnjpeg_copy_pixel_buffer_attributes(uint32_t w, uint32_t h, + bool t) { + (void)w, (void)h, (void)t; + return CFDictionaryCreate(NULL, NULL, NULL, 0, NULL, NULL); +} +int vcnjpeg_decode(VcnJpeg* d, const uint8_t* chunk, size_t size, int64_t tag, + VcnJpegOutputFn fn, void* ctx) { + (void)size; + fake_decode_begin(d); + if (chunk[0] == 5) slow_decode(); + if (chunk[0] == 1 || chunk[0] == 2 || chunk[0] == 5) + fn(ctx, picture, NULL, 16, 16, tag); + hiddenOnly = chunk[0] == 6; + lastFailure = fake_failure(chunk[0]); + fake_decode_end(); + return (chunk[0] >= 2 && chunk[0] <= 4) || chunk[0] == 7 ? -1 : 0; +} +int vcnjpeg_failure(VcnJpeg* d) { + (void)d; + return lastFailure; +} +CVPixelBufferRef vcnjpeg_hidden_picture(VcnJpeg* d) { + (void)d; + return hiddenOnly ? picture : NULL; +} #endif #if defined(TEST_AV1) @@ -394,13 +445,20 @@ static int fake_failure(uint8_t what) { : what == 7 ? VCNLEGACY_FAIL_REFERENCE : VCNLEGACY_FAIL_STREAM; } -#else +#elif defined(TEST_VP9) static int fake_failure(uint8_t what) { return what == 3 ? VCNVP9_FAIL_DEVICE : what == 4 ? VCNVP9_FAIL_MEMORY : what == 7 ? VCNVP9_FAIL_REFERENCE : VCNVP9_FAIL_STREAM; } +#else +static int fake_failure(uint8_t what) { + return what == 3 ? VCNJPEG_FAIL_DEVICE + : what == 4 ? VCNJPEG_FAIL_MEMORY + : what == 7 ? VCNJPEG_FAIL_REFERENCE + : VCNJPEG_FAIL_STREAM; +} #endif // ---- helpers @@ -445,7 +503,7 @@ static CMVideoFormatDescriptionRef format(CMVideoCodecType codec, return f; } -#if !defined(TEST_LEGACY) +#if defined(TEST_AV1) || defined(TEST_VP9) static VTVideoDecoderRef dec; // Test 16: a format description with colour extensions; NULL values are left // out. @@ -757,7 +815,7 @@ int main(void) { CFRelease(nomem); expect("a new start takes the format again", !dec_start_session(dec, NULL, fmt) && dec_can_accept_format(dec, fmt)); -#if !defined(TEST_LEGACY) +#if defined(TEST_AV1) || defined(TEST_VP9) color_tests(); expect("the session takes the first format again", !dec_start_session(dec, NULL, fmt) && dec_can_accept_format(dec, fmt)); diff --git a/GPU/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--