From 065a44e992c46b4eeaeb7183a32a20036bccf748 Mon Sep 17 00:00:00 2001 From: DrogaBox Date: Wed, 25 Nov 2026 09:42:57 -0300 Subject: [PATCH 1/3] GPU decoders 0.3.6: a session from before a system sleep is not used again A user reports that with the AV1 and VP9 decoders a wake from sleep hangs the Mac a while later, with glitches first, and that right after a wake a VP9 video was red and broken in Chrome while Safari played it fine. His log shows Chrome's decoder process keeping two VP9 sessions open across the sleep, an AV1 session it opened after the wake never decoding a frame, and the hang after the next wake. Read in IDA (AMDRadeonX6000, 26.7.3 KDK): the kernel keeps a decoder's video context across a sleep but stops the VCN rings before it (systemWillSleep -> setSuspendResumeState(false)) and starts the engine again at wake (powerUpHW, internalDidWake -> enableContext), restoring only clocks and the power client; saveVCNSession is empty. Nothing tells the program: AMDRadeonVADriver2, AppleGVA and VideoToolbox have no sleep handling. AMDRadeonVADriver2 sends the engine a create-session command when a decoder opens and a destroy-session command, waited for with no time limit, when it closes. So, in decode/common: - vcn_sleep_mark: the time spent asleep since boot (mach_continuous_time minus mach_absolute_time) and kern.waketime. No notification: the decoder service's sandbox does not allow the user client IORegisterForSystemPower opens. - vcn_session_lost: a session opened before a sleep writes nothing more into its bitstream pool and schedules nothing; its frames fail as a malfunction, so VideoToolbox makes a new session. - vcn_session_close of such a session skips DeleteContexts, FreeBitstreamBufferPool and DeleteDriver and only destroys the accelerator, on the background queue; the kernel's close of the video context sends the engine nothing. - vcn_session_open refuses while a session of the same process from before a sleep is still open, in any of the plug-ins (they ask each other through the local notification center): VideoToolbox decodes in software until those are closed. AV1, VP9 and the legacy decoders call it. vtvp9test gets -renew and a line per pass, vtav1test -loop and -renew, for a sleep test. New tests: sessiontest section 12 and staletest (two plug-ins in one process), with a made-up sleep. Not run on a GPU or across a real sleep. --- GPU/CHANGELOG.md | 25 +++++ GPU/decode/VERSION | 2 +- GPU/decode/av1/vcnav1.c | 17 +++- GPU/decode/build.sh | 11 ++- GPU/decode/common/vcndriver.c | 25 +++++ GPU/decode/common/vcndriver.h | 76 +++++++++++++-- GPU/decode/common/vcnlegacy.c | 15 ++- GPU/decode/common/vcnsession.c | 160 ++++++++++++++++++++++++++++--- GPU/decode/tests/gpu/README.md | 7 +- GPU/decode/tests/gpu/vtav1test.c | 98 ++++++++++++++----- GPU/decode/tests/gpu/vtvp9test.c | 58 +++++++++-- GPU/decode/tests/sessiontest.c | 133 ++++++++++++++++++++++++- GPU/decode/tests/stalelib.c | 81 ++++++++++++++++ GPU/decode/tests/staletest.c | 83 ++++++++++++++++ GPU/decode/vp9/vcnvp9.c | 17 +++- GPU/docs/how-it-works.md | 41 ++++++++ GPU/docs/testing.md | 10 ++ GPU/tests/run.sh | 6 +- 18 files changed, 799 insertions(+), 66 deletions(-) create mode 100644 GPU/decode/tests/stalelib.c create mode 100644 GPU/decode/tests/staletest.c diff --git a/GPU/CHANGELOG.md b/GPU/CHANGELOG.md index 24a1cfcd..fde5abd3 100644 --- a/GPU/CHANGELOG.md +++ b/GPU/CHANGELOG.md @@ -2,6 +2,31 @@ The encoding fix keeps its own history in `encode/CHANGELOG.md`. +## Decoders 0.3.6 (not released; host tests only) + +- A decode session from before a system sleep is no longer used after it. A user reported + that with the AV1 and VP9 decoders a wake from sleep hung the Mac a while later, with + glitches before it, and that a VP9 video came out red and broken in Chrome right after a + wake while Safari played it fine. Apple's kernel driver keeps a decoder's video context + across a sleep but restarts the video engine under it, and nothing tells the program + (see "A system sleep" in `docs/how-it-works.md`). The plug-ins now notice a sleep from the + time the Mac spent asleep or the time of its last wake, with no notification. A session + opened before it writes and sends nothing more: its frames fail as a malfunction + (-12911), so VideoToolbox makes a new session, and the host gets a working decoder again + or falls back to software. Closing such a session leaves out the driver's own teardown, + which would send the restarted engine a command for the lost session and wait for it + with no time limit; only the accelerator's connections are closed, on a background + thread. The MPEG-2, VC-1 and MPEG-4 decoders share the code and get the same. +- While such a session is still open in a process, no new session opens there, in any of + the plug-ins: VideoToolbox decodes the new stream in software until the old sessions are + closed. The reporter's log showed why: a browser's decoder process kept two VP9 sessions + open across a sleep, the AV1 session it opened after the wake never decoded a frame, and + the Mac hung after the next wake. +- `vtvp9test` has `-renew` (a new session for every `-loop` pass, in the same process) and + prints a line per pass with the time; `vtav1test` gets `-loop` and `-renew` too. They are + for the sleep test in `docs/testing.md`. +- Not run across a real sleep yet. + ## 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/decode/VERSION b/GPU/decode/VERSION index c2c0004f..449d7e73 100644 --- a/GPU/decode/VERSION +++ b/GPU/decode/VERSION @@ -1 +1 @@ -0.3.5 +0.3.6 diff --git a/GPU/decode/av1/vcnav1.c b/GPU/decode/av1/vcnav1.c index 9d97a5d7..3e394687 100644 --- a/GPU/decode/av1/vcnav1.c +++ b/GPU/decode/av1/vcnav1.c @@ -258,7 +258,7 @@ static void destroy_now(VcnAV1* d) { void vcnav1_destroy(VcnAV1* d) { if (!d) return; - vcn_teardown(d->stuck, vlog(), "AV1 session", ^{ + vcn_teardown(d->stuck, vcn_session_lost(&d->s), vlog(), "AV1 session", ^{ destroy_now(d); }); } @@ -647,6 +647,15 @@ static int on_frame(void* vctx, AV1Parser* p, AV1ParseResult kind) { d->dpb[slot] = target; pack_seq(d); pack_frame(d); + // Nothing goes into the pool or to the engine for a session from before a + // system sleep (vcndriver.h). + if (vcn_session_lost(&d->s)) { + d->broken = true; + d->failure = VCNAV1_FAIL_DEVICE; + snprintf(d->err, sizeof(d->err), "%s", + "the system slept since this session opened"); + return -1; + } // bitstream: concatenated tile data int bi = d->bsNext; d->bsNext = (d->bsNext + 1) % NUM_BS; @@ -743,10 +752,12 @@ int vcnav1_decode(VcnAV1* d, const uint8_t* tu, size_t size, int64_t userTag, CVPixelBufferRelease(d->hidden); d->hidden = NULL; } + if (!d->broken && vcn_session_lost(&d->s)) d->broken = true; if (d->broken) { snprintf(d->err, sizeof(d->err), "session stopped: %s", - d->stuck ? "the GPU did not finish an earlier frame" - : "an earlier driver call failed"); + d->stuck ? "the GPU did not finish an earlier frame" + : d->s.lost ? "the system slept since it opened" + : "an earlier driver call failed"); d->failure = VCNAV1_FAIL_DEVICE; return -1; } diff --git a/GPU/decode/build.sh b/GPU/decode/build.sh index 5812415c..606504b6 100755 --- a/GPU/decode/build.sh +++ b/GPU/decode/build.sh @@ -109,8 +109,17 @@ if [[ ${1:-} == tests ]]; then -o $T/legacypick 2>&1 | { grep -v -E "pointer not aligned in '_k(Base|Decoder)Class'|disabling chained fixups" || true; } xcrun clang $TFLAGS -Icommon tests/acceltest.c common/vcndriver.c -framework CoreFoundation -framework IOKit \ -o $T/acceltest - xcrun clang $TFLAGS -Icommon tests/waittest.c common/vcnsession.c -framework CoreFoundation -framework IOKit \ + # vcndriver.c for vcn_sleep_mark, which vcnsession.c reads when a session opens or closes + xcrun clang $TFLAGS -Icommon tests/waittest.c common/vcnsession.c common/vcndriver.c -framework CoreFoundation \ + -framework IOKit \ -o $T/waittest + # Two plug-ins in one process, each with its own copy of the session code (stalelib.c built + # twice), and a made-up sleep: one's session from before the sleep stops the other's new one. + for l in a b; do + xcrun clang $TFLAGS -dynamiclib -fvisibility=hidden -Icommon tests/stalelib.c common/vcnsession.c \ + -framework CoreFoundation -framework IOKit -install_name @rpath/libstale-$l.dylib -o $T/libstale-$l.dylib + done + xcrun clang $TFLAGS -Icommon tests/staletest.c -o $T/staletest # The decoder sessions against a made-up driver: sessiontest.c stands in for common/vcndriver.c. for c in av1 vp9; do xcrun clang $TFLAGS -DTEST_${(U)c} -Icommon -I$c tests/sessiontest.c $c/vcn$c.c $c/${c}parse.c \ diff --git a/GPU/decode/common/vcndriver.c b/GPU/decode/common/vcndriver.c index 19970a78..0f61de74 100644 --- a/GPU/decode/common/vcndriver.c +++ b/GPU/decode/common/vcndriver.c @@ -3,8 +3,11 @@ #include #include #include +#include #include #include +#include +#include bool vcn_codec_is_amd(CFTypeRef codec) { return codec && CFGetTypeID(codec) == CFStringGetTypeID() && @@ -75,3 +78,25 @@ bool vcn_driver_load(VcnDriverLib* lib, char* err, size_t errLen) { } return true; } + +void vcn_sleep_mark(VcnSleepMark* m) { + static mach_timebase_info_data_t tb; + if (!tb.denom) mach_timebase_info(&tb); + // mach_continuous_time is mach_absolute_time plus the time spent asleep. The + // two are read apart: a reading whose two absolute times are more than 10 us + // apart (the thread was preempted between them) is taken again. + uint64_t asleep = 0; + for (int i = 0; i < 8; i++) { + uint64_t a = mach_absolute_time(), c = mach_continuous_time(), + b = mach_absolute_time(); + asleep = c > b ? c - b : 0; + if ((b - a) * tb.numer / tb.denom < 10000) break; + } + m->asleepNs = asleep * tb.numer / tb.denom; + struct timeval wake = {0}; + size_t len = sizeof(wake); + m->wakeUs = + sysctlbyname("kern.waketime", &wake, &len, NULL, 0) || len != sizeof(wake) + ? 0 + : (int64_t)wake.tv_sec * 1000000 + wake.tv_usec; +} diff --git a/GPU/decode/common/vcndriver.h b/GPU/decode/common/vcndriver.h index d62f4054..e1059c5c 100644 --- a/GPU/decode/common/vcndriver.h +++ b/GPU/decode/common/vcndriver.h @@ -43,6 +43,37 @@ bool vcn_driver_load(VcnDriverLib* lib, char* err, size_t errLen); // frame takes 5-60 ms on Navi 21, even at the video engine's lowest clock. enum { VCN_COMMAND_TIMEOUT_MS = 1000 }; +// A system sleep, as a session sees it. Apple's kernel driver keeps a decoder's +// video context across a sleep, but stops the video engine before it and starts +// it again at wake, and saves nothing of the session on the engine +// (AMDRadeonX6000, 26.7.3 KDK, read in IDA: systemWillSleep stops the VCN rings +// once their last command finished, powerUpHW and internalDidWake start them +// again, saveVCNSession is empty). Nothing in the driver, AppleGVA or +// VideoToolbox tells a decoder about it. A session opened before a sleep is +// therefore never used again: it decodes nothing more, and closing it skips the +// driver's own teardown, which would send the engine a command for that session +// and wait for it with no time limit (vcn_session_close). +// +// The mark is the time this Mac has spent asleep since it started, as the +// kernel counts it (mach_continuous_time runs on during a sleep, +// mach_absolute_time does not), and the time of the last wake (kern.waketime). +// Either changing means the system slept. Neither needs a notification, which a +// decoder could not get anyway: VideoToolbox's decoder service is sandboxed +// without the root power domain's user client that IORegisterForSystemPower +// opens (VTDecoderSandboxProfile.sb). +typedef struct { + uint64_t asleepNs; // time asleep since boot + int64_t wakeUs; // last wake in microseconds since 1970; 0 when unknown +} VcnSleepMark; + +// Reads both now (vcndriver.c: it asks the system). +void vcn_sleep_mark(VcnSleepMark* m); + +// True when the system has slept between `then` and `now`. A change of the +// time asleep below 1 ms is the error of the reading, not a sleep: a real one +// takes seconds. +bool vcn_slept_between(const VcnSleepMark* then, const VcnSleepMark* now); + typedef enum { VCN_WAIT_DONE = 0, // finished; *hwStatus = firmware result, 0 = no error VCN_WAIT_TIMEOUT = 1, // still running after timeoutMs: the GPU is stuck @@ -65,7 +96,7 @@ enum { VCN_NUM_BS = 4 }; // One accelerator, one driver and its bitstream pool: what a decoder session // holds of the driver. The codec adds its context (ctx) itself. -typedef struct { +typedef struct VcnDriverSession { AVD_DestroyAVDAccelerator_fn destroy; AVD_Accelerator* accel; void* drv; @@ -73,6 +104,10 @@ typedef struct { void* bsAddr[VCN_NUM_BS]; io_service_t svc; // the accelerator service; released by close bool poolAllocated; + VcnSleepMark opened; // taken when open began + bool lost; // the system slept since: see vcn_session_lost + bool listed; // in this plug-in's list of open sessions (vcnsession.c) + struct VcnDriverSession* nextOpen; os_log_t log; } VcnDriverSession; @@ -80,20 +115,49 @@ typedef struct { // taken over: close releases it, and so does a failed open. On failure every // part opened so far is closed again, s is left empty and err says which call // failed. +// +// It also fails, before it opens anything, while a session of this process +// that opened before a system sleep is still open, in any of the plug-ins (they +// ask each other through the process's local notification center). A reported +// hang began exactly so: two VP9 sessions of a browser's decoder process stayed +// open across a sleep, and the AV1 session the same process opened after the +// wake never decoded a frame. VideoToolbox then gives the stream to another +// decoder (software); once those sessions are closed, new ones open again. bool vcn_session_open(VcnDriverSession* s, const VcnDriverLib* lib, io_service_t svc, os_log_t log, char* err, size_t errLen); +// True once the system has slept since s opened (see VcnSleepMark), and from +// then on; the first time, it says so in the log. The codec asks before it +// writes a frame into the bitstream pool and before it schedules a command, and +// refuses the frame as a device failure: VideoToolbox then makes a new session, +// which opens on the restarted engine. A session with no accelerator is never +// lost. +bool vcn_session_lost(VcnDriverSession* s); + // Closes what open (and the codec's CreateContexts) made, in the order Apple's // own decoders use: DeleteContexts, FreeBitstreamBufferPool (only when the pool // was allocated), DeleteDriver, AVD_DestroyAVDAccelerator, then the service. // Every step can block in the kernel while a command is still on the GPU. +// +// A lost session (vcn_session_lost) skips the first three. DeleteContexts, and +// DeleteDriver for a context still open, send the engine a destroy command for +// the session and wait for it with no time limit (AMDRadeonVADriver2: +// VADecoder::Terminate -> DestroyDecodeSession -> waitForCurrentEvent), for a +// session the engine lost at wake; the pool's textures may wait for a command +// the wake dropped. Only AVD_DestroyAVDAccelerator runs: it closes the +// accelerator's device, shared and video context connections, and the kernel's +// close of a video context sends the engine nothing (AMDRadeonX6000: +// contextStop -> destroyVCNSession -> submitDestroyCommand, which returns at +// once). What the driver allocated in this process stays allocated: nothing +// touches it again. void vcn_session_close(VcnDriverSession* s); -// Runs close() now, or, when stuck (a command never finished), on a background -// queue, with a log line before and after: the driver's teardown then waits in -// the kernel for that command, and the caller (VideoToolbox's invalidate) must -// not wait with it. what names the session in the log. -void vcn_teardown(bool stuck, os_log_t log, const char* what, +// Runs close() now, or on a background queue when stuck (a command never +// finished) or lost (the system slept since the session opened), with a log +// line before and after: the teardown may then wait in the kernel, and the +// caller (VideoToolbox's invalidate) must not wait with it. what names the +// session in the log. +void vcn_teardown(bool stuck, bool lost, os_log_t log, const char* what, void (^close)(void)); // Waits until every teardown handed to the background queue has finished, at diff --git a/GPU/decode/common/vcnlegacy.c b/GPU/decode/common/vcnlegacy.c index 88c73806..afc3ea37 100644 --- a/GPU/decode/common/vcnlegacy.c +++ b/GPU/decode/common/vcnlegacy.c @@ -660,9 +660,10 @@ static void destroy_now(VcnLegacy* d) { void vcnlegacy_destroy(VcnLegacy* d) { if (!d) return; - vcn_teardown(d->stuck, d->log, "legacy codec session", ^{ - destroy_now(d); - }); + vcn_teardown(d->stuck, vcn_session_lost(&d->s), d->log, + "legacy codec session", ^{ + destroy_now(d); + }); } static bool driver_validated(const VcnDriverLib* lib) { @@ -846,10 +847,14 @@ int vcnlegacy_decode(VcnLegacy* d, const void* block, uint32_t blockSize, d->err[0] = 0; d->failure = VCNLEGACY_FAIL_STREAM; d->haveStatus = false; + // Nothing goes into the pool or to the engine for a session from before a + // system sleep (vcndriver.h). + if (!d->broken && vcn_session_lost(&d->s)) d->broken = true; if (d->broken) { snprintf(d->err, sizeof(d->err), "session stopped: %s", - d->stuck ? "the GPU did not finish an earlier picture" - : "an earlier driver call failed"); + d->stuck ? "the GPU did not finish an earlier picture" + : d->s.lost ? "the system slept since it opened" + : "an earlier driver call failed"); d->failure = VCNLEGACY_FAIL_DEVICE; return -1; } diff --git a/GPU/decode/common/vcnsession.c b/GPU/decode/common/vcnsession.c index ebf3c9e5..2efb8b4b 100644 --- a/GPU/decode/common/vcnsession.c +++ b/GPU/decode/common/vcnsession.c @@ -1,9 +1,11 @@ // The part of a decoder session that only talks to the driver through its // function pointers: the wait for a command, opening and closing the -// accelerator, driver and bitstream pool. See vcndriver.h. +// accelerator, driver and bitstream pool, and what a system sleep does to a +// session. See vcndriver.h. #include #include #include +#include #include #include #include @@ -61,16 +63,127 @@ VcnWaitResult vcn_wait_command(AVD_QueryAVDCommandStatus_fn query, void* driver, #define FN(name) ((AVD_##name##_fn)s->accel->fn[AVD_FN_##name]) +bool vcn_slept_between(const VcnSleepMark* then, const VcnSleepMark* now) { + if (now->asleepNs > then->asleepNs + 1000000) return true; + return then->wakeUs && now->wakeUs && then->wakeUs != now->wakeUs; +} + +bool vcn_session_lost(VcnDriverSession* s) { + if (s->lost) return true; + if (!s->accel) return false; + VcnSleepMark now; + vcn_sleep_mark(&now); + if (!vcn_slept_between(&s->opened, &now)) return false; + s->lost = true; + os_log_error(s->log, + "the system slept since this session opened (%.1f s asleep in " + "between): the video engine was restarted at wake, the session " + "sends it nothing more", + now.asleepNs > s->opened.asleepNs + ? (double)(now.asleepNs - s->opened.asleepNs) / 1e9 + : 0.0); + return true; +} + +// The open sessions of this plug-in, and how the plug-ins of a process count +// each other's sessions from before a sleep. Each plug-in bundle has its own +// copy of this file. They meet in the process's local notification center, +// which calls every observer, in every image, on the posting thread before the +// post returns. +static pthread_mutex_t g_open_lock = PTHREAD_MUTEX_INITIALIZER; +static VcnDriverSession* g_open; + +static void list_open(VcnDriverSession* s) { + pthread_mutex_lock(&g_open_lock); + s->nextOpen = g_open; + g_open = s; + s->listed = true; + pthread_mutex_unlock(&g_open_lock); +} +static void unlist(VcnDriverSession* s) { + if (!s->listed) return; + pthread_mutex_lock(&g_open_lock); + for (VcnDriverSession** p = &g_open; *p; p = &(*p)->nextOpen) + if (*p == s) { + *p = s->nextOpen; + break; + } + s->listed = false; + pthread_mutex_unlock(&g_open_lock); +} + +#define STALE_QUERY CFSTR("com.droga.vcn.sessions-from-before-a-sleep") +typedef struct { + VcnSleepMark now; + int stale; +} StaleQuery; + +// One plug-in's answer: how many of its open sessions opened before a sleep. +static void count_stale(CFNotificationCenterRef center, void* observer, + CFNotificationName name, const void* object, + CFDictionaryRef info) { + (void)center, (void)observer, (void)name, (void)object; + CFNumberRef n = info ? CFDictionaryGetValue(info, CFSTR("query")) : NULL; + int64_t addr = 0; + if (!n || CFGetTypeID(n) != CFNumberGetTypeID() || + !CFNumberGetValue(n, kCFNumberSInt64Type, &addr) || !addr) + return; + StaleQuery* q = (StaleQuery*)(intptr_t)addr; + pthread_mutex_lock(&g_open_lock); + for (VcnDriverSession* s = g_open; s; s = s->nextOpen) + if (vcn_slept_between(&s->opened, &q->now)) q->stale++; + pthread_mutex_unlock(&g_open_lock); +} + +static void pin_this_image(void); + +// Sessions of this process, in every plug-in, opened before a sleep and still +// open; -1 when the question could not be asked. +static int stale_sessions(const VcnSleepMark* now) { + static dispatch_once_t once; + dispatch_once(&once, ^{ + // The observer is called from other plug-ins: this image must stay. + pin_this_image(); + CFNotificationCenterAddObserver( + CFNotificationCenterGetLocalCenter(), (const void*)&g_open, count_stale, + STALE_QUERY, NULL, CFNotificationSuspensionBehaviorDeliverImmediately); + }); + StaleQuery q = {.now = *now}; + int64_t addr = (int64_t)(intptr_t)&q; + CFNumberRef n = CFNumberCreate(NULL, kCFNumberSInt64Type, &addr); + const void* k[] = {CFSTR("query")}; + const void* v[] = {n}; + CFDictionaryRef info = + n ? CFDictionaryCreate(NULL, k, v, 1, &kCFTypeDictionaryKeyCallBacks, + &kCFTypeDictionaryValueCallBacks) + : NULL; + if (n) CFRelease(n); + if (!info) return -1; + CFNotificationCenterPostNotification(CFNotificationCenterGetLocalCenter(), + STALE_QUERY, NULL, info, true); + CFRelease(info); + return q.stale; +} + bool vcn_session_open(VcnDriverSession* s, const VcnDriverLib* lib, io_service_t svc, os_log_t log, char* err, size_t errLen) { *s = (VcnDriverSession){.destroy = lib->destroy, .svc = svc, .log = log}; + // Before anything is opened: a sleep during the open loses the session too. + vcn_sleep_mark(&s->opened); #define FAIL(...) \ do { \ snprintf(err, errLen, __VA_ARGS__); \ vcn_session_close(s); \ return false; \ } while (0) + // No new session beside one from before a sleep (vcndriver.h). + int stale = stale_sessions(&s->opened); + if (stale > 0) + FAIL( + "%d session(s) of this process from before a system sleep still " + "open: no new one until they close", + stale); if (!lib->destroy) { // Said once per process: every session would say the same. static bool told; @@ -119,12 +232,16 @@ bool vcn_session_open(VcnDriverSession* s, const VcnDriverLib* lib, for (int i = 0; i < VCN_NUM_BS; i++) if (!s->bsAddr[i]) FAIL("AllocateBitstreamBufferPool: no buffer %d", i); #undef FAIL + list_open(s); return true; } void vcn_session_close(VcnDriverSession* s) { + // Asked here too: a session can be closed without having been asked since + // the wake (a paused video that is closed after it). + bool lost = vcn_session_lost(s); if (s->accel) { - if (s->drv) { + if (s->drv && !lost) { if (s->ctx) { void* ctxs[1] = {s->ctx}; AVD_DriverContextDelete del = {.count = 1, .contexts = ctxs}; @@ -134,7 +251,17 @@ void vcn_session_close(VcnDriverSession* s) { FN(DeleteDriver)(s->drv); } if (s->destroy) s->destroy(s->accel); + if (lost) + os_log_error(s->log, + "session from before the sleep closed without the driver's " + "own teardown%{public}s", + s->destroy ? "" + : " (this driver build has no " + "AVD_DestroyAVDAccelerator: it stays open)"); } + // Out of the list only now: until the accelerator is closed, the session + // still counts as open for a new one. + unlist(s); // Released only after the driver is gone: it may hold on to the service. if (s->svc) IOObjectRelease(s->svc); os_log_t log = s->log; @@ -156,32 +283,39 @@ static dispatch_queue_t teardown_queue(void) { // A close may still run after the host is done with the plug-in. If the // host unloaded the bundle by then, the queue would run code that is gone: // this image stays loaded for the life of the process. - Dl_info info; - if (dladdr((const void*)vcn_teardown, &info) && info.dli_fname) - dlopen(info.dli_fname, RTLD_NOW | RTLD_NOLOAD | RTLD_NODELETE); + pin_this_image(); }); return q; } -void vcn_teardown(bool stuck, os_log_t log, const char* what, +static void pin_this_image(void) { + Dl_info info; + if (dladdr((const void*)vcn_teardown, &info) && info.dli_fname) + dlopen(info.dli_fname, RTLD_NOW | RTLD_NOLOAD | RTLD_NODELETE); +} + +void vcn_teardown(bool stuck, bool lost, os_log_t log, const char* what, void (^close)(void)) { - if (!stuck) { + if (!stuck && !lost) { close(); return; } // Kept for the line after the close, which runs once the caller is gone. char* name = strdup(what ? what : "session"); - os_log_error(log, - "%{public}s: a command never finished; closing the session on " - "a background thread, the driver may wait for the GPU", - name ? name : "session"); + os_log_error( + log, + "%{public}s: %{public}s; closing the session on a background " + "thread, the close may wait for the GPU", + name ? name : "session", + stuck ? "a command never finished" : "the system slept since it opened"); dispatch_queue_t q = teardown_queue(); // also makes the group // dispatch_group_async copies this block, and with it close. dispatch_group_async(teardown_group, q, ^{ double t0 = wait_now_ms(); close(); - os_log_error(log, "%{public}s: stuck session closed after %.0f ms", - name ? name : "session", wait_now_ms() - t0); + os_log_error(log, "%{public}s: %{public}s session closed after %.0f ms", + name ? name : "session", stuck ? "stuck" : "lost", + wait_now_ms() - t0); free(name); }); } diff --git a/GPU/decode/tests/gpu/README.md b/GPU/decode/tests/gpu/README.md index 4ff98ea4..3b65b2f8 100644 --- a/GPU/decode/tests/gpu/README.md +++ b/GPU/decode/tests/gpu/README.md @@ -165,8 +165,11 @@ decode/build/gpu/vtvp9test -load decode/build/VP9VCNDecoder.bundle v.ivf v.ivf.m bundle cannot be registered. Pass `-id` with the decoder ID that `list` prints for it, or VideoToolbox may pick the installed decoder instead of the one you loaded. - `-n` reads no pixels. `-a` decodes asynchronously. `-pace fps` feeds frames at a fixed - rate and reports how late they come out. `vtvp9test` also has `-loop N` (the file N times - in one session), `-frames N` and `-sw` (does not ask for hardware). `vtav1test -sw` decodes + rate and reports how late they come out. `-loop N` feeds the file N times in one session + and prints a line with the time after each pass; `-renew` makes a new session for every + pass, in the same process. Together they make the sleep test: `-loop 100 -pace 30` across + `pmset sleepnow` (`docs/testing.md`). `vtvp9test` also has `-frames N` and `-sw` (does + not ask for hardware). `vtav1test -sw` decodes in software only: it turns hardware decoders off and stops before the first frame if VideoToolbox gives one anyway. (Apple's software AV1 decoder refused every stream here on macOS 26.7.3, 8-bit too: -12906.) diff --git a/GPU/decode/tests/gpu/vtav1test.c b/GPU/decode/tests/gpu/vtav1test.c index 04fab5a3..d8fb28d7 100644 --- a/GPU/decode/tests/gpu/vtav1test.c +++ b/GPU/decode/tests/gpu/vtav1test.c @@ -5,20 +5,23 @@ // shows the av01 decoders VideoToolbox knows about (LIST_ALL=1: all of // them) // vtav1test [-load bundle] file.ivf [file.md5] [-n] [-a] [-pace fps] -// [-id decoder] [-sw] [-attach] +// [-loop N] [-renew] [-id decoder] [-sw] [-attach] // decodes the file with a VTDecompressionSession that requires // hardware, compares the MD5 of every frame as I420 with the reference, // and reports timing // // -load registers the bundle in this process only, nothing is installed on the // system. -n reads no pixels, -a decodes asynchronously, -pace feeds at a fixed -// rate and reports lateness, -id picks one decoder when several handle av01 -// (the installed one and a -load'ed build). -sw decodes in software only: -// with -id com.apple.videotoolbox.videodecoder.av1.sw, Apple's decoder; a -// session VideoToolbox gives a hardware decoder anyway decodes nothing. -attach -// prints the colour attachments of the first picture, and again whenever they -// change. VTAV1_DUMP_Y= appends the 8-bit luma of every frame to that -// file. +// rate and reports lateness, -loop feeds the file N times in one session (the +// reference starts again each time), -renew makes that a new session for every +// pass, in this same process; with -loop a line per pass says when it ended and +// how it went (for a run across a system sleep). -id picks one decoder when +// several handle av01 (the installed one and a -load'ed build). -sw decodes in +// software only: with -id com.apple.videotoolbox.videodecoder.av1.sw, Apple's +// decoder; a session VideoToolbox gives a hardware decoder anyway decodes +// nothing. -attach prints the colour attachments of the first picture, and +// again whenever they change. VTAV1_DUMP_Y= appends the 8-bit luma of +// every frame to that file. // // There is no switch to arm here: a decode run goes to the GPU as soon as an // AV1 hardware decoder is installed or loaded. @@ -29,10 +32,12 @@ #include #include #include +#include #include #include #include #include +#include #include #include "av1parse.h" @@ -247,7 +252,7 @@ static int usage(void) { fprintf(stderr, "usage: vtav1test [-load bundle] list\n" " vtav1test [-load bundle] file.ivf [file.md5] [-n] [-a] " - "[-pace fps] [-id decoder] [-sw] [-attach]\n" + "[-pace fps] [-loop N] [-renew] [-id decoder] [-sw] [-attach]\n" "A decode run goes to the GPU: there is no switch to arm.\n"); return 1; } @@ -268,7 +273,7 @@ int main(int argc, char** argv) { if (!strcmp(argv[1], "list")) return list(); if (argv[1][0] == '-') return usage(); Ctx c = {0}; - int async = 0, require_hw = 1; + int async = 0, require_hw = 1, loops = 1, renew = 0; double pace = 0; // feed frames at this rate (fps) and report output latency const char *decoderID = NULL, *md5Path = NULL; for (int i = 2; i < argc; i++) { @@ -286,6 +291,14 @@ int main(int argc, char** argv) { double v = strtod(s, &end); if (!end || end == s || *end || !(v >= 0)) return fail("invalid -pace"); pace = v; + } else if (!strcmp(argv[i], "-loop") && i + 1 < argc) { + char* end = NULL; + long v = strtol(argv[++i], &end, 10); + if (!end || *end || v < 1 || v > INT_MAX / 2) + return fail("invalid -loop"); + loops = (int)v; + } else if (!strcmp(argv[i], "-renew")) { + renew = 1; } else if (!strcmp(argv[i], "-id") && i + 1 < argc) { decoderID = argv[++i]; } else if (argv[i][0] == '-' || md5Path) { @@ -393,9 +406,10 @@ int main(int argc, char** argv) { CFDictionarySetValue(spec, CFSTR("DecoderID"), id); CFRelease(id); } + size_t total = cnt * (size_t)loops; if (pace > 0) { - c.fed = calloc(cnt, sizeof(double)); - c.lat = calloc(cnt, sizeof(double)); + c.fed = calloc(total, sizeof(double)); + c.lat = calloc(total, sizeof(double)); if (!c.fed || !c.lat) return fail("out of memory"); } VTDecompressionOutputCallbackRecord cb = {out_cb, &c}; @@ -416,7 +430,37 @@ int main(int argc, char** argv) { return fail("-sw: VideoToolbox gave a hardware decoder; nothing decoded"); double t0 = now_ms(); - for (size_t i = 0; i < cnt; i++) { + int passFrames = 0, passMismatches = 0, passErrors = 0; + for (size_t i = 0; i < total; i++) { + size_t k = i % cnt; // the temporal unit of the file + if (k == 0 && i > 0) { + // The pass before is all out: say how it went, with the wall clock, so + // that a pass across a sleep can be told from the ones before and after. + VTDecompressionSessionWaitForAsynchronousFrames(sess); + time_t now = time(NULL); + char when[32]; + strftime(when, sizeof(when), "%H:%M:%S", localtime(&now)); + printf("pass %zu ended %s: %d frames, %d mismatches, %d errors\n", + i / cnt, when, c.frames - passFrames, + c.mismatches - passMismatches, c.errors - passErrors); + fflush(stdout); + passFrames = c.frames; + passMismatches = c.mismatches; + passErrors = c.errors; + if (c.md5) rewind(c.md5); + if (renew) { + VTDecompressionSessionInvalidate(sess); + CFRelease(sess); + sess = NULL; + st = VTDecompressionSessionCreate(NULL, fmt, spec, NULL, &cb, &sess); + if (st) { + printf("pass %zu: VTDecompressionSessionCreate = %d\n", i / cnt + 1, + (int)st); + c.errors++; + break; + } + } + } if (pace > 0) { double due = t0 + i * 1000.0 / pace; while (now_ms() < due) usleep(200); @@ -425,12 +469,12 @@ int main(int argc, char** argv) { c.fed[i] = due; } CMBlockBufferRef bb = NULL; - CMBlockBufferCreateWithMemoryBlock(NULL, tus[i], sizes[i], kCFAllocatorNull, - NULL, 0, sizes[i], 0, &bb); + CMBlockBufferCreateWithMemoryBlock(NULL, tus[k], sizes[k], kCFAllocatorNull, + NULL, 0, sizes[k], 0, &bb); CMSampleBufferRef sb = NULL; CMSampleTimingInfo ti = {CMTimeMake(1, 30), CMTimeMake((int64_t)i, 30), kCMTimeInvalid}; - size_t ss = sizes[i]; + size_t ss = sizes[k]; if (bb) CMSampleBufferCreateReady(NULL, bb, fmt, 1, 1, &ti, 1, &ss, &sb); if (!sb) { printf("frame %zu: no sample buffer\n", i); @@ -446,15 +490,23 @@ int main(int argc, char** argv) { CFRelease(sb); CFRelease(bb); } - VTDecompressionSessionWaitForAsynchronousFrames(sess); + if (sess) VTDecompressionSessionWaitForAsynchronousFrames(sess); double t = now_ms() - t0; + if (loops > 1) { + time_t now = time(NULL); + char when[32]; + strftime(when, sizeof(when), "%H:%M:%S", localtime(&now)); + printf("last pass ended %s: %d frames, %d mismatches, %d errors\n", when, + c.frames - passFrames, c.mismatches - passMismatches, + c.errors - passErrors); + } printf("%s: %d frames, %d mismatches, %d errors, %.1f ms (%.1f fps%s)\n", argv[1], c.frames, c.mismatches, c.errors, t, c.frames * 1000.0 / t, c.nohash ? (async ? ", async" : "") : ", incl. CPU hashing"); if (pace > 0) { int late33 = 0, late50 = 0; double mx = 0, sum = 0; - for (size_t i = 0; i < cnt; i++) { + for (size_t i = 0; i < total; i++) { double l = c.lat[i]; sum += l; if (l > mx) mx = l; @@ -464,9 +516,11 @@ int main(int argc, char** argv) { printf( "paced %.0f fps: latency avg %.1f ms, max %.1f ms, >2 frames late %d, " ">3 frames late %d (of %zu)\n", - pace, sum / cnt, mx, late33, late50, cnt); + pace, sum / total, mx, late33, late50, total); + } + if (sess) { + VTDecompressionSessionInvalidate(sess); + CFRelease(sess); } - VTDecompressionSessionInvalidate(sess); - CFRelease(sess); - return c.mismatches || c.errors || c.frames != (int)cnt ? 2 : 0; + return c.mismatches || c.errors || c.frames != (int)total ? 2 : 0; } diff --git a/GPU/decode/tests/gpu/vtvp9test.c b/GPU/decode/tests/gpu/vtvp9test.c index 1f17af0f..62bc90df 100644 --- a/GPU/decode/tests/gpu/vtvp9test.c +++ b/GPU/decode/tests/gpu/vtvp9test.c @@ -4,7 +4,7 @@ // vtvp9test [-load bundle] list // shows the vp09 decoders VideoToolbox knows about // vtvp9test [-load bundle] file [reference] [-n] [-a] [-pace fps] [-loop N] -// [-frames N] [-id decoder] [-sw] [-attach] +// [-renew] [-frames N] [-id decoder] [-sw] [-attach] // [-color primaries,transfer,matrix] [-hdr] // decodes the file (IVF or WebM) and compares the MD5 of every frame as // I420 with a reference in the format of FFmpeg's FATE suite @@ -12,7 +12,10 @@ // -load registers the bundle in this process only, nothing is installed on the // system. -n reads no pixels, -a decodes asynchronously, -pace feeds at a fixed // rate and reports lateness, -loop feeds the file N times in one session (a -// seek back to a keyframe), -frames stops after N container frames, -id picks +// seek back to a keyframe), -renew makes that a new session for every pass, in +// this same process (a browser that opens one video after another), and with +// -loop a line per pass says when it ended and how it went (for a run across a +// system sleep), -frames stops after N container frames, -id picks // one decoder when several handle vp09, -sw doesn't ask for hardware. // -attach prints the colour attachments of the first picture, and again // whenever they change. The format description carries no colour unless @@ -36,6 +39,7 @@ #include #include #include +#include #include #include "container.h" @@ -231,7 +235,8 @@ static int usage(void) { fprintf(stderr, "usage: vtvp9test [-load bundle] list\n" " vtvp9test [-load bundle] file [reference] [-n] [-a] " - "[-pace fps] [-loop N] [-frames N] [-id decoder] [-sw] [-attach]\n" + "[-pace fps] [-loop N] [-renew] [-frames N] [-id decoder] [-sw] " + "[-attach]\n" " [-color primaries,transfer,matrix] [-hdr]\n" "A decode run goes to the GPU: there is no switch to arm.\n"); return 1; @@ -265,7 +270,7 @@ int main(int argc, char** argv) { if (!strcmp(argv[1], "list")) return list(); if (argv[1][0] == '-') return usage(); Ctx c = {0}; - int async = 0, loops = 1, limit = 0, require_hw = 1; + int async = 0, loops = 1, limit = 0, require_hw = 1, renew = 0; // -color: the colour a container would give (vpcC and the format // description's extensions), as Safari passes a WebM Colour element. 2 = // unspecified, what a stream with no container colour gets. @@ -296,6 +301,8 @@ int main(int argc, char** argv) { pace = v; } else if (!strcmp(argv[i], "-loop") && i + 1 < argc) { if ((loops = parse_count(argv[++i], 1)) < 0) return fail("invalid -loop"); + } else if (!strcmp(argv[i], "-renew")) { + renew = 1; } else if (!strcmp(argv[i], "-frames") && i + 1 < argc) { if ((limit = parse_count(argv[++i], 0)) < 0) return fail("invalid -frames"); @@ -442,7 +449,34 @@ int main(int argc, char** argv) { double t0 = now_ms(); size_t fed = 0; + int passFrames = 0, passMismatches = 0, passErrors = 0; for (int l = 0; l < loops; l++) { + if (l > 0 && loops > 1) { + // The pass before is all out: say how it went, with the wall clock, so + // that a pass across a sleep can be told from the ones before and after. + VTDecompressionSessionWaitForAsynchronousFrames(sess); + time_t now = time(NULL); + char when[32]; + strftime(when, sizeof(when), "%H:%M:%S", localtime(&now)); + printf("pass %d ended %s: %d frames, %d mismatches, %d errors\n", l, when, + c.frames - passFrames, c.mismatches - passMismatches, + c.errors - passErrors); + fflush(stdout); + passFrames = c.frames; + passMismatches = c.mismatches; + passErrors = c.errors; + } + if (l > 0 && renew) { + VTDecompressionSessionInvalidate(sess); + CFRelease(sess); + sess = NULL; + st = VTDecompressionSessionCreate(NULL, fmt, spec, NULL, &cb, &sess); + if (st) { + printf("pass %d: VTDecompressionSessionCreate = %d\n", l + 1, (int)st); + c.errors++; + break; + } + } if (c.ref) { // Every pass over the file starts the reference again, once the frames // of the pass before are all out. @@ -482,8 +516,16 @@ int main(int argc, char** argv) { CFRelease(bb); } } - VTDecompressionSessionWaitForAsynchronousFrames(sess); + if (sess) VTDecompressionSessionWaitForAsynchronousFrames(sess); double t = now_ms() - t0; + if (loops > 1) { + time_t now = time(NULL); + char when[32]; + strftime(when, sizeof(when), "%H:%M:%S", localtime(&now)); + printf("last pass ended %s: %d frames, %d mismatches, %d errors\n", when, + c.frames - passFrames, c.mismatches - passMismatches, + c.errors - passErrors); + } // A decoder that shows fewer frames than the reference lists must not pass. // With -frames the file was cut short on purpose. int missing = 0; @@ -513,8 +555,10 @@ int main(int argc, char** argv) { "50 ms %d (of %zu)\n", pace, sum / (double)total, mx, late33, late50, total); } - VTDecompressionSessionInvalidate(sess); - CFRelease(sess); + if (sess) { + VTDecompressionSessionInvalidate(sess); + CFRelease(sess); + } return c.mismatches || missing || c.errors || c.frames + c.dropped != (int)total ? 2 diff --git a/GPU/decode/tests/sessiontest.c b/GPU/decode/tests/sessiontest.c index 98a2d54c..6206c81b 100644 --- a/GPU/decode/tests/sessiontest.c +++ b/GPU/decode/tests/sessiontest.c @@ -35,7 +35,18 @@ // 11. (AV1) a 12-bit sequence header is refused as unsupported (VideoToolbox // then gives the stream to the software decoder); a 10-bit BT.2020 PQ // one is taken, and the session reports its colour and the light level -// of its metadata OBU (vcnav1_color). +// of its metadata OBU (vcnav1_color); +// 12. a system sleep (a made-up sleep mark, standing in for the clocks and +// kern.waketime): a session opened before it sends nothing after it, not +// even into the bitstream pool, and fails as a device; its close, on the +// background queue, skips DeleteContexts, FreeBitstreamBufferPool and +// DeleteDriver and only destroys the accelerator; the same for a session +// that was stuck when the sleep came, and for one that is only closed +// after the wake; a new wake time alone counts as a sleep, a change of +// the time asleep under 1 ms does not; a session opened after the wake +// decodes and closes fully; while one from before the sleep is still +// open, a new session is refused before it opens anything, and opens +// again once that one is closed. // // usage: sessiontest [clip with hidden frames] // Exit status 0 = pass. @@ -110,6 +121,7 @@ static struct { bool useAfterDestroy; // a driver call after the accelerator was destroyed bool deleteCtxOnMain; // DeleteContexts ran on the test's own thread bool gateTimedOut; // DeleteContexts waited at the gate in vain + bool destroyOnMain; // a gated close destroyed on the test's own thread } st; // What it should get wrong. static struct { @@ -124,7 +136,7 @@ static struct { } fault; enum { kFakeBuffer = 1 << 20 }; // larger than any frame of the test clips -typedef struct { +typedef struct FakeDrv { void* va; // +8 holds the VAContext pointer, as the real driver's does void* factory; // what va+75072 points to (VP9 swaps its class pointer) bool poolAllocated; @@ -135,6 +147,10 @@ typedef struct { AVD_Accelerator a; bool destroyed; } FakeAccel; +// The start of every bitstream buffer of the last driver made, to see that +// nothing was written into the pool after a sleep. +static FakeDrv* lastDrv; +static uint8_t poolSnapshot[VCN_NUM_BS][64]; static int f_create_driver(void** out, AVD_DriverCreate* dc) { st.createDrivers++; @@ -153,10 +169,21 @@ static int f_create_driver(void** out, AVD_DriverCreate* dc) { // keep FakeDrv reachable from the handle: raw[0] raw[0] = d; st.liveDrivers++; + lastDrv = d; *out = raw; return 0; } static FakeDrv* drv_of(void* h) { return ((void**)h)[0]; } +static void snapshot_pool(void) { + for (int i = 0; lastDrv && i < VCN_NUM_BS; i++) + if (lastDrv->buffers[i]) memcpy(poolSnapshot[i], lastDrv->buffers[i], 64); +} +static bool pool_untouched(void) { + for (int i = 0; lastDrv && i < VCN_NUM_BS; i++) + if (lastDrv->buffers[i] && memcmp(poolSnapshot[i], lastDrv->buffers[i], 64)) + return false; + return lastDrv != NULL; +} static int f_delete_driver(void* h) { st.deleteDrivers++; st.seqDeleteDriver = ++st.seq; @@ -216,6 +243,14 @@ static int f_delete_ctx(void* h, AVD_DriverContextDelete* del) { } return del->count == 1 && del->contexts[0] ? 0 : 5; } +// What vcn_sleep_mark reports: the test moves it to make a sleep. +static VcnSleepMark fakeSleep = {.asleepNs = 5000000000ull, + .wakeUs = 1795000000000000ll}; +static void sleep_for(uint64_t ns) { + fakeSleep.asleepNs += ns; + fakeSleep.wakeUs += 1000000; +} + static int f_schedule(void* h, AVD_CmdList* l, AVD_RefConList* r) { (void)h, (void)l; st.schedules++; @@ -276,6 +311,8 @@ static int f_create_accel(AVD_Accelerator** out, AVD_AcceleratorCreate* in, } static int f_destroy_accel(AVD_Accelerator* acc) { st.destroys++; + if (closeGate && pthread_equal(pthread_self(), mainThread)) + st.destroyOnMain = true; st.seqDestroy = ++st.seq; FakeAccel* a = (FakeAccel*)acc; if (a->destroyed) st.useAfterDestroy = true; @@ -299,6 +336,7 @@ bool vcn_driver_uuid(char out[33]) { snprintf(out, 33, "1181E2CA31B33DF090E23AE70552D753"); return true; } +void vcn_sleep_mark(VcnSleepMark* m) { *m = fakeSleep; } bool vcn_driver_load(VcnDriverLib* lib, char* err, size_t errLen) { (void)err, (void)errLen; *lib = (VcnDriverLib){.create = f_create_accel, @@ -365,6 +403,23 @@ static bool closed_in_background(Vcn* d) { !st.gateTimedOut; } +// Destroys a session from before a sleep: its close runs on the background +// queue and calls nothing of the driver but AVD_DestroyAVDAccelerator. The +// driver handle it never deleted stays: the made-up driver counts it live. +static bool closed_quietly(Vcn* d) { + int before = st.deleteCtx + st.frees + st.deleteDrivers; + closeGate = dispatch_semaphore_create(0); + DESTROY(d); + // Nothing calls DeleteContexts, so nothing waits at the gate: open it anyway. + dispatch_semaphore_signal(closeGate); + bool drained = vcn_teardown_drain(10000); + if (drained) dispatch_release(closeGate); + closeGate = NULL; + return drained && st.deleteCtx + st.frees + st.deleteDrivers == before && + st.destroys == 1 && st.liveAccels == 0 && !st.useAfterDestroy && + !st.destroyOnMain; +} + // ---- samples split the way FFmpeg sends them typedef struct { uint8_t* data; @@ -676,6 +731,80 @@ int main(int argc, char** argv) { d && rj != 0 && FAILURE(d) == FAIL_STREAM && st.schedules == 0); if (d) DESTROY(d); + // 12. A system sleep. + reset(); + d = make(); + int rb = d ? DECODE(d, frame0, frame0Size, 0, on_out, NULL) : -1; + expect("before the sleep, a frame decodes", d && rb == 0); + int schedulesBefore12 = st.schedules; + snapshot_pool(); + sleep_for(30000000000ull); + int ra = d ? DECODE(d, frame0, frame0Size, 1, on_out, NULL) : 0; + int ka = d ? FAILURE(d) : -1; + printf(" after the sleep: %s\n", d ? LASTERR(d) : ""); + int ra2 = d ? DECODE(d, frame0, frame0Size, 2, on_out, NULL) : 0; + expect( + "after it, the session fails as a device and sends nothing, not even " + "into the pool", + ra != 0 && ka == FAIL_DEVICE && ra2 != 0 && FAILURE(d) == FAIL_DEVICE && + st.schedules == schedulesBefore12 && pool_untouched()); + expect( + "its close skips the driver's own teardown and only destroys the " + "accelerator, in the background", + d && closed_quietly(d)); + + reset(); + d = make(); + sleep_for(10000000000ull); + expect("a session only closed after the wake closes the same way", + d && closed_quietly(d) && st.schedules == 0); + + reset(); + d = make(); + fault.hang = true; + int rs12 = d ? DECODE(d, frame0, frame0Size, 0, on_out, NULL) : 0; + sleep_for(10000000000ull); + expect("a session stuck when the sleep came closes the same way", + rs12 != 0 && d && closed_quietly(d)); + + reset(); + d = make(); + fakeSleep.wakeUs += 1000000; // a wake whose time asleep was not counted + int rw = d ? DECODE(d, frame0, frame0Size, 0, on_out, NULL) : 0; + expect("a new wake time alone counts as a sleep", + rw != 0 && d && FAILURE(d) == FAIL_DEVICE && st.schedules == 0); + if (d) closed_quietly(d); + + reset(); + d = make(); + fakeSleep.asleepNs += 900000; // 0.9 ms: the reading's error, no sleep + int rj12 = d ? DECODE(d, frame0, frame0Size, 0, on_out, NULL) : -1; + if (d) DESTROY(d); + expect("a change of the time asleep under 1 ms is not a sleep", + rj12 == 0 && st.deleteCtx == 1 && all_released()); + + reset(); + Vcn* before = make(); + sleep_for(10000000000ull); + int createsBefore = st.creates; + Vcn* beside = make(); + expect( + "while a session from before the sleep is open, a new one is refused " + "before it opens anything", + before && !beside && st.creates == createsBefore); + if (beside) DESTROY(beside); + if (before) closed_quietly(before); + + reset(); + d = make(); + int rn = d ? DECODE(d, frame0, frame0Size, 0, on_out, NULL) : -1; + if (d) DESTROY(d); + expect( + "once it is closed, a session opened after the wake decodes and closes " + "fully", + rn == 0 && st.deleteCtx == 1 && st.destroys == 1 && all_released() && + released_in_order()); + if (argc == 3) hidden_frames(argv[2]); free(frame0); diff --git a/GPU/decode/tests/stalelib.c b/GPU/decode/tests/stalelib.c new file mode 100644 index 00000000..8fe65cff --- /dev/null +++ b/GPU/decode/tests/stalelib.c @@ -0,0 +1,81 @@ +// stalelib: one plug-in's copy of common/vcnsession.c with a made-up driver, +// built twice as two libraries for staletest.c. Two copies in one process are +// what two plug-in bundles (VP9 and AV1) are: each has its own list of open +// sessions, and they find each other's sessions from before a sleep through +// the local notification center. Nothing here opens the real driver. +#include +#include + +#include "vcndriver.h" + +#define EXPORT __attribute__((visibility("default"))) + +// The sleep mark comes from the test program, the same for both copies. +static void (*g_mark)(VcnSleepMark*); +void vcn_sleep_mark(VcnSleepMark* m) { + if (g_mark) + g_mark(m); + else + *m = (VcnSleepMark){0}; +} + +static int f_create_driver(void** out, AVD_DriverCreate* dc) { + (void)dc; + *out = calloc(1, 16); + return 0; +} +static int f_delete_driver(void* h) { + free(h); + return 0; +} +static void* g_buffers[VCN_NUM_BS]; +static int f_alloc(void* h, AVD_BitstreamPool* p) { + (void)h; + for (int i = 0; i < VCN_NUM_BS; i++) p->addressesOut[i] = &g_buffers[i]; + return 0; +} +static int f_free(void* h, uint32_t type) { + (void)h, (void)type; + return 0; +} +static int f_delete_ctx(void* h, AVD_DriverContextDelete* del) { + (void)h, (void)del; + return 0; +} +static int g_live; // accelerators made and not destroyed +static int f_create_accel(AVD_Accelerator** out, AVD_AcceleratorCreate* in, + void* info) { + (void)in, (void)info; + AVD_Accelerator* a = calloc(1, sizeof(*a)); + a->fn[AVD_FN_CreateDriver] = (void*)f_create_driver; + a->fn[AVD_FN_DeleteDriver] = (void*)f_delete_driver; + a->fn[AVD_FN_DeleteContexts] = (void*)f_delete_ctx; + a->fn[AVD_FN_AllocateBitstreamBufferPool] = (void*)f_alloc; + a->fn[AVD_FN_FreeBitstreamBufferPool] = (void*)f_free; + g_live++; + *out = a; + return 0; +} +static int f_destroy_accel(AVD_Accelerator* a) { + free(a); + g_live--; + return 0; +} + +EXPORT void stale_set_mark(void (*mark)(VcnSleepMark*)) { g_mark = mark; } + +// Opens a session on a made-up driver; NULL, with err set, when it is refused. +EXPORT VcnDriverSession* stale_open(char* err, size_t errLen) { + VcnDriverSession* s = calloc(1, sizeof(*s)); + VcnDriverLib lib = {.create = f_create_accel, .destroy = f_destroy_accel}; + if (!s || !vcn_session_open(s, &lib, 0, OS_LOG_DEFAULT, err, errLen)) { + free(s); + return NULL; + } + return s; +} +EXPORT void stale_close(VcnDriverSession* s) { + vcn_session_close(s); + free(s); +} +EXPORT int stale_live(void) { return g_live; } diff --git a/GPU/decode/tests/staletest.c b/GPU/decode/tests/staletest.c new file mode 100644 index 00000000..4a19840b --- /dev/null +++ b/GPU/decode/tests/staletest.c @@ -0,0 +1,83 @@ +// staletest: two plug-ins in one process (two copies of common/vcnsession.c, +// libstale-a and libstale-b, built from stalelib.c) with a made-up driver and a +// made-up sleep. A session of one that opened before a sleep and is still open +// stops the other from opening one, as the VP9 sessions of a browser's decoder +// process should have stopped the AV1 session it opened after the wake; once +// it is closed, the other opens again. Without a sleep both open side by side. +// +// usage: staletest . Exit status 0 = pass. +#include +#include + +#include "vcndriver.h" + +static VcnSleepMark g_now = {.asleepNs = 1000000000ull, .wakeUs = 1}; +static void mark(VcnSleepMark* m) { *m = g_now; } + +typedef struct { + void (*setMark)(void (*)(VcnSleepMark*)); + VcnDriverSession* (*open)(char*, size_t); + void (*close)(VcnDriverSession*); + int (*live)(void); +} Lib; + +static bool load(const char* path, Lib* l) { + void* h = dlopen(path, RTLD_NOW | RTLD_LOCAL); + if (!h) { + printf("FAIL cannot load %s: %s\n", path, dlerror()); + return false; + } + l->setMark = dlsym(h, "stale_set_mark"); + l->open = dlsym(h, "stale_open"); + l->close = dlsym(h, "stale_close"); + l->live = dlsym(h, "stale_live"); + if (!l->setMark || !l->open || !l->close || !l->live) { + printf("FAIL %s lacks its functions\n", path); + return false; + } + l->setMark(mark); + return true; +} + +static int failures; +static void expect(const char* what, bool ok) { + printf("%s %s\n", ok ? "PASS" : "FAIL", what); + if (!ok) failures++; +} + +int main(int argc, char** argv) { + if (argc != 3) { + fprintf(stderr, "usage: staletest \n"); + return 1; + } + Lib a, b; + if (!load(argv[1], &a) || !load(argv[2], &b)) return 1; + char err[256] = ""; + VcnDriverSession* sa = a.open(err, sizeof(err)); + VcnDriverSession* sb = b.open(err, sizeof(err)); + expect("without a sleep, both plug-ins open a session", sa && sb); + if (sb) b.close(sb); + g_now.asleepNs += 20000000000ull; // a 20 s sleep + g_now.wakeUs += 1; + err[0] = 0; + sb = b.open(err, sizeof(err)); + printf(" refused: %s\n", err); + expect( + "after it, one plug-in's session from before the sleep, still open, " + "stops the other from opening one, before it opens anything", + sa && !sb && b.live() == 0); + if (sb) b.close(sb); + VcnDriverSession* sa2 = a.open(err, sizeof(err)); + expect("and the same plug-in from opening another", sa && !sa2); + if (sa2) a.close(sa2); + if (sa) a.close(sa); + expect("its close (without the driver's teardown) frees the accelerator", + a.live() == 0); + sb = b.open(err, sizeof(err)); + sa2 = a.open(err, sizeof(err)); + expect("once it is closed, both open sessions again", sb && sa2); + if (sb) b.close(sb); + if (sa2) a.close(sa2); + expect("and close them", a.live() == 0 && b.live() == 0); + return failures ? 1 : 0; +} diff --git a/GPU/decode/vp9/vcnvp9.c b/GPU/decode/vp9/vcnvp9.c index f0c062c2..5404c4e1 100644 --- a/GPU/decode/vp9/vcnvp9.c +++ b/GPU/decode/vp9/vcnvp9.c @@ -655,7 +655,7 @@ static void destroy_now(VcnVP9* d) { void vcnvp9_destroy(VcnVP9* d) { if (!d) return; - vcn_teardown(d->stuck, vlog(), "VP9 session", ^{ + vcn_teardown(d->stuck, vcn_session_lost(&d->s), vlog(), "VP9 session", ^{ destroy_now(d); }); } @@ -806,6 +806,15 @@ static int on_frame(void* vctx, VP9Parser* p, VP9ParseResult kind, } if (d->dpb[slot]) CVPixelBufferRelease(d->dpb[slot]); d->dpb[slot] = target; + // Nothing goes into the pool or to the engine for a session from before a + // system sleep (vcndriver.h). + if (vcn_session_lost(&d->s)) { + d->broken = true; + d->failure = VCNVP9_FAIL_DEVICE; + snprintf(d->err, sizeof(d->err), "%s", + "the system slept since this session opened"); + return -1; + } int bi = d->bsNext; d->bsNext = (d->bsNext + 1) % NUM_BS; memcpy(d->s.bsAddr[bi], data, size); @@ -870,10 +879,12 @@ int vcnvp9_decode(VcnVP9* d, const uint8_t* chunk, size_t size, int64_t tag, CVPixelBufferRelease(d->hidden); d->hidden = NULL; } + if (!d->broken && vcn_session_lost(&d->s)) d->broken = true; if (d->broken) { snprintf(d->err, sizeof(d->err), "session stopped: %s", - d->stuck ? "the GPU did not finish an earlier frame" - : "an earlier driver call failed"); + d->stuck ? "the GPU did not finish an earlier frame" + : d->s.lost ? "the system slept since it opened" + : "an earlier driver call failed"); d->failure = VCNVP9_FAIL_DEVICE; return -1; } diff --git a/GPU/docs/how-it-works.md b/GPU/docs/how-it-works.md index 146523a7..a1df6f9b 100644 --- a/GPU/docs/how-it-works.md +++ b/GPU/docs/how-it-works.md @@ -145,6 +145,47 @@ ends. A failed driver call or a stuck command is reported to VideoToolbox as a m `canAcceptFormatDescription` says no from then on. It reads the format under a lock of its own, so it never waits for a frame the GPU is decoding. +### A system sleep (0.3.6) + +Apple's kernel driver keeps a decoder's video context across a sleep, but restarts the +video engine under it. Read in IDA (AMDRadeonX6000, 26.7.3 KDK): `systemWillSleep` calls +each video context's `setSuspendResumeState(false)`, which waits for the last command of +every VCN ring and then stops the rings; `saveVCNSession`, called on the way down, is +empty. At wake, `powerUpHW` and `internalDidWake` start the rings again, and +`restoreVCNSession` only sends the context's clocks and power client again. Nothing tells +the program: AMDRadeonVADriver2, AppleGVA and VideoToolbox have no sleep handling at all. +The engine has lost the sessions it had (the driver sends a create-session command once, +when a decoder opens, and a destroy-session command when it closes). + +So a session opened before a sleep is never used again (`vcn_session_lost` in +`decode/common/vcnsession.c`). A sleep is seen without any notification: the time the Mac +has spent asleep (`mach_continuous_time` minus `mach_absolute_time`) or the time of the +last wake (`kern.waketime`) changed since the session opened. Such a session writes nothing +more into its bitstream pool and schedules nothing; its frames fail as a malfunction, and +VideoToolbox makes a new session, which opens on the restarted engine. Closing it skips +`DeleteContexts`, `FreeBitstreamBufferPool` and `DeleteDriver`: the first sends the engine +a destroy-session command for a session it no longer has and waits for it with no time +limit, and `DeleteDriver` does the same for a context still open. Only +`AVD_DestroyAVDAccelerator` runs, on the background queue: it closes the three IOKit +connections, and the kernel's own close of the video context sends the engine nothing +(`submitDestroyCommand` returns at once). What the driver allocated in the process stays +until the process ends. A notification could not be used anyway: VideoToolbox's decoder +service runs in a sandbox (`VTDecoderSandboxProfile.sb`) that does not allow the power +domain's user client `IORegisterForSystemPower` opens. + +While a session from before a sleep is still open in a process, no new session opens in +that process, in any of the plug-ins: `vcn_session_open` fails before it opens anything, +and VideoToolbox gives the stream to another decoder (software). A reported hang began just +so: a browser's decoder process kept two VP9 sessions open across a sleep, and the AV1 +session it opened after the wake never decoded a frame; the Mac hung after the next wake. +Each plug-in bundle has its own copy of the session code, so they count each other's open +sessions through the process's local notification center (`CFNotificationCenterGetLocalCenter`, +which calls every observer on the posting thread). Once those sessions are closed, new ones +open on the GPU again. + +The kernel side has been read, not run across a sleep with a decode going: the CPU tests +(`sessiontest`, a made-up sleep) cover the plug-in side. + ### The parsers The engine decodes the tile data; the host must read the headers. Each decoder has its own diff --git a/GPU/docs/testing.md b/GPU/docs/testing.md index 7ffb7ada..ee3fe84c 100644 --- a/GPU/docs/testing.md +++ b/GPU/docs/testing.md @@ -109,4 +109,14 @@ them, when, on which card and macOS build, and add the result to `docs/status.md leaves no context to delete, and `QueryAVDCommandStatus` with `.wait = 0` returns at once (status 1 done, 2 running). Still open: how long the kernel's own wait can last after a GPU restart. +- Decoders 0.3.6, a system sleep during a decode: `vtvp9test` and `vtav1test` with + `-loop N -pace 30` keep one session going across `pmset sleepnow`, and `-renew` makes a + new session for every pass in the same process. The session from before the sleep must + fail as a malfunction (-12911) at the first frame after the wake, with no GPU restart in + the kernel log and no hang; with `-renew`, the passes after the wake must match their + reference again. The plug-ins log "the system slept since this session opened" and + "session from before the sleep closed without the driver's own teardown". In a browser: + a VP9 video left open (paused) across the sleep, then a second video in the same browser + after the wake must play (in software while the first tab stays open) and the Mac must + not hang. Only `sessiontest` and `staletest` (made-up driver and sleep) have run. - Everything at once: `install/check.sh` ends in one line. diff --git a/GPU/tests/run.sh b/GPU/tests/run.sh index f6d06449..c91cf23d 100755 --- a/GPU/tests/run.sh +++ b/GPU/tests/run.sh @@ -22,7 +22,8 @@ # the parsers survive damaged streams: libvpx's invalid files and thousands of copies # damaged at random, under the address and undefined-behaviour sanitizers # 5. the rule that picks AMD's accelerator; the wait for a decode command gives up on a -# command that never finishes (waittest, with a made-up driver) +# command that never finishes (waittest, with a made-up driver); two plug-ins of one +# process: a session from before a sleep stops new ones until it closes (staletest) # 5b. the loader kext: its decisions, that it builds twice to the same bytes and lists the # plug-ins just built, that install/loader.sh puts it on an EFI and takes it off again # (on made-up EFI folders), and that it accepts the AMFI functions of this Mac @@ -143,6 +144,9 @@ check "$rounds damaged copies of each stream are survived" damaged step "decoders: accelerator rule" check "only AMD's accelerator is taken" decode/build/tests/acceltest check "a decode command that never finishes times out" decode/build/tests/waittest +stale() { decode/build/tests/staletest decode/build/tests/libstale-{a,b}.dylib > decode/build/tests/staletest.txt || + { cat decode/build/tests/staletest.txt; return 1; }; } +check "two plug-ins of one process: a session from before a sleep stops new ones until it closes" stale sessions() { decode/build/tests/sessiontest-av1 tests/media/av1/av1-1-b8-01-size-16x16.ivf tests/media/av1/av1-1-b8-05-mv.ivf > decode/build/tests/sessiontest-av1.txt && decode/build/tests/sessiontest-vp9 tests/media/vp9/vp90-2-12-droppable_1.ivf \ From be05e73e2907b3c27637db4508a7f6fbaecc2e41 Mon Sep 17 00:00:00 2001 From: DrogaBox Date: Thu, 26 Nov 2026 00:02:35 -0300 Subject: [PATCH 2/3] GPU decoders: after a sleep, rebuild a session instead of failing it A session that finds the system slept since it opened now drops its old driver objects without sending them anything, opens a new driver, context and buffer pool in the same plug-in session, and drops frames until a key frame. The sleep is also noticed when the wall clock runs ahead of mach_absolute_time, and kern.waketime is read at most every 100 ms. Sessions from before a sleep no longer stop new ones from opening; they are counted once per process for the log. The loss is checked before a frame takes a picture slot. --- GPU/decode/av1/vcnav1.c | 179 +++++++++++++++++------ GPU/decode/common/vcndriver.c | 38 ++++- GPU/decode/common/vcndriver.h | 68 ++++++--- GPU/decode/common/vcnsession.c | 132 ++++++++++++++--- GPU/decode/tests/sessiontest.c | 184 +++++++++++++++++++----- GPU/decode/tests/staletest.c | 14 +- GPU/decode/vp9/vcnvp9.c | 254 +++++++++++++++++++++++---------- 7 files changed, 675 insertions(+), 194 deletions(-) diff --git a/GPU/decode/av1/vcnav1.c b/GPU/decode/av1/vcnav1.c index 3e394687..bc1d609c 100644 --- a/GPU/decode/av1/vcnav1.c +++ b/GPU/decode/av1/vcnav1.c @@ -23,6 +23,10 @@ int vcnav1_gpu_armed = 0; #define VCN_MODE_VCN0 4 #define NUM_DPB 9 +// A rebuild after a sleep waits for a key frame; at 60 fps this is ten +// seconds of frames. A stream that does not send one by then is stopped the +// way PR 160 stopped it, so the host can hand it to another decoder. +#define REBUILD_MAX_DROPPED 600 #define NUM_BS VCN_NUM_BS #define BS_SIZE VCN_BS_SIZE #define SEQ_BYTES 2048 @@ -60,10 +64,13 @@ struct VcnAV1 { pool; // decode targets; references live in the driver's internal DPB uint32_t poolW, poolH; bool poolTen; - bool stuck; // a command never finished: the GPU may still hold it - bool broken; // stuck, or a driver call failed: nothing more goes out - int failure; // VCNAV1_FAIL_* of the last error - bool shown; // the current decode call output a frame + bool stuck; // a command never finished: the GPU may still hold it + bool broken; // stuck, or a driver call failed: nothing more goes out + bool needKey; // rebuilt after a sleep: drop frames until a key frame + unsigned dropped; // frames dropped since that rebuild + unsigned rebuilds; // driver objects rebuilt in this session (one per sleep) + int failure; // VCNAV1_FAIL_* of the last error + bool shown; // the current decode call output a frame CVPixelBufferRef hidden; // retained: last frame it decoded without showing unsigned fwErrors; // decodes the firmware reported as failed unsigned done; // decode commands that finished @@ -172,6 +179,45 @@ static CVPixelBufferRef new_target(VcnAV1* d, uint32_t w, uint32_t h, if (CVPixelBufferPoolCreatePixelBuffer(NULL, d->pool, &pb)) return NULL; return pb; } +// One AV1 context on the driver handle this session has open: what a create +// and a rebuild after a sleep both need. +static int av1_create_context(VcnAV1* d) { + AVD_ContextList list = {0}; + void* ctxOut[2] = {0}; + AVD_FunctionInfo* fis[1] = {&list.inlineInfo}; + list.count = 1; + list.functions = fis; + list.contextsOut = ctxOut; + // mode 3/5 => VAVcnDecoder::Init(1) => second VCN instance (VCN1Dec), which + // has NO AV1 on Navi21 and hangs the GPU. Mode 4 (what AppleGVA uses for + // H.264) => Init(0) => VCN0Dec. + list.inlineInfo = (AVD_FunctionInfo){.kind = 1, + .function = AVD_FUNC_AV1, + .mode = VCN_MODE_VCN0, + .pixelRate = d->maxW * d->maxH * 60, + .width = d->maxW, + .height = d->maxH, + .inFormat = 0x72617762, + .inFormatCount = 1, + .outFormat = 0x4e563132, + .outFormatCount = 1}; + AVD_DriverContextInit ci = {.list = &list}; + int r = FN(CreateContexts)(d->s.drv, &ci); + if (r || !ctxOut[0]) return r ? r : 1; + d->s.ctx = ctxOut[0]; + return 0; +} + +// The builds the AV1 parameter blocks were validated against, or the override +// a dry run sets (vcndriver.h). +static bool av1_driver_allowed(const VcnDriverLib* lib) { + for (size_t i = 0; i < sizeof(kValidatedDrivers) / sizeof(*kValidatedDrivers); + i++) + if (!strcmp(lib->uuid, kValidatedDrivers[i])) return true; + const char* ov = getenv("VCNAV1_ALLOW_UNVALIDATED_DRIVER"); + return ov && !strcmp(ov, "1"); +} + VcnAV1* vcnav1_create(uint32_t maxWidth, uint32_t maxHeight, char* err, size_t errLen) { VcnAV1* d = calloc(1, sizeof(*d)); @@ -215,33 +261,64 @@ VcnAV1* vcnav1_create(uint32_t maxWidth, uint32_t maxHeight, char* err, // included. if (!vcn_session_open(&d->s, &lib, svc, vlog(), why, sizeof(why))) FAIL("%s", why); - AVD_ContextList list = {0}; - void* ctxOut[2] = {0}; - AVD_FunctionInfo* fis[1] = {&list.inlineInfo}; - list.count = 1; - list.functions = fis; - list.contextsOut = ctxOut; - // mode 3/5 => VAVcnDecoder::Init(1) => second VCN instance (VCN1Dec), which - // has NO AV1 on Navi21 and hangs the GPU. Mode 4 (what AppleGVA uses for - // H.264) => Init(0) => VCN0Dec. - list.inlineInfo = (AVD_FunctionInfo){.kind = 1, - .function = AVD_FUNC_AV1, - .mode = VCN_MODE_VCN0, - .pixelRate = maxWidth * maxHeight * 60, - .width = maxWidth, - .height = maxHeight, - .inFormat = 0x72617762, - .inFormatCount = 1, - .outFormat = 0x4e563132, - .outFormatCount = 1}; - AVD_DriverContextInit ci = {.list = &list}; - int r = FN(CreateContexts)(d->s.drv, &ci); - if (r || !ctxOut[0]) FAIL("CreateContexts(AV1) %d", r); - d->s.ctx = ctxOut[0]; + int r = av1_create_context(d); + if (r) FAIL("CreateContexts(AV1) %d", r); DBG("created: drv=%p ctx=%p bs=%p\n", d->s.drv, d->s.ctx, d->s.bsAddr[0]); return d; } +// Rebuilds the driver side of a session the system slept through (plan B of +// the sleep fix, job 178): the objects from before the sleep are dropped +// without a word to the driver, and a fresh accelerator, driver, context and +// bitstream pool are opened for the same plug-in session, so the host's decoder +// object lives on instead of failing frames with kVTVideoDecoderMalfunctionErr. +// Nothing decoded before the sleep can be referenced after it, so the DPB, the +// reference slots, the parser and the pictures go, and the next frames are +// dropped until a key frame (on_frame). False when the rebuild fails: the +// caller then stops the session as PR 160 did. +static bool av1_rebuild(VcnAV1* d, char* why, size_t whyLen) { + vcn_session_drop(&d->s); + for (int i = 0; i < NUM_DPB; i++) + if (d->dpb[i]) { + CVPixelBufferRelease(d->dpb[i]); + d->dpb[i] = NULL; + } + memset(d->dpbRefs, 0, sizeof(d->dpbRefs)); + if (d->hidden) { + CVPixelBufferRelease(d->hidden); + d->hidden = NULL; + } + av1_parser_free(&d->parser); + av1_parser_init(&d->parser); + d->bsNext = 0; + d->needKey = true; + d->dropped = 0; + VcnDriverLib lib; + if (!vcn_driver_load(&lib, why, whyLen)) return false; + if (!av1_driver_allowed(&lib)) { + snprintf(why, whyLen, "AMDRadeonVADriver2 build %s not validated", + lib.uuid); + return false; + } + io_service_t svc = vcn_find_accelerator(); + if (!svc) { + snprintf(why, whyLen, "no AMD accelerator"); + return false; + } + if (!vcn_session_reopen(&d->s, &lib, svc, vlog(), why, whyLen)) return false; + int r = av1_create_context(d); + if (r) { + snprintf(why, whyLen, "CreateContexts(AV1) %d", r); + vcn_session_drop(&d->s); + return false; + } + d->rebuilds++; + os_log_error(vlog(), + "the system slept since this session opened: driver rebuilt, " + "frames are dropped until the next key frame"); + return true; +} + static void destroy_now(VcnAV1* d) { vcn_session_close(&d->s); // The pictures go after the driver: a stuck command may still write one. @@ -574,6 +651,27 @@ static bool seq_supported(const AV1Seq* s) { static int on_frame(void* vctx, AV1Parser* p, AV1ParseResult kind) { VcnAV1* d = vctx; const AV1Frame* h = &p->fh; + // After a rebuild nothing from before the sleep can be used: every frame but + // a key frame is dropped (no picture for this sample, which is what a hidden + // frame looks like to the host, not an error), and a key frame starts the + // decoder again. Bounded: a stream that never sends one is stopped as a + // device failure, PR 160's behaviour. + if (d->needKey) { + if (kind != AV1_PARSE_FRAME_READY || h->frame_type != AV1_KEY_FRAME) { + if (++d->dropped > REBUILD_MAX_DROPPED) { + d->broken = true; + d->failure = VCNAV1_FAIL_DEVICE; + snprintf(d->err, sizeof(d->err), + "no key frame in %u frames after the system sleep", + d->dropped); + return -1; + } + return 0; + } + vcnav1_flush(d); + d->needKey = false; + d->dropped = 0; + } if (kind == AV1_PARSE_SHOW_EXISTING) { AV1RefSlot* r = &p->ref[h->frame_to_show_map_idx]; if (!r->valid || r->dpb_slot < 0 || r->dpb_slot >= NUM_DPB || @@ -647,15 +745,6 @@ static int on_frame(void* vctx, AV1Parser* p, AV1ParseResult kind) { d->dpb[slot] = target; pack_seq(d); pack_frame(d); - // Nothing goes into the pool or to the engine for a session from before a - // system sleep (vcndriver.h). - if (vcn_session_lost(&d->s)) { - d->broken = true; - d->failure = VCNAV1_FAIL_DEVICE; - snprintf(d->err, sizeof(d->err), "%s", - "the system slept since this session opened"); - return -1; - } // bitstream: concatenated tile data int bi = d->bsNext; d->bsNext = (d->bsNext + 1) % NUM_BS; @@ -752,12 +841,22 @@ int vcnav1_decode(VcnAV1* d, const uint8_t* tu, size_t size, int64_t userTag, CVPixelBufferRelease(d->hidden); d->hidden = NULL; } - if (!d->broken && vcn_session_lost(&d->s)) d->broken = true; + if (!d->broken && vcn_session_lost(&d->s)) { + char why[200]; + if (!av1_rebuild(d, why, sizeof(why))) { + d->broken = true; + snprintf(d->err, sizeof(d->err), + "session stopped: the system slept since it opened and the " + "rebuild failed (%s)", + why); + d->failure = VCNAV1_FAIL_DEVICE; + return -1; + } + } if (d->broken) { snprintf(d->err, sizeof(d->err), "session stopped: %s", - d->stuck ? "the GPU did not finish an earlier frame" - : d->s.lost ? "the system slept since it opened" - : "an earlier driver call failed"); + d->stuck ? "the GPU did not finish an earlier frame" + : "an earlier driver call failed"); d->failure = VCNAV1_FAIL_DEVICE; return -1; } diff --git a/GPU/decode/common/vcndriver.c b/GPU/decode/common/vcndriver.c index 0f61de74..3f6e6afe 100644 --- a/GPU/decode/common/vcndriver.c +++ b/GPU/decode/common/vcndriver.c @@ -85,18 +85,42 @@ void vcn_sleep_mark(VcnSleepMark* m) { // mach_continuous_time is mach_absolute_time plus the time spent asleep. The // two are read apart: a reading whose two absolute times are more than 10 us // apart (the thread was preempted between them) is taken again. - uint64_t asleep = 0; + uint64_t asleep = 0, mono = 0; for (int i = 0; i < 8; i++) { uint64_t a = mach_absolute_time(), c = mach_continuous_time(), b = mach_absolute_time(); asleep = c > b ? c - b : 0; + mono = b; if ((b - a) * tb.numer / tb.denom < 10000) break; } m->asleepNs = asleep * tb.numer / tb.denom; - struct timeval wake = {0}; - size_t len = sizeof(wake); - m->wakeUs = - sysctlbyname("kern.waketime", &wake, &len, NULL, 0) || len != sizeof(wake) - ? 0 - : (int64_t)wake.tv_sec * 1000000 + wake.tv_usec; + m->monoNs = mono * tb.numer / tb.denom; + struct timeval wall; + gettimeofday(&wall, NULL); + m->wallUs = (int64_t)wall.tv_sec * 1000000 + wall.tv_usec; + // kern.waketime changes once per sleep and costs a sysctl; the codecs ask for + // a mark on every frame (60 to 120 times a second at 4K60), so the value is + // read again at most every 100 ms of mach_absolute_time. Time spent asleep + // does not advance that clock, so a waketime read a moment before a sleep can + // be reused for a moment after the wake; the time asleep is read every time + // and is what notices the sleep. Relaxed reads and writes: a value read twice + // by two threads is the same one. + static uint64_t wakeReadAtNs; + static int64_t wakeUs; + static bool wakeKnown; + if (!__atomic_load_n(&wakeReadAtNs, __ATOMIC_RELAXED) || + m->monoNs - __atomic_load_n(&wakeReadAtNs, __ATOMIC_RELAXED) >= + 100000000ull) { + struct timeval wake = {0}; + size_t len = sizeof(wake); + bool failed = sysctlbyname("kern.waketime", &wake, &len, NULL, 0) || + len != sizeof(wake); + __atomic_store_n(&wakeUs, + failed ? 0 : (int64_t)wake.tv_sec * 1000000 + wake.tv_usec, + __ATOMIC_RELAXED); + __atomic_store_n(&wakeKnown, !failed, __ATOMIC_RELAXED); + __atomic_store_n(&wakeReadAtNs, m->monoNs, __ATOMIC_RELAXED); + } + m->wakeUs = __atomic_load_n(&wakeUs, __ATOMIC_RELAXED); + m->wakeKnown = __atomic_load_n(&wakeKnown, __ATOMIC_RELAXED); } diff --git a/GPU/decode/common/vcndriver.h b/GPU/decode/common/vcndriver.h index e1059c5c..a612b6a0 100644 --- a/GPU/decode/common/vcndriver.h +++ b/GPU/decode/common/vcndriver.h @@ -56,22 +56,35 @@ enum { VCN_COMMAND_TIMEOUT_MS = 1000 }; // // The mark is the time this Mac has spent asleep since it started, as the // kernel counts it (mach_continuous_time runs on during a sleep, -// mach_absolute_time does not), and the time of the last wake (kern.waketime). -// Either changing means the system slept. Neither needs a notification, which a +// mach_absolute_time does not), the time of the last wake (kern.waketime), and +// the wall clock read next to mach_absolute_time. Any of the three changing +// means the system slept. The third is there for a machine whose sleep path +// skips the kernel's wake accounting, where the first signal never moves, and +// whose kern.waketime is refused inside the sandbox, where the second one is +// dead: the RTC counts through a sleep even when the kernel counted none of it, +// so a wall clock that ran ahead of mach_absolute_time is a sleep the other two +// would miss. None of the three needs a notification, which a // decoder could not get anyway: VideoToolbox's decoder service is sandboxed // without the root power domain's user client that IORegisterForSystemPower // opens (VTDecoderSandboxProfile.sb). typedef struct { uint64_t asleepNs; // time asleep since boot int64_t wakeUs; // last wake in microseconds since 1970; 0 when unknown + bool wakeKnown; // kern.waketime could be read (its value may still be 0) + uint64_t monoNs; // mach_absolute_time at the same reading, in ns + int64_t wallUs; // that same moment on the wall clock, us since 1970 } VcnSleepMark; -// Reads both now (vcndriver.c: it asks the system). +// Reads all of it now (vcndriver.c: it asks the system). kern.waketime is a +// sysctl and the codecs ask for a mark on every frame, so that one value is +// reused for 100 ms of mach_absolute_time; a sleep is still noticed at once +// through the time asleep. void vcn_sleep_mark(VcnSleepMark* m); -// True when the system has slept between `then` and `now`. A change of the -// time asleep below 1 ms is the error of the reading, not a sleep: a real one -// takes seconds. +// True when the system has slept between `then` and `now`: the time asleep +// moved by more than 1 ms (the error of a reading, not a sleep: a real one +// takes seconds), the wake time is two different non-zero values, or the wall +// clock ran more than a second ahead of mach_absolute_time (see above). bool vcn_slept_between(const VcnSleepMark* then, const VcnSleepMark* now); typedef enum { @@ -116,22 +129,45 @@ typedef struct VcnDriverSession { // part opened so far is closed again, s is left empty and err says which call // failed. // -// It also fails, before it opens anything, while a session of this process -// that opened before a system sleep is still open, in any of the plug-ins (they -// ask each other through the process's local notification center). A reported +// It counts, once per process, the sessions of this process that opened before +// a system sleep and are still open in any of the plug-ins (they ask each +// other through the process's local notification center). It no longer refuses +// because of them: those sessions rebuild for themselves now, and refusing +// would turn a paused tab into no hardware decode in the whole process (F3 of +// the review). A reported // hang began exactly so: two VP9 sessions of a browser's decoder process stayed // open across a sleep, and the AV1 session the same process opened after the -// wake never decoded a frame. VideoToolbox then gives the stream to another -// decoder (software); once those sessions are closed, new ones open again. +// wake never decoded a frame. That is why a decoder session does not fail when +// it finds the system slept: it rebuilds its driver side (vcn_session_reopen) +// and drops frames until a key frame, so the host's decoder object lives on and +// never sees a malfunction. What is left of the refusal below is the case where +// the rebuild itself fails. bool vcn_session_open(VcnDriverSession* s, const VcnDriverLib* lib, io_service_t svc, os_log_t log, char* err, size_t errLen); +// Opens the driver side of a session that replaces one the system slept +// through: the same work without the check for other sessions of the process +// from before the sleep (this one is being replaced, not added beside them), +// and it clears `lost`, because what it opens is from after the wake. The +// session stays in this plug-in's list of open ones. +bool vcn_session_reopen(VcnDriverSession* s, const VcnDriverLib* lib, + io_service_t svc, os_log_t log, char* err, + size_t errLen); + +// Drops the driver objects of a lost session without telling the driver +// anything: AVD_DestroyAVDAccelerator (that is what closes the IOKit clients) +// and the service. The driver handle, its context and the bitstream pool are +// left where they are, because only the driver can free them and it may be +// wedged after a wake (F4 of the review); a rebuild leaks that once per sleep +// and starts a new pool. The session stays listed as open. +void vcn_session_drop(VcnDriverSession* s); + // True once the system has slept since s opened (see VcnSleepMark), and from -// then on; the first time, it says so in the log. The codec asks before it -// writes a frame into the bitstream pool and before it schedules a command, and -// refuses the frame as a device failure: VideoToolbox then makes a new session, -// which opens on the restarted engine. A session with no accelerator is never -// lost. +// then on; the first time, it says so in the log. A codec that finds this +// rebuilds its driver side (vcnav1.c / vcnvp9.c: vcn_session_drop then +// vcn_session_reopen) and drops frames until a key frame; only a rebuild that +// fails stops the session, with kVTVideoDecoderMalfunctionErr (-12911), which +// is PR 160's behaviour. A session with no accelerator is never lost. bool vcn_session_lost(VcnDriverSession* s); // Closes what open (and the codec's CreateContexts) made, in the order Apple's diff --git a/GPU/decode/common/vcnsession.c b/GPU/decode/common/vcnsession.c index 2efb8b4b..cca1fa1f 100644 --- a/GPU/decode/common/vcnsession.c +++ b/GPU/decode/common/vcnsession.c @@ -65,7 +65,18 @@ VcnWaitResult vcn_wait_command(AVD_QueryAVDCommandStatus_fn query, void* driver, bool vcn_slept_between(const VcnSleepMark* then, const VcnSleepMark* now) { if (now->asleepNs > then->asleepNs + 1000000) return true; - return then->wakeUs && now->wakeUs && then->wakeUs != now->wakeUs; + if (then->wakeUs && now->wakeUs && then->wakeUs != now->wakeUs) return true; + // The wall clock counts through a sleep even when the kernel counted none of + // it, and mach_absolute_time does not: the two running apart by more than a + // second is a sleep neither of the other signals saw. A wall clock set back + // (NTP, a manual change) makes the difference negative and is not a sleep; a + // clock set forward is, which is the safe direction. + if (then->wallUs && now->wallUs) { + int64_t wallUs = now->wallUs - then->wallUs; + int64_t monoUs = (int64_t)(now->monoNs - then->monoNs) / 1000; + if (wallUs - monoUs > 1000000) return true; + } + return false; } bool vcn_session_lost(VcnDriverSession* s) { @@ -165,25 +176,65 @@ static int stale_sessions(const VcnSleepMark* now) { return q.stale; } -bool vcn_session_open(VcnDriverSession* s, const VcnDriverLib* lib, - io_service_t svc, os_log_t log, char* err, - size_t errLen) { +// Shared by open and reopen. `rebuild` keeps the session in this plug-in's +// list of open sessions (it is replacing one, not adding one) and skips the +// question asked of the other plug-ins, which was for a new session opened +// beside a stale one; a rebuild is the answer to that case now. +static bool open_session(VcnDriverSession* s, const VcnDriverLib* lib, + io_service_t svc, os_log_t log, bool rebuild, + char* err, size_t errLen) { + bool listed = s->listed; + VcnDriverSession* nextOpen = s->nextOpen; *s = (VcnDriverSession){.destroy = lib->destroy, .svc = svc, .log = log}; + if (rebuild) { + // Already in the list: keep it there (close unlists it if this fails). + s->listed = listed; + s->nextOpen = nextOpen; + } // Before anything is opened: a sleep during the open loses the session too. vcn_sleep_mark(&s->opened); + if (!s->opened.wakeKnown) { + // Not fatal: the other two signals still count. Said once, because in a + // sandbox it is the expected case (container.sb lists kern.waketime by + // name, so a profile stricter than that one refuses it) and the value is + // never read later, which used to be invisible. + static bool told; + if (!__atomic_exchange_n(&told, true, __ATOMIC_RELAXED)) + os_log_error(log, + "kern.waketime is not readable in this process: a sleep is " + "noticed through the monotonic and wall clocks only"); + } #define FAIL(...) \ do { \ snprintf(err, errLen, __VA_ARGS__); \ vcn_session_close(s); \ return false; \ } while (0) - // No new session beside one from before a sleep (vcndriver.h). - int stale = stale_sessions(&s->opened); - if (stale > 0) - FAIL( - "%d session(s) of this process from before a system sleep still " - "open: no new one until they close", - stale); + // Other sessions of this process from before a sleep are only counted now: a + // new session opens beside them and each one rebuilds for itself, which is + // what stops a paused tab from turning hardware decode off for the process + // (F3 of the review). A rebuild does not ask at all. + int stale = rebuild ? 0 : stale_sessions(&s->opened); + if (stale < 0) { + // The question could not be asked (no memory for the dictionary). Fail + // open, as a decoder must, but say so once: this is the one case where + // the guard is not in force. + static bool toldQuery; + if (!__atomic_exchange_n(&toldQuery, true, __ATOMIC_RELAXED)) + os_log_error(log, + "could not ask the other plug-ins for sessions from before " + "a sleep: this session opens beside them"); + } + if (stale > 0) { + // Once per process: the count is a diagnostic, not a refusal any more. + static bool toldStale; + if (!__atomic_exchange_n(&toldStale, true, __ATOMIC_RELAXED)) + os_log_error(log, + "%d session(s) of this process from before a system sleep " + "are still open: this one opens beside them and rebuilds " + "for itself if it needs to", + stale); + } if (!lib->destroy) { // Said once per process: every session would say the same. static bool told; @@ -232,10 +283,43 @@ bool vcn_session_open(VcnDriverSession* s, const VcnDriverLib* lib, for (int i = 0; i < VCN_NUM_BS; i++) if (!s->bsAddr[i]) FAIL("AllocateBitstreamBufferPool: no buffer %d", i); #undef FAIL - list_open(s); + if (!rebuild) list_open(s); return true; } +bool vcn_session_open(VcnDriverSession* s, const VcnDriverLib* lib, + io_service_t svc, os_log_t log, char* err, + size_t errLen) { + return open_session(s, lib, svc, log, false, err, errLen); +} + +bool vcn_session_reopen(VcnDriverSession* s, const VcnDriverLib* lib, + io_service_t svc, os_log_t log, char* err, + size_t errLen) { + return open_session(s, lib, svc, log, true, err, errLen); +} + +void vcn_session_drop(VcnDriverSession* s) { + if (!s->accel) return; + // No DeleteContexts, FreeBitstreamBufferPool or DeleteDriver: those send the + // engine a command for a session it has forgotten and wait with no limit. + if (s->destroy) s->destroy(s->accel); + s->accel = NULL; + s->drv = NULL; + s->ctx = NULL; + s->poolAllocated = false; + memset(s->bsAddr, 0, sizeof(s->bsAddr)); + if (s->svc) IOObjectRelease(s->svc); + s->svc = 0; +} + +// Skipping the driver's own teardown keeps this close from waiting on a command +// for a session the engine has forgotten, but it does not make it a +// non-blocking call: AVD_DestroyAVDAccelerator below still closes three IOKit +// user clients, and on the kernel side a context stop goes through PowerPlay's +// notify (escape 0x34), which can wait after a failed wake. That is why a lost +// or stuck session is closed on the teardown queue (vcn_teardown) and never on +// the caller's thread. void vcn_session_close(VcnDriverSession* s) { // Asked here too: a session can be closed without having been asked since // the wake (a paused video that is closed after it). @@ -251,13 +335,23 @@ void vcn_session_close(VcnDriverSession* s) { FN(DeleteDriver)(s->drv); } if (s->destroy) s->destroy(s->accel); - if (lost) - os_log_error(s->log, - "session from before the sleep closed without the driver's " - "own teardown%{public}s", - s->destroy ? "" - : " (this driver build has no " - "AVD_DestroyAVDAccelerator: it stays open)"); + if (lost) { + // What the skipped teardown leaves behind, and how much of it this + // process has left behind so far: the driver's pool and context go with + // the driver handle, which is never deleted here. Accounting only; the + // fix is a process that does not sleep with sessions open. + static long lostCloses; + long n = __atomic_add_fetch(&lostCloses, 1, __ATOMIC_RELAXED); + os_log_error( + s->log, + "session from before the sleep closed without the driver's own " + "teardown: %ld so far in this process, up to %lld MiB of the " + "driver's bitstream pool and its context not returned%{public}s", + n, (long long)n * VCN_NUM_BS * VCN_BS_SIZE / (1024 * 1024), + s->destroy ? "" + : " (this driver build has no " + "AVD_DestroyAVDAccelerator: it stays open)"); + } } // Out of the list only now: until the accelerator is closed, the session // still counts as open for a new one. diff --git a/GPU/decode/tests/sessiontest.c b/GPU/decode/tests/sessiontest.c index 6206c81b..37c1feb3 100644 --- a/GPU/decode/tests/sessiontest.c +++ b/GPU/decode/tests/sessiontest.c @@ -133,6 +133,8 @@ static struct { bool hang; // commands never finish unsigned firmware; // result of every finished command bool noDestroy; // the build has no AVD_DestroyAVDAccelerator + bool + rebuildFail; // CreateDriver fails: the rebuild after a sleep cannot open } fault; enum { kFakeBuffer = 1 << 20 }; // larger than any frame of the test clips @@ -156,6 +158,7 @@ static int f_create_driver(void** out, AVD_DriverCreate* dc) { st.createDrivers++; if (((FakeAccel*)dc->accel)->destroyed) st.useAfterDestroy = true; if (fault.createDriver) return fault.createDriver; + if (fault.rebuildFail) return 7; // the rebuild's own CreateDriver FakeDrv* d = calloc(1, sizeof(*d)); d->va = calloc(1, 75080); d->factory = calloc(1, 16); @@ -245,10 +248,13 @@ static int f_delete_ctx(void* h, AVD_DriverContextDelete* del) { } // What vcn_sleep_mark reports: the test moves it to make a sleep. static VcnSleepMark fakeSleep = {.asleepNs = 5000000000ull, - .wakeUs = 1795000000000000ll}; + .wakeUs = 1795000000000000ll, + .wallUs = 1795000000000000ll}; static void sleep_for(uint64_t ns) { fakeSleep.asleepNs += ns; fakeSleep.wakeUs += 1000000; + // The wall clock counts through a sleep, mach_absolute_time does not. + fakeSleep.wallUs += (int64_t)(ns / 1000); } static int f_schedule(void* h, AVD_CmdList* l, AVD_RefConList* r) { @@ -378,6 +384,15 @@ static bool released_in_order(void) { } return true; } +// After a rebuild the driver handle from before the sleep is still open: that +// is the leak F4 of the review describes, one per rebuild, left behind on +// purpose because only the driver could free it and it may be wedged. What +// must hold is that every accelerator is closed, and that exactly the dropped +// drivers are left. +static bool closed_after_rebuild(int dropped) { + return st.liveAccels == 0 && st.liveDrivers == dropped && + !st.useAfterDestroy && !st.freeWithoutPool; +} static bool all_released(void) { return st.liveAccels == 0 && st.liveDrivers == 0 && !st.useAfterDestroy && !st.freeWithoutPool; @@ -427,6 +442,10 @@ typedef struct { } Sample; static Sample clip[64]; static int clipCount; +static void clip_clear(void) { + for (int i = 0; i < clipCount; i++) free(clip[i].data); + clipCount = 0; +} static bool read_clip(const char* path) { FILE* f = fopen(path, "rb"); uint8_t h[32], fh[12]; @@ -731,32 +750,48 @@ int main(int argc, char** argv) { d && rj != 0 && FAILURE(d) == FAIL_STREAM && st.schedules == 0); if (d) DESTROY(d); - // 12. A system sleep. + // 12. A system sleep, and the rebuild that follows it instead of failing + // every frame (plan B, job 178). + clip_clear(); + bool haveSamples = read_clip(argv[1]); + if (!haveSamples) printf(" the clip did not read for the sleep tests\n"); + bool haveInter = haveSamples && clipCount > 1; + // A second sample only exercises "dropped until a key frame" if it really + // needs references: on a fresh session such a frame fails as a reference + // error, while a second key frame would decode. + bool interUsable = false; + if (haveInter) { + reset(); + Vcn* probe = make(); + if (probe) DECODE(probe, clip[1].data, clip[1].size, 0, on_out, NULL); + interUsable = probe && FAILURE(probe) == FAIL_REFERENCE; + if (probe) DESTROY(probe); + } + reset(); d = make(); int rb = d ? DECODE(d, frame0, frame0Size, 0, on_out, NULL) : -1; expect("before the sleep, a frame decodes", d && rb == 0); - int schedulesBefore12 = st.schedules; - snapshot_pool(); + int createsBefore12 = st.creates, ctxBefore12 = st.createCtx; sleep_for(30000000000ull); - int ra = d ? DECODE(d, frame0, frame0Size, 1, on_out, NULL) : 0; - int ka = d ? FAILURE(d) : -1; - printf(" after the sleep: %s\n", d ? LASTERR(d) : ""); - int ra2 = d ? DECODE(d, frame0, frame0Size, 2, on_out, NULL) : 0; - expect( - "after it, the session fails as a device and sends nothing, not even " - "into the pool", - ra != 0 && ka == FAIL_DEVICE && ra2 != 0 && FAILURE(d) == FAIL_DEVICE && - st.schedules == schedulesBefore12 && pool_untouched()); + int shown12 = 0; + int ra = d ? DECODE(d, frame0, frame0Size, 1, on_out, &shown12) : -1; + printf(" after the sleep: %s\n", d && ra ? LASTERR(d) : "driver rebuilt"); expect( - "its close skips the driver's own teardown and only destroys the " - "accelerator, in the background", - d && closed_quietly(d)); + "after it, the session rebuilds the driver and decodes the key frame on " + "it, with no error", + d && ra == 0 && shown12 == 1 && st.creates == createsBefore12 + 1 && + st.createCtx == ctxBefore12 + 1); + if (d) DESTROY(d); + expect("and the rebuilt session closes fully, only the dropped driver left", + closed_after_rebuild(1)); + // Closed after the wake without a frame: still the quiet close of PR 160, + // because no rebuild happened. reset(); d = make(); sleep_for(10000000000ull); - expect("a session only closed after the wake closes the same way", + expect("a session only closed after the wake closes quietly", d && closed_quietly(d) && st.schedules == 0); reset(); @@ -770,10 +805,10 @@ int main(int argc, char** argv) { reset(); d = make(); fakeSleep.wakeUs += 1000000; // a wake whose time asleep was not counted - int rw = d ? DECODE(d, frame0, frame0Size, 0, on_out, NULL) : 0; - expect("a new wake time alone counts as a sleep", - rw != 0 && d && FAILURE(d) == FAIL_DEVICE && st.schedules == 0); - if (d) closed_quietly(d); + int rw = d ? DECODE(d, frame0, frame0Size, 0, on_out, NULL) : -1; + expect("a new wake time alone counts as a sleep, and the session rebuilds", + d && rw == 0 && st.creates == 2); + if (d) DESTROY(d); reset(); d = make(); @@ -781,30 +816,113 @@ int main(int argc, char** argv) { int rj12 = d ? DECODE(d, frame0, frame0Size, 0, on_out, NULL) : -1; if (d) DESTROY(d); expect("a change of the time asleep under 1 ms is not a sleep", - rj12 == 0 && st.deleteCtx == 1 && all_released()); + rj12 == 0 && st.deleteCtx == 1 && st.creates == 1 && all_released()); + + reset(); + d = make(); + // A machine whose sleep path skipped the kernel's wake accounting: the + // counters do not move, only the wall clock does (the RTC counts through a + // sleep even when the kernel counted none of it). + fakeSleep.wallUs += 30000000; + int rwall = d ? DECODE(d, frame0, frame0Size, 0, on_out, NULL) : -1; + expect("a wall clock that ran ahead of the counters counts as a sleep", + d && rwall == 0 && st.creates == 2); + if (d) DESTROY(d); + fakeSleep.wallUs -= 30000000; + + reset(); + d = make(); + fakeSleep.wallUs += 2000000; // the same two seconds on both clocks + fakeSleep.monoNs += 2000000000ull; + int rboth = d ? DECODE(d, frame0, frame0Size, 0, on_out, NULL) : -1; + if (d) DESTROY(d); + expect("the wall clock and the counters moving together is not a sleep", + rboth == 0 && st.deleteCtx == 1 && st.creates == 1); + fakeSleep.wallUs -= 2000000; + fakeSleep.monoNs -= 2000000000ull; + + if (interUsable) { + // An inter frame after the sleep: the rebuild happens, the frame is dropped + // with no picture and no error, and the next key frame decodes. + reset(); + d = make(); + int k0 = d ? DECODE(d, clip[0].data, clip[0].size, 0, on_out, NULL) : -1; + sleep_for(10000000000ull); + int createsBefore2 = st.creates; + int shownI = 0; + int di = d ? DECODE(d, clip[1].data, clip[1].size, 1, on_out, &shownI) : -1; + expect( + "an inter frame after the sleep rebuilds and is dropped, with no " + "picture and no error", + d && k0 == 0 && di == 0 && shownI == 0 && + st.creates == createsBefore2 + 1); + int shownK = 0; + int dk = d ? DECODE(d, clip[0].data, clip[0].size, 2, on_out, &shownK) : -1; + if (dk) printf(" key frame after the drop: %s\n", d ? LASTERR(d) : ""); + expect("the next key frame decodes on the rebuilt driver", + d && dk == 0 && shownK == 1); + if (d) DESTROY(d); + expect("and that session closes fully, only the dropped driver left", + closed_after_rebuild(1)); + + // A stream that never sends one: frames are dropped for a while, then the + // session stops the way PR 160 stopped it. + reset(); + d = make(); + if (d) DECODE(d, clip[0].data, clip[0].size, 0, on_out, NULL); + sleep_for(10000000000ull); + int stopped = 0, iters = 0; + for (; d && iters < 1000 && !stopped; iters++) + stopped = DECODE(d, clip[1].data, clip[1].size, iters, on_out, NULL) != 0; + expect( + "with no key frame the frames are dropped up to the limit, then the " + "session stops as a device failure", + d && stopped && FAILURE(d) == FAIL_DEVICE); + if (d) DESTROY(d); + expect("and it still releases everything, only the dropped driver left", + closed_after_rebuild(1)); + } + // A rebuild that fails is the case the refusal is left for. + reset(); + d = make(); + if (d) DECODE(d, frame0, frame0Size, 0, on_out, NULL); + sleep_for(10000000000ull); + fault.rebuildFail = true; + int rf = d ? DECODE(d, frame0, frame0Size, 1, on_out, NULL) : 0; + printf(" rebuild failure: %s\n", d ? LASTERR(d) : ""); + fault.rebuildFail = false; + expect("a rebuild that fails stops the session, as PR 160 did", + d && rf != 0 && FAILURE(d) == FAIL_DEVICE); + int rf2 = d ? DECODE(d, frame0, frame0Size, 2, on_out, NULL) : 0; + expect("and later frames fail without opening anything else", + d && rf2 != 0 && st.creates == 2); + if (d) DESTROY(d); + expect("the failed rebuild leaves nothing open, only the dropped driver", + closed_after_rebuild(1)); + + // A new session opens beside one from before the sleep: no process-wide + // refusal any more, each session rebuilds for itself. reset(); Vcn* before = make(); sleep_for(10000000000ull); - int createsBefore = st.creates; + int createsB = st.creates; Vcn* beside = make(); - expect( - "while a session from before the sleep is open, a new one is refused " - "before it opens anything", - before && !beside && st.creates == createsBefore); + expect("a new session opens beside one from before the sleep", + before && beside && st.creates == createsB + 1); + int rn = beside ? DECODE(beside, frame0, frame0Size, 0, on_out, NULL) : -1; + expect("and decodes on its own driver", beside && rn == 0); if (beside) DESTROY(beside); if (before) closed_quietly(before); reset(); d = make(); - int rn = d ? DECODE(d, frame0, frame0Size, 0, on_out, NULL) : -1; + int rn2 = d ? DECODE(d, frame0, frame0Size, 0, on_out, NULL) : -1; if (d) DESTROY(d); - expect( - "once it is closed, a session opened after the wake decodes and closes " - "fully", - rn == 0 && st.deleteCtx == 1 && st.destroys == 1 && all_released() && - released_in_order()); + expect("a session opened after the wake decodes and closes fully", + rn2 == 0 && st.deleteCtx == 1 && st.destroys == 1 && all_released()); + clip_clear(); if (argc == 3) hidden_frames(argv[2]); free(frame0); diff --git a/GPU/decode/tests/staletest.c b/GPU/decode/tests/staletest.c index 4a19840b..515f58bb 100644 --- a/GPU/decode/tests/staletest.c +++ b/GPU/decode/tests/staletest.c @@ -1,9 +1,9 @@ // staletest: two plug-ins in one process (two copies of common/vcnsession.c, // libstale-a and libstale-b, built from stalelib.c) with a made-up driver and a // made-up sleep. A session of one that opened before a sleep and is still open -// stops the other from opening one, as the VP9 sessions of a browser's decoder -// process should have stopped the AV1 session it opened after the wake; once -// it is closed, the other opens again. Without a sleep both open side by side. +// is seen by the other plug-in (the local notification center), but it no +// longer stops it from opening one: each session rebuilds for itself after a +// sleep (plan B of the sleep fix). Without a sleep both open side by side. // // usage: staletest . Exit status 0 = pass. #include @@ -63,12 +63,12 @@ int main(int argc, char** argv) { sb = b.open(err, sizeof(err)); printf(" refused: %s\n", err); expect( - "after it, one plug-in's session from before the sleep, still open, " - "stops the other from opening one, before it opens anything", - sa && !sb && b.live() == 0); + "after it, one plug-in's session from before the sleep, still open, no " + "longer stops the other from opening one", + sa && sb && b.live() == 1); if (sb) b.close(sb); VcnDriverSession* sa2 = a.open(err, sizeof(err)); - expect("and the same plug-in from opening another", sa && !sa2); + expect("nor the same plug-in from opening another", sa && sa2); if (sa2) a.close(sa2); if (sa) a.close(sa); expect("its close (without the driver's teardown) frees the accelerator", diff --git a/GPU/decode/vp9/vcnvp9.c b/GPU/decode/vp9/vcnvp9.c index 5404c4e1..16926c72 100644 --- a/GPU/decode/vp9/vcnvp9.c +++ b/GPU/decode/vp9/vcnvp9.c @@ -26,6 +26,10 @@ int vcnvp9_gpu_armed = 0; #define VCN_MODE_VCN0 \ 4 // VP9 runs on both instances, but AV1 contexts only work on VCN0 #define NUM_DPB 9 +// A rebuild after a sleep waits for a key frame; at 60 fps this is ten +// seconds of frames. A stream that does not send one by then is stopped the +// way PR 160 stopped it, so the host can hand it to another decoder. +#define REBUILD_MAX_DROPPED 600 #define NUM_BS VCN_NUM_BS #define BS_SIZE VCN_BS_SIZE #define FRAME_BYTES 4096 @@ -66,10 +70,13 @@ struct VcnVP9 { CVPixelBufferPoolRef pool; uint32_t poolW, poolH; bool poolTen; - bool stuck; // a command never finished: the GPU may still hold it - bool broken; // stuck, or a driver call failed: nothing more goes out - int failure; // VCNVP9_FAIL_* of the last error - bool shown; // the current decode call output a frame + bool stuck; // a command never finished: the GPU may still hold it + bool broken; // stuck, or a driver call failed: nothing more goes out + bool needKey; // rebuilt after a sleep: drop frames until a key frame + unsigned dropped; // frames dropped since that rebuild + unsigned rebuilds; // driver objects rebuilt in this session (one per sleep) + int failure; // VCNVP9_FAIL_* of the last error + bool shown; // the current decode call output a frame CVPixelBufferRef hidden; // retained: last frame it decoded without showing unsigned fwErrors; // decodes the firmware reported as failed unsigned done; // decode commands that finished @@ -522,6 +529,78 @@ static CVPixelBufferRef new_target(VcnVP9* d, uint32_t w, uint32_t h, return pb; } +// One VP9 context on the driver handle this session has open: what a create and +// a rebuild after a sleep both need. The factory's class pointer is swapped +// only for the length of CreateContexts, as it always was. +static int vp9_create_context(VcnVP9* d, char* err, size_t errLen) { + AVD_ContextList list = {0}; + void* ctxOut[2] = {0}; + AVD_FunctionInfo* fis[1] = {&list.inlineInfo}; + list.count = 1; + list.functions = fis; + list.contextsOut = ctxOut; + list.inlineInfo = (AVD_FunctionInfo){.kind = 1, + .function = AVD_FUNC_AV1, + .mode = VCN_MODE_VCN0, + .pixelRate = d->maxW * d->maxH * 60, + .width = d->maxW, + .height = d->maxH, + .inFormat = 0x72617762, + .inFormatCount = 1, + .outFormat = 0x4e563132, + .outFormatCount = 1}; + AVD_DriverContextInit ci = {.list = &list}; + // Swap the vtable pointer on this driver's factory, only for the length of + // CreateContexts. + static pthread_mutex_t create_lock = PTHREAD_MUTEX_INITIALIZER; + // The wrapped copy of the factory's class vtable. Built once, under + // create_lock, before any factory points at it: threads of other sessions + // may read it at any time once it is published, so it never changes again. + static void* factoryVt[FACTORY_SLOTS + 2]; + static void** factoryOrigVt; + // driver+8 is the VAContext, VAContext+75072 its VAFactory (avd.h, + // AVD_CreateDriver_fn). Each is checked before it is read through: a NULL + // fails the start like any other step instead of a read at a small address. + uint8_t* va = PTR(d->s.drv, 8); + if (!va) { + snprintf(err, errLen, "no VAContext"); + return 1; + } + void*** factory = (void***)PTR(va, 75072); + if (!factory || !*factory) { + snprintf(err, errLen, "no factory"); + return 1; + } + vcnvp9_dryrun_checkpoint(1); + pthread_mutex_lock(&create_lock); + void** origFactoryVt = *factory; + if (!factoryOrigVt) { + memcpy(factoryVt, origFactoryVt - 2, sizeof(factoryVt)); + g_orig_create_processor = + (void* (*)(void*, int, void*))origFactoryVt[FACTORY_CREATE_PROCESSOR]; + factoryVt[2 + FACTORY_CREATE_PROCESSOR] = (void*)hook_create_processor; + factoryOrigVt = origFactoryVt; + } + if (origFactoryVt != factoryOrigVt) { + pthread_mutex_unlock(&create_lock); + snprintf(err, errLen, "the driver's factory class changed (%p, was %p)", + (void*)origFactoryVt, (void*)factoryOrigVt); + return 1; + } + __atomic_store_n(factory, &factoryVt[2], __ATOMIC_RELEASE); + t_creating = 1; + int r = FN(CreateContexts)(d->s.drv, &ci); + t_creating = 0; + __atomic_store_n(factory, origFactoryVt, __ATOMIC_RELEASE); + pthread_mutex_unlock(&create_lock); + if (r || !ctxOut[0]) { + snprintf(err, errLen, "CreateContexts %d", r); + return 1; + } + d->s.ctx = ctxOut[0]; + return 0; +} + VcnVP9* vcnvp9_create(uint32_t maxWidth, uint32_t maxHeight, char* err, size_t errLen) { #define FAIL(...) \ @@ -580,66 +659,69 @@ VcnVP9* vcnvp9_create(uint32_t maxWidth, uint32_t maxHeight, char* err, // included. if (!vcn_session_open(&d->s, &lib, svc, vlog(), why, sizeof(why))) FAIL("%s", why); - AVD_ContextList list = {0}; - void* ctxOut[2] = {0}; - AVD_FunctionInfo* fis[1] = {&list.inlineInfo}; - list.count = 1; - list.functions = fis; - list.contextsOut = ctxOut; - list.inlineInfo = (AVD_FunctionInfo){.kind = 1, - .function = AVD_FUNC_AV1, - .mode = VCN_MODE_VCN0, - .pixelRate = maxWidth * maxHeight * 60, - .width = maxWidth, - .height = maxHeight, - .inFormat = 0x72617762, - .inFormatCount = 1, - .outFormat = 0x4e563132, - .outFormatCount = 1}; - AVD_DriverContextInit ci = {.list = &list}; - // Swap the vtable pointer on this driver's factory, only for the length of - // CreateContexts. - static pthread_mutex_t create_lock = PTHREAD_MUTEX_INITIALIZER; - // The wrapped copy of the factory's class vtable. Built once, under - // create_lock, before any factory points at it: threads of other sessions - // may read it at any time once it is published, so it never changes again. - static void* factoryVt[FACTORY_SLOTS + 2]; - static void** factoryOrigVt; - // driver+8 is the VAContext, VAContext+75072 its VAFactory (avd.h, - // AVD_CreateDriver_fn). Each is checked before it is read through: a NULL - // fails the start like any other step instead of a read at a small address. - uint8_t* va = PTR(d->s.drv, 8); - if (!va) FAIL("no VAContext"); - void*** factory = (void***)PTR(va, 75072); - if (!factory || !*factory) FAIL("no factory"); - vcnvp9_dryrun_checkpoint(1); - pthread_mutex_lock(&create_lock); - void** origFactoryVt = *factory; - if (!factoryOrigVt) { - memcpy(factoryVt, origFactoryVt - 2, sizeof(factoryVt)); - g_orig_create_processor = - (void* (*)(void*, int, void*))origFactoryVt[FACTORY_CREATE_PROCESSOR]; - factoryVt[2 + FACTORY_CREATE_PROCESSOR] = (void*)hook_create_processor; - factoryOrigVt = origFactoryVt; - } - if (origFactoryVt != factoryOrigVt) { - pthread_mutex_unlock(&create_lock); - FAIL("the driver's factory class changed (%p, was %p)", - (void*)origFactoryVt, (void*)factoryOrigVt); - } - __atomic_store_n(factory, &factoryVt[2], __ATOMIC_RELEASE); - t_creating = 1; - int r = FN(CreateContexts)(d->s.drv, &ci); - t_creating = 0; - __atomic_store_n(factory, origFactoryVt, __ATOMIC_RELEASE); - pthread_mutex_unlock(&create_lock); - if (r || !ctxOut[0]) FAIL("CreateContexts %d", r); - d->s.ctx = ctxOut[0]; + if (vp9_create_context(d, why, sizeof(why))) FAIL("%s", why); DBG("created: driver %s session=%s drv=%p ctx=%p\n", lib.uuid, sess, d->s.drv, d->s.ctx); return d; } +// Rebuilds the driver side of a session the system slept through (plan B of +// the sleep fix, job 178): the objects from before the sleep are dropped +// without a word to the driver, and a fresh accelerator, driver, context and +// bitstream pool are opened for the same plug-in session, so the host's decoder +// object lives on instead of failing frames with kVTVideoDecoderMalfunctionErr. +// Nothing decoded before the sleep can be referenced after it, so the DPB, the +// references, the parser state and the pictures go, and frames are dropped +// until a key frame (on_frame). False when the rebuild fails: the caller then +// stops the session as PR 160 did. +static bool vp9_rebuild(VcnVP9* d, char* why, size_t whyLen) { + vcn_session_drop(&d->s); + for (int i = 0; i < NUM_DPB; i++) + if (d->dpb[i]) { + CVPixelBufferRelease(d->dpb[i]); + d->dpb[i] = NULL; + } + memset(d->dpbRefs, 0, sizeof(d->dpbRefs)); + for (size_t i = 0; i < sizeof(d->parser.ref) / sizeof(d->parser.ref[0]); + i++) { + d->parser.ref[i].valid = 0; + d->parser.ref[i].dpb_slot = -1; + } + if (d->hidden) { + CVPixelBufferRelease(d->hidden); + d->hidden = NULL; + } + d->bsNext = 0; + d->needKey = true; + d->dropped = 0; + VcnDriverLib lib; + if (!vcn_driver_load(&lib, why, whyLen)) return false; + bool validated = false; + for (size_t i = 0; i < sizeof(kValidatedDrivers) / sizeof(*kValidatedDrivers); + i++) + if (!strcmp(lib.uuid, kValidatedDrivers[i])) validated = true; + if (!validated) { + snprintf(why, whyLen, "AMDRadeonVADriver2 build %s not validated for VP9", + lib.uuid); + return false; + } + io_service_t svc = vcn_find_accelerator(); + if (!svc) { + snprintf(why, whyLen, "no AMD accelerator"); + return false; + } + if (!vcn_session_reopen(&d->s, &lib, svc, vlog(), why, whyLen)) return false; + if (vp9_create_context(d, why, whyLen)) { + vcn_session_drop(&d->s); + return false; + } + d->rebuilds++; + os_log_error(vlog(), + "the system slept since this session opened: driver rebuilt, " + "frames are dropped until the next key frame"); + return true; +} + static void destroy_now(VcnVP9* d) { vcn_session_close(&d->s); // The pictures go after the driver: a stuck command may still write one. @@ -746,6 +828,33 @@ static int on_frame(void* vctx, VP9Parser* p, VP9ParseResult kind, const uint8_t* data, size_t size) { VcnVP9* d = vctx; const VP9Frame* h = &p->fh; + // After a rebuild nothing from before the sleep can be used: every frame but + // a key frame (or an intra-only one, which refreshes every slot) is dropped, + // with no picture and no error, and a key frame starts the decoder again. + // Bounded: a stream that never sends one is stopped as a device failure, + // PR 160's behaviour. + if (d->needKey) { + bool key = + kind == VP9_PARSE_DECODE && (h->frame_type == 0 || h->intra_only); + if (!key) { + if (++d->dropped > REBUILD_MAX_DROPPED) { + d->broken = true; + d->failure = VCNVP9_FAIL_DEVICE; + snprintf(d->err, sizeof(d->err), + "no key frame in %u frames after the system sleep", + d->dropped); + return -1; + } + return 0; + } + for (size_t i = 0; i < sizeof(p->ref) / sizeof(p->ref[0]); i++) { + p->ref[i].valid = 0; + p->ref[i].dpb_slot = -1; + } + memset(d->dpbRefs, 0, sizeof(d->dpbRefs)); + d->needKey = false; + d->dropped = 0; + } if (kind == VP9_PARSE_SHOW_EXISTING) { const VP9Ref* r = &p->ref[h->frame_to_show]; if (!r->valid || r->dpb_slot < 0 || r->dpb_slot >= NUM_DPB || @@ -806,15 +915,6 @@ static int on_frame(void* vctx, VP9Parser* p, VP9ParseResult kind, } if (d->dpb[slot]) CVPixelBufferRelease(d->dpb[slot]); d->dpb[slot] = target; - // Nothing goes into the pool or to the engine for a session from before a - // system sleep (vcndriver.h). - if (vcn_session_lost(&d->s)) { - d->broken = true; - d->failure = VCNVP9_FAIL_DEVICE; - snprintf(d->err, sizeof(d->err), "%s", - "the system slept since this session opened"); - return -1; - } int bi = d->bsNext; d->bsNext = (d->bsNext + 1) % NUM_BS; memcpy(d->s.bsAddr[bi], data, size); @@ -879,12 +979,22 @@ int vcnvp9_decode(VcnVP9* d, const uint8_t* chunk, size_t size, int64_t tag, CVPixelBufferRelease(d->hidden); d->hidden = NULL; } - if (!d->broken && vcn_session_lost(&d->s)) d->broken = true; + if (!d->broken && vcn_session_lost(&d->s)) { + char why[200]; + if (!vp9_rebuild(d, why, sizeof(why))) { + d->broken = true; + snprintf(d->err, sizeof(d->err), + "session stopped: the system slept since it opened and the " + "rebuild failed (%s)", + why); + d->failure = VCNVP9_FAIL_DEVICE; + return -1; + } + } if (d->broken) { snprintf(d->err, sizeof(d->err), "session stopped: %s", - d->stuck ? "the GPU did not finish an earlier frame" - : d->s.lost ? "the system slept since it opened" - : "an earlier driver call failed"); + d->stuck ? "the GPU did not finish an earlier frame" + : "an earlier driver call failed"); d->failure = VCNVP9_FAIL_DEVICE; return -1; } From dc1328b27c246719661735a736bfbf4fdcfd59b5 Mon Sep 17 00:00:00 2001 From: DrogaBox Date: Thu, 26 Nov 2026 00:02:35 -0300 Subject: [PATCH 3/3] GPU decoders 0.3.7: a session from before a sleep keeps decoding, rebuilt at its next key frame A real sleep test showed 0.3.6 failing every frame of the sessions open across the sleep, while 0.3.5 kept decoding them correctly. The AV1 and VP9 sessions now keep decoding after a sleep and replace their driver objects at the next key frame that refreshes every reference, with no frame dropped. Only when the old session fails after the wake is it rebuilt at once, dropping frames up to a key frame. A command on the old session may take 15 s before it is given up on. -12911 is left for a rebuild that fails. --- GPU/CHANGELOG.md | 28 ++++- GPU/decode/VERSION | 2 +- GPU/decode/av1/vcnav1.c | 190 ++++++++++++++++++++++--------- GPU/decode/build.sh | 2 +- GPU/decode/common/vcndriver.h | 73 ++++++++---- GPU/decode/common/vcnsession.c | 43 +++++-- GPU/decode/tests/sessiontest.c | 197 ++++++++++++++++++++++++++++----- GPU/decode/vp9/vcnvp9.c | 196 +++++++++++++++++++++++--------- GPU/docs/how-it-works.md | 87 +++++++++------ GPU/docs/testing.md | 18 +-- GPU/tests/run.sh | 7 +- 11 files changed, 638 insertions(+), 205 deletions(-) diff --git a/GPU/CHANGELOG.md b/GPU/CHANGELOG.md index fde5abd3..91b4c503 100644 --- a/GPU/CHANGELOG.md +++ b/GPU/CHANGELOG.md @@ -2,7 +2,33 @@ The encoding fix keeps its own history in `encode/CHANGELOG.md`. -## Decoders 0.3.6 (not released; host tests only) +## Decoders 0.3.7 (not released; host tests only) + +- 0.3.6 made things worse in the first real sleep test on this Mac (RX 6800 XT, Tahoe + 26.7.3): it noticed the sleep (132 s asleep), but every session from before it then + failed all its frames with -12911, and the new sessions after the wake lost their first + frames to the refusal below. The same test with 0.3.5, which knows nothing of sleeps, + kept decoding on the old sessions after the wake with every frame matching its reference. +- So an AV1 or VP9 session from before a sleep now keeps decoding, as 0.3.5 did, and at its + next key frame (AV1: a key frame that refreshes every reference slot; VP9: a key frame, or + an intra-only frame that refreshes every slot and resets every probability context) its + driver objects are replaced inside the same decoder: the old accelerator is closed without + the driver's own teardown and a new accelerator, driver, context and bitstream pool are + opened, and the key frame decodes on them. No frame is dropped and the host sees no error. +- Only when the old session fails after the wake (a driver call, a command that does not + finish, a firmware error) is it replaced at once; that frame and the ones up to the next + key frame are then dropped (no picture, no error), at most 600 of them. A command that did + not finish has its accelerator closed on the background thread. Right after a wake a + command on the old session may take up to 15 s instead of 1 s (in the test one frame of + each decode took about 10 s and then decoded correctly). +- -12911 is left for a replacement that fails, or no key frame within those 600 frames. +- A new session no longer refuses to open while one from before a sleep is still open. +- The MPEG-2, VC-1 and MPEG-4 decoders are unchanged: their sessions from before a sleep + still stop as in 0.3.6. +- Each replacement leaves the old driver handle and its bitstream pool (up to 96 MiB) in the + process, as the quiet close already did. + +## Decoders 0.3.6 (not released; replaced by 0.3.7) - A decode session from before a system sleep is no longer used after it. A user reported that with the AV1 and VP9 decoders a wake from sleep hung the Mac a while later, with diff --git a/GPU/decode/VERSION b/GPU/decode/VERSION index 449d7e73..0f826853 100644 --- a/GPU/decode/VERSION +++ b/GPU/decode/VERSION @@ -1 +1 @@ -0.3.6 +0.3.7 diff --git a/GPU/decode/av1/vcnav1.c b/GPU/decode/av1/vcnav1.c index bc1d609c..42009362 100644 --- a/GPU/decode/av1/vcnav1.c +++ b/GPU/decode/av1/vcnav1.c @@ -23,9 +23,10 @@ int vcnav1_gpu_armed = 0; #define VCN_MODE_VCN0 4 #define NUM_DPB 9 -// A rebuild after a sleep waits for a key frame; at 60 fps this is ten -// seconds of frames. A stream that does not send one by then is stopped the -// way PR 160 stopped it, so the host can hand it to another decoder. +// A session that failed after a sleep is rebuilt and waits for a key frame, +// dropping the frames before it; at 60 fps this is ten seconds of frames. A +// stream that does not send one by then is stopped the way PR 160 stopped it, +// so the host can hand it to another decoder. #define REBUILD_MAX_DROPPED 600 #define NUM_BS VCN_NUM_BS #define BS_SIZE VCN_BS_SIZE @@ -64,11 +65,16 @@ struct VcnAV1 { pool; // decode targets; references live in the driver's internal DPB uint32_t poolW, poolH; bool poolTen; - bool stuck; // a command never finished: the GPU may still hold it - bool broken; // stuck, or a driver call failed: nothing more goes out - bool needKey; // rebuilt after a sleep: drop frames until a key frame + bool stuck; // a command never finished: the GPU may still hold it + bool broken; // stuck, or a driver call failed: nothing more goes out + // The system slept since the driver side opened: frames still go to it, and + // it is rebuilt at the next key frame (on_frame). + bool rebuildAtKey; + unsigned keptAfterWake; // frames decoded on it since the sleep was seen + bool needKey; // rebuilt after a failure: drop frames until a key frame unsigned dropped; // frames dropped since that rebuild unsigned rebuilds; // driver objects rebuilt in this session (one per sleep) + uint32_t lastFw; // firmware result of the last command that finished int failure; // VCNAV1_FAIL_* of the last error bool shown; // the current decode call output a frame CVPixelBufferRef hidden; // retained: last frame it decoded without showing @@ -267,32 +273,44 @@ VcnAV1* vcnav1_create(uint32_t maxWidth, uint32_t maxHeight, char* err, return d; } -// Rebuilds the driver side of a session the system slept through (plan B of -// the sleep fix, job 178): the objects from before the sleep are dropped -// without a word to the driver, and a fresh accelerator, driver, context and -// bitstream pool are opened for the same plug-in session, so the host's decoder -// object lives on instead of failing frames with kVTVideoDecoderMalfunctionErr. -// Nothing decoded before the sleep can be referenced after it, so the DPB, the -// reference slots, the parser and the pictures go, and the next frames are -// dropped until a key frame (on_frame). False when the rebuild fails: the +// Rebuilds the driver side of a session the system slept through: the objects +// from before the sleep are dropped without a word to the driver, and a fresh +// accelerator, driver, context and bitstream pool are opened for the same +// plug-in session, so the host's decoder object lives on. The references live +// in the old driver's DPB, so the DPB pictures and the reference slots go; the +// parser keeps the sequence header (a key frame does not always repeat it) and +// the frame header being decoded. busy: the old session's last command may +// still be on the GPU, so its accelerator is closed on the teardown queue and +// the pictures are let go only after that. False when the rebuild fails: the // caller then stops the session as PR 160 did. -static bool av1_rebuild(VcnAV1* d, char* why, size_t whyLen) { - vcn_session_drop(&d->s); +static bool av1_rebuild(VcnAV1* d, bool busy, char* why, size_t whyLen) { + CVPixelBufferRef old[NUM_DPB + 1]; + int n = 0; for (int i = 0; i < NUM_DPB; i++) if (d->dpb[i]) { - CVPixelBufferRelease(d->dpb[i]); + old[n++] = d->dpb[i]; d->dpb[i] = NULL; } - memset(d->dpbRefs, 0, sizeof(d->dpbRefs)); - if (d->hidden) { - CVPixelBufferRelease(d->hidden); + if (d->hidden) { // its own reference to one of them + old[n++] = d->hidden; d->hidden = NULL; } - av1_parser_free(&d->parser); - av1_parser_init(&d->parser); + if (busy) { + // Without memory for the list the pictures are never let go: a command + // still on the GPU may write into them. + CVPixelBufferRef* keep = n ? malloc((size_t)n * sizeof(*keep)) : NULL; + if (keep) memcpy(keep, old, (size_t)n * sizeof(*keep)); + int kept = keep ? n : 0; + vcn_session_drop_later(&d->s, "AV1 session from before the sleep", ^{ + for (int i = 0; i < kept; i++) CVPixelBufferRelease(keep[i]); + free(keep); + }); + } else { + vcn_session_drop(&d->s); + for (int i = 0; i < n; i++) CVPixelBufferRelease(old[i]); + } + vcnav1_flush(d); d->bsNext = 0; - d->needKey = true; - d->dropped = 0; VcnDriverLib lib; if (!vcn_driver_load(&lib, why, whyLen)) return false; if (!av1_driver_allowed(&lib)) { @@ -313,12 +331,61 @@ static bool av1_rebuild(VcnAV1* d, char* why, size_t whyLen) { return false; } d->rebuilds++; - os_log_error(vlog(), - "the system slept since this session opened: driver rebuilt, " - "frames are dropped until the next key frame"); return true; } +// Rebuilds now (av1_rebuild) and leaves the session decoding on the new driver; +// dropUntilKey: the frames before the next key frame are dropped. False, with +// the session stopped as a device failure, when the rebuild fails. +static bool rebuild_now(VcnAV1* d, bool busy, bool dropUntilKey, + const char* cause) { + char why[200]; + unsigned kept = d->keptAfterWake; + if (!av1_rebuild(d, busy, why, sizeof(why))) { + d->rebuildAtKey = false; + d->broken = true; + d->failure = VCNAV1_FAIL_DEVICE; + snprintf(d->err, sizeof(d->err), + "session stopped: the system slept since it opened and the " + "rebuild failed (%s)", + why); + return false; + } + // What these said was about the old driver objects. + d->rebuildAtKey = false; + d->stuck = d->broken = false; + d->keptAfterWake = 0; + d->needKey = dropUntilKey; + d->dropped = 0; + if (dropUntilKey) + os_log_error( + vlog(), + "the session from before the sleep failed after the wake " + "(%{public}s, %u frames decoded on it before): driver rebuilt, " + "frames are dropped until the next key frame", + cause, kept); + else + os_log_error(vlog(), + "driver rebuilt at the first key frame after the sleep (%u " + "frames decoded on the session from before it), no frame " + "dropped", + kept); + return true; +} + +// The session from before the sleep failed on the frame being decoded: it is +// rebuilt at once and this frame is dropped, like the ones after it until a +// key frame. 0, or -1 when the rebuild fails. +static int failed_after_wake(VcnAV1* d, bool busy) { + char cause[256]; + snprintf(cause, sizeof(cause), "%s", d->err); + if (!rebuild_now(d, busy, true, cause)) return -1; + d->err[0] = 0; + d->failure = VCNAV1_FAIL_STREAM; + d->dropped = 1; + return 0; +} + static void destroy_now(VcnAV1* d) { vcn_session_close(&d->s); // The pictures go after the driver: a stuck command may still write one. @@ -607,9 +674,12 @@ static int submit(VcnAV1* d, AV1Params* prm, double* sched, double* wait) { } uint32_t fw = 0; int ds = 0; - VcnWaitResult w = - vcn_wait_command(FN(QueryAVDCommandStatus), d->s.drv, refcons[0], - VCN_COMMAND_TIMEOUT_MS, &fw, &ds); + // Longer on the session from before a sleep: right after a wake the driver + // can take seconds before a command runs (vcndriver.h). + unsigned limit = + d->rebuildAtKey ? vcn_wake_command_timeout_ms : VCN_COMMAND_TIMEOUT_MS; + VcnWaitResult w = vcn_wait_command(FN(QueryAVDCommandStatus), d->s.drv, + refcons[0], limit, &fw, &ds); *sched = t1 - t0; *wait = tnow_ms() - t1; DBG("wait=%d firmware=%u driver=%d\n", (int)w, fw, ds); @@ -618,8 +688,7 @@ static int submit(VcnAV1* d, AV1Params* prm, double* sched, double* wait) { // target, could only make things worse: the session stops here. d->stuck = d->broken = true; snprintf(d->err, sizeof(d->err), - "the GPU did not finish a frame in %d ms; session stopped", - VCN_COMMAND_TIMEOUT_MS); + "the GPU did not finish a frame in %u ms; session stopped", limit); return -1; } if (w != VCN_WAIT_DONE) { @@ -631,6 +700,7 @@ static int submit(VcnAV1* d, AV1Params* prm, double* sched, double* wait) { } d->failure = VCNAV1_FAIL_STREAM; d->done++; + d->lastFw = fw; // Counted, not refused: what each firmware result means for the picture // has not been checked on a GPU yet. The first one of a session is logged // at once, the count goes in the stats line. @@ -651,13 +721,25 @@ static bool seq_supported(const AV1Seq* s) { static int on_frame(void* vctx, AV1Parser* p, AV1ParseResult kind) { VcnAV1* d = vctx; const AV1Frame* h = &p->fh; - // After a rebuild nothing from before the sleep can be used: every frame but - // a key frame is dropped (no picture for this sample, which is what a hidden - // frame looks like to the host, not an error), and a key frame starts the - // decoder again. Bounded: a stream that never sends one is stopped as a - // device failure, PR 160's behaviour. + // A key frame that refreshes every reference slot (a shown key frame always + // does): nothing decoded before it is used after it, so the driver objects + // can be replaced here without losing a frame. A hidden key frame that keeps + // some slots is not one: the frames after it may still use those. + bool restart = kind == AV1_PARSE_FRAME_READY && + h->frame_type == AV1_KEY_FRAME && + h->refresh_frame_flags == 0xFF; + // The system slept since the driver side opened, and it kept decoding (a + // real sleep on this Mac did not break it): it is replaced at the first such + // key frame, which then decodes on the new one. + if (d->rebuildAtKey && restart && !rebuild_now(d, false, false, NULL)) + return -1; + // After a rebuild that followed a failure nothing from before it can be + // used: every frame but such a key frame is dropped (no picture for this + // sample, which is what a hidden frame looks like to the host, not an + // error), and the key frame starts the decoder again. Bounded: a stream that + // never sends one is stopped as a device failure, PR 160's behaviour. if (d->needKey) { - if (kind != AV1_PARSE_FRAME_READY || h->frame_type != AV1_KEY_FRAME) { + if (!restart) { if (++d->dropped > REBUILD_MAX_DROPPED) { d->broken = true; d->failure = VCNAV1_FAIL_DEVICE; @@ -787,7 +869,18 @@ static int on_frame(void* vctx, AV1Parser* p, AV1ParseResult kind) { h->TileRows, p->tile_data_size, slot, h->refresh_frame_flags); double tf1 = timing ? tnow_ms() : 0; double tSched, tWait; - if (submit(d, &prm, &tSched, &tWait)) return -1; + if (submit(d, &prm, &tSched, &tWait)) + // On the session from before a sleep, a driver failure is taken for the + // sleep's doing: rebuilt at once, instead of stopping the session. + return d->rebuildAtKey && d->broken ? failed_after_wake(d, d->stuck) : -1; + if (d->rebuildAtKey) { + if (d->lastFw) { + // A firmware error on it after the wake: its picture is not trusted. + snprintf(d->err, sizeof(d->err), "firmware result %u", d->lastFw); + return failed_after_wake(d, false); + } + d->keptAfterWake++; + } if (timing) fprintf(stderr, "timing bytes=%zu prep=%.2f sched=%.2f wait=%.2f\n", p->tile_data_size, tf1 - tf0, tSched, tWait); @@ -841,17 +934,14 @@ int vcnav1_decode(VcnAV1* d, const uint8_t* tu, size_t size, int64_t userTag, CVPixelBufferRelease(d->hidden); d->hidden = NULL; } - if (!d->broken && vcn_session_lost(&d->s)) { - char why[200]; - if (!av1_rebuild(d, why, sizeof(why))) { - d->broken = true; - snprintf(d->err, sizeof(d->err), - "session stopped: the system slept since it opened and the " - "rebuild failed (%s)", - why); - d->failure = VCNAV1_FAIL_DEVICE; - return -1; - } + // A sleep since the driver side opened: it keeps decoding, and on_frame + // rebuilds it at the next key frame (or at once if it fails). + if (!d->broken && !d->rebuildAtKey && vcn_session_lost(&d->s)) { + d->rebuildAtKey = true; + d->keptAfterWake = 0; + os_log_error(vlog(), + "AV1 session from before the sleep: it keeps decoding and is " + "rebuilt at the next key frame"); } if (d->broken) { snprintf(d->err, sizeof(d->err), "session stopped: %s", diff --git a/GPU/decode/build.sh b/GPU/decode/build.sh index 606504b6..3b3f6706 100755 --- a/GPU/decode/build.sh +++ b/GPU/decode/build.sh @@ -114,7 +114,7 @@ if [[ ${1:-} == tests ]]; then -framework IOKit \ -o $T/waittest # Two plug-ins in one process, each with its own copy of the session code (stalelib.c built - # twice), and a made-up sleep: one's session from before the sleep stops the other's new one. + # twice), and a made-up sleep: the other sees a session from before the sleep and opens anyway. for l in a b; do xcrun clang $TFLAGS -dynamiclib -fvisibility=hidden -Icommon tests/stalelib.c common/vcnsession.c \ -framework CoreFoundation -framework IOKit -install_name @rpath/libstale-$l.dylib -o $T/libstale-$l.dylib diff --git a/GPU/decode/common/vcndriver.h b/GPU/decode/common/vcndriver.h index a612b6a0..e0906ecb 100644 --- a/GPU/decode/common/vcndriver.h +++ b/GPU/decode/common/vcndriver.h @@ -43,16 +43,38 @@ bool vcn_driver_load(VcnDriverLib* lib, char* err, size_t errLen); // frame takes 5-60 ms on Navi 21, even at the video engine's lowest clock. enum { VCN_COMMAND_TIMEOUT_MS = 1000 }; +// The same for a command on a session from before a sleep, until it is +// rebuilt. Around a real wake on this Mac (2026-11-25, 0.3.5) one frame of +// each decode took 10.2 to 10.9 s and then decoded correctly. That time was +// spent in Apple's calls (0.3.5 already gave up on a command after 1 s and +// reported no error), probably while the GPU was being started again; a +// command that waits like that on the engine itself must not be taken for a +// stuck one. A variable, so a test can make it short; the plug-ins never +// change it. +enum { VCN_WAKE_COMMAND_TIMEOUT_MS = 15000 }; +extern unsigned vcn_wake_command_timeout_ms; + // A system sleep, as a session sees it. Apple's kernel driver keeps a decoder's // video context across a sleep, but stops the video engine before it and starts // it again at wake, and saves nothing of the session on the engine // (AMDRadeonX6000, 26.7.3 KDK, read in IDA: systemWillSleep stops the VCN rings // once their last command finished, powerUpHW and internalDidWake start them // again, saveVCNSession is empty). Nothing in the driver, AppleGVA or -// VideoToolbox tells a decoder about it. A session opened before a sleep is -// therefore never used again: it decodes nothing more, and closing it skips the -// driver's own teardown, which would send the engine a command for that session -// and wait for it with no time limit (vcn_session_close). +// VideoToolbox tells a decoder about it. +// +// On this Mac (RX 6800 XT, 26.7.3, 2026-11-25) a real sleep did not break the +// sessions that were open across it: 0.3.5, which knows nothing of sleeps, kept +// decoding on them after the wake with every frame matching its reference. So +// an AV1 or VP9 session from before a sleep keeps decoding, and is rebuilt +// quietly at its next key frame (vcnav1.c / vcnvp9.c), where nothing from +// before the rebuild is needed any more: no frame is dropped and no error +// reaches the host. (The MPEG-2, VC-1 and MPEG-4 sessions, vcnlegacy.c, still +// stop at the first picture after a sleep, as in 0.3.6.) Only +// when the old session fails after the wake (a driver call, a command that +// does not finish, a firmware error) is it rebuilt at once, and the frames are +// dropped until a key frame. Closing it still skips the driver's own teardown, +// which would send the engine a command for that session and wait for it with +// no time limit (vcn_session_close). // // The mark is the time this Mac has spent asleep since it started, as the // kernel counts it (mach_continuous_time runs on during a sleep, @@ -131,17 +153,14 @@ typedef struct VcnDriverSession { // // It counts, once per process, the sessions of this process that opened before // a system sleep and are still open in any of the plug-ins (they ask each -// other through the process's local notification center). It no longer refuses -// because of them: those sessions rebuild for themselves now, and refusing -// would turn a paused tab into no hardware decode in the whole process (F3 of -// the review). A reported -// hang began exactly so: two VP9 sessions of a browser's decoder process stayed -// open across a sleep, and the AV1 session the same process opened after the -// wake never decoded a frame. That is why a decoder session does not fail when -// it finds the system slept: it rebuilds its driver side (vcn_session_reopen) -// and drops frames until a key frame, so the host's decoder object lives on and -// never sees a malfunction. What is left of the refusal below is the case where -// the rebuild itself fails. +// other through the process's local notification center), for the log. It +// does not refuse because of them: those sessions rebuild for themselves, and +// refusing turned a paused tab into no hardware decode in the whole process +// (F3 of the review; in the real sleep test of 0.3.6, every new session after +// the wake lost its first frames to it). A decoder session does not fail when +// it finds the system slept either: it keeps decoding and rebuilds its driver +// side (vcn_session_reopen) at the next key frame, so the host's decoder object +// lives on and never sees a malfunction. Only a rebuild that fails stops it. bool vcn_session_open(VcnDriverSession* s, const VcnDriverLib* lib, io_service_t svc, os_log_t log, char* err, size_t errLen); @@ -159,15 +178,27 @@ bool vcn_session_reopen(VcnDriverSession* s, const VcnDriverLib* lib, // and the service. The driver handle, its context and the bitstream pool are // left where they are, because only the driver can free them and it may be // wedged after a wake (F4 of the review); a rebuild leaks that once per sleep -// and starts a new pool. The session stays listed as open. +// and starts a new pool. The session stays listed as open. On a session whose +// last command finished this took 0-1 ms after a real wake (0.3.6 test, +// 2026-11-25). void vcn_session_drop(VcnDriverSession* s); +// The same, for a session whose last command may still be on the GPU (it did +// not finish in time, or its status could not be read): the accelerator is +// destroyed on the teardown queue (vcn_teardown), because that close can wait +// for the command in the kernel, and then `after` runs there (the codec lets go +// of the pictures the command may still write). The session is empty when this +// returns and can be opened again at once. +void vcn_session_drop_later(VcnDriverSession* s, const char* what, + void (^after)(void)); + // True once the system has slept since s opened (see VcnSleepMark), and from -// then on; the first time, it says so in the log. A codec that finds this -// rebuilds its driver side (vcnav1.c / vcnvp9.c: vcn_session_drop then -// vcn_session_reopen) and drops frames until a key frame; only a rebuild that -// fails stops the session, with kVTVideoDecoderMalfunctionErr (-12911), which -// is PR 160's behaviour. A session with no accelerator is never lost. +// then on; the first time, it says so in the log. The AV1 or VP9 codec that +// finds this keeps decoding on the session and rebuilds its driver side at the +// next key frame (vcnav1.c / vcnvp9.c: vcn_session_drop then +// vcn_session_reopen), or at once if the session fails after the wake; only a +// rebuild that fails stops the session, with kVTVideoDecoderMalfunctionErr +// (-12911). A session with no accelerator is never lost. bool vcn_session_lost(VcnDriverSession* s); // Closes what open (and the codec's CreateContexts) made, in the order Apple's diff --git a/GPU/decode/common/vcnsession.c b/GPU/decode/common/vcnsession.c index cca1fa1f..d746a11b 100644 --- a/GPU/decode/common/vcnsession.c +++ b/GPU/decode/common/vcnsession.c @@ -63,6 +63,8 @@ VcnWaitResult vcn_wait_command(AVD_QueryAVDCommandStatus_fn query, void* driver, #define FN(name) ((AVD_##name##_fn)s->accel->fn[AVD_FN_##name]) +unsigned vcn_wake_command_timeout_ms = VCN_WAKE_COMMAND_TIMEOUT_MS; + bool vcn_slept_between(const VcnSleepMark* then, const VcnSleepMark* now) { if (now->asleepNs > then->asleepNs + 1000000) return true; if (then->wakeUs && now->wakeUs && then->wakeUs != now->wakeUs) return true; @@ -88,8 +90,7 @@ bool vcn_session_lost(VcnDriverSession* s) { s->lost = true; os_log_error(s->log, "the system slept since this session opened (%.1f s asleep in " - "between): the video engine was restarted at wake, the session " - "sends it nothing more", + "between)", now.asleepNs > s->opened.asleepNs ? (double)(now.asleepNs - s->opened.asleepNs) / 1e9 : 0.0); @@ -299,20 +300,46 @@ bool vcn_session_reopen(VcnDriverSession* s, const VcnDriverLib* lib, return open_session(s, lib, svc, log, true, err, errLen); } -void vcn_session_drop(VcnDriverSession* s) { - if (!s->accel) return; - // No DeleteContexts, FreeBitstreamBufferPool or DeleteDriver: those send the - // engine a command for a session it has forgotten and wait with no limit. - if (s->destroy) s->destroy(s->accel); +// Takes the accelerator and the service out of s and forgets the rest of the +// driver objects (see vcn_session_drop); the session stays listed. +static void detach(VcnDriverSession* s, AVD_Accelerator** accel, + io_service_t* svc) { + *accel = s->accel; + *svc = s->svc; s->accel = NULL; s->drv = NULL; s->ctx = NULL; s->poolAllocated = false; memset(s->bsAddr, 0, sizeof(s->bsAddr)); - if (s->svc) IOObjectRelease(s->svc); s->svc = 0; } +void vcn_session_drop(VcnDriverSession* s) { + if (!s->accel) return; + // No DeleteContexts, FreeBitstreamBufferPool or DeleteDriver: those send the + // engine a command for a session it has forgotten and wait with no limit. + AVD_Accelerator* accel; + io_service_t svc; + detach(s, &accel, &svc); + if (s->destroy) s->destroy(accel); + if (svc) IOObjectRelease(svc); +} + +void vcn_session_drop_later(VcnDriverSession* s, const char* what, + void (^after)(void)) { + AVD_Accelerator* accel; + io_service_t svc; + detach(s, &accel, &svc); + AVD_DestroyAVDAccelerator_fn destroy = s->destroy; + // vcn_teardown copies the block, and with it `after`. + vcn_teardown(true, false, s->log, what, ^{ + if (accel && destroy) destroy(accel); + // Released only after the driver is gone: it may hold on to the service. + if (svc) IOObjectRelease(svc); + if (after) after(); + }); +} + // Skipping the driver's own teardown keeps this close from waiting on a command // for a session the engine has forgotten, but it does not make it a // non-blocking call: AVD_DestroyAVDAccelerator below still closes three IOKit diff --git a/GPU/decode/tests/sessiontest.c b/GPU/decode/tests/sessiontest.c index 37c1feb3..e52d6258 100644 --- a/GPU/decode/tests/sessiontest.c +++ b/GPU/decode/tests/sessiontest.c @@ -37,16 +37,23 @@ // one is taken, and the session reports its colour and the light level // of its metadata OBU (vcnav1_color); // 12. a system sleep (a made-up sleep mark, standing in for the clocks and -// kern.waketime): a session opened before it sends nothing after it, not -// even into the bitstream pool, and fails as a device; its close, on the -// background queue, skips DeleteContexts, FreeBitstreamBufferPool and -// DeleteDriver and only destroys the accelerator; the same for a session -// that was stuck when the sleep came, and for one that is only closed -// after the wake; a new wake time alone counts as a sleep, a change of -// the time asleep under 1 ms does not; a session opened after the wake -// decodes and closes fully; while one from before the sleep is still -// open, a new session is refused before it opens anything, and opens -// again once that one is closed. +// kern.waketime), 0.3.7: a key frame right after it rebuilds the driver +// objects and decodes on the new ones; an inter frame after it still +// decodes on the old ones, with no error and no frame dropped, and the +// next key frame rebuilds; a second sleep rebuilds again; with no key +// frame the old session decodes on past the drop limit; when the old +// session fails after the wake (ScheduleAVDCommands, a command that does +// not finish within the longer wake limit, a firmware result) it is +// rebuilt at once, the frame is dropped with no error, the frames up to +// the next key frame too, and the key frame decodes; a command that did +// not finish has its accelerator closed on the background queue; with no +// key frame after such a failure the session stops as a device failure +// at the limit; a rebuild that fails stops the session; a session only +// closed after the wake, or stuck when the sleep came, closes quietly on +// the background queue (only AVD_DestroyAVDAccelerator); a new wake time +// alone or a wall clock that ran ahead counts as a sleep, a change of +// the time asleep under 1 ms or both clocks moving together does not; a +// new session opens beside one from before the sleep and decodes. // // usage: sessiontest [clip with hidden frames] // Exit status 0 = pass. @@ -57,6 +64,7 @@ #include #include #include +#include #include #include "vcndriver.h" @@ -759,10 +767,16 @@ int main(int argc, char** argv) { // A second sample only exercises "dropped until a key frame" if it really // needs references: on a fresh session such a frame fails as a reference // error, while a second key frame would decode. - bool interUsable = false; + bool interUsable = false; // reported below: the tests it gates must run if (haveInter) { reset(); Vcn* probe = make(); +#if defined(TEST_AV1) + // An AV1 frame needs the sequence header of the first sample, and the + // references dropped after it. + if (probe) DECODE(probe, clip[0].data, clip[0].size, 0, on_out, NULL); + if (probe) vcnav1_flush(probe); +#endif if (probe) DECODE(probe, clip[1].data, clip[1].size, 0, on_out, NULL); interUsable = probe && FAILURE(probe) == FAIL_REFERENCE; if (probe) DESTROY(probe); @@ -841,43 +855,172 @@ int main(int argc, char** argv) { fakeSleep.wallUs -= 2000000; fakeSleep.monoNs -= 2000000000ull; + expect( + "the clip's second sample needs references (the inter frame tests run)", + interUsable); if (interUsable) { - // An inter frame after the sleep: the rebuild happens, the frame is dropped - // with no picture and no error, and the next key frame decodes. + // An inter frame after the sleep decodes on the driver objects from before + // it (a real sleep on this Mac did not break them), and the next key frame + // rebuilds them. reset(); d = make(); int k0 = d ? DECODE(d, clip[0].data, clip[0].size, 0, on_out, NULL) : -1; sleep_for(10000000000ull); - int createsBefore2 = st.creates; + int createsB = st.creates, ctxB = st.createCtx, schedB = st.schedules; int shownI = 0; int di = d ? DECODE(d, clip[1].data, clip[1].size, 1, on_out, &shownI) : -1; + if (di) printf(" inter frame after the sleep: %s\n", LASTERR(d)); expect( - "an inter frame after the sleep rebuilds and is dropped, with no " - "picture and no error", - d && k0 == 0 && di == 0 && shownI == 0 && - st.creates == createsBefore2 + 1); + "an inter frame after the sleep decodes on the old session: shown, no " + "error, no rebuild", + d && k0 == 0 && di == 0 && shownI == 1 && st.creates == createsB && + st.schedules == schedB + 1); int shownK = 0; int dk = d ? DECODE(d, clip[0].data, clip[0].size, 2, on_out, &shownK) : -1; - if (dk) printf(" key frame after the drop: %s\n", d ? LASTERR(d) : ""); - expect("the next key frame decodes on the rebuilt driver", - d && dk == 0 && shownK == 1); + if (dk) printf(" key frame after it: %s\n", d ? LASTERR(d) : ""); + expect("the next key frame rebuilds the driver and decodes on the new one", + d && dk == 0 && shownK == 1 && st.creates == createsB + 1 && + st.createCtx == ctxB + 1); + int shownI2 = 0; + int di2 = + d ? DECODE(d, clip[1].data, clip[1].size, 3, on_out, &shownI2) : -1; + expect("an inter frame after the rebuild decodes, no second rebuild", + d && di2 == 0 && shownI2 == 1 && st.creates == createsB + 1); + sleep_for(10000000000ull); + int shownK2 = 0; + int dk2 = + d ? DECODE(d, clip[0].data, clip[0].size, 4, on_out, &shownK2) : -1; + expect("a second sleep: the next key frame rebuilds again", + d && dk2 == 0 && shownK2 == 1 && st.creates == createsB + 2); + if (d) DESTROY(d); + expect("and that session closes, only the two dropped drivers left", + closed_after_rebuild(2)); + + // With no key frame at all, the old session simply decodes on: nothing is + // dropped, past the limit that applies after a failure. + reset(); + d = make(); + if (d) DECODE(d, clip[0].data, clip[0].size, 0, on_out, NULL); + sleep_for(10000000000ull); + int shownN = 0, failedN = 0; + for (int i = 0; d && i < 700; i++) + if (DECODE(d, clip[1].data, clip[1].size, i, on_out, &shownN)) failedN++; + expect( + "with no key frame the old session decodes on: 700 frames shown, no " + "error, no rebuild", + d && failedN == 0 && shownN == 700 && st.creates == 1); + if (d) DESTROY(d); + bool drainedN = vcn_teardown_drain(10000); + expect("and, never rebuilt, it closes quietly: nothing but the accelerator", + drainedN && st.deleteCtx == 0 && st.liveAccels == 0 && + st.liveDrivers == 1); + + // The old session fails after the wake: rebuilt at once, the frame + // dropped with no picture and no error, the frames up to the next key + // frame too, and the key frame decodes on the new driver. + reset(); + d = make(); + if (d) DECODE(d, clip[0].data, clip[0].size, 0, on_out, NULL); + sleep_for(10000000000ull); + fault.schedule = 3; + int shownF = 0; + int df = d ? DECODE(d, clip[1].data, clip[1].size, 1, on_out, &shownF) : -1; + fault.schedule = 0; + if (df) printf(" schedule failure after the sleep: %s\n", LASTERR(d)); + expect( + "a ScheduleAVDCommands failure after the sleep rebuilds at once and " + "drops the frame, with no error", + d && df == 0 && shownF == 0 && st.creates == 2); + int schedF = st.schedules, shownD = 0; + int dd = d ? DECODE(d, clip[1].data, clip[1].size, 2, on_out, &shownD) : -1; + expect("the next inter frame is dropped too, sending nothing", + d && dd == 0 && shownD == 0 && st.schedules == schedF); + int shownFK = 0; + int dfk = + d ? DECODE(d, clip[0].data, clip[0].size, 3, on_out, &shownFK) : -1; + expect("and the key frame decodes on the rebuilt driver", + d && dfk == 0 && shownFK == 1 && st.creates == 2); + if (d) DESTROY(d); + expect("and that session closes fully, only the dropped driver left", + closed_after_rebuild(1)); + + // A command on the old session that does not finish: it is waited for up + // to the wake limit (longer than the usual one), then the session is + // rebuilt and the old accelerator closed on the background queue. + reset(); + d = make(); + if (d) DECODE(d, clip[0].data, clip[0].size, 0, on_out, NULL); + sleep_for(10000000000ull); + vcn_wake_command_timeout_ms = 1500; // above the usual 1000 ms + fault.hang = true; + closeGate = dispatch_semaphore_create(0); // marks a destroy on this thread + int shownH = 0; + double h0 = (double)clock_gettime_nsec_np(CLOCK_UPTIME_RAW) / 1e6; + int dh = d ? DECODE(d, clip[1].data, clip[1].size, 1, on_out, &shownH) : -1; + double waited = (double)clock_gettime_nsec_np(CLOCK_UPTIME_RAW) / 1e6 - h0; + fault.hang = false; + vcn_wake_command_timeout_ms = VCN_WAKE_COMMAND_TIMEOUT_MS; + printf(" waited %.0f ms for the command on the old session\n", waited); + bool drainedH = vcn_teardown_drain(10000); + if (drainedH) dispatch_release(closeGate); + closeGate = NULL; + expect( + "a command on the old session that does not finish is waited for up " + "to the wake limit, not the usual one", + waited >= 1400); + expect( + "then the session is rebuilt, the frame dropped with no error, and the " + "old accelerator closed on the background queue", + d && dh == 0 && shownH == 0 && st.creates == 2 && drainedH && + st.destroys == 1 && !st.destroyOnMain && st.deleteCtx == 0); + int shownHK = 0; + int dhk = + d ? DECODE(d, clip[0].data, clip[0].size, 2, on_out, &shownHK) : -1; + expect("and the key frame decodes on the rebuilt driver", + d && dhk == 0 && shownHK == 1); + if (d) DESTROY(d); + expect("and that session closes fully, only the dropped driver left", + closed_after_rebuild(1)); + + // A firmware result on the old session after the wake: its picture is not + // trusted, the session is rebuilt and the frame dropped. + reset(); + d = make(); + if (d) DECODE(d, clip[0].data, clip[0].size, 0, on_out, NULL); + sleep_for(10000000000ull); + fault.firmware = 6; + int shownW = 0; + int dw = d ? DECODE(d, clip[1].data, clip[1].size, 1, on_out, &shownW) : -1; + fault.firmware = 0; + expect( + "a firmware result on the old session after the sleep rebuilds and " + "drops the frame, with no error", + d && dw == 0 && shownW == 0 && st.creates == 2); + int shownWK = 0; + int dwk = + d ? DECODE(d, clip[0].data, clip[0].size, 2, on_out, &shownWK) : -1; + expect("and the key frame decodes on the rebuilt driver", + d && dwk == 0 && shownWK == 1); if (d) DESTROY(d); expect("and that session closes fully, only the dropped driver left", closed_after_rebuild(1)); - // A stream that never sends one: frames are dropped for a while, then the - // session stops the way PR 160 stopped it. + // A stream that never sends a key frame after such a failure: frames are + // dropped for a while, then the session stops the way PR 160 stopped it. reset(); d = make(); if (d) DECODE(d, clip[0].data, clip[0].size, 0, on_out, NULL); sleep_for(10000000000ull); + fault.schedule = 3; + int dl = d ? DECODE(d, clip[1].data, clip[1].size, 1, on_out, NULL) : -1; + fault.schedule = 0; int stopped = 0, iters = 0; - for (; d && iters < 1000 && !stopped; iters++) + for (; d && dl == 0 && iters < 1000 && !stopped; iters++) stopped = DECODE(d, clip[1].data, clip[1].size, iters, on_out, NULL) != 0; expect( - "with no key frame the frames are dropped up to the limit, then the " - "session stops as a device failure", - d && stopped && FAILURE(d) == FAIL_DEVICE); + "with no key frame after a failure the frames are dropped up to the " + "limit, then the session stops as a device failure", + d && dl == 0 && stopped && FAILURE(d) == FAIL_DEVICE); if (d) DESTROY(d); expect("and it still releases everything, only the dropped driver left", closed_after_rebuild(1)); diff --git a/GPU/decode/vp9/vcnvp9.c b/GPU/decode/vp9/vcnvp9.c index 16926c72..3c6ea7ff 100644 --- a/GPU/decode/vp9/vcnvp9.c +++ b/GPU/decode/vp9/vcnvp9.c @@ -26,9 +26,10 @@ int vcnvp9_gpu_armed = 0; #define VCN_MODE_VCN0 \ 4 // VP9 runs on both instances, but AV1 contexts only work on VCN0 #define NUM_DPB 9 -// A rebuild after a sleep waits for a key frame; at 60 fps this is ten -// seconds of frames. A stream that does not send one by then is stopped the -// way PR 160 stopped it, so the host can hand it to another decoder. +// A session that failed after a sleep is rebuilt and waits for a key frame, +// dropping the frames before it; at 60 fps this is ten seconds of frames. A +// stream that does not send one by then is stopped the way PR 160 stopped it, +// so the host can hand it to another decoder. #define REBUILD_MAX_DROPPED 600 #define NUM_BS VCN_NUM_BS #define BS_SIZE VCN_BS_SIZE @@ -70,11 +71,16 @@ struct VcnVP9 { CVPixelBufferPoolRef pool; uint32_t poolW, poolH; bool poolTen; - bool stuck; // a command never finished: the GPU may still hold it - bool broken; // stuck, or a driver call failed: nothing more goes out - bool needKey; // rebuilt after a sleep: drop frames until a key frame + bool stuck; // a command never finished: the GPU may still hold it + bool broken; // stuck, or a driver call failed: nothing more goes out + // The system slept since the driver side opened: frames still go to it, and + // it is rebuilt at the next key frame (on_frame). + bool rebuildAtKey; + unsigned keptAfterWake; // frames decoded on it since the sleep was seen + bool needKey; // rebuilt after a failure: drop frames until a key frame unsigned dropped; // frames dropped since that rebuild unsigned rebuilds; // driver objects rebuilt in this session (one per sleep) + uint32_t lastFw; // firmware result of the last command that finished int failure; // VCNVP9_FAIL_* of the last error bool shown; // the current decode call output a frame CVPixelBufferRef hidden; // retained: last frame it decoded without showing @@ -665,35 +671,49 @@ VcnVP9* vcnvp9_create(uint32_t maxWidth, uint32_t maxHeight, char* err, return d; } -// Rebuilds the driver side of a session the system slept through (plan B of -// the sleep fix, job 178): the objects from before the sleep are dropped -// without a word to the driver, and a fresh accelerator, driver, context and -// bitstream pool are opened for the same plug-in session, so the host's decoder -// object lives on instead of failing frames with kVTVideoDecoderMalfunctionErr. -// Nothing decoded before the sleep can be referenced after it, so the DPB, the -// references, the parser state and the pictures go, and frames are dropped -// until a key frame (on_frame). False when the rebuild fails: the caller then -// stops the session as PR 160 did. -static bool vp9_rebuild(VcnVP9* d, char* why, size_t whyLen) { - vcn_session_drop(&d->s); +// Rebuilds the driver side of a session the system slept through: the objects +// from before the sleep are dropped without a word to the driver, and a fresh +// accelerator, driver, context and bitstream pool are opened for the same +// plug-in session, so the host's decoder object lives on. The references live +// in the old driver's DPB and the probability contexts in its context, so the +// pictures and the reference slots go; the parser keeps the header being +// decoded. busy: the old session's last command may still be on the GPU, so +// its accelerator is closed on the teardown queue and the pictures are let go +// only after that. False when the rebuild fails: the caller then stops the +// session as PR 160 did. +static bool vp9_rebuild(VcnVP9* d, bool busy, char* why, size_t whyLen) { + CVPixelBufferRef old[NUM_DPB + 1]; + int n = 0; for (int i = 0; i < NUM_DPB; i++) if (d->dpb[i]) { - CVPixelBufferRelease(d->dpb[i]); + old[n++] = d->dpb[i]; d->dpb[i] = NULL; } + if (d->hidden) { // its own reference to one of them + old[n++] = d->hidden; + d->hidden = NULL; + } + if (busy) { + // Without memory for the list the pictures are never let go: a command + // still on the GPU may write into them. + CVPixelBufferRef* keep = n ? malloc((size_t)n * sizeof(*keep)) : NULL; + if (keep) memcpy(keep, old, (size_t)n * sizeof(*keep)); + int kept = keep ? n : 0; + vcn_session_drop_later(&d->s, "VP9 session from before the sleep", ^{ + for (int i = 0; i < kept; i++) CVPixelBufferRelease(keep[i]); + free(keep); + }); + } else { + vcn_session_drop(&d->s); + for (int i = 0; i < n; i++) CVPixelBufferRelease(old[i]); + } memset(d->dpbRefs, 0, sizeof(d->dpbRefs)); for (size_t i = 0; i < sizeof(d->parser.ref) / sizeof(d->parser.ref[0]); i++) { d->parser.ref[i].valid = 0; d->parser.ref[i].dpb_slot = -1; } - if (d->hidden) { - CVPixelBufferRelease(d->hidden); - d->hidden = NULL; - } d->bsNext = 0; - d->needKey = true; - d->dropped = 0; VcnDriverLib lib; if (!vcn_driver_load(&lib, why, whyLen)) return false; bool validated = false; @@ -716,12 +736,61 @@ static bool vp9_rebuild(VcnVP9* d, char* why, size_t whyLen) { return false; } d->rebuilds++; - os_log_error(vlog(), - "the system slept since this session opened: driver rebuilt, " - "frames are dropped until the next key frame"); return true; } +// Rebuilds now (vp9_rebuild) and leaves the session decoding on the new driver; +// dropUntilKey: the frames before the next key frame are dropped. False, with +// the session stopped as a device failure, when the rebuild fails. +static bool rebuild_now(VcnVP9* d, bool busy, bool dropUntilKey, + const char* cause) { + char why[200]; + unsigned kept = d->keptAfterWake; + if (!vp9_rebuild(d, busy, why, sizeof(why))) { + d->rebuildAtKey = false; + d->broken = true; + d->failure = VCNVP9_FAIL_DEVICE; + snprintf(d->err, sizeof(d->err), + "session stopped: the system slept since it opened and the " + "rebuild failed (%s)", + why); + return false; + } + // What these said was about the old driver objects. + d->rebuildAtKey = false; + d->stuck = d->broken = false; + d->keptAfterWake = 0; + d->needKey = dropUntilKey; + d->dropped = 0; + if (dropUntilKey) + os_log_error( + vlog(), + "the session from before the sleep failed after the wake " + "(%{public}s, %u frames decoded on it before): driver rebuilt, " + "frames are dropped until the next key frame", + cause, kept); + else + os_log_error(vlog(), + "driver rebuilt at the first key frame after the sleep (%u " + "frames decoded on the session from before it), no frame " + "dropped", + kept); + return true; +} + +// The session from before the sleep failed on the frame being decoded: it is +// rebuilt at once and this frame is dropped, like the ones after it until a +// key frame. 0, or -1 when the rebuild fails. +static int failed_after_wake(VcnVP9* d, bool busy) { + char cause[256]; + snprintf(cause, sizeof(cause), "%s", d->err); + if (!rebuild_now(d, busy, true, cause)) return -1; + d->err[0] = 0; + d->failure = VCNVP9_FAIL_STREAM; + d->dropped = 1; + return 0; +} + static void destroy_now(VcnVP9* d) { vcn_session_close(&d->s); // The pictures go after the driver: a stuck command may still write one. @@ -791,16 +860,18 @@ static int submit(VcnVP9* d, VP9Params* prm) { } uint32_t fw = 0; int ds = 0; - VcnWaitResult w = - vcn_wait_command(FN(QueryAVDCommandStatus), d->s.drv, refcons[0], - VCN_COMMAND_TIMEOUT_MS, &fw, &ds); + // Longer on the session from before a sleep: right after a wake the driver + // can take seconds before a command runs (vcndriver.h). + unsigned limit = + d->rebuildAtKey ? vcn_wake_command_timeout_ms : VCN_COMMAND_TIMEOUT_MS; + VcnWaitResult w = vcn_wait_command(FN(QueryAVDCommandStatus), d->s.drv, + refcons[0], limit, &fw, &ds); if (w == VCN_WAIT_TIMEOUT) { // The GPU still holds this command. Sending more work, or reading the // target, could only make things worse: the session stops here. d->stuck = d->broken = true; snprintf(d->err, sizeof(d->err), - "the GPU did not finish a frame in %d ms; session stopped", - VCN_COMMAND_TIMEOUT_MS); + "the GPU did not finish a frame in %u ms; session stopped", limit); return -1; } if (w != VCN_WAIT_DONE) { @@ -812,6 +883,7 @@ static int submit(VcnVP9* d, VP9Params* prm) { } d->failure = VCNVP9_FAIL_STREAM; d->done++; + d->lastFw = fw; // Counted, not refused: the VP9 result goes through the AV1 processor's // status reader, and what it reports for VP9 has not been checked on a GPU. // The first one of a session is logged at once, the count goes in the stats @@ -828,15 +900,27 @@ static int on_frame(void* vctx, VP9Parser* p, VP9ParseResult kind, const uint8_t* data, size_t size) { VcnVP9* d = vctx; const VP9Frame* h = &p->fh; - // After a rebuild nothing from before the sleep can be used: every frame but - // a key frame (or an intra-only one, which refreshes every slot) is dropped, - // with no picture and no error, and a key frame starts the decoder again. - // Bounded: a stream that never sends one is stopped as a device failure, - // PR 160's behaviour. + // A frame after which nothing decoded before it is used: a key frame + // (refreshes every slot and resets the four probability contexts), or an + // intra-only frame that does both (all eight slots refreshed, and + // error_res or reset_frame_context 3). Another intra-only frame keeps + // slots or contexts the frames after it may use, which live in the old + // driver's DPB and context. + bool restart = + kind == VP9_PARSE_DECODE && + (h->frame_type == 0 || (h->intra_only && h->refresh_frame_flags == 0xff && + (h->error_res || h->reset_frame_context == 3))); + // The system slept since the driver side opened, and it kept decoding (a + // real sleep on this Mac did not break it): it is replaced at the first such + // frame, which then decodes on the new one. + if (d->rebuildAtKey && restart && !rebuild_now(d, false, false, NULL)) + return -1; + // After a rebuild that followed a failure nothing from before it can be + // used: every frame but such a key frame is dropped, with no picture and no + // error, and the key frame starts the decoder again. Bounded: a stream that + // never sends one is stopped as a device failure, PR 160's behaviour. if (d->needKey) { - bool key = - kind == VP9_PARSE_DECODE && (h->frame_type == 0 || h->intra_only); - if (!key) { + if (!restart) { if (++d->dropped > REBUILD_MAX_DROPPED) { d->broken = true; d->failure = VCNVP9_FAIL_DEVICE; @@ -954,7 +1038,18 @@ static int on_frame(void* vctx, VP9Parser* p, VP9ParseResult kind, "refresh=%02x\n", h->frame_type, h->intra_only, h->show_frame, h->width, h->height, h->bit_depth, h->base_q_idx, size, slot, h->refresh_frame_flags); - if (submit(d, &prm)) return -1; + if (submit(d, &prm)) + // On the session from before a sleep, a driver failure is taken for the + // sleep's doing: rebuilt at once, instead of stopping the session. + return d->rebuildAtKey && d->broken ? failed_after_wake(d, d->stuck) : -1; + if (d->rebuildAtKey) { + if (d->lastFw) { + // A firmware error on it after the wake: its picture is not trusted. + snprintf(d->err, sizeof(d->err), "firmware result %u", d->lastFw); + return failed_after_wake(d, false); + } + d->keptAfterWake++; + } vp9_frame_done(p, slot); recount_refs(d); if (h->show_frame) { @@ -979,17 +1074,14 @@ int vcnvp9_decode(VcnVP9* d, const uint8_t* chunk, size_t size, int64_t tag, CVPixelBufferRelease(d->hidden); d->hidden = NULL; } - if (!d->broken && vcn_session_lost(&d->s)) { - char why[200]; - if (!vp9_rebuild(d, why, sizeof(why))) { - d->broken = true; - snprintf(d->err, sizeof(d->err), - "session stopped: the system slept since it opened and the " - "rebuild failed (%s)", - why); - d->failure = VCNVP9_FAIL_DEVICE; - return -1; - } + // A sleep since the driver side opened: it keeps decoding, and on_frame + // rebuilds it at the next key frame (or at once if it fails). + if (!d->broken && !d->rebuildAtKey && vcn_session_lost(&d->s)) { + d->rebuildAtKey = true; + d->keptAfterWake = 0; + os_log_error(vlog(), + "VP9 session from before the sleep: it keeps decoding and is " + "rebuilt at the next key frame"); } if (d->broken) { snprintf(d->err, sizeof(d->err), "session stopped: %s", diff --git a/GPU/docs/how-it-works.md b/GPU/docs/how-it-works.md index a1df6f9b..4ff87d83 100644 --- a/GPU/docs/how-it-works.md +++ b/GPU/docs/how-it-works.md @@ -145,7 +145,7 @@ ends. A failed driver call or a stuck command is reported to VideoToolbox as a m `canAcceptFormatDescription` says no from then on. It reads the format under a lock of its own, so it never waits for a frame the GPU is decoding. -### A system sleep (0.3.6) +### A system sleep (0.3.7) Apple's kernel driver keeps a decoder's video context across a sleep, but restarts the video engine under it. Read in IDA (AMDRadeonX6000, 26.7.3 KDK): `systemWillSleep` calls @@ -154,37 +154,60 @@ every VCN ring and then stops the rings; `saveVCNSession`, called on the way dow empty. At wake, `powerUpHW` and `internalDidWake` start the rings again, and `restoreVCNSession` only sends the context's clocks and power client again. Nothing tells the program: AMDRadeonVADriver2, AppleGVA and VideoToolbox have no sleep handling at all. -The engine has lost the sessions it had (the driver sends a create-session command once, -when a decoder opens, and a destroy-session command when it closes). - -So a session opened before a sleep is never used again (`vcn_session_lost` in -`decode/common/vcnsession.c`). A sleep is seen without any notification: the time the Mac -has spent asleep (`mach_continuous_time` minus `mach_absolute_time`) or the time of the -last wake (`kern.waketime`) changed since the session opened. Such a session writes nothing -more into its bitstream pool and schedules nothing; its frames fail as a malfunction, and -VideoToolbox makes a new session, which opens on the restarted engine. Closing it skips -`DeleteContexts`, `FreeBitstreamBufferPool` and `DeleteDriver`: the first sends the engine -a destroy-session command for a session it no longer has and waits for it with no time -limit, and `DeleteDriver` does the same for a context still open. Only -`AVD_DestroyAVDAccelerator` runs, on the background queue: it closes the three IOKit -connections, and the kernel's own close of the video context sends the engine nothing -(`submitDestroyCommand` returns at once). What the driver allocated in the process stays -until the process ends. A notification could not be used anyway: VideoToolbox's decoder -service runs in a sandbox (`VTDecoderSandboxProfile.sb`) that does not allow the power -domain's user client `IORegisterForSystemPower` opens. - -While a session from before a sleep is still open in a process, no new session opens in -that process, in any of the plug-ins: `vcn_session_open` fails before it opens anything, -and VideoToolbox gives the stream to another decoder (software). A reported hang began just -so: a browser's decoder process kept two VP9 sessions open across a sleep, and the AV1 -session it opened after the wake never decoded a frame; the Mac hung after the next wake. -Each plug-in bundle has its own copy of the session code, so they count each other's open -sessions through the process's local notification center (`CFNotificationCenterGetLocalCenter`, -which calls every observer on the posting thread). Once those sessions are closed, new ones -open on the GPU again. - -The kernel side has been read, not run across a sleep with a decode going: the CPU tests -(`sessiontest`, a made-up sleep) cover the plug-in side. + +What that does to a session was measured on this Mac (RX 6800 XT, 26.7.3, 2026-11-25): with +0.3.5 the sessions open across a real sleep kept decoding after the wake, every frame +matching its reference; one frame of each decode took about 10 s around the wake, inside +Apple's calls. A reporter on another machine (RX 6900 XT, Sequoia) saw broken pictures and +a hang after a wake, which was not reproduced here. + +So an AV1 or VP9 session from before a sleep keeps decoding (`vcn_session_lost` in +`decode/common/vcnsession.c` only notices the sleep), and its driver objects are replaced at +its next key frame, where nothing decoded before is needed any more (`rebuild_now` in +`vcnav1.c` and `vcnvp9.c`): an AV1 key frame that refreshes all eight reference slots, a VP9 +key frame, or a VP9 intra-only frame that refreshes all eight and resets all four +probability contexts. The old accelerator is closed with `AVD_DestroyAVDAccelerator` only, +a new accelerator, driver, context and bitstream pool are opened in the same plug-in +session, and the key frame decodes on them; no frame is dropped. If the old session fails +after the wake (a driver call fails, a command does not finish, or the firmware reports an +error), it is replaced at once and the frames up to the next such key frame are dropped: +noErr with no picture, as for a hidden frame, at most 600 of them, then a malfunction +(-12911). A command that did not finish has its accelerator closed on the background +queue, and its pictures are let go after that. Until the replacement, a command on the old +session may take 15 s instead of 1 s. A replacement that fails stops the session with +-12911, and VideoToolbox makes a new decoder. + +A sleep is seen without any notification: the time the Mac has spent asleep +(`mach_continuous_time` minus `mach_absolute_time`), the time of the last wake +(`kern.waketime`), or a wall clock that ran ahead of `mach_absolute_time` changed since the +session opened. A notification could not be used anyway: VideoToolbox's decoder service +runs in a sandbox (`VTDecoderSandboxProfile.sb`) that does not allow the power domain's user +client `IORegisterForSystemPower` opens. + +Closing a session from before a sleep that was never replaced skips `DeleteContexts`, +`FreeBitstreamBufferPool` and `DeleteDriver`: the first sends the engine a destroy-session +command and waits for it with no time limit, and `DeleteDriver` does the same for a context +still open. Only `AVD_DestroyAVDAccelerator` runs, on the background queue: it closes the +three IOKit connections, and the kernel's own close of the video context sends the engine +nothing (`submitDestroyCommand` returns at once). What the driver allocated in the process +(its handle, context and bitstream pool) stays until the process ends, once per replacement +or such close. + +New sessions open while one from before a sleep is still open; the plug-ins only count those +for the log, through the process's local notification center +(`CFNotificationCenterGetLocalCenter`, which calls every observer on the posting thread), +because each plug-in bundle has its own copy of the session code. The MPEG-2, VC-1 and +MPEG-4 decoders (`vcnlegacy.c`) do not replace their sessions: one from before a sleep +fails its pictures as a malfunction, as in 0.3.6. + +What still waits with no limit the plug-in can set is inside Apple's code: the driver calls +themselves (`ScheduleAVDCommands`, `QueryAVDCommandStatus`, `CreateAVDAccelerator`, +`CreateDriver`, `AllocateBitstreamBufferPool`, `CreateContexts`, +`AVD_DestroyAVDAccelerator`, and in a normal close `DeleteContexts` and `DeleteDriver`), +the pixel buffer pool, and the kernel's own wait for the last command before a sleep. The +plug-in's VideoToolbox side waits for its own decode queue (a free queue slot, the queued +frames on finish and invalidate, the decode lock on invalidate); those waits end when the +frame being decoded ends, so they too wait as long as a driver call does. ### The parsers diff --git a/GPU/docs/testing.md b/GPU/docs/testing.md index ee3fe84c..58d33330 100644 --- a/GPU/docs/testing.md +++ b/GPU/docs/testing.md @@ -109,14 +109,14 @@ them, when, on which card and macOS build, and add the result to `docs/status.md leaves no context to delete, and `QueryAVDCommandStatus` with `.wait = 0` returns at once (status 1 done, 2 running). Still open: how long the kernel's own wait can last after a GPU restart. -- Decoders 0.3.6, a system sleep during a decode: `vtvp9test` and `vtav1test` with +- Decoders 0.3.7, a system sleep during a decode: `vtvp9test` and `vtav1test` with `-loop N -pace 30` keep one session going across `pmset sleepnow`, and `-renew` makes a - new session for every pass in the same process. The session from before the sleep must - fail as a malfunction (-12911) at the first frame after the wake, with no GPU restart in - the kernel log and no hang; with `-renew`, the passes after the wake must match their - reference again. The plug-ins log "the system slept since this session opened" and - "session from before the sleep closed without the driver's own teardown". In a browser: - a VP9 video left open (paused) across the sleep, then a second video in the same browser - after the wake must play (in software while the first tab stays open) and the Mac must - not hang. Only `sessiontest` and `staletest` (made-up driver and sleep) have run. + new session for every pass in the same process. No pass may have errors or frames that + differ from the reference, before or after the wake, and the kernel log must show no GPU + restart and no hang. The plug-ins log "the system slept since this session opened", then + "keeps decoding and is rebuilt at the next key frame" and "driver rebuilt at the first key + frame after the sleep"; "failed after the wake" means the old session failed and frames + were dropped up to a key frame. A first real run of 0.3.6 on this Mac (2026-11-25) failed + every frame of the old sessions; 0.3.5 passed. Only `sessiontest` and `staletest` (made-up + driver and sleep) have run for 0.3.7. - Everything at once: `install/check.sh` ends in one line. diff --git a/GPU/tests/run.sh b/GPU/tests/run.sh index c91cf23d..44e8b362 100755 --- a/GPU/tests/run.sh +++ b/GPU/tests/run.sh @@ -23,7 +23,8 @@ # damaged at random, under the address and undefined-behaviour sanitizers # 5. the rule that picks AMD's accelerator; the wait for a decode command gives up on a # command that never finishes (waittest, with a made-up driver); two plug-ins of one -# process: a session from before a sleep stops new ones until it closes (staletest) +# process: a session from before a sleep is seen by the other, which opens anyway +# (staletest) # 5b. the loader kext: its decisions, that it builds twice to the same bytes and lists the # plug-ins just built, that install/loader.sh puts it on an EFI and takes it off again # (on made-up EFI folders), and that it accepts the AMFI functions of this Mac @@ -146,14 +147,14 @@ check "only AMD's accelerator is taken" decode/build/tests/acceltest check "a decode command that never finishes times out" decode/build/tests/waittest stale() { decode/build/tests/staletest decode/build/tests/libstale-{a,b}.dylib > decode/build/tests/staletest.txt || { cat decode/build/tests/staletest.txt; return 1; }; } -check "two plug-ins of one process: a session from before a sleep stops new ones until it closes" stale +check "two plug-ins of one process: a session from before a sleep is seen, new ones open anyway" stale sessions() { decode/build/tests/sessiontest-av1 tests/media/av1/av1-1-b8-01-size-16x16.ivf tests/media/av1/av1-1-b8-05-mv.ivf > decode/build/tests/sessiontest-av1.txt && decode/build/tests/sessiontest-vp9 tests/media/vp9/vp90-2-12-droppable_1.ivf \ tests/media/vp9-invalid/invalid-vp90-2-09-aq2.webm.ivf.s3984_r01-05_b6-.ivf > decode/build/tests/sessiontest-vp9.txt || { cat decode/build/tests/sessiontest-av1.txt decode/build/tests/sessiontest-vp9.txt 2>/dev/null | grep -v ^PASS; return 1; } } -check "decoder sessions release the driver once, also after failures and a stuck GPU; hidden frames keep their picture (made-up driver)" sessions +check "decoder sessions release the driver once, also after failures and a stuck GPU; a sleep: decode on, rebuild at a key frame; hidden frames keep their picture (made-up driver)" sessions step "decoders: loader kext" check "the kext's decisions" decode/build/tests/loadertest