CPU, round two: cheaper client captures, content-only redraws, damage-limited KMS and nested output
CI / test (push) Failing after 19s

Measured on the MoonBit host, 1080p, cloud container (two runs each, before -> after):
- full-screen (tiled) client redrawing at 60 fps: 43/39% -> 31/35%
- 800x600 floating client at 60 fps: 15.5/13.2% -> 10.4/11.9%
- client inside the nested window: nested 18% -> 12%, outer 17% -> 11.6%
- Alt+Tab open over two animating clients: 36.6% -> 25.4%
- idle (headless / nested): 0.2-0.6% -> 0.1-0.3%

wasmhost raster:
- capture keeps client pools mapped (keyed by dev/inode/size, dropped after 1 s unused) and
  reuses released surface buffers, swizzling a word at a time: 3.2 -> 2.1 ms per 1080p commit.
- a window whose only change is a new buffer damages just its client area, and the topmost
  opaque buffer that covers the damage is drawn first (no backdrop copy, desktop card, lower
  windows or its own decoration under it): submit 3.2 -> 0.8 ms per full-screen frame.
- the framebuffer tracks what changed since each output took it. The nested window's frames
  are a ring of three mapped memfds, each updated only where the screen changed, instead of
  a new memfd with a full 8 MB conversion and write every frame.
- KMS: present copies only the rows the back buffer is missing (this frame's change and the
  last one's), and kms_stub.c is compiled with -O2 (its stub-cc-flags dropped moon's default,
  so the per-frame copy ran unoptimised).
- images re-filled under the same handle (Alt+Tab previews) damage where the panel draws them:
  before, a live preview only repainted where it overlapped the window that redrew.

compositor:
- Alt+Tab previews of a window that keeps redrawing are remade at most every 100 ms (scaling a
  1080p buffer takes ~2 ms); the loop keeps its pace while one is pending.
- set-tokens is sent to the host only when the theme changes (it was 9 calls a frame).
- /proc is sampled only when a module imports `system`; a machine without a battery looks for
  one every 30 s instead of probing eight sysfs paths every second.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DPL5hkh3qygSXtftCTVhSZ
This commit is contained in:
Claude committed 2026-11-25 21:16:41 +00:00
1 parent 99c6c66726
commit 442f9477b4
11 files changed
+455 -61

No files matched your search

+92 -5
View File
@@ -153,6 +153,31 @@ extern "C" fn rs_thumbnail(id : UInt, w : Int, h : Int, reuse : Int) -> Int = "r
///|
extern "C" fn rs_blit_surface(id : UInt, x : Int, y : Int, w : Int, h : Int) -> Int = "rs_blit_surface"
///|
extern "C" fn rs_surface_covers(id : UInt, w : Int, h : Int) -> Int = "rs_surface_covers"
///|
extern "C" fn rs_maps_gc() = "rs_maps_gc"
///|
extern "C" fn rs_image_take_changed(handle : Int) -> Int = "rs_image_take_changed"
///| Where the panel layer draws an image whose pixels changed under the same handle (the
/// Alt+Tab switcher's live previews): the ops alone compare equal, so this is damage too.
fn changed_images(panel : @wt.Val) -> R {
let mut d : R = { x: 0, y: 0, w: 0, h: 0 }
for op in panel.to_list() {
if op is Variant("draw-image", Some(p)) &&
rs_image_take_changed(p.field("image").to_int()) != 0 {
d = union(d, rect_of(p.field("area")))
}
}
d
}
///|
extern "C" fn rs_damage(x : Int, y : Int, w : Int, h : Int) = "rs_damage"
///|
extern "C" fn rs_save_backdrop() = "rs_save_backdrop"
@@ -524,6 +549,43 @@ fn window_footprint(win : @wt.Val) -> R {
}
}
///| True when window `b` is window `a` with only a new client buffer (a client redrawing): same
/// place, size and decoration.
fn only_contents_changed(a : @wt.Val, b : @wt.Val) -> Bool {
a.field("geometry") == b.field("geometry") &&
a.field("fullscreen") == b.field("fullscreen") &&
a.field("inset-top") == b.field("inset-top") &&
a.field("inset-right") == b.field("inset-right") &&
a.field("inset-bottom") == b.field("inset-bottom") &&
a.field("inset-left") == b.field("inset-left") &&
a.field("deco") == b.field("deco")
}
///| True when `inner` lies inside `outer`.
fn contains(outer : R, inner : R) -> Bool {
inner.x >= outer.x &&
inner.y >= outer.y &&
inner.x + inner.w <= outer.x + outer.w &&
inner.y + inner.h <= outer.y + outer.h
}
///| The index of the topmost window whose opaque client buffer covers all of `area`: nothing
/// under it (backdrop, desktop card, lower windows, its own decoration) shows there, so none of
/// that is drawn. -1 when no window covers it.
fn occluder(windows : Array[@wt.Val], area : R) -> Int {
let mut i = windows.length() - 1
while i >= 0 {
let win = windows[i]
let g = rect_of(win.field("geometry"))
if contains(g, area) &&
rs_surface_covers(win.field("surface").to_uint(), g.w, g.h) != 0 {
return i
}
i = i - 1
}
-1
}
///| The part of the screen `f` changes over `prev`, as one rectangle; None when all of it must
/// be redrawn. Only window changes are narrowed down: any change to the wallpaper, desktop card,
/// panel or the set of windows redraws everything.
@@ -545,8 +607,14 @@ fn damage(prev : Frame, f : Frame) -> R? {
if a == b {
continue
}
if only_contents_changed(a, b) {
// A new buffer in the same place: only the client area is drawn again.
d = union(d, rect_of(b.field("geometry")))
continue
}
d = union(d, union(window_footprint(a), window_footprint(b)))
}
d = union(d, changed_images(f.panel))
if prev.popups != f.popups {
for p in prev.popups.to_list() {
d = union(d, rect_of(p.field("area")))
@@ -623,9 +691,25 @@ fn submit(v : @wt.Val) -> Unit {
Some(k) => k.w * k.h
None => w * h
}
rs_maps_gc()
match clip {
Some(k) => rs_damage(k.x, k.y, k.w, k.h)
None => rs_damage(0, 0, w, h)
}
// A full-screen (or tiled) client redrawing covers the whole damaged area with its own opaque
// pixels: start from that window instead of from the backdrop.
// (Only with the backdrop cached: a new wallpaper must still be drawn once to be kept.)
let top = if backdrop_ready {
occluder(f.windows, clip.unwrap_or({ x: 0, y: 0, w, h }))
} else {
-1
}
let occluded = top >= 0
let first = if occluded { top } else { 0 }
// 1. Wallpaper: drawn once, copied back while unchanged (only the damaged part).
match f.wallpaper {
Some(_) if occluded => ()
Some(ops) =>
if backdrop_ready {
set_clip(clip)
@@ -636,15 +720,18 @@ fn submit(v : @wt.Val) -> Unit {
backdrop_ops.val = Some(ops)
}
None =>
if rs_has_backdrop() != 0 {
if rs_has_backdrop() != 0 && !occluded {
set_clip(clip)
rs_copy_backdrop()
}
}
draw_ops(f.background.to_list(), 0, 0, clip)
if !occluded {
draw_ops(f.background.to_list(), 0, 0, clip)
}
// 2. Windows, bottom to top.
for win in f.windows {
// 2. Windows, bottom to top (from the one covering the damage, when one does).
for wi = first; wi < f.windows.length(); wi = wi + 1 {
let win = f.windows[wi]
let g = rect_of(win.field("geometry"))
if clip is Some(_) {
match intersect(Some(window_footprint(win)), clip) {
@@ -652,7 +739,7 @@ fn submit(v : @wt.Val) -> Unit {
_ => continue
}
}
if !win.field("fullscreen").to_bool() {
if !win.field("fullscreen").to_bool() && !(occluded && wi == first) {
let it = win.field("inset-top").to_int()
let ir = win.field("inset-right").to_int()
let ib = win.field("inset-bottom").to_int()
+212 -34
View File
@@ -18,6 +18,7 @@
#include <sys/mman.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <time.h>
#include <unistd.h>
#include "moonbit.h"
@@ -310,6 +311,7 @@ typedef struct {
uint8_t *rgba; /* pixels, or NULL for an SVG */
NSVGimage *svg;
Sized *sized; /* the image at the sizes it was drawn at */
int changed; /* new pixels under an old handle since the last frame (a preview) */
} Image;
static Image *images;
@@ -369,6 +371,7 @@ int32_t rs_image_put(int32_t reuse, int32_t w, int32_t h, moonbit_bytes_t rgba)
int32_t id = image_slot(reuse);
Image *im = &images[id - 1];
im->w = w; im->h = h;
im->changed = id == reuse;
im->rgba = malloc((size_t)w * h * 4);
memcpy(im->rgba, rgba, (size_t)w * h * 4);
return id;
@@ -530,6 +533,101 @@ static Surface *surface(uint32_t id) {
return NULL;
}
/* Pixel buffers of released surfaces, kept for the next capture of the same size: a client
* that redraws every frame then reuses two or three buffers instead of the allocator handing
* back fresh (unfaulted, zeroed) pages for megabytes every frame. */
#define SPARE_MAX 4
static uint8_t *spare_px[SPARE_MAX];
static size_t spare_len[SPARE_MAX];
static uint8_t *px_alloc(size_t len) {
for (int i = 0; i < SPARE_MAX; i++)
if (spare_px[i] && spare_len[i] == len) { uint8_t *p = spare_px[i]; spare_px[i] = NULL; return p; }
return malloc(len);
}
static void px_free(uint8_t *p, size_t len) {
if (!p) return;
for (int i = 0; i < SPARE_MAX; i++)
if (!spare_px[i]) { spare_px[i] = p; spare_len[i] = len; return; }
/* Full: replace the oldest-looking slot (0) so sizes in use now win. */
free(spare_px[0]);
memmove(spare_px, spare_px + 1, (SPARE_MAX - 1) * sizeof *spare_px);
memmove(spare_len, spare_len + 1, (SPARE_MAX - 1) * sizeof *spare_len);
spare_px[SPARE_MAX - 1] = p; spare_len[SPARE_MAX - 1] = len;
}
/* Little-endian B, G, R, A rows -> R, G, B, A, one pixel as one 32-bit word (the compiler turns
* it into vector shuffles). Returns 1 when every pixel came out opaque. */
static int swizzle_rows(const uint8_t *src, int stride, uint8_t *dst, int w, int h, int xrgb) {
uint32_t force = xrgb ? 0xff000000u : 0, acc = 0xff000000u;
for (int y = 0; y < h; y++) {
const uint32_t *s = (const uint32_t *)(src + (size_t)y * stride);
uint32_t *d = (uint32_t *)(dst + (size_t)y * w * 4);
for (int x = 0; x < w; x++) {
uint32_t v = s[x] | force;
acc &= v;
d[x] = (v & 0xff00ff00u) | ((v >> 16) & 0xffu) | ((v & 0xffu) << 16);
}
}
return (acc >> 24) == 0xff;
}
/* Client pools stay mapped between captures: mapping a pool again for every commit costs a page
* fault per 4 KiB on the copy (about half the time of a full-screen capture). A mapping is known by
* the file behind the descriptor (device, inode, size), so a reused descriptor number or a pool
* that grew maps afresh; mappings unused for a second are dropped, so a closed client's memory
* is not kept for long. */
#define MAP_CACHE 4
typedef struct {
uint8_t *p;
size_t len;
dev_t dev;
ino_t ino;
int64_t used_ms;
} PoolMap;
static PoolMap pool_maps[MAP_CACHE];
static int64_t mono_ms(void) {
struct timespec t;
clock_gettime(CLOCK_MONOTONIC, &t);
return (int64_t)t.tv_sec * 1000 + t.tv_nsec / 1000000;
}
static void pool_maps_gc(int64_t now) {
for (int i = 0; i < MAP_CACHE; i++)
if (pool_maps[i].p && now - pool_maps[i].used_ms > 1000) {
munmap(pool_maps[i].p, pool_maps[i].len);
pool_maps[i].p = NULL;
}
}
/* Drop pool mappings not used for a while (called with each submitted frame). */
void rs_maps_gc(void) { pool_maps_gc(mono_ms()); }
/* The whole file behind fd (st_size bytes) mapped read-only, from the cache when it is there. */
static const uint8_t *pool_map(int fd, const struct stat *st) {
int64_t now = mono_ms();
pool_maps_gc(now);
for (int i = 0; i < MAP_CACHE; i++) {
PoolMap *m = &pool_maps[i];
if (m->p && m->dev == st->st_dev && m->ino == st->st_ino && m->len == (size_t)st->st_size) {
m->used_ms = now;
return m->p;
}
}
uint8_t *p = mmap(NULL, (size_t)st->st_size, PROT_READ, MAP_SHARED, fd, 0);
if (p == MAP_FAILED) return NULL;
int slot = 0;
for (int i = 0; i < MAP_CACHE; i++) {
if (!pool_maps[i].p) { slot = i; break; }
if (pool_maps[i].used_ms < pool_maps[slot].used_ms) slot = i;
}
if (pool_maps[slot].p) munmap(pool_maps[slot].p, pool_maps[slot].len);
pool_maps[slot] = (PoolMap){ p, (size_t)st->st_size, st->st_dev, st->st_ino, now };
return p;
}
/* Copy a client buffer (stride * height bytes at `offset` of the file behind fd, little-endian
* B, G, R, A/X) into a surface. 0 on failure. */
uint32_t rs_capture(int32_t fd, int32_t offset, int32_t stride, int32_t w, int32_t h, int32_t format) {
@@ -537,22 +635,11 @@ uint32_t rs_capture(int32_t fd, int32_t offset, int32_t stride, int32_t w, int32
int64_t len = (int64_t)stride * h, end = offset + len;
struct stat st;
if (fstat(fd, &st) < 0 || st.st_size < end) return 0;
/* Mapping a large pool only reserves address space; just the pages copied are touched. */
uint8_t *p = mmap(NULL, (size_t)end, PROT_READ, MAP_SHARED, fd, 0);
if (p == MAP_FAILED) return 0;
const uint8_t *src = p + offset;
uint8_t *rgba = malloc((size_t)w * h * 4);
int opaque = 1, xrgb = format == 1;
for (int y = 0; y < h; y++) {
const uint8_t *s = src + (size_t)y * stride;
uint8_t *d = rgba + (size_t)y * w * 4;
for (int x = 0; x < w; x++, s += 4, d += 4) {
d[0] = s[2]; d[1] = s[1]; d[2] = s[0];
d[3] = xrgb ? 0xff : s[3];
opaque &= d[3] == 0xff;
}
}
munmap(p, (size_t)end);
const uint8_t *p = pool_map(fd, &st);
if (!p) return 0;
uint8_t *rgba = px_alloc((size_t)w * h * 4);
if (!rgba) return 0;
int opaque = swizzle_rows(p + offset, stride, rgba, w, h, format == 1);
do { next_surface++; } while (next_surface == 0 || surface(next_surface));
Surface *sf = malloc(sizeof *sf);
sf->id = next_surface; sf->w = w; sf->h = h; sf->rgba = rgba; sf->opaque = opaque;
@@ -564,7 +651,12 @@ uint32_t rs_capture(int32_t fd, int32_t offset, int32_t stride, int32_t w, int32
void rs_release(uint32_t id) {
Surface **p = &surfaces[id % SURF_BUCKETS];
while (*p) {
if ((*p)->id == id) { Surface *s = *p; *p = s->next; free(s->rgba); free(s); return; }
if ((*p)->id == id) {
Surface *s = *p; *p = s->next;
px_free(s->rgba, (size_t)s->w * s->h * 4);
free(s);
return;
}
p = &(*p)->next;
}
}
@@ -575,6 +667,21 @@ int32_t rs_surface_count(void) {
return n;
}
/* 1 when image `handle` got new pixels since the last call for it (so where it is drawn must be
* drawn again even though the frame's ops did not change). */
int32_t rs_image_take_changed(int32_t handle) {
if (handle <= 0 || handle > n_images || !images[handle - 1].changed) return 0;
images[handle - 1].changed = 0;
return 1;
}
/* 1 when surface `id` is opaque and at least w x h, so blitting it into a w x h window covers
* every pixel there (what is under it need not be drawn). */
int32_t rs_surface_covers(uint32_t id, int32_t w, int32_t h) {
Surface *s = surface(id);
return s && s->opaque && s->w >= w && s->h >= h;
}
/* A w x h scaled copy of surface `id` as an image (see rs_image_put for `reuse`). */
int32_t rs_thumbnail(uint32_t id, int32_t w, int32_t h, int32_t reuse) {
if (w <= 0 || h <= 0 || w > MAX_IMAGE || h > MAX_IMAGE) return 0;
@@ -583,6 +690,7 @@ int32_t rs_thumbnail(uint32_t id, int32_t w, int32_t h, int32_t reuse) {
uint8_t *px = scale_rgba(s->rgba, s->w, s->h, w, h);
int32_t img = image_slot(reuse);
images[img - 1].w = w; images[img - 1].h = h; images[img - 1].rgba = px;
images[img - 1].changed = img == reuse;
return img;
}
@@ -666,31 +774,101 @@ void rs_read_frame(moonbit_bytes_t out) {
if (fb && (size_t)Moonbit_array_length(out) >= n) memcpy(out, fb, n);
}
/* A new memfd holding the framebuffer as little-endian ARGB8888 (B, G, R, 255). -1 on failure. */
/* ---- damage: what changed in the framebuffer since each output last took it ---- */
/* x0, y0, x1, y1; empty when x0 >= x1. */
typedef struct { int x0, y0, x1, y1; } Box;
static void box_add(Box *b, int x0, int y0, int x1, int y1) {
if (x0 >= x1 || y0 >= y1) return;
if (b->x0 >= b->x1 || b->y0 >= b->y1) { *b = (Box){ x0, y0, x1, y1 }; return; }
b->x0 = imin(b->x0, x0); b->y0 = imin(b->y0, y0);
b->x1 = imax(b->x1, x1); b->y1 = imax(b->y1, y1);
}
/* Clipped to the framebuffer. */
static Box box_fb(Box b) {
return (Box){ imax(b.x0, 0), imax(b.y0, 0), imin(b.x1, fb_w), imin(b.y1, fb_h) };
}
#define EXPORT_SLOTS 3
static Box kms_damage;
static Box slot_damage[EXPORT_SLOTS];
/* The frame just drawn changed (x, y, w, h) of the framebuffer. */
void rs_damage(int32_t x, int32_t y, int32_t w, int32_t h) {
box_add(&kms_damage, x, y, x + w, y + h);
for (int i = 0; i < EXPORT_SLOTS; i++) box_add(&slot_damage[i], x, y, x + w, y + h);
}
/* RGBA8888 -> little-endian XRGB8888 (B, G, R, 255) for the rows and columns of `b`. */
static void to_xrgb(uint8_t *dst, Box b) {
for (int y = b.y0; y < b.y1; y++) {
const uint32_t *s = (const uint32_t *)(fb + (size_t)y * fb_w * 4);
uint32_t *d = (uint32_t *)(dst + (size_t)y * fb_w * 4);
for (int x = b.x0; x < b.x1; x++) {
uint32_t v = s[x];
d[x] = 0xff000000u | (v & 0x0000ff00u) | ((v >> 16) & 0xffu) | ((v & 0xffu) << 16);
}
}
}
/* The nested window's frames: a ring of memfds kept mapped, each updated only where the
* framebuffer changed since that one was last sent (a client redrawing a small window no longer
* costs converting and writing the whole screen every frame). A slot comes round again three
* frames later; the main loop sends a frame only after the host's frame callback for the last one,
* so by then the host compositor has shown two newer frames and is done with the slot's pixels. */
static int slot_fd[EXPORT_SLOTS] = { -1, -1, -1 };
static uint8_t *slot_map[EXPORT_SLOTS];
static int32_t slot_w, slot_h;
static int next_slot;
static void slots_drop(void) {
for (int i = 0; i < EXPORT_SLOTS; i++) {
if (slot_map[i]) munmap(slot_map[i], (size_t)slot_w * slot_h * 4);
if (slot_fd[i] >= 0) close(slot_fd[i]);
slot_map[i] = NULL; slot_fd[i] = -1;
}
slot_w = slot_h = 0;
}
/* A memfd holding the framebuffer as little-endian ARGB8888 (B, G, R, 255), for a wl_shm pool;
* the caller closes it (it is a duplicate of the slot's own). -1 on failure. */
int32_t rs_export_memfd(void) {
if (!fb) return -1;
size_t n = (size_t)fb_w * fb_h * 4;
uint8_t *data = malloc(n);
for (size_t i = 0; i < n; i += 4) {
data[i] = fb[i + 2]; data[i + 1] = fb[i + 1]; data[i + 2] = fb[i]; data[i + 3] = 0xff;
if (slot_w != fb_w || slot_h != fb_h) {
slots_drop();
for (int i = 0; i < EXPORT_SLOTS; i++) {
int fd = memfd_create("chandra-frame", MFD_CLOEXEC);
if (fd < 0 || ftruncate(fd, (off_t)n) < 0) { if (fd >= 0) close(fd); slots_drop(); return -1; }
uint8_t *m = mmap(NULL, n, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
if (m == MAP_FAILED) { close(fd); slots_drop(); return -1; }
slot_fd[i] = fd; slot_map[i] = m;
slot_damage[i] = (Box){ 0, 0, fb_w, fb_h };
}
slot_w = fb_w; slot_h = fb_h;
}
int fd = memfd_create("chandra-frame", MFD_CLOEXEC);
if (fd < 0) { free(data); return -1; }
size_t done = 0;
while (done < n) {
ssize_t w = write(fd, data + done, n - done);
if (w <= 0) { close(fd); free(data); return -1; }
done += (size_t)w;
}
free(data);
return fd;
int i = next_slot;
next_slot = (next_slot + 1) % EXPORT_SLOTS;
Box b = box_fb(slot_damage[i]);
if (b.x0 < b.x1 && b.y0 < b.y1) to_xrgb(slot_map[i], b);
slot_damage[i] = (Box){ 0, 0, 0, 0 };
return fcntl(slot_fd[i], F_DUPFD_CLOEXEC, 0);
}
/* compositor/kms/kms_stub.c: show an RGBA8888 frame on the login session's output. */
int32_t mp_kms_present(moonbit_bytes_t pixels, int32_t w, int32_t h);
/* compositor/kms/kms_stub.c: show an RGBA8888 frame on the login session's output, copying only
* what changed. */
int32_t mp_kms_present_damage(moonbit_bytes_t pixels, int32_t w, int32_t h, int32_t dx, int32_t dy, int32_t dw,
int32_t dh);
void rs_present_kms(void) {
if (fb) mp_kms_present((moonbit_bytes_t)fb, fb_w, fb_h);
if (!fb) return;
Box b = box_fb(kms_damage);
if (b.x0 >= b.x1 || b.y0 >= b.y1) b = (Box){ 0, 0, 0, 0 };
/* The display keeps what it was not given yet, so the damage is handed over either way. */
mp_kms_present_damage((moonbit_bytes_t)fb, fb_w, fb_h, b.x0, b.y0, b.x1 - b.x0, b.y1 - b.y0);
kms_damage = (Box){ 0, 0, 0, 0 };
}
/* ---- screen recording: the frame in flight stays here ---- */