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: 1 addition & 1 deletion CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ endif()

function(mx_link_system target)
if(WIN32)
target_link_libraries(${target} PRIVATE ws2_32)
target_link_libraries(${target} PRIVATE ws2_32 iphlpapi)
else()
target_link_libraries(${target} PRIVATE Threads::Threads)
if(CMAKE_SYSTEM_NAME STREQUAL "Linux")
Expand Down
11 changes: 10 additions & 1 deletion include/modavd_extras.h
Original file line number Diff line number Diff line change
Expand Up @@ -136,7 +136,13 @@ MODAVD_API int modavd_parse_console_port(const char* adb_address);
* opening the mapping: named regions can survive an emulator restart. Console
* auth/command failures return MODAVD_E_IO, even if an old mapping exists.
* The first frame may not have arrived yet; capture then returns NOT_READY.
* MODAVD_E_NOT_FOUND: frame sharing is off and nothing answers on the console port.
* On Windows the handle holds the mapping only while the emulator listening on
* the console port runs: when it exits the mapping is released, so the next
* emulator on the port can share frames at its own size (ModAVD/ModAVD#210).
* MODAVD_E_NOT_FOUND: frame sharing is off and nothing answers on the console
* port; on Windows also a region with no emulator on the
* port (left over, held by another program; unless
* MODAVD_OPEN_NO_START is set).
* MODAVD_E_NOT_READY: the console answered (or MODAVD_OPEN_NO_START is set) but
* frame sharing did not come up in time. */
MODAVD_API int modavd_open(const modavd_open_params* params, modavd_handle* out);
Expand All @@ -152,6 +158,9 @@ MODAVD_API int modavd_console_port(modavd_handle h); /* > 0, or MODAVD_E_IN
* MODAVD_E_NOT_READY: no frame yet, or the emulator published a new frame
* during each of the copies, so buf may mix two frames;
* call again. MODAVD_E_RESIZED: reopen the handle.
* MODAVD_E_NOT_FOUND (Windows): the emulator exited and no new one shares
* frames on the port yet; call again later, the handle
* maps the next emulator's region by itself.
* MODAVD_E_BUFFER: buf_size < info->stride * info->height. */
MODAVD_API int modavd_capture(modavd_handle h, int display, uint32_t format, uint32_t flags, void* buf,
size_t buf_size, modavd_frame_info* info);
Expand Down
4 changes: 2 additions & 2 deletions shim/mumu_shim.c
Original file line number Diff line number Diff line change
Expand Up @@ -269,8 +269,8 @@ EXPORT int nemu_capture_display(int handle, unsigned int display_id, int buffer_
* 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_copy_frame(&h->shm, MODAVD_FMT_RGBA, MODAVD_CAPTURE_BOTTOM_UP | MX_CAPTURE_UNPUBLISHED, h->simd,
size ? pixels : NULL, size, &info);
int 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;
}
Expand Down
34 changes: 34 additions & 0 deletions src/console.c
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
#define WIN32_LEAN_AND_MEAN
#include <winsock2.h>
#include <windows.h>
#include <iphlpapi.h>
typedef SOCKET mx_socket;
#define MX_BAD_SOCKET INVALID_SOCKET
#define mx_close_socket closesocket
Expand Down Expand Up @@ -190,6 +191,39 @@ int mx_console_query(mx_console* c, const char* command, char* reply, size_t cap

int mx_console_send(mx_console* c, const char* command) { return mx_console_query(c, command, NULL, 0); }

#ifdef _WIN32
unsigned long mx_console_owner_pid(int port)
{
/* The listener table, filtered by Windows itself: no need to know what
* value this Windows build uses for the listening state. */
ULONG size = 0;
MIB_TCPTABLE_OWNER_PID* table = NULL;
DWORD rc = ERROR_INSUFFICIENT_BUFFER;
for (int attempt = 0; attempt < 4 && rc == ERROR_INSUFFICIENT_BUFFER; ++attempt) {
free(table);
table = size ? (MIB_TCPTABLE_OWNER_PID*)malloc(size) : NULL;
if (size && !table) {
return 0;
}
rc = GetExtendedTcpTable(table, &size, FALSE, AF_INET, TCP_TABLE_OWNER_PID_LISTENER, 0);
}
unsigned long pid = 0;
if (rc == NO_ERROR && table) {
for (DWORD i = 0; i < table->dwNumEntries; ++i) {
const MIB_TCPROW_OWNER_PID* row = &table->table[i];
DWORD addr = ntohl(row->dwLocalAddr);
if (ntohs((u_short)row->dwLocalPort) == (u_short)port &&
(addr == INADDR_LOOPBACK || addr == INADDR_ANY)) {
pid = row->dwOwningPid;
break;
}
}
}
free(table);
return pid;
}
#endif

void mx_console_close(mx_console* c)
{
if (c->sock == (intptr_t)MX_BAD_SOCKET) {
Expand Down
130 changes: 129 additions & 1 deletion src/core.c
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,81 @@ static void sleep_ms(int ms)
#define MODAVD_EXTRAS_VERSION "0.0.0"
#endif

#ifdef _WIN32
/* Thread pool callback: the watched emulator exited. Drops the mapping so the
* next emulator on this port can create its region at its own size. */
static void CALLBACK emulator_exited(PVOID ctx, BOOLEAN timed_out)
{
(void)timed_out;
struct modavd_instance* h = (struct modavd_instance*)ctx;
AcquireSRWLockExclusive((PSRWLOCK)&h->shm_lock);
if (h->shm.view) {
mx_log(MODAVD_LOG_INFO, "port=%d: the emulator exited, released its shared memory", h->console_port);
mx_shm_close(&h->shm);
}
ReleaseSRWLockExclusive((PSRWLOCK)&h->shm_lock);
}

static int watch_emulator(struct modavd_instance* h, unsigned long pid)
{
HANDLE process = OpenProcess(SYNCHRONIZE, FALSE, (DWORD)pid);
if (!process) {
return MODAVD_E_IO;
}
HANDLE wait = NULL;
if (!RegisterWaitForSingleObject(&wait, process, emulator_exited, h, INFINITE, WT_EXECUTEONLYONCE)) {
CloseHandle(process);
return MODAVD_E_IO;
}
h->emu_process = process;
h->emu_wait = wait;
return MODAVD_OK;
}

/* block: wait for a running callback to return. Only without shm_lock held,
* since the callback takes it. */
static void unwatch_emulator(struct modavd_instance* h, int block)
{
if (h->emu_wait) {
UnregisterWaitEx((HANDLE)h->emu_wait, block ? INVALID_HANDLE_VALUE : NULL);
h->emu_wait = NULL;
}
if (h->emu_process) {
CloseHandle((HANDLE)h->emu_process);
h->emu_process = NULL;
}
}

/* With shm_lock held exclusively and no mapping: maps the region of the
* emulator now on the port, at most once a second. */
static void reattach(struct modavd_instance* h)
{
ULONGLONG now = GetTickCount64();
if (h->reattach_ms && now - h->reattach_ms < 1000) {
return;
}
h->reattach_ms = now;
/* The old wait has fired (that is what dropped the mapping) and its
* callback is done with the lock, so this does not need to block. */
unwatch_emulator(h, 0);
unsigned long pid = mx_console_owner_pid(h->console_port);
if (!pid) {
return;
}
mx_shm shm = { 0 };
if (mx_shm_open(h->console_port, &shm) != MODAVD_OK) {
return;
}
if (watch_emulator(h, pid) != MODAVD_OK) {
mx_log(MODAVD_LOG_WARN, "port=%d: cannot watch emulator process %lu", h->console_port, pid);
}
h->shm = shm;
const volatile mx_video_info* vi = (const volatile mx_video_info*)shm.view;
mx_log(MODAVD_LOG_INFO, "port=%d: mapped the shared memory of the new emulator, %ux%u size=%zu", h->console_port,
vi->width, vi->height, shm.size);
}
#endif

uint32_t modavd_api_version(void) { return MODAVD_API_VERSION; }

const char* modavd_version_string(void) { return MODAVD_EXTRAS_VERSION; }
Expand Down Expand Up @@ -132,6 +207,20 @@ int modavd_open(const modavd_open_params* params, modavd_handle* out)
return rc;
}

#ifdef _WIN32
/* The emulator whose region this is: the program on the console port. */
unsigned long pid = mx_console_owner_pid(port);
if (!pid && !(params->flags & MODAVD_OPEN_NO_START)) {
/* A region with no emulator behind it is left over from an emulator
* that exited while another program still held it. Holding it too
* would keep it alive for the next emulator on this port. */
mx_log(MODAVD_LOG_WARN, "port=%d: shared memory is there but no emulator listens on the console port",
port);
mx_shm_close(&shm);
return MODAVD_E_NOT_FOUND;
}
#endif

struct modavd_instance* inst = (struct modavd_instance*)calloc(1, sizeof(*inst));
struct mx_input* input = mx_input_create(port);
if (!inst || !input) {
Expand All @@ -147,6 +236,14 @@ int modavd_open(const modavd_open_params* params, modavd_handle* out)
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 : "-");
#ifdef _WIN32
InitializeSRWLock((PSRWLOCK)&inst->shm_lock);
/* NO_START with no console trusts the mapping as it is, unwatched. */
if (pid && watch_emulator(inst, pid) != MODAVD_OK) {
mx_log(MODAVD_LOG_WARN, "port=%d: cannot watch emulator process %lu; its shared memory stays mapped", port,
pid);
}
#endif
*out = inst;
return MODAVD_OK;
}
Expand All @@ -156,6 +253,10 @@ void modavd_close(modavd_handle h)
if (!h) {
return;
}
#ifdef _WIN32
/* Waits for a running emulator_exited() before the handle goes away. */
unwatch_emulator(h, 1);
#endif
/* Lifts the contacts this handle left down. */
mx_input_destroy(h->input);
mx_shm_close(&h->shm);
Expand Down Expand Up @@ -359,6 +460,33 @@ int mx_copy_frame(const mx_shm* shm, uint32_t format, uint32_t flags, int simd,
return MX_TORN;
}

int mx_capture_frame(struct modavd_instance* h, uint32_t format, uint32_t flags, void* buf, size_t buf_size,
modavd_frame_info* info)
{
#ifdef _WIN32
PSRWLOCK lock = (PSRWLOCK)&h->shm_lock;
AcquireSRWLockShared(lock);
if (!h->shm.view) {
ReleaseSRWLockShared(lock);
AcquireSRWLockExclusive(lock);
if (!h->shm.view) {
reattach(h);
}
ReleaseSRWLockExclusive(lock);
AcquireSRWLockShared(lock);
if (!h->shm.view) {
ReleaseSRWLockShared(lock);
return MODAVD_E_NOT_FOUND;
}
}
int rc = mx_copy_frame(&h->shm, format, flags, h->simd, buf, buf_size, info);
ReleaseSRWLockShared(lock);
return rc;
#else
return mx_copy_frame(&h->shm, format, flags, h->simd, buf, buf_size, info);
#endif
}

int modavd_capture(modavd_handle h, int display, uint32_t format, uint32_t flags, void* buf, size_t buf_size,
modavd_frame_info* info)
{
Expand All @@ -368,7 +496,7 @@ int modavd_capture(modavd_handle h, int display, uint32_t format, uint32_t flags
if (display != 0) {
return MODAVD_E_UNSUPPORTED;
}
int rc = mx_copy_frame(&h->shm, format, flags & ~MX_CAPTURE_UNPUBLISHED, h->simd, buf, buf_size, info);
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);
Expand Down
25 changes: 25 additions & 0 deletions src/mx_internal.h
Original file line number Diff line number Diff line change
Expand Up @@ -144,8 +144,33 @@ struct modavd_instance {
int simd; /* mx_cpu_simd() at open */
mx_shm shm;
struct mx_input* input;
#ifdef _WIN32
/* The emulator owns the name of the shared frame, but a mapping stays
* alive while anyone holds it. If this handle kept the old mapping after
* the emulator exited, the next emulator on the same port would get the
* old, possibly smaller region back and could not share frames (ModAVD#210).
* So the handle watches the emulator process (the one listening on the
* console port) and drops the mapping when it exits; the next capture maps
* the new emulator's region. shm_lock (an SRWLOCK) guards shm: shared
* while copying, exclusive while mapping or unmapping. */
void* shm_lock;
void* emu_process; /* HANDLE of the watched emulator, NULL when none */
void* emu_wait; /* its RegisterWaitForSingleObject wait, NULL when none */
uint64_t reattach_ms; /* GetTickCount64() of the last attempt to map again */
#endif
};

/* Copies one frame of the handle, as mx_copy_frame() does on its mapping.
* Windows: when the emulator exited the mapping is gone; this maps the region
* of the emulator now on the port (at most once a second) and otherwise
* returns MODAVD_E_NOT_FOUND. */
int mx_capture_frame(struct modavd_instance* h, uint32_t format, uint32_t flags, void* buf, size_t buf_size,
modavd_frame_info* info);

/* Windows: process id of the program listening on 127.0.0.1:port (or any
* address) over TCP, 0 when none. */
unsigned long mx_console_owner_pid(int port);

/* 1 when this CPU runs the vector row conversion (SSSE3 on x86, NEON on
* ARM64), else 0. */
int mx_cpu_simd(void);
Expand Down
35 changes: 35 additions & 0 deletions tests/fake_frame.h
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@

#ifdef _WIN32
#define WIN32_LEAN_AND_MEAN
#include <winsock2.h>
#include <windows.h>
#else
#include <fcntl.h>
Expand Down Expand Up @@ -110,4 +111,38 @@ static void fake_frame_destroy(fake_frame* f)
memset(f, 0, sizeof(*f));
}

#ifdef _WIN32
/* Listens on 127.0.0.1:port without ever answering, so the library sees an
* emulator (this process) on that console port. INVALID_SOCKET on failure. */
static SOCKET fake_listen(int port)
{
WSADATA wsa;
if (WSAStartup(MAKEWORD(2, 2), &wsa) != 0) {
return INVALID_SOCKET;
}
SOCKET s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
struct sockaddr_in a;
memset(&a, 0, sizeof(a));
a.sin_family = AF_INET;
a.sin_port = htons((u_short)port);
a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
if (s == INVALID_SOCKET || bind(s, (struct sockaddr*)&a, sizeof(a)) != 0 || listen(s, 4) != 0) {
if (s != INVALID_SOCKET) {
closesocket(s);
}
WSACleanup();
return INVALID_SOCKET;
}
return s;
}

static void fake_unlisten(SOCKET s)
{
if (s != INVALID_SOCKET) {
closesocket(s);
WSACleanup();
}
}
#endif

#endif /* FAKE_FRAME_H */
Loading
Loading