Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions changelog.d/torn-frames-431.fix.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
截图不再偶尔拿到上下两半来自不同画面的撕裂帧 (ModAVD/ModAVD#431)
Screenshots no longer occasionally come out torn, with the top and bottom from different frames
30 changes: 19 additions & 11 deletions shim/mumu_shim.c
Original file line number Diff line number Diff line change
Expand Up @@ -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];
Expand Down Expand Up @@ -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]) {
Expand Down Expand Up @@ -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)
{
Expand All @@ -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) {
Expand Down
101 changes: 89 additions & 12 deletions src/core.c
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,30 @@
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
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 <sched.h>
#include <time.h>
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)
Expand Down Expand Up @@ -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. */
Expand Down Expand Up @@ -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)
Expand All @@ -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. */
Expand All @@ -440,21 +495,42 @@ 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);
}
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;
Expand Down Expand Up @@ -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;
Expand Down
63 changes: 54 additions & 9 deletions src/mx_internal.h
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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 <intrin.h>
#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
}
Expand Down
28 changes: 28 additions & 0 deletions tests/fake_frame.h
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Loading
Loading