diff --git a/capture/uur-pw-capture.c b/capture/uur-pw-capture.c index 3fa3ad4..c8a4a49 100644 --- a/capture/uur-pw-capture.c +++ b/capture/uur-pw-capture.c @@ -16,6 +16,8 @@ #include #include #include +#include +#include #include #include #include @@ -23,14 +25,20 @@ #include #include #include +#include #include +#include #include #include #include +#include #include "../hook/frame-protocol.h" #define FRAME_FORMAT_BGRX 1 +#ifndef SPA_CHUNK_FLAG_EMPTY +#define SPA_CHUNK_FLAG_EMPTY (1u << 1) +#endif struct frame_header { uint32_t magic; @@ -63,16 +71,31 @@ struct capture { int shm_fd; uint8_t *shm; size_t shm_size; + int dmabuf_usable; + int exit_status; + volatile sig_atomic_t stopping; + int was_streaming; + uint64_t started_ms; + uint64_t paused_ms; char frame_path[PATH_MAX]; }; static struct capture *active_capture; +static uint64_t monotonic_ms(void) +{ + struct timespec now; + clock_gettime(CLOCK_MONOTONIC, &now); + return (uint64_t)now.tv_sec * 1000 + (uint64_t)now.tv_nsec / 1000000; +} + static void stop_capture(int signal_number) { (void)signal_number; - if (active_capture != NULL && active_capture->loop != NULL) + if (active_capture != NULL && active_capture->loop != NULL) { + active_capture->stopping = 1; pw_main_loop_quit(active_capture->loop); + } } static struct frame_slot *slot_at(struct capture *c, uint64_t n) @@ -88,8 +111,8 @@ static uint8_t *slot_frame(struct frame_slot *slot) return (uint8_t *)slot + sizeof(struct frame_slot); } -/* Create (or resize) the shared file for the negotiated geometry and write - * the header. Called once, from param_changed, before any frame exists. */ +/* Publish a new inode for every geometry. A Wine reader may still map the + * previous inode: never truncate or resize memory another process is reading. */ static int shm_setup(struct capture *c) { size_t slot_bytes = sizeof(struct frame_slot) + @@ -103,26 +126,30 @@ static int shm_setup(struct capture *c) return -1; } - c->shm_fd = open(c->frame_path, O_RDWR | O_CREAT | O_TRUNC | O_CLOEXEC, - 0600); - if (c->shm_fd < 0) { + char temporary[PATH_MAX]; + if (snprintf(temporary, sizeof(temporary), "%s.XXXXXX", c->frame_path) >= + (int)sizeof(temporary)) + return -1; + int fd = mkostemp(temporary, O_CLOEXEC); + if (fd < 0) { perror("open frame transport"); return -1; } - if (ftruncate(c->shm_fd, (off_t)total) < 0) { + if (fchmod(fd, 0600) < 0 || ftruncate(fd, (off_t)total) < 0) { perror("ftruncate"); + close(fd); + unlink(temporary); return -1; } - c->shm = mmap(NULL, total, PROT_READ | PROT_WRITE, MAP_SHARED, - c->shm_fd, 0); - if (c->shm == MAP_FAILED) { + uint8_t *mapping = mmap(NULL, total, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); + if (mapping == MAP_FAILED) { perror("mmap"); - c->shm = NULL; + close(fd); + unlink(temporary); return -1; } - c->shm_size = total; - struct frame_header *header = (struct frame_header *)c->shm; + struct frame_header *header = (struct frame_header *)mapping; header->magic = 0x46525555u; /* "UURF" */ header->version = UURF_VERSION; header->width = c->width; @@ -131,8 +158,29 @@ static int shm_setup(struct capture *c) header->format = FRAME_FORMAT_BGRX; atomic_init(&header->total_frames, 0); for (uint32_t i = 0; i < UURF_SLOT_COUNT; ++i) { - atomic_init(&slot_at(c, (uint64_t)i)->seq, 0); + struct frame_slot *slot = (struct frame_slot *)(mapping + + UURF_HEADER_BYTES + i * slot_bytes); + atomic_init(&slot->seq, 0); } + if (rename(temporary, c->frame_path) < 0) { + perror("publish frame transport"); + munmap(mapping, total); + close(fd); + unlink(temporary); + return -1; + } + if (c->shm != NULL) { + struct frame_header *previous = (struct frame_header *)c->shm; + atomic_store_explicit(&previous->total_frames, 0, memory_order_release); + munmap(c->shm, c->shm_size); + } + if (c->shm_fd >= 0) + close(c->shm_fd); + c->shm = mapping; + c->shm_fd = fd; + c->shm_size = total; + c->counter = 0; + c->started_ms = monotonic_ms(); return 0; } @@ -180,6 +228,16 @@ static void publish_frame(struct capture *c, const uint8_t *pixels, memory_order_release); } +static int sync_dmabuf(int fd, uint64_t flags) +{ + struct dma_buf_sync sync = {.flags = flags}; + int result; + do { + result = ioctl(fd, DMA_BUF_IOCTL_SYNC, &sync); + } while (result < 0 && errno == EINTR); + return result; +} + static void on_process(void *userdata) { struct capture *c = userdata; @@ -193,38 +251,67 @@ static void on_process(void *userdata) uint8_t *pixels = NULL; void *mapping = MAP_FAILED; size_t mapping_size = 0; + int synchronized = 0; + int dmabuf = plane->type == SPA_DATA_DmaBuf; - if (plane->chunk == NULL) { - pw_stream_queue_buffer(c->stream, buffer); - return; + if (plane->chunk == NULL || plane->chunk->stride < 0 || + (plane->chunk->flags & (SPA_CHUNK_FLAG_CORRUPTED | SPA_CHUNK_FLAG_EMPTY))) + goto done; + uint32_t row_bytes = c->width * + (c->format == SPA_VIDEO_FORMAT_BGR || c->format == SPA_VIDEO_FORMAT_RGB ? 3u : 4u); + uint32_t stride = plane->chunk->stride > 0 ? + (uint32_t)plane->chunk->stride : row_bytes; + uint64_t span = (uint64_t)stride * (c->height - 1) + row_bytes; + uint32_t data_offset = plane->chunk->offset; + if (stride < row_bytes || span > 256u * 1024 * 1024) + goto done; + if (dmabuf) { + // DMA-BUF maxsize/chunk size may be zero or placeholders. Query + // the fd and include BOTH the plane mapping and chunk offsets. + if (!c->dmabuf_usable || plane->fd < 0) + goto done; + off_t extent = lseek((int)plane->fd, 0, SEEK_END); + uint64_t end = (uint64_t)plane->mapoffset + data_offset + span; + if (extent < 0 || end > (uint64_t)extent) + goto done; + struct pollfd ready = {.fd = (int)plane->fd, .events = POLLIN}; + if (poll(&ready, 1, 100) <= 0 || !(ready.revents & POLLIN) || + sync_dmabuf((int)plane->fd, DMA_BUF_SYNC_START | DMA_BUF_SYNC_READ) < 0) + goto done; + synchronized = 1; + } else { + if (plane->maxsize == 0) + goto done; + data_offset %= plane->maxsize; + if ((uint64_t)data_offset + span > plane->maxsize || + span > plane->chunk->size) + goto done; } if (plane->data != NULL) { - pixels = plane->data + plane->chunk->offset; - } else if (plane->type == SPA_DATA_MemFd && plane->fd >= 0) { + pixels = (uint8_t *)plane->data + data_offset; + } else if ((dmabuf || plane->type == SPA_DATA_MemFd) && plane->fd >= 0) { long page_size = sysconf(_SC_PAGESIZE); - uint64_t offset = (uint64_t)plane->mapoffset + plane->chunk->offset; + uint64_t offset = (uint64_t)plane->mapoffset + data_offset; uint64_t page_mask = (uint64_t)(page_size > 0 ? page_size : 4096) - 1; off_t aligned = (off_t)(offset & ~page_mask); size_t delta = (size_t)(offset - (uint64_t)aligned); - mapping_size = delta + plane->chunk->size; - mapping = mmap(NULL, mapping_size, PROT_READ, MAP_PRIVATE, + mapping_size = delta + (size_t)span; + mapping = mmap(NULL, mapping_size, PROT_READ, MAP_SHARED, plane->fd, aligned); if (mapping != MAP_FAILED) pixels = (uint8_t *)mapping + delta; } if (pixels != NULL) { - int32_t signed_stride = plane->chunk->stride; - uint32_t stride = signed_stride > 0 - ? (uint32_t)signed_stride - : (c->format == SPA_VIDEO_FORMAT_BGR || - c->format == SPA_VIDEO_FORMAT_RGB - ? c->width * 3 - : c->width * 4); - uint32_t rows = stride > 0 ? plane->chunk->size / stride : 0; - publish_frame(c, pixels, stride, rows); - if (mapping != MAP_FAILED) - munmap(mapping, mapping_size); + if (c->counter == 0) + fprintf(stderr, "capture buffer: %s, source stride %u, chunk offset %u\n", + dmabuf ? "linear DMA-BUF" : "shared memory", stride, data_offset); + publish_frame(c, pixels, stride, c->height); } +done: + if (synchronized) + (void)sync_dmabuf((int)plane->fd, DMA_BUF_SYNC_END | DMA_BUF_SYNC_READ); + if (mapping != MAP_FAILED) + munmap(mapping, mapping_size); } pw_stream_queue_buffer(c->stream, buffer); @@ -237,7 +324,7 @@ static void on_param_changed(void *userdata, uint32_t id, if (param == NULL || id != SPA_PARAM_Format) return; - struct spa_video_info_raw info; + struct spa_video_info_raw info = {0}; if (spa_format_video_raw_parse(param, &info) < 0) return; if (info.format != SPA_VIDEO_FORMAT_BGRx && @@ -250,29 +337,92 @@ static void on_param_changed(void *userdata, uint32_t id, return; } + if (info.size.width == 0 || info.size.height == 0 || + info.size.width > 16384 || info.size.height > 16384 || + (uint64_t)info.size.width * 4 * info.size.height > 256u * 1024 * 1024) { + fprintf(stderr, "unsupported capture geometry\n"); + c->exit_status = 1; + pw_main_loop_quit(c->loop); + return; + } c->width = (uint32_t)info.size.width; c->height = (uint32_t)info.size.height; c->format = info.format; c->stride = SPA_ROUND_UP_N(c->width * 4, 4); - fprintf(stderr, "negotiated: %ux%u stride %u\n", c->width, c->height, - c->stride); + /* The DMA-BUF path mmaps the fd directly, which is only correct for a + * linear layout. A tiled modifier needs a real importer (GBM/EGL), so + * refuse to publish garbage rather than emit a corrupt frame. */ + c->dmabuf_usable = spa_pod_find_prop(param, NULL, SPA_FORMAT_VIDEO_modifier) != NULL && + info.modifier == DRM_FORMAT_MOD_LINEAR; + fprintf(stderr, "negotiated: %ux%u stride %u modifier %#llx%s\n", c->width, + c->height, c->stride, (unsigned long long)info.modifier, + c->dmabuf_usable ? "" : " (DMA-BUF CPU mapping disabled)"); - if (c->shm == NULL && shm_setup(c) < 0) { - pw_main_loop_quit(c->loop); + const struct frame_header *header = (const struct frame_header *)c->shm; + if (header == NULL || header->width != c->width || header->height != c->height) { + if (shm_setup(c) < 0) { + c->exit_status = 1; + pw_main_loop_quit(c->loop); + } } } static void on_state_changed(void *userdata, enum pw_stream_state old, enum pw_stream_state state, const char *error) { - (void)userdata; - (void)old; + struct capture *c = userdata; fprintf(stderr, "stream state: %s%s%s\n", pw_stream_state_as_string(state), error != NULL && error[0] != '\0' ? " - " : "", error != NULL ? error : ""); + if (c->stopping) + return; + if (state == PW_STREAM_STATE_STREAMING) { + c->was_streaming = 1; + c->paused_ms = 0; + } else if (state == PW_STREAM_STATE_PAUSED && c->was_streaming) { + if (c->paused_ms == 0) + c->paused_ms = monotonic_ms(); + } else if (state == PW_STREAM_STATE_ERROR || + (state == PW_STREAM_STATE_UNCONNECTED && old != state)) { + c->exit_status = 75; + pw_main_loop_quit(c->loop); + } } +static void on_watchdog(void *userdata, uint64_t expirations) +{ + struct capture *c = userdata; + (void)expirations; + uint64_t now = monotonic_ms(); + // A static desktop can legitimately produce no new frames while streaming. + // Only a prolonged PAUSED state or a stream with no FIRST frame is fatal. + if (!c->stopping && + ((c->paused_ms != 0 && now - c->paused_ms >= 10000) || + (c->counter == 0 && now - c->started_ms >= 30000))) { + fprintf(stderr, "capture stream stopped producing usable frames; reconnecting\n"); + c->exit_status = 75; + pw_main_loop_quit(c->loop); + } +} + +static void on_core_error(void *userdata, uint32_t id, int sequence, + int result, const char *message) +{ + struct capture *c = userdata; + (void)sequence; + if (!c->stopping && id == PW_ID_CORE && result < 0) { + fprintf(stderr, "PipeWire connection failed: %s\n", message); + c->exit_status = 75; + pw_main_loop_quit(c->loop); + } +} + +static const struct pw_core_events core_events = { + PW_VERSION_CORE_EVENTS, + .error = on_core_error, +}; + static const struct pw_stream_events stream_events = { .version = PW_VERSION_STREAM_EVENTS, .process = on_process, @@ -280,6 +430,27 @@ static const struct pw_stream_events stream_events = { .state_changed = on_state_changed, }; +static const struct spa_pod *capture_format(struct spa_pod_builder *builder, + int dmabuf) +{ + struct spa_pod_frame frame; + spa_pod_builder_push_object(builder, &frame, SPA_TYPE_OBJECT_Format, + SPA_PARAM_EnumFormat); + spa_pod_builder_add(builder, + SPA_FORMAT_mediaType, SPA_POD_Id(SPA_MEDIA_TYPE_video), + SPA_FORMAT_mediaSubtype, SPA_POD_Id(SPA_MEDIA_SUBTYPE_raw), + SPA_FORMAT_VIDEO_format, + SPA_POD_CHOICE_ENUM_Id(6, SPA_VIDEO_FORMAT_BGRx, SPA_VIDEO_FORMAT_BGRA, + SPA_VIDEO_FORMAT_RGBx, SPA_VIDEO_FORMAT_RGBA, + SPA_VIDEO_FORMAT_BGR, SPA_VIDEO_FORMAT_RGB), 0); + if (dmabuf) { + spa_pod_builder_prop(builder, SPA_FORMAT_VIDEO_modifier, + SPA_POD_PROP_FLAG_MANDATORY); + spa_pod_builder_long(builder, DRM_FORMAT_MOD_LINEAR); + } + return spa_pod_builder_pop(builder, &frame); +} + int main(void) { const char *fd_text = getenv("UUR_PW_FD"); @@ -330,6 +501,8 @@ int main(void) fprintf(stderr, "pw_context_connect_fd failed\n"); return 1; } + struct spa_hook core_listener; + pw_core_add_listener(core, &core_listener, &core_events, &c); struct pw_properties *props = pw_properties_new( PW_KEY_MEDIA_TYPE, "Video", PW_KEY_MEDIA_CATEGORY, "Capture", @@ -344,39 +517,45 @@ int main(void) uint8_t pod_buffer[1024]; struct spa_pod_builder pod_builder = SPA_POD_BUILDER_INIT(pod_buffer, sizeof(pod_buffer)); - const struct spa_pod *params[1]; - params[0] = spa_pod_builder_add_object( - &pod_builder, SPA_TYPE_OBJECT_Format, SPA_PARAM_EnumFormat, - SPA_FORMAT_mediaType, SPA_POD_Id(SPA_MEDIA_TYPE_video), - SPA_FORMAT_mediaSubtype, SPA_POD_Id(SPA_MEDIA_SUBTYPE_raw), - SPA_FORMAT_VIDEO_format, - SPA_POD_CHOICE_ENUM_Id(6, SPA_VIDEO_FORMAT_BGRx, - SPA_VIDEO_FORMAT_BGRA, - SPA_VIDEO_FORMAT_RGBx, - SPA_VIDEO_FORMAT_RGBA, - SPA_VIDEO_FORMAT_BGR, - SPA_VIDEO_FORMAT_RGB)); + const struct spa_pod *params[2]; + params[0] = capture_format(&pod_builder, 1); + params[1] = capture_format(&pod_builder, 0); + c.started_ms = monotonic_ms(); if (pw_stream_connect(c.stream, PW_DIRECTION_INPUT, node_id, PW_STREAM_FLAG_MAP_BUFFERS | - PW_STREAM_FLAG_AUTOCONNECT | - PW_STREAM_FLAG_RT_PROCESS, - params, 1) < 0) { + PW_STREAM_FLAG_AUTOCONNECT, + params, 2) < 0) { fprintf(stderr, "pw_stream_connect failed\n"); return 1; } + struct spa_source *watchdog = pw_loop_add_timer(pw_main_loop_get_loop(loop), + on_watchdog, &c); + struct timespec interval = {.tv_sec = 1}; + if (watchdog == NULL || pw_loop_update_timer(pw_main_loop_get_loop(loop), + watchdog, &interval, &interval, false) < 0) { + fprintf(stderr, "could not start capture watchdog\n"); + return 1; + } pw_main_loop_run(loop); + c.stopping = 1; active_capture = NULL; + pw_loop_destroy_source(pw_main_loop_get_loop(loop), watchdog); pw_stream_destroy(c.stream); + spa_hook_remove(&core_listener); + pw_core_disconnect(core); pw_context_destroy(context); pw_main_loop_destroy(loop); - if (c.shm != NULL) + if (c.shm != NULL) { + struct frame_header *header = (struct frame_header *)c.shm; + atomic_store_explicit(&header->total_frames, 0, memory_order_release); munmap(c.shm, c.shm_size); + } if (c.shm_fd >= 0) close(c.shm_fd); unlink(c.frame_path); pw_deinit(); - return 0; + return c.exit_status; } diff --git a/docs/capture-protocol.md b/docs/capture-protocol.md index 11e9589..3c98162 100644 --- a/docs/capture-protocol.md +++ b/docs/capture-protocol.md @@ -47,3 +47,38 @@ mutexes; a torn read is detected, never observed. The transport path is created per user and passed to the Wine adapter through the managed prefix configuration. It is never a global shared-memory name. + +## Geometry and session changes + +Each transport inode has immutable geometry. A negotiated size change creates +a new mode-0600 file, initializes its header and slots, then atomically replaces +the transport path. The previous mapping remains valid for existing readers; +the producer never truncates it. The Wine adapter checks file identity at least +every 250 ms and remaps replacements while serializing its capture readers. + +The PipeWire consumer accepts explicitly linear DMA-BUFs and retains a separate +shared-memory format offer. DMA-BUF reads use the source stride, plane offsets, +fd extent, readiness fence and CPU-access synchronization. Implicit modifiers +require a graphics importer and are not advertised by this CPU consumer. + +A stream error, lost connection or ten seconds in PAUSED after streaming makes +the helper exit with status 75. The ScreenCast supervisor retries up to three +times using the saved restore token, with a one-second backoff. Thirty seconds +of healthy capture resets the retry budget. An unchanged desktop in STREAMING +does not trigger this watchdog. Recovery keeps the saved token and performs no +token-less fallback or switch to direct capture. The portal controls whether +restoring that choice requires confirmation. A portal Session.Closed signal +without a matching Mutter layout change ends sharing; the user starts a new +session explicitly. The supervisor subscribes to the raw signal on the session's +own connection, accepting both dictionary and empty signal bodies. + +When Mutter's DisplayConfig service is already present, the supervisor also +subscribes to MonitorsChanged and proactively restores capture after a layout +change. It coalesces signals during the reconnect delay. Mutter may close the +old session before forwarding MonitorsChanged, so a Closed signal has a 250 ms +window to correlate that transaction. Closed without a matching change stops +capture, and process stop requests always take priority. This optional listener +never starts a GNOME service on other desktops. +Successful layout-driven restarts do not consume the failure retry budget. +Only the initial session can make a token-less interactive selection; later +restores keep that boundary even when the failure counter has been reset. diff --git a/hook/uur-hook.c b/hook/uur-hook.c index 5f90e05..b2d26d2 100644 --- a/hook/uur-hook.c +++ b/hook/uur-hook.c @@ -17,6 +17,10 @@ */ #define WIN32_LEAN_AND_MEAN +#ifndef _WIN32_WINNT +#define _WIN32_WINNT 0x0601 +#endif + #include #include #include @@ -234,6 +238,9 @@ static uint64_t frame_slot_bytes; static unsigned char *frame_snapshot; static size_t frame_snapshot_capacity; static size_t frame_map_size; +static BY_HANDLE_FILE_INFORMATION frame_identity; +static ULONGLONG frame_checked_at; +static SRWLOCK frame_lock = SRWLOCK_INIT; static char *read_ini_value(const char *path, const char *key); @@ -264,39 +271,70 @@ static uint64_t load_u64(const unsigned char *p) return load_u32(p) | ((uint64_t)load_u32(p + 4) << 32); } -/* Open (or re-open after a resolution change) the capture file that the - * native uur-pw-capture helper publishes. */ +static void clear_frame_map(void) +{ + if (frame_map != NULL) + UnmapViewOfFile(frame_map); + if (frame_map_handle != NULL) + CloseHandle(frame_map_handle); + frame_map = NULL; + frame_map_handle = NULL; + frame_map_size = 0; +} + +/* Producers publish immutable geometry via atomic replacement. Re-check the + * file identity periodically, including after an ungraceful helper restart. */ static int ensure_frame_map(void) { HANDLE file; void *view; const unsigned char *header; LARGE_INTEGER size; + BY_HANDLE_FILE_INFORMATION identity; WCHAR path[32768]; + ULONGLONG now = GetTickCount64(); - if (frame_map != NULL) + if (frame_map != NULL && now - frame_checked_at < 250 && + load_u64((const unsigned char *)frame_map + 24) != 0) return 1; if (!resolve_frame_path(path, (int)(sizeof(path) / sizeof(path[0])))) return 0; file = CreateFileW(path, GENERIC_READ, - FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, + FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL, OPEN_EXISTING, 0, NULL); - if (file == INVALID_HANDLE_VALUE) - return 0; - if (!GetFileSizeEx(file, &size) || size.QuadPart < UURF_HEADER_BYTES || - (uint64_t)size.QuadPart > SIZE_MAX) { - CloseHandle(file); + if (file == INVALID_HANDLE_VALUE) { + clear_frame_map(); return 0; } + if (!GetFileInformationByHandle(file, &identity) || + !GetFileSizeEx(file, &size) || size.QuadPart < UURF_HEADER_BYTES || + (uint64_t)size.QuadPart > UURF_HEADER_BYTES + + UURF_SLOT_COUNT * (8ull + 256ull * 1024 * 1024)) { + CloseHandle(file); + clear_frame_map(); + return 0; + } + frame_checked_at = now; + if (frame_map != NULL && + identity.dwVolumeSerialNumber == frame_identity.dwVolumeSerialNumber && + identity.nFileIndexHigh == frame_identity.nFileIndexHigh && + identity.nFileIndexLow == frame_identity.nFileIndexLow && + (uint64_t)size.QuadPart == frame_map_size) { + CloseHandle(file); + return 1; + } + clear_frame_map(); frame_map_handle = CreateFileMappingW(file, NULL, PAGE_READONLY, 0, 0, NULL); CloseHandle(file); if (frame_map_handle == NULL) return 0; view = MapViewOfFile(frame_map_handle, FILE_MAP_READ, 0, 0, 0); - if (view == NULL) + if (view == NULL) { + clear_frame_map(); return 0; + } header = (const unsigned char *)view; if (load_u32(header) != UURF_MAGIC || @@ -311,7 +349,10 @@ static int ensure_frame_map(void) frame_stride = load_u32(header + 16); frame_slot_bytes = 8ull + (uint64_t)frame_stride * frame_height; uint64_t expected = UURF_HEADER_BYTES + UURF_SLOT_COUNT * frame_slot_bytes; - if (frame_width == 0 || frame_height == 0 || frame_stride < frame_width * 4 || + if (frame_width == 0 || frame_height == 0 || + frame_width > 16384 || frame_height > 16384 || + frame_stride != frame_width * 4 || + (uint64_t)frame_stride * frame_height > 256ull * 1024 * 1024 || expected > (uint64_t)size.QuadPart) { UnmapViewOfFile(view); CloseHandle(frame_map_handle); @@ -320,6 +361,7 @@ static int ensure_frame_map(void) } frame_map_size = (size_t)size.QuadPart; frame_map = view; + frame_identity = identity; return 1; } @@ -389,7 +431,7 @@ static void draw_cursor_overlay(HDC hdc_dest, int x, int y, int width, int heigh /* Feed the newest desktop frame into the capture destination by drawing * our shared-memory frame with StretchDIBits. Works regardless of the * destination bitmap type (DDB or DIB section). */ -static BOOL feed_capture_frame(HDC hdc_dest, int x, int y, int width, +static BOOL feed_capture_frame_locked(HDC hdc_dest, int x, int y, int width, int height, int source_x, int source_y, int source_width, int source_height) { @@ -407,7 +449,8 @@ static BOOL feed_capture_frame(HDC hdc_dest, int x, int y, int width, fstride = load_u32(header + 16); size_t frame_bytes = (size_t)fstride * fh; total = load_u64(header + 24); - if (fw == 0 || fh == 0 || fstride < fw * 4 || total == 0 || + if (fw != frame_width || fh != frame_height || fstride != frame_stride || + fw == 0 || fh == 0 || fstride < fw * 4 || total == 0 || frame_bytes / fstride != fh || UURF_HEADER_BYTES + UURF_SLOT_COUNT * frame_slot_bytes > frame_map_size) return FALSE; @@ -472,6 +515,17 @@ static BOOL feed_capture_frame(HDC hdc_dest, int x, int y, int width, return ok; } +static BOOL feed_capture_frame(HDC hdc_dest, int x, int y, int width, + int height, int source_x, int source_y, + int source_width, int source_height) +{ + AcquireSRWLockExclusive(&frame_lock); + BOOL result = feed_capture_frame_locked(hdc_dest, x, y, width, height, + source_x, source_y, source_width, source_height); + ReleaseSRWLockExclusive(&frame_lock); + return result; +} + static BOOL try_capture_feed(HDC hdc_dest, int x, int y, DWORD rop, HDC hdc_src, int width, int height, int source_x, int source_y, int source_width, int source_height) diff --git a/src/capture.rs b/src/capture.rs index 42f0489..38968ff 100644 --- a/src/capture.rs +++ b/src/capture.rs @@ -13,6 +13,7 @@ //! a headless remote host. use anyhow::{anyhow, Context, Result}; +use futures::{FutureExt, StreamExt}; use std::io::Read; use std::os::fd::AsRawFd; use std::os::fd::OwnedFd; @@ -20,9 +21,21 @@ use std::path::{Path, PathBuf}; use std::process::{Child, Command}; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::Arc; +use std::time::{Duration, Instant}; use crate::config::Config; +type PortalSession = + ashpd::desktop::Session<'static, ashpd::desktop::screencast::Screencast<'static>>; + +struct PortalCapture { + fd: OwnedFd, + node: u32, + restore_token: Option, + session: PortalSession, + closed: zbus::proxy::SignalStream<'static>, +} + /// Run the capture path until interrupted. pub fn run_standalone() -> Result<()> { // Public capture uses the same lifecycle lock as run/setup so stop and @@ -62,31 +75,170 @@ pub fn run() -> Result<()> { if config.capture_backend != "portal" { anyhow::bail!("unknown capture backend {:?}", config.capture_backend); } - let runtime = tokio::runtime::Runtime::new().context("creating capture runtime")?; + let runtime = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .context("creating capture runtime")?; // The portal's D-Bus connection runs on this runtime. Keep it running // throughout capture, including on capture-only compositors such as niri. runtime.block_on(async { - let (pw_fd, node) = tokio::select! { - result = portal_session(&mut config) => result?, - _ = wait_for_stop(&stopping) => return Ok(()), - }; - println!("{}", t!("capture.session_ready", node = node)); - let mut helper = CaptureHelper(spawn_helper(pw_fd, node)?); + let frames = frame_path()?; + let mut failures = 0; + let mut initial_session = true; + let mut display_changes = watch_display_changes().await; loop { + let opened = tokio::select! { + result = portal_session(&mut config, initial_session) => result, + _ = wait_for_stop(&stopping) => return Ok(()), + }; + let PortalCapture { + fd: pw_fd, + node, + session, + mut closed, + .. + } = match opened { + Ok(opened) => opened, + Err(error) if !initial_session && failures < 3 => { + failures += 1; + eprintln!("capture reconnect {failures}/3 failed: {error:#}"); + tokio::select! { + _ = tokio::time::sleep(Duration::from_secs(1)) => continue, + _ = wait_for_stop(&stopping) => return Ok(()), + } + } + Err(error) => return Err(error), + }; + initial_session = false; + println!("{}", t!("capture.session_ready", node = node)); + match std::fs::remove_file(&frames) { + Ok(()) => {} + Err(error) if error.kind() == std::io::ErrorKind::NotFound => {} + Err(error) => return Err(error).context("retiring the previous capture transport"), + } + let mut helper = CaptureHelper(spawn_helper(pw_fd, node)?); + let mut healthy_since = None; + let mut portal_closed = false; + let mut reconfigure = false; + let status = loop { + tokio::select! { + biased; + _ = wait_for_stop(&stopping) => break None, + _ = closed.next() => { + // Mutter can close the old stream before forwarding + // MonitorsChanged. Correlate that layout transaction; + // a user Stop without a display change stays closed. + reconfigure = tokio::time::timeout( + Duration::from_millis(250), + next_display_change(&mut display_changes), + ).await.is_ok(); + portal_closed = !reconfigure; + break None; + } + _ = next_display_change(&mut display_changes) => { + reconfigure = true; + break None; + } + _ = tokio::time::sleep(Duration::from_millis(50)) => { + if has_frame(&frames) && healthy_since.is_none() { + healthy_since = Some(Instant::now()); + } + if let Some(status) = helper.0.try_wait() + .context("waiting for capture helper")? { + break Some(status); + } + } + } + }; + drop(closed); + drop(helper); + let _ = tokio::time::timeout(Duration::from_secs(2), session.close()).await; if stopping.load(Ordering::Relaxed) { return Ok(()); } - if let Some(status) = helper.0.try_wait().context("waiting for capture helper")? { - if !status.success() { - anyhow::bail!("{}", t!("capture.helper_failed")); + // Closed without a matching layout change means Stop sharing. + // Never silently restore that permission or use direct capture. + if portal_closed { + anyhow::bail!( + "screen sharing was closed by the portal; restart uur run to share again" + ); + } + if healthy_since.is_some_and(|since| since.elapsed() >= Duration::from_secs(30)) { + failures = 0; + } + if reconfigure { + eprintln!("display configuration changed; restoring capture"); + } else { + failures += 1; + if failures > 3 { + anyhow::bail!( + "capture recovery failed repeatedly; restart uur run to share again" + ); } - return Ok(()); + let status = status.context("capture helper stopped without an exit status")?; + if !matches!(status.code(), Some(0 | 75) | None) { + anyhow::bail!( + "{} ({status}); capture recovery stopped", + t!("capture.helper_failed") + ); + } + eprintln!("capture stream interrupted ({status}); reconnecting {failures}/3"); + } + tokio::select! { + _ = tokio::time::sleep(Duration::from_secs(1)) => {}, + _ = wait_for_stop(&stopping) => return Ok(()), + } + // Several signals can describe one layout transaction. The next + // handshake reads the final layout rather than replaying each one. + if reconfigure { + while let Some(stream) = display_changes.as_mut() { + match stream.next().now_or_never() { + Some(Some(_)) => {} + Some(None) => { + display_changes = None; + break; + } + None => break, + } + } } - tokio::time::sleep(std::time::Duration::from_millis(50)).await; } }) } +async fn watch_display_changes() -> Option> { + let connection = zbus::Connection::session().await.ok()?; + let bus = zbus::fdo::DBusProxy::new(&connection).await.ok()?; + let name = "org.gnome.Mutter.DisplayConfig".try_into().ok()?; + if !bus.name_has_owner(name).await.ok()? { + return None; + } + drop(bus); + let proxy = zbus::Proxy::new_owned( + connection, + "org.gnome.Mutter.DisplayConfig", + "/org/gnome/Mutter/DisplayConfig", + "org.gnome.Mutter.DisplayConfig", + ) + .await + .ok()?; + proxy.receive_signal("MonitorsChanged").await.ok() +} + +async fn next_display_change(changes: &mut Option>) { + loop { + match changes.as_mut() { + Some(stream) => { + if stream.next().await.is_some() { + return; + } + *changes = None; + } + None => std::future::pending::<()>().await, + } + } +} + async fn wait_for_stop(stopping: &AtomicBool) { while !stopping.load(Ordering::Relaxed) { tokio::time::sleep(std::time::Duration::from_millis(50)).await; @@ -175,8 +327,7 @@ fn frame_path() -> Result { /// First attempt reuses the stored restore token; if that fails (stale /// token, monitor changed, compositor restart) fall back to one /// interactive attempt and store the fresh token. -#[allow(clippy::type_complexity)] -async fn portal_session(config: &mut Config) -> Result<(OwnedFd, u32)> { +async fn portal_session(config: &mut Config, interactive: bool) -> Result { let saved_token = config.capture_restore_token.clone(); let screencast = ashpd::desktop::screencast::Screencast::new() .await @@ -188,22 +339,24 @@ async fn portal_session(config: &mut Config) -> Result<(OwnedFd, u32)> { .clone() .map(Some) .into_iter() - .chain(std::iter::once(None)) + .chain(interactive.then_some(None)) { match negotiate(&screencast, source, token.as_deref()).await { - Ok((fd, node, fresh_token)) => { - if fresh_token != saved_token { - config.capture_restore_token = fresh_token; + Ok(capture) => { + if capture.restore_token != saved_token { + config.capture_restore_token = capture.restore_token.clone(); config.store().context("storing the new restore token")?; } - return Ok((fd, node)); + return Ok(capture); } Err(error) => { last_error = Some(error); } } } - Err(last_error.unwrap_or_else(|| anyhow!("portal session failed"))) + Err(last_error.unwrap_or_else(|| { + anyhow!("capture permission could not be restored; restart uur run to share again") + })) } /// Choose a cursor mode from the flags the portal advertises. @@ -257,13 +410,29 @@ pub(crate) async fn preferred_cursor_mode( /// One full portal handshake. Returns the PipeWire fd, the video node id /// and the restore token the portal issued for this selection. async fn negotiate( - screencast: &ashpd::desktop::screencast::Screencast<'_>, + screencast: &ashpd::desktop::screencast::Screencast<'static>, source: ashpd::desktop::screencast::SourceType, restore_token: Option<&str>, -) -> Result<(OwnedFd, u32, Option)> { +) -> Result { use ashpd::desktop::PersistMode; let session = screencast.create_session().await?; + // Session.Closed carries a{sv}. ashpd 0.10 deserializes it as (), which + // silently drops the signal. Subscribe on the SAME connection (the + // frontend unicasts it) before starting, and ignore its optional details. + let serialized = serde_json::to_value(&session)?; + let path = serialized + .as_str() + .context("invalid portal session path")? + .to_owned(); + let session_proxy = zbus::Proxy::new_owned( + screencast.connection().clone(), + "org.freedesktop.portal.Desktop", + path, + "org.freedesktop.portal.Session", + ) + .await?; + let closed = session_proxy.receive_signal("Closed").await?; let cursor_mode = preferred_cursor_mode(screencast).await?; screencast @@ -289,7 +458,13 @@ async fn negotiate( .open_pipe_wire_remote(&session) .await .context("opening the PipeWire remote")?; - Ok((fd, node, fresh_token)) + Ok(PortalCapture { + fd, + node, + restore_token: fresh_token, + session, + closed, + }) } pub(crate) fn source_type(value: &str) -> ashpd::desktop::screencast::SourceType { @@ -310,13 +485,7 @@ pub fn list_wayland_outputs() -> Result<()> { } fn find_helper(name: &str) -> Result { - let mut candidates = vec![ - PathBuf::from("/usr/lib/uur").join(name), - PathBuf::from("/usr/local/lib/uur").join(name), - ]; - if let Ok(home) = std::env::var("HOME") { - candidates.push(PathBuf::from(home).join(".local/lib/uur").join(name)); - } + let mut candidates = Vec::new(); if let Ok(exe) = std::env::current_exe() { // dev checkout: target/debug/uur -> capture/uur-pw-capture if let Some(dir) = exe.parent() { @@ -325,6 +494,11 @@ fn find_helper(name: &str) -> Result { candidates.push(dir.join(name)); } } + candidates.push(PathBuf::from("/usr/lib/uur").join(name)); + candidates.push(PathBuf::from("/usr/local/lib/uur").join(name)); + if let Ok(home) = std::env::var("HOME") { + candidates.push(PathBuf::from(home).join(".local/lib/uur").join(name)); + } if let Ok(cwd) = std::env::current_dir() { candidates.push(cwd.join("capture").join(name)); } diff --git a/src/session.rs b/src/session.rs index 1f5d65b..da172ed 100644 --- a/src/session.rs +++ b/src/session.rs @@ -45,13 +45,7 @@ fn complete_hook_directory(dir: &Path) -> bool { } fn hook_dir() -> Result { - let mut candidates = vec![ - PathBuf::from("/usr/lib/uur/hook"), - PathBuf::from("/usr/local/lib/uur/hook"), - ]; - if let Ok(home) = std::env::var("HOME") { - candidates.push(PathBuf::from(home).join(".local/lib/uur/hook")); - } + let mut candidates = Vec::new(); if let Ok(exe) = std::env::current_exe() { if let Some(dir) = exe.parent() { candidates.push(dir.join("../lib/uur/hook")); @@ -59,6 +53,14 @@ fn hook_dir() -> Result { candidates.push(dir.to_path_buf()); } } + candidates.push(PathBuf::from("/usr/lib/uur/hook")); + candidates.push(PathBuf::from("/usr/local/lib/uur/hook")); + if let Ok(home) = std::env::var("HOME") { + candidates.push(PathBuf::from(home).join(".local/lib/uur/hook")); + } + if let Ok(directory) = std::env::current_dir() { + candidates.push(directory.join("build/hook")); + } candidates .into_iter() .find(|dir| complete_hook_directory(dir)) @@ -66,32 +68,7 @@ fn hook_dir() -> Result { } fn hook_source_dir() -> Result { - let mut candidates = vec![PathBuf::from("/usr/lib/uur/hook")]; - if let Ok(home) = std::env::var("HOME") { - candidates.push(PathBuf::from(home).join(".local/lib/uur/hook")); - } - candidates.push( - std::env::current_exe() - .ok() - .and_then(|exe| exe.parent().map(|d| d.join("../lib/uur/hook"))) - .unwrap_or_default(), - ); - candidates.push( - std::env::current_exe() - .ok() - .and_then(|exe| exe.parent().map(|d| d.join("../../build/hook"))) - .unwrap_or_default(), - ); - candidates.push( - std::env::current_dir() - .ok() - .map(|dir| dir.join("build/hook")) - .unwrap_or_default(), - ); - candidates - .into_iter() - .find(|dir| complete_hook_directory(dir)) - .context("hook DLLs not found (run the build first)") + hook_dir() } static DEPLOY_TEMP_SEQUENCE: AtomicU64 = AtomicU64::new(0);