From 8800d4460f273421752538d716dd972a0724e282 Mon Sep 17 00:00:00 2001 From: qiyinxi Date: Fri, 4 Dec 2026 10:35:53 +0100 Subject: [PATCH] =?UTF-8?q?=E6=88=AA=E5=9B=BE=E6=8C=89=E5=B8=A7=E5=BA=8F?= =?UTF-8?q?=E5=8F=B7=E5=8D=8F=E8=AE=AE=E5=88=A4=E6=96=AD=E6=95=B4=E5=B8=A7?= =?UTF-8?q?=EF=BC=8C=E5=A4=96=E5=A3=B3=E4=B8=8D=E5=86=8D=E4=BA=A4=E5=87=BA?= =?UTF-8?q?=E6=92=95=E8=A3=82=E5=B8=A7?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 模拟器原地往共享内存写像素,旧的判断(复制前后帧号相等就算完整)漏掉一种情况:复制开始时模拟器已经在写下一帧、帧号还没变,复制又在写完前结束,撕裂的帧照样通过。 协议:新模拟器把帧头 fps 的最高位(0x80000000)置上,表示按序号写帧号:写像素前加 1(奇数 = 正在写),写完像素和 ts_us 后再加 1(偶数 = 完整)。帧头布局不变,帧号每帧跳 2,可能回绕。 - mx_copy_frame():带这一位时,序号是奇数就让出 CPU 等它变偶数(每次截图从第一次看到奇数起最多等 MX_SEQ_WAIT_MS = 50 ms,超时算失败);读序号后、读回序号前各放一道 acquire 屏障(x86 上是编译器屏障,ARM64 上是 dmb),ts_us 在第二道屏障之前读;前后序号相等才算成功。交给调用方的帧号是序号 / 2,外面看到的仍是每帧加 1。重试次数仍是 3,用完 modavd_capture() 照旧返回 MODAVD_E_NOT_READY。 - 不带这一位(旧模拟器):沿用原来的前后比较,奇数帧号不代表正在写,不等待。 - 外壳 external_renderer_ipc.dll:收到 MX_TORN 不再当成功交出,再试最多 10 轮,还不行就按无帧返回 -2,并在 avdshim.log 记一行。 - open、connect 日志里的 fps 去掉标志位,带这一位时行里标 seqlock。 兼容性:新库配旧模拟器,截图行为不变(只有外壳在一直撕裂时改为返回失败);新库配新模拟器,撕裂帧被挡住;旧库配新模拟器,截图照旧能用,帧号每帧跳 2、日志里 fps 是个很大的数,撕裂照旧可能漏过。 测试:假共享内存加上新模拟器模式。单线程用例覆盖序号一直是奇数时等到超时失败、复制中途写了一帧或开始写下一帧时重试、序号回绕、旧模式奇数帧号不等待、日志里 fps 不带标志位;多线程压力用例一个线程按序号不停写帧、本线程连续截 5000 次,断言每次成功的帧所有像素一致、帧号和时间戳对得上;外壳在帧一直写不完时返回 -2、不动缓冲区。 Refs ModAVD/ModAVD#431 --- changelog.d/torn-frames-431.fix.md | 2 + shim/mumu_shim.c | 30 ++- src/core.c | 101 +++++++- src/mx_internal.h | 63 ++++- tests/fake_frame.h | 28 +++ tests/test_core.c | 377 ++++++++++++++++++++++++++++- tests/test_shim.c | 45 ++++ 7 files changed, 613 insertions(+), 33 deletions(-) create mode 100644 changelog.d/torn-frames-431.fix.md diff --git a/changelog.d/torn-frames-431.fix.md b/changelog.d/torn-frames-431.fix.md new file mode 100644 index 0000000..b0335e0 --- /dev/null +++ b/changelog.d/torn-frames-431.fix.md @@ -0,0 +1,2 @@ +截图不再偶尔拿到上下两半来自不同画面的撕裂帧 (ModAVD/ModAVD#431) +Screenshots no longer occasionally come out torn, with the top and bottom from different frames diff --git a/shim/mumu_shim.c b/shim/mumu_shim.c index da0b60b..d7c57f1 100644 --- a/shim/mumu_shim.c +++ b/shim/mumu_shim.c @@ -35,6 +35,9 @@ #define MAX_SLOTS 16 #define DEFAULT_PORT_BASE 20000 #define PORT_STEP 10 +/* Calls of mx_capture_frame() per capture while each copy may mix two frames + * (MX_TORN), before the capture fails. */ +#define SHIM_TORN_ROUNDS 10 static modavd_handle g_slots[MAX_SLOTS]; static int g_slot_ports[MAX_SLOTS]; @@ -203,9 +206,10 @@ EXPORT int nemu_connect(const wchar_t* path, int index) shim_log("connect index=%d port=%d: shared memory unavailable (%s)", index, port, modavd_strerror(rc)); return 0; } - const mx_video_info* vi = (const mx_video_info*)h->shm.view; - shim_log("connect index=%d port=%d handle=%d %ux%u fps=%u frame=%u size=%zu", index, port, handle, vi->width, - vi->height, vi->fps, vi->frame_number, h->shm.size); + const volatile mx_video_info* vi = (const volatile mx_video_info*)h->shm.view; + uint32_t fps = vi->fps; + shim_log("connect index=%d port=%d handle=%d %ux%u fps=%u frame=%u size=%zu%s", index, port, handle, vi->width, + vi->height, fps & MX_FPS_MASK, vi->frame_number, h->shm.size, (fps & MX_FPS_SEQLOCK) ? " seqlock" : ""); EnterCriticalSection(&g_lock); if (g_slots[handle - 1]) { @@ -251,7 +255,7 @@ EXPORT int nemu_get_display_id(int handle, const char* pkg, int app_index) } /* Returns 0 on success (MuMu convention), -1 for a bad handle, -2 when no - * frame is available, -3 when the buffer is too small. */ + * whole frame is available, -3 when the buffer is too small. */ EXPORT int nemu_capture_display(int handle, unsigned int display_id, int buffer_size, int* width, int* height, unsigned char* pixels) { @@ -264,15 +268,19 @@ EXPORT int nemu_capture_display(int handle, unsigned int display_id, int buffer_ memset(&info, 0, sizeof(info)); info.size = sizeof(info); size_t size = (buffer_size > 0 && pixels) ? (size_t)buffer_size : 0; - /* mx_copy_frame, not modavd_capture: as the DLL this replaces did, report - * the size and a black frame before the first frame is published, and hand - * the last copy over when a new frame arrived during every copy, instead - * of failing (MaaCore would give up on this path at connect, or drop to its - * screencap speed test again). */ - int rc = mx_capture_frame(h, MODAVD_FMT_RGBA, MODAVD_CAPTURE_BOTTOM_UP | MX_CAPTURE_UNPUBLISHED, + /* mx_capture_frame, not modavd_capture: as the DLL this replaces did, report + * the size and a black frame before the first frame is published, instead + * of failing (MaaCore would give up on this path at connect). A copy that + * may mix two frames (MX_TORN) is tried again a few times here, and then + * the capture fails: a torn frame handed over makes MaaCore match and tap + * against a picture that never was on screen (ModAVD#431). */ + int rc = MX_TORN; + for (int round = 0; round < SHIM_TORN_ROUNDS && rc == MX_TORN; ++round) { + rc = mx_capture_frame(h, MODAVD_FMT_RGBA, MODAVD_CAPTURE_BOTTOM_UP | MX_CAPTURE_UNPUBLISHED, size ? pixels : NULL, size, &info); + } if (rc == MX_TORN) { - rc = MODAVD_OK; + shim_log("capture handle=%d: no whole frame in %d rounds", handle, SHIM_TORN_ROUNDS); } if (rc == MODAVD_OK || rc == MODAVD_E_BUFFER) { if (width) { diff --git a/src/core.c b/src/core.c index df2dd88..e8b33ab 100644 --- a/src/core.c +++ b/src/core.c @@ -12,13 +12,30 @@ #define WIN32_LEAN_AND_MEAN #include static void sleep_ms(int ms) { Sleep((DWORD)ms); } +static void yield_cpu(void) { SwitchToThread(); } +static uint64_t now_us(void) +{ + LARGE_INTEGER t, f; + QueryPerformanceCounter(&t); + QueryPerformanceFrequency(&f); + return (uint64_t)(t.QuadPart / f.QuadPart) * 1000000u + (uint64_t)(t.QuadPart % f.QuadPart) * 1000000u / + (uint64_t)f.QuadPart; +} #else +#include #include static void sleep_ms(int ms) { struct timespec ts = { ms / 1000, (long)(ms % 1000) * 1000000L }; nanosleep(&ts, NULL); } +static void yield_cpu(void) { sched_yield(); } +static uint64_t now_us(void) +{ + struct timespec ts; + clock_gettime(CLOCK_MONOTONIC, &ts); + return (uint64_t)ts.tv_sec * 1000000u + (uint64_t)ts.tv_nsec / 1000u; +} #endif #if defined(__x86_64__) || defined(__i386__) || defined(_M_X64) || defined(_M_IX86) @@ -234,8 +251,10 @@ int modavd_open(const modavd_open_params* params, modavd_handle* out) inst->simd = mx_cpu_simd(); inst->shm = shm; const volatile mx_video_info* vi = (const volatile mx_video_info*)shm.view; - mx_log(MODAVD_LOG_INFO, "open port=%d %ux%u fps=%u frame=%u size=%zu client=%s", port, vi->width, vi->height, - vi->fps, vi->frame_number, shm.size, params->client_name ? params->client_name : "-"); + uint32_t fps = vi->fps; + mx_log(MODAVD_LOG_INFO, "open port=%d %ux%u fps=%u frame=%u size=%zu%s client=%s", port, vi->width, vi->height, + fps & MX_FPS_MASK, vi->frame_number, shm.size, (fps & MX_FPS_SEQLOCK) ? " seqlock" : "", + params->client_name ? params->client_name : "-"); #ifdef _WIN32 InitializeSRWLock((PSRWLOCK)&inst->shm_lock); /* NO_START with no console trusts the mapping as it is, unwatched. */ @@ -405,6 +424,38 @@ void mx_convert_row(const uint8_t* src, uint8_t* dst, uint32_t width, uint32_t f void (*mx_test_after_copy)(void* user) = NULL; void* mx_test_after_copy_user = NULL; +int mx_test_seq_wait_ms = MX_SEQ_WAIT_MS; + +/* Sequence mode: yield the CPU this long while a frame is being written before + * sleeping a millisecond at a time (a sleep may take a whole timer tick). */ +#define MX_SEQ_SPIN_US 2000 + +/* Sequence mode: reads the sequence number until it is even (no frame being + * written) and returns 1 with it in *seq. Returns 0 once MX_SEQ_WAIT_MS have + * passed since the first odd number of this capture (*odd_since, 0 = none yet). */ +static int seq_wait_even(const volatile mx_video_info* vi, uint64_t* odd_since, uint32_t* seq) +{ + for (;;) { + uint32_t s = vi->frame_number; + if (!(s & 1u)) { + *seq = s; + return 1; + } + uint64_t now = now_us() + 1; /* never 0 */ + if (!*odd_since) { + *odd_since = now; + } + uint64_t waited = now - *odd_since; + if (waited >= (uint64_t)mx_test_seq_wait_ms * 1000u) { + return 0; + } + if (waited < MX_SEQ_SPIN_US) { + yield_cpu(); + } else { + sleep_ms(1); + } + } +} int mx_copy_frame(const mx_shm* shm, uint32_t format, uint32_t flags, int simd, void* buf, size_t buf_size, modavd_frame_info* info) @@ -414,13 +465,17 @@ int mx_copy_frame(const mx_shm* shm, uint32_t format, uint32_t flags, int simd, return MODAVD_E_INVALID; } const volatile mx_video_info* vi = (const volatile mx_video_info*)shm->view; + /* An emulator that writes the sequence number says so in fps; one that + * does not keeps the old check below (an odd number means nothing there). */ + int seqlock = (vi->fps & MX_FPS_SEQLOCK) != 0; uint32_t w = vi->width; uint32_t h = vi->height; info->width = (int32_t)w; info->height = (int32_t)h; info->stride = (int32_t)(w * (uint32_t)bpp); info->format = format; - info->frame_number = vi->frame_number; + /* Callers see one more per frame either way. */ + info->frame_number = seqlock ? vi->frame_number >> 1 : vi->frame_number; info->timestamp_us = vi->ts_us; /* Dimensions are set before the first frame is published. The counter * can wrap to zero, and a published static frame need not advance. */ @@ -440,9 +495,19 @@ int mx_copy_frame(const mx_shm* shm, uint32_t format, uint32_t flags, int simd, const uint8_t* src = shm->view + MX_HEADER_SIZE; uint8_t* dst = (uint8_t*)buf; size_t src_stride = (size_t)w * 4; - /* No lock on the writer's side: copy again if a new frame was published meanwhile. */ + /* No lock on the writer's side: copy again if a frame was written meanwhile. */ + uint64_t odd_since = 0; for (int attempt = 0; attempt < MX_MAX_COPY_ATTEMPTS; ++attempt) { - uint32_t before = vi->frame_number; + uint32_t before; + if (seqlock) { + /* Odd: the emulator is writing a frame right now; copy once it is done. */ + if (!seq_wait_even(vi, &odd_since, &before)) { + return MX_TORN; + } + mx_acquire_fence(); /* the pixels are read after the sequence number */ + } else { + before = vi->frame_number; + } for (uint32_t y = 0; y < h; ++y) { uint32_t sy = (flags & MODAVD_CAPTURE_BOTTOM_UP) ? h - 1 - y : y; mx_convert_row(src + (size_t)sy * src_stride, dst + (size_t)y * (size_t)info->stride, w, format, simd); @@ -450,11 +515,22 @@ int mx_copy_frame(const mx_shm* shm, uint32_t format, uint32_t flags, int simd, if (mx_test_after_copy) { mx_test_after_copy(mx_test_after_copy_user); } - uint32_t after = vi->frame_number; - info->frame_number = after; - info->timestamp_us = vi->ts_us; - if (after == before) { - return MODAVD_OK; + if (seqlock) { + uint64_t ts = vi->ts_us; + mx_acquire_fence(); /* the pixels and ts_us are read before the sequence number again */ + if (vi->frame_number == before) { + /* Unchanged and even: no frame was written during the copy. */ + info->frame_number = before >> 1; + info->timestamp_us = ts; + return MODAVD_OK; + } + } else { + uint32_t after = vi->frame_number; + info->frame_number = after; + info->timestamp_us = vi->ts_us; + if (after == before) { + return MODAVD_OK; + } } } return MX_TORN; @@ -498,8 +574,9 @@ int modavd_capture(modavd_handle h, int display, uint32_t format, uint32_t flags } int rc = mx_capture_frame(h, format, flags & ~MX_CAPTURE_UNPUBLISHED, buf, buf_size, info); if (rc == MX_TORN) { - mx_log(MODAVD_LOG_WARN, "port=%d: a new frame arrived during each of %d copies", h->console_port, - MX_MAX_COPY_ATTEMPTS); + mx_log(MODAVD_LOG_WARN, + "port=%d: no whole frame: a new frame arrived during each of %d copies, or one stayed half-written", + h->console_port, MX_MAX_COPY_ATTEMPTS); return MODAVD_E_NOT_READY; } return rc; diff --git a/src/mx_internal.h b/src/mx_internal.h index 6994edc..6133d5c 100644 --- a/src/mx_internal.h +++ b/src/mx_internal.h @@ -17,25 +17,45 @@ extern "C" { #endif /* Layout of the emulator's shared frame (AOSP VideoFrameSharer.h, VideoInfo): - * this header, then width * height BGRA pixels, rows top-down. The emulator - * writes the pixels first and then frameNumber / tsUs, without a lock. */ + * this header, then width * height BGRA pixels, rows top-down, written in + * place without a lock. + * + * Two ways the emulator publishes frames (ModAVD#431): + * - Old emulators: frame_number is a plain counter, raised by one after the + * pixels and ts_us are written. An odd number means nothing. A copy that + * starts while the next frame is being written and ends before it is + * published sees the same number before and after, so a torn frame can + * pass; there is no way to tell from here. + * - Emulators that set MX_FPS_SEQLOCK in fps: frame_number is a sequence + * number. It goes up by one (odd: being written) before the pixels are + * written and by one again (even: complete) after the pixels and ts_us. + * It moves by two per frame and may wrap. */ typedef struct mx_video_info { uint32_t width; uint32_t height; - uint32_t fps; + uint32_t fps; /* frames per second; the top bit is MX_FPS_SEQLOCK, not part of it */ uint32_t frame_number; uint64_t ts_us; } mx_video_info; +#define MX_FPS_SEQLOCK 0x80000000u /* fps bit: frame_number is a sequence number, see above */ +#define MX_FPS_MASK 0x7FFFFFFFu /* the frames per second in fps */ + #define MX_HEADER_SIZE 24 #define MX_MAX_COPY_ATTEMPTS 3 #define MX_DEFAULT_TIMEOUT_MS 2000 - -/* mx_copy_frame() when the emulator published a new frame during every one - * of the MX_MAX_COPY_ATTEMPTS copies: the buffer may mix two frames. Internal - * only (positive, never a MODAVD_* code): modavd_capture() reports - * MODAVD_E_NOT_READY; the MuMu-shaped shim hands the last copy over, as the - * DLL it replaces did. */ +/* Sequence mode: how long one mx_copy_frame() waits in all for an odd + * sequence number (a frame being written) to turn even. Writing a frame takes + * a few milliseconds; a number that stays odd this long belongs to an + * emulator that stopped mid-frame (paused, crashed), and the copy fails. */ +#define MX_SEQ_WAIT_MS 50 + +/* mx_copy_frame() when no copy is known to be whole: the emulator published + * a new frame during every one of the MX_MAX_COPY_ATTEMPTS copies, or (in + * sequence mode) a frame stayed half-written past MX_SEQ_WAIT_MS. The buffer + * may mix two frames. Internal only (positive, never a MODAVD_* code): + * modavd_capture() reports MODAVD_E_NOT_READY; the MuMu-shaped shim tries a + * few more times and then fails the capture, never handing such a buffer over. */ #define MX_TORN 1 /* mx_copy_frame() flag, internal only (modavd_capture() clears it): copy the @@ -190,6 +210,31 @@ int mx_copy_frame(const mx_shm* shm, uint32_t format, uint32_t flags, int simd, * everywhere else. */ extern void (*mx_test_after_copy)(void* user); extern void* mx_test_after_copy_user; +/* Tests only: the wait limit for an odd sequence number, MX_SEQ_WAIT_MS + * unless a test lowers it so a stuck writer does not keep it waiting. */ +extern int mx_test_seq_wait_ms; + +/* Memory ordering for the sequence protocol on the shared frame (the header + * is volatile, the pixels are not). mx_acquire_fence(): loads before it are + * done before any load or store after it. mx_release_fence(): loads and + * stores before it are done before any store after it (for the writer in the + * tests). x86 keeps loads in order and stores in order, so only the compiler + * must not move accesses across; ARM64 needs a real barrier. */ +#if defined(_MSC_VER) && !defined(__clang__) +#include +#if defined(_M_ARM64) || defined(_M_ARM64EC) +#define mx_acquire_fence() __dmb(_ARM64_BARRIER_ISHLD) +#define mx_release_fence() __dmb(_ARM64_BARRIER_ISH) +#else +#define mx_acquire_fence() _ReadWriteBarrier() +#define mx_release_fence() _ReadWriteBarrier() +#endif +#elif defined(__GNUC__) || defined(__clang__) +#define mx_acquire_fence() __atomic_thread_fence(__ATOMIC_ACQUIRE) +#define mx_release_fence() __atomic_thread_fence(__ATOMIC_RELEASE) +#else +#error "no memory barrier for this compiler" +#endif #ifdef __cplusplus } diff --git a/tests/fake_frame.h b/tests/fake_frame.h index baefd3c..b76f9d5 100644 --- a/tests/fake_frame.h +++ b/tests/fake_frame.h @@ -91,6 +91,34 @@ static void fake_frame_set_size(fake_frame* f, uint32_t w, uint32_t h) vi->height = h; } +/* Makes the region one of an emulator that writes a sequence number + * (ModAVD#431): fps gets MX_FPS_SEQLOCK and frame_number is 2 * frame + * (even: no frame being written), so captures report frame. */ +static inline void fake_frame_use_seqlock(fake_frame* f, uint32_t frame) +{ + volatile mx_video_info* vi = (volatile mx_video_info*)f->view; + vi->fps = (vi->fps & MX_FPS_MASK) | MX_FPS_SEQLOCK; + vi->frame_number = frame * 2u; +} + +/* Sequence mode writer, as the emulator does it: odd before the pixels... */ +static inline void fake_frame_seq_begin(fake_frame* f) +{ + volatile mx_video_info* vi = (volatile mx_video_info*)f->view; + vi->frame_number = vi->frame_number + 1u; + mx_release_fence(); /* the odd number is seen before any pixel */ +} + +/* ...and even after the pixels and the timestamp. */ +static inline void fake_frame_seq_end(fake_frame* f, uint64_t ts_us) +{ + volatile mx_video_info* vi = (volatile mx_video_info*)f->view; + mx_release_fence(); /* the pixels are seen before the timestamp */ + vi->ts_us = ts_us; + mx_release_fence(); /* and both before the even number */ + vi->frame_number = vi->frame_number + 1u; +} + static void fake_frame_destroy(fake_frame* f) { #ifdef _WIN32 diff --git a/tests/test_core.c b/tests/test_core.c index 488d8b7..98ace97 100644 --- a/tests/test_core.c +++ b/tests/test_core.c @@ -12,6 +12,11 @@ #include "fake_frame.h" #include "modavd_extras.h" +#ifndef _WIN32 +#include +#include +#endif + static int g_failures; #define CHECK(cond) \ @@ -318,7 +323,7 @@ static void test_capture_new_frame_mid_copy(void) CHECK_EQ(modavd_capture(h, 0, MODAVD_FMT_BGRA, 0, buf, sizeof(buf), &info), MODAVD_E_NOT_READY); CHECK_EQ(s.calls, MX_MAX_COPY_ATTEMPTS); - /* The shim's call: it hands the last copy over, so it needs to tell this apart. */ + /* The shim's call: it tries again and then fails, so it needs to tell this apart. */ s.remaining = MX_MAX_COPY_ATTEMPTS; s.calls = 0; CHECK_EQ(mx_copy_frame(&h->shm, MODAVD_FMT_RGBA, MODAVD_CAPTURE_BOTTOM_UP, 0, buf, sizeof(buf), &info), @@ -331,6 +336,372 @@ static void test_capture_new_frame_mid_copy(void) fake_frame_destroy(&f); } +static uint64_t test_now_ms(void) +{ +#ifdef _WIN32 + LARGE_INTEGER t, f; + QueryPerformanceCounter(&t); + QueryPerformanceFrequency(&f); + return (uint64_t)(t.QuadPart / (f.QuadPart / 1000)); +#else + struct timespec ts; + clock_gettime(CLOCK_MONOTONIC, &ts); + return (uint64_t)ts.tv_sec * 1000u + (uint64_t)ts.tv_nsec / 1000000u; +#endif +} + +static modavd_handle open_fake(int port) +{ + modavd_open_params p; + memset(&p, 0, sizeof(p)); + p.size = sizeof(p); + p.console_port = port; + p.flags = MODAVD_OPEN_NO_START; + modavd_handle h = NULL; + CHECK_EQ(modavd_open(&p, &h), MODAVD_OK); + return h; +} + +/* The hook as an emulator in sequence mode: a whole frame (two steps) written + * after each of the next `remaining` copies. */ +static void seq_frame_after_copy(void* user) +{ + publish_state* s = (publish_state*)user; + ++s->calls; + if (s->remaining > 0) { + --s->remaining; + fake_frame_seq_begin(s->frame); + fake_frame_seq_end(s->frame, 123456789ull); + } +} + +/* The hook as an emulator in sequence mode that starts the next frame during + * the copy and is still writing it when the copy ends. */ +static void seq_begin_after_copy(void* user) +{ + publish_state* s = (publish_state*)user; + ++s->calls; + if (s->remaining > 0) { + --s->remaining; + fake_frame_seq_begin(s->frame); + } +} + +/* ModAVD#431, sequence mode, one thread: the frame number callers see, waiting + * on a frame being written, a frame written during the copy, wrapping. */ +static void test_capture_seqlock(void) +{ + const int port = 65024; + const uint32_t w = 8, hgt = 4; + fake_frame f; + if (fake_frame_create(&f, port, w, hgt, w, hgt) != 0) { + CHECK(!"cannot create the fake frame"); + return; + } + fake_frame_use_seqlock(&f, 7); /* sequence number 14 */ + volatile mx_video_info* vi = (volatile mx_video_info*)f.view; + modavd_handle h = open_fake(port); + if (!h) { + fake_frame_destroy(&f); + return; + } + /* Whole frames, every format: frame_number is the sequence number / 2 (check_capture wants 7). */ + check_capture(h, MODAVD_FMT_BGRA, 4, 0, w, hgt); + check_capture(h, MODAVD_FMT_BGR, 3, MODAVD_CAPTURE_BOTTOM_UP, w, hgt); + modavd_frame_info info; + memset(&info, 0, sizeof(info)); + info.size = sizeof(info); + CHECK_EQ(modavd_capture(h, 0, MODAVD_FMT_BGRA, 0, NULL, 0, &info), MODAVD_OK); /* size probe */ + CHECK_EQ(info.frame_number, 7); + + uint8_t buf[8 * 4 * 4]; + int saved_wait = mx_test_seq_wait_ms; + mx_test_seq_wait_ms = 20; + + /* A frame is being written when the capture starts and stays so: wait, then fail, without copying. */ + vi->frame_number = 15; + memset(buf, 0xA5, sizeof(buf)); + uint64_t t0 = test_now_ms(); + CHECK_EQ(mx_copy_frame(&h->shm, MODAVD_FMT_BGRA, 0, 0, buf, sizeof(buf), &info), MX_TORN); + uint64_t took = test_now_ms() - t0; + CHECK(took >= 19 && took < 2000); + for (size_t i = 0; i < sizeof(buf); ++i) { + CHECK_EQ(buf[i], 0xA5); + } + CHECK_EQ(modavd_capture(h, 0, MODAVD_FMT_BGRA, 0, buf, sizeof(buf), &info), MODAVD_E_NOT_READY); + /* The shim's flag does not skip the wait either. */ + CHECK_EQ(mx_copy_frame(&h->shm, MODAVD_FMT_RGBA, MX_CAPTURE_UNPUBLISHED, 0, buf, sizeof(buf), &info), MX_TORN); + vi->frame_number = 16; + CHECK_EQ(modavd_capture(h, 0, MODAVD_FMT_BGRA, 0, buf, sizeof(buf), &info), MODAVD_OK); + CHECK_EQ(info.frame_number, 8); + + /* A whole frame written during the first copy: the second copy is taken. */ + publish_state s = { &f, 1, 0 }; + mx_test_after_copy = seq_frame_after_copy; + mx_test_after_copy_user = &s; + CHECK_EQ(modavd_capture(h, 0, MODAVD_FMT_BGRA, 0, buf, sizeof(buf), &info), MODAVD_OK); + CHECK_EQ(s.calls, 2); + CHECK_EQ(info.frame_number, 9); + CHECK_EQ(vi->frame_number, 18); + + /* A frame written during every copy: no frame. */ + s.remaining = MX_MAX_COPY_ATTEMPTS; + s.calls = 0; + CHECK_EQ(mx_copy_frame(&h->shm, MODAVD_FMT_BGRA, 0, 0, buf, sizeof(buf), &info), MX_TORN); + CHECK_EQ(s.calls, MX_MAX_COPY_ATTEMPTS); + + /* The next frame starts during the copy and is not done when the copy + * ends: the frame number has not changed yet in the old scheme's sense, + * but it is odd now, so the copy does not count and the next one waits. */ + s.remaining = 1; + s.calls = 0; + mx_test_after_copy = seq_begin_after_copy; + CHECK_EQ(mx_copy_frame(&h->shm, MODAVD_FMT_BGRA, 0, 0, buf, sizeof(buf), &info), MX_TORN); + CHECK_EQ(s.calls, 1); + fake_frame_seq_end(&f, 123456789ull); + + /* The sequence number wraps: frame numbers go on from 0. */ + mx_test_after_copy = seq_frame_after_copy; + vi->frame_number = 0xFFFFFFFEu; + s.remaining = 0; + s.calls = 0; + CHECK_EQ(modavd_capture(h, 0, MODAVD_FMT_BGRA, 0, buf, sizeof(buf), &info), MODAVD_OK); + CHECK_EQ(info.frame_number, 0x7FFFFFFFu); + s.remaining = 1; + CHECK_EQ(modavd_capture(h, 0, MODAVD_FMT_BGRA, 0, buf, sizeof(buf), &info), MODAVD_OK); + CHECK_EQ(vi->frame_number, 0); + CHECK_EQ(info.frame_number, 0); + + /* Started, nothing published yet (sequence 0, timestamp 0): not ready, as before. */ + mx_test_after_copy = NULL; + mx_test_after_copy_user = NULL; + vi->ts_us = 0; + CHECK_EQ(modavd_capture(h, 0, MODAVD_FMT_BGRA, 0, buf, sizeof(buf), &info), MODAVD_E_NOT_READY); + CHECK_EQ(mx_copy_frame(&h->shm, MODAVD_FMT_BGRA, MX_CAPTURE_UNPUBLISHED, 0, buf, sizeof(buf), &info), MODAVD_OK); + CHECK_EQ(info.frame_number, 0); + + mx_test_seq_wait_ms = saved_wait; + modavd_close(h); + fake_frame_destroy(&f); +} + +/* An emulator without the sequence flag: an odd frame number is just a + * number. The capture neither waits nor fails on it. */ +static void test_capture_old_odd_frame(void) +{ + const int port = 65025; + fake_frame f; + if (fake_frame_create(&f, port, 8, 4, 8, 4) != 0) { + CHECK(!"cannot create the fake frame"); + return; + } + volatile mx_video_info* vi = (volatile mx_video_info*)f.view; + CHECK_EQ(vi->fps & MX_FPS_SEQLOCK, 0); + modavd_handle h = open_fake(port); + if (h) { + int saved_wait = mx_test_seq_wait_ms; + mx_test_seq_wait_ms = 5000; /* a wait would show in the time taken */ + uint8_t buf[8 * 4 * 4]; + modavd_frame_info info; + memset(&info, 0, sizeof(info)); + info.size = sizeof(info); + uint64_t t0 = test_now_ms(); + for (uint32_t n = 1; n < 40; n += 2) { + vi->frame_number = n; + CHECK_EQ(modavd_capture(h, 0, MODAVD_FMT_BGRA, 0, buf, sizeof(buf), &info), MODAVD_OK); + CHECK_EQ(info.frame_number, n); + } + CHECK(test_now_ms() - t0 < 1000); + mx_test_seq_wait_ms = saved_wait; + modavd_close(h); + } + fake_frame_destroy(&f); +} + +static char g_last_open_log[512]; +static void keep_open_log(int level, const char* msg, void* user) +{ + (void)level; + (void)user; + if (strncmp(msg, "open ", 5) == 0) { + snprintf(g_last_open_log, sizeof(g_last_open_log), "%s", msg); + } +} + +/* The flag is not part of the frame rate the log shows. */ +static void test_open_log_fps(void) +{ + const int port = 65026; + fake_frame f; + if (fake_frame_create(&f, port, 8, 4, 8, 4) != 0) { + CHECK(!"cannot create the fake frame"); + return; + } + modavd_set_log(keep_open_log, NULL); + g_last_open_log[0] = 0; + modavd_handle h = open_fake(port); + modavd_close(h); + CHECK(strstr(g_last_open_log, " fps=60 frame=7 ") != NULL); + CHECK(strstr(g_last_open_log, "seqlock") == NULL); + + fake_frame_use_seqlock(&f, 7); + g_last_open_log[0] = 0; + h = open_fake(port); + modavd_close(h); + modavd_set_log(NULL, NULL); + CHECK(strstr(g_last_open_log, " fps=60 frame=14 ") != NULL); + CHECK(strstr(g_last_open_log, " seqlock ") != NULL); + CHECK(strstr(g_last_open_log, "2147483") == NULL); + fake_frame_destroy(&f); +} + +/* ---- sequence mode under a real writer ---- */ + +typedef struct seq_writer { + fake_frame* frame; + uint32_t w, h; + volatile int stop; + uint32_t frames; /* written, read after the thread ended */ +} seq_writer; + +/* Writes one frame the way the emulator does in sequence mode: every pixel is + * the frame number callers will see for it, and the timestamp derives from it. */ +static void seq_write_frame(fake_frame* f, size_t pixels) +{ + volatile mx_video_info* vi = (volatile mx_video_info*)f->view; + uint32_t* px = (uint32_t*)(void*)(f->view + MX_HEADER_SIZE); + uint32_t next = (vi->frame_number + 2u) >> 1; + fake_frame_seq_begin(f); + for (size_t i = 0; i < pixels; ++i) { + px[i] = next; + } + fake_frame_seq_end(f, (uint64_t)next * 1000u + 1u); +} + +/* Writes frames until told to stop. Between frames it idles for a varying + * while (busy, so that it does not sleep a whole timer tick), so readers find + * both quiet moments and frames being written. */ +static void seq_writer_run(seq_writer* wr) +{ + volatile uint32_t idle = 0; + while (!wr->stop) { + seq_write_frame(wr->frame, (size_t)wr->w * wr->h); + ++wr->frames; + uint32_t spins = (wr->frames * 7919u) % 40000u; + for (uint32_t i = 0; i < spins; ++i) { + idle = idle + 1u; + } + } +} + +#ifdef _WIN32 +static DWORD WINAPI seq_writer_main(LPVOID arg) +{ + seq_writer_run((seq_writer*)arg); + return 0; +} +#else +static void* seq_writer_main(void* arg) +{ + seq_writer_run((seq_writer*)arg); + return NULL; +} +#endif + +static void count_copy(void* user) { ++*(int*)user; } + +/* ModAVD#431: one thread writes frames in sequence mode without pause, this + * one captures thousands of times. Every capture that succeeds holds exactly + * one frame: all pixels the same, and the frame number and timestamp match. */ +static void test_capture_seqlock_stress(void) +{ + const int port = 65027, captures = 5000; + const uint32_t w = 256, hgt = 128; + fake_frame f; + if (fake_frame_create(&f, port, w, hgt, w, hgt) != 0) { + CHECK(!"cannot create the fake frame"); + return; + } + fake_frame_use_seqlock(&f, 0); + seq_write_frame(&f, (size_t)w * hgt); /* frame 1, before the writer runs */ + modavd_handle h = open_fake(port); + size_t size = (size_t)w * hgt * 4; + uint32_t* buf = (uint32_t*)malloc(size); + if (!h || !buf) { + CHECK(!"cannot open the fake frame"); + free(buf); + modavd_close(h); + fake_frame_destroy(&f); + return; + } + seq_writer wr; + memset(&wr, 0, sizeof(wr)); + wr.frame = &f; + wr.w = w; + wr.h = hgt; +#ifdef _WIN32 + HANDLE thread = CreateThread(NULL, 0, seq_writer_main, &wr, 0, NULL); + CHECK(thread != NULL); +#else + pthread_t thread; + CHECK(pthread_create(&thread, NULL, seq_writer_main, &wr) == 0); +#endif + int copies = 0; + mx_test_after_copy = count_copy; + mx_test_after_copy_user = &copies; + int ok = 0, not_ready = 0, torn = 0; + uint32_t last = 0; + for (int i = 0; i < captures; ++i) { + modavd_frame_info info; + memset(&info, 0, sizeof(info)); + info.size = sizeof(info); + int rc = modavd_capture(h, 0, MODAVD_FMT_BGRA, 0, buf, size, &info); + if (rc == MODAVD_E_NOT_READY) { + ++not_ready; + continue; + } + CHECK_EQ(rc, MODAVD_OK); + if (rc != MODAVD_OK) { + continue; + } + ++ok; + size_t bad = 0; + for (size_t p = 0; p < (size_t)w * hgt; ++p) { + if (buf[p] != buf[0]) { + ++bad; + } + } + if (bad || buf[0] != info.frame_number || info.timestamp_us != (uint64_t)info.frame_number * 1000u + 1u) { + if (torn < 5) { + fprintf(stderr, "capture %d: frame %u ts %llu, first pixel %u, %zu pixels differ\n", i, + info.frame_number, (unsigned long long)info.timestamp_us, buf[0], bad); + } + ++torn; + } + CHECK(info.frame_number >= last); /* never goes back */ + last = info.frame_number; + } + mx_test_after_copy = NULL; + mx_test_after_copy_user = NULL; + wr.stop = 1; +#ifdef _WIN32 + if (thread) { + WaitForSingleObject(thread, INFINITE); + CloseHandle(thread); + } +#else + pthread_join(thread, NULL); +#endif + printf("test_core: seqlock stress: %d captures, %d whole, %d not ready, %d copies, %u frames written, %d torn\n", + captures, ok, not_ready, copies, wr.frames, torn); + CHECK_EQ(torn, 0); + CHECK(ok >= captures / 100); + CHECK(wr.frames > 100); + free(buf); + modavd_close(h); + fake_frame_destroy(&f); +} + /* Same frame through the public call at sizes that leave every possible tail after the * 16- and 4-pixel blocks, top-down and bottom-up. */ static void test_capture_odd_sizes(void) @@ -612,6 +983,10 @@ int main(int argc, char** argv) test_capture_from_fake_frame(); test_capture_before_first_frame(); test_capture_new_frame_mid_copy(); + test_capture_seqlock(); + test_capture_old_odd_frame(); + test_open_log_fps(); + test_capture_seqlock_stress(); test_capture_odd_sizes(); test_convert_row(); test_log_callback(); diff --git a/tests/test_shim.c b/tests/test_shim.c index 9499a97..f4fefb8 100644 --- a/tests/test_shim.c +++ b/tests/test_shim.c @@ -110,6 +110,46 @@ int main(int argc, char** argv) nemu_disconnect(handle); CHECK(nemu_capture_display(handle, 0, 0, &cw, &ch, NULL) == -1); + + /* ModAVD#431: an emulator that writes the sequence number. A whole frame + * is handed over; a frame that stays half-written is not: the capture + * fails (-2, like no frame) and the buffer is left alone. */ + { + const int sport = 65023; + fake_frame sf; + SOCKET sl = fake_listen(sport); + if (fake_frame_create(&sf, sport, w, h, w, h) != 0 || sl == INVALID_SOCKET) { + fprintf(stderr, "cannot create the sequence mode fake frame\n"); + return 1; + } + fake_frame_use_seqlock(&sf, 7); + int sh = nemu_connect(scratch, sport); + CHECK(sh > 0); + CHECK(nemu_capture_display(sh, 0, (int)size, &cw, &ch, buf) == 0); + CHECK(cw == (int)w && ch == (int)h); + CHECK(buf[0] == (uint8_t)(h - 1) && buf[1] == (uint8_t)(h - 1) && buf[2] == 0 && buf[3] == 0xFF); + + volatile mx_video_info* svi = (volatile mx_video_info*)sf.view; + svi->frame_number = 15; /* being written, and the writer never finishes */ + memset(buf, 0xA5, size); + cw = ch = -1; + DWORD t0 = GetTickCount(); + CHECK(nemu_capture_display(sh, 0, (int)size, &cw, &ch, buf) == -2); + DWORD took = GetTickCount() - t0; + CHECK(took < 5000); /* 10 tries of at most ~50 ms each */ + CHECK(cw == -1 && ch == -1); + int touched = 0; + for (size_t i = 0; i < size; ++i) { + touched |= buf[i] != 0xA5; + } + CHECK(!touched); + /* Once the frame is done, captures go on. */ + svi->frame_number = 16; + CHECK(nemu_capture_display(sh, 0, (int)size, &cw, &ch, buf) == 0); + nemu_disconnect(sh); + fake_frame_destroy(&sf); + fake_unlisten(sl); + } free(buf); /* No frame on that port and nothing listens: connect fails with 0. */ @@ -206,6 +246,11 @@ int main(int argc, char** argv) CHECK(strstr(text, "connect index=65003 port=65003 handle=1 48x20 fps=60 frame=7") != NULL); CHECK(strstr(text, "disconnect handle=1 port=65003") != NULL); CHECK(strstr(text, "connect index=65021 port=65021: shared memory unavailable") != NULL); + /* The sequence flag is not part of the frame rate. */ + CHECK(strstr(text, "connect index=65023 port=65023 handle=1 48x20 fps=60 frame=14 size=") != NULL); + CHECK(strstr(text, " seqlock\n") != NULL || strstr(text, " seqlock\r\n") != NULL); + CHECK(strstr(text, "capture handle=1: no whole frame in 10 rounds") != NULL); + CHECK(strstr(text, "2147483") == NULL); } /* A frame left over with no emulator behind it: not mapped, so it can go. */