Files
chandra/wasmhost/bin/raster_stub.c
T
nandi bfc60ee0e5
CI / test (push) Failing after 50s
Add chandra-remote: VNC and web control over Tailscale
- remote/: shared-memory framebuffer mirror served as RFB 3.8 (VNC, port 5900) and an HTTP/WebSocket PWA (port 6080), bound to the Tailscale interface and loopback by default
- Compositor: remote pointer, button, scroll, modifier, key, key-tap, text and clipboard input, routed past OLED blanking
- chandra-ctl: add status, refresh and osk commands; add input-* and clipboard-set for remote control
- Camera: debayer 10-bit CSI-2 Quad-Bayer frames for imx371 and high-quality still capture
- Camera: rotate frames by the libcamera mounting angle (CCW for 90), fix the expected test values, and restyle the UI for a dark theme
2026-11-28 17:57:55 -08:00

1363 lines
54 KiB
C

/* The host's rasteriser (chandra:host/raster), pixel work in C.
*
* A port of compositor/renderer, so a frame comes out pixel for pixel the same. raster.mbt decides what to draw (layers, damage, the wallpaper cache);
* this file owns the framebuffer, the captured client surfaces, the images and the glyph cache,
* and draws one primitive per call, inside the current clip.
*
* Glyphs come from stb_truetype through compositor/font's shim (mp_font_*); SVG icons from
* nanosvg (third_party/nanosvg). */
#define _GNU_SOURCE
#include <errno.h>
#include <fcntl.h>
#include <math.h>
#include <poll.h>
#include <pthread.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mman.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <time.h>
#include <unistd.h>
#include "moonbit.h"
#include "../../remote/chandra_fb_shm.h"
#define NANOSVG_IMPLEMENTATION
#define NANOSVGRAST_IMPLEMENTATION
#include "../../third_party/nanosvg/nanosvg.h"
#include "../../third_party/nanosvg/nanosvgrast.h"
/* compositor/font/font_stub.c */
int32_t mp_font_load(int32_t slot, moonbit_bytes_t path_bytes);
void mp_font_metrics(int32_t slot, int32_t cp, int32_t size, int32_t *info);
void mp_font_bitmap(int32_t slot, int32_t cp, int32_t size, int32_t w, int32_t h, moonbit_bytes_t buf);
/* ------------------------------------------------------------------ canvas */
static int32_t fb_w, fb_h;
static uint8_t *fb; /* RGBA8888 */
static int clip_on;
static int32_t clip_x, clip_y, clip_w, clip_h;
static inline int clamp_u8(int v) { return v < 0 ? 0 : v > 255 ? 255 : v; }
static inline int imin(int a, int b) { return a < b ? a : b; }
static inline int imax(int a, int b) { return a > b ? a : b; }
/* Resize the framebuffer (zeroed). 1 when the size changed. */
int32_t rs_resize(int32_t w, int32_t h) {
if (w < 1) w = 1;
if (h < 1) h = 1;
if (fb && w == fb_w && h == fb_h) return 0;
free(fb);
fb = calloc((size_t)w * h, 4);
fb_w = w;
fb_h = h;
return 1;
}
void rs_clear(void) { if (fb) memset(fb, 0, (size_t)fb_w * fb_h * 4); }
void rs_set_clip(int32_t on, int32_t x, int32_t y, int32_t w, int32_t h) {
clip_on = on;
clip_x = x; clip_y = y; clip_w = w; clip_h = h;
}
/* Colour (r, g, b) at alpha a over the RGBA8888 pixel at p: two channels at a time in 16-bit
* lanes, with an exact floor(v / 255). The same pixels as, per channel,
* c' = (c_src * a + c * (255 - a) + 127) / 255 and alpha' = a + (alpha * (255 - a) + 127) / 255
* (the alpha lane adds a * 255 before the division, which is the same thing). */
static inline uint32_t blend32(uint32_t px, uint32_t inv, uint32_t rbadd, uint32_t agadd) {
uint32_t rb = (px & 0x00FF00FFu) * inv + rbadd;
uint32_t ag = ((px >> 8) & 0x00FF00FFu) * inv + agadd;
rb = ((rb + ((rb >> 8) & 0x00FF00FFu) + 0x00010001u) >> 8) & 0x00FF00FFu;
ag = (ag + ((ag >> 8) & 0x00FF00FFu) + 0x00010001u) & 0xFF00FF00u;
return rb | ag;
}
/* The lane constants for colour (r, g, b) at alpha a. */
#define BLEND_ADDS(r, g, b, a) \
uint32_t rbadd = ((uint32_t)((b) * (a) + 127) << 16) | (uint32_t)((r) * (a) + 127); \
uint32_t agadd = ((uint32_t)(255 * (a) + 127) << 16) | (uint32_t)((g) * (a) + 127)
static inline uint32_t opaque32(int r, int g, int b) {
return 0xFF000000u | ((uint32_t)b << 16) | ((uint32_t)g << 8) | (uint32_t)r;
}
static inline void blend_pixel(int x, int y, int r, int g, int b, int a) {
if (x < 0 || y < 0 || x >= fb_w || y >= fb_h || a <= 0) return;
if (clip_on && (x < clip_x || y < clip_y || x >= clip_x + clip_w || y >= clip_y + clip_h)) return;
uint32_t *d = (uint32_t *)fb + (size_t)y * fb_w + x;
if (a >= 255) { *d = opaque32(r, g, b); return; }
BLEND_ADDS(r, g, b, a);
*d = blend32(*d, 255u - (uint32_t)a, rbadd, agadd);
}
/* Blend a colour over pixels [xa, xb) of row y; the span is already clipped. */
static void blend_span(int y, int xa, int xb, int r, int g, int b, int a) {
if (xa >= xb || a <= 0) return;
uint32_t *p = (uint32_t *)fb + (size_t)y * fb_w + xa, *end = (uint32_t *)fb + (size_t)y * fb_w + xb;
if (a >= 255) {
uint32_t c = opaque32(r, g, b);
for (; p < end; p++) *p = c;
return;
}
uint32_t inv = 255u - (uint32_t)a;
BLEND_ADDS(r, g, b, a);
for (; p < end; p++) *p = blend32(*p, inv, rbadd, agadd);
}
static int in_rounded_rect(int px, int py, int rx, int ry, int rw, int rh, int rad) {
if (px < rx || py < ry || px >= rx + rw || py >= ry + rh) return 0;
if (rad <= 0) return 1;
int r = imin(rad, imin(rw, rh) / 2);
if (r <= 0) return 1;
int x_left = rx + r, x_right = rx + rw - r - 1, y_top = ry + r, y_bot = ry + rh - r - 1;
#define CORNER(dx, dy) ((dx) * (dx) + (dy) * (dy) <= r * r)
if (px < x_left && py < y_top) return CORNER(x_left - px, y_top - py);
if (px > x_right && py < y_top) return CORNER(px - x_right, y_top - py);
if (px < x_left && py > y_bot) return CORNER(x_left - px, py - y_bot);
if (px > x_right && py > y_bot) return CORNER(px - x_right, py - y_bot);
#undef CORNER
return 1;
}
/* The part of the rect on the canvas and inside the clip. 0 when empty. */
static int visible(int x, int y, int w, int h, int *x0, int *y0, int *x1, int *y1) {
*x0 = imax(x, 0); *y0 = imax(y, 0);
*x1 = imin(x + w, fb_w); *y1 = imin(y + h, fb_h);
if (clip_on) {
*x0 = imax(*x0, clip_x); *y0 = imax(*y0, clip_y);
*x1 = imin(*x1, clip_x + clip_w); *y1 = imin(*y1, clip_y + clip_h);
}
return *x0 < *x1 && *y0 < *y1;
}
void rs_fill_rect(int32_t x, int32_t y, int32_t w, int32_t h, int32_t cr, int32_t cg, int32_t cb, int32_t ca,
int32_t radius) {
if (!fb || w <= 0 || h <= 0 || ca == 0) return;
int x0, y0, x1, y1;
if (!visible(x, y, w, h, &x0, &y0, &x1, &y1)) return;
if (radius <= 0) {
for (int yy = y0; yy < y1; yy++) blend_span(yy, x0, x1, cr, cg, cb, ca);
return;
}
int r = imin(radius, imin(w, h) / 2);
int x_left = x + r, x_right = x + w - r - 1, y_top = y + r, y_bot = y + h - r - 1;
for (int yy = y0; yy < y1; yy++) {
if (yy >= y_top && yy <= y_bot) { blend_span(yy, x0, x1, cr, cg, cb, ca); continue; }
int xx = x0;
while (xx < x1 && xx < x_left) {
if (in_rounded_rect(xx, yy, x, y, w, h, radius)) blend_span(yy, xx, xx + 1, cr, cg, cb, ca);
xx++;
}
int mid_a = imax(x_left, x0), mid_b = imin(x_right + 1, x1);
blend_span(yy, mid_a, mid_b, cr, cg, cb, ca);
xx = imax(imax(x_right + 1, x0), mid_a);
while (xx < x1) {
if (in_rounded_rect(xx, yy, x, y, w, h, radius)) blend_span(yy, xx, xx + 1, cr, cg, cb, ca);
xx++;
}
}
}
void rs_stroke_rect(int32_t x, int32_t y, int32_t w, int32_t h, int32_t cr, int32_t cg, int32_t cb, int32_t ca,
int32_t width, int32_t radius) {
if (!fb || w <= 0 || h <= 0 || width <= 0 || ca == 0) return;
int x0 = imax(x, 0), y0 = imax(y, 0), x1 = imin(x + w, fb_w), y1 = imin(y + h, fb_h);
int inner_x = x + width, inner_y = y + width, inner_w = w - width * 2, inner_h = h - width * 2;
int inner_r = radius > width ? radius - width : 0;
int cx0 = clip_on ? clip_x : 0, cx1 = clip_on ? clip_x + clip_w : fb_w;
int cy0 = clip_on ? clip_y : 0, cy1 = clip_on ? clip_y + clip_h : fb_h;
int mid_a = inner_y + inner_r, mid_b = inner_y + inner_h - inner_r;
for (int yy = y0; yy < y1; yy++) {
if (inner_w > 0 && inner_h > 0 && yy >= mid_a && yy < mid_b) {
if (yy >= cy0 && yy < cy1) {
int l0 = imax(x0, cx0), l1 = imin(imin(inner_x, x1), cx1);
blend_span(yy, l0, l1, cr, cg, cb, ca);
int r0 = imax(imax(inner_x + inner_w, x0), cx0);
blend_span(yy, r0, imin(x1, cx1), cr, cg, cb, ca);
}
continue;
}
for (int xx = x0; xx < x1; xx++) {
int in_outer = in_rounded_rect(xx, yy, x, y, w, h, radius);
int in_inner = inner_w > 0 && inner_h > 0 && in_rounded_rect(xx, yy, inner_x, inner_y, inner_w, inner_h, inner_r);
if (in_outer && !in_inner) blend_pixel(xx, yy, cr, cg, cb, ca);
}
}
}
void rs_line(int32_t x0, int32_t y0, int32_t x1, int32_t y1, int32_t cr, int32_t cg, int32_t cb, int32_t ca,
int32_t width) {
if (!fb) return;
int half = width <= 1 ? 0 : width / 2;
int dx = abs(x1 - x0), sx = x0 < x1 ? 1 : -1;
int dy = -abs(y1 - y0), sy = y0 < y1 ? 1 : -1;
int err = dx + dy;
for (;;) {
for (int oy = -half; oy <= half; oy++)
for (int ox = -half; ox <= half; ox++) blend_pixel(x0 + ox, y0 + oy, cr, cg, cb, ca);
if (x0 == x1 && y0 == y1) break;
int e2 = 2 * err;
if (e2 >= dy) { err += dy; x0 += sx; }
if (e2 <= dx) { err += dx; y0 += sy; }
}
}
/* Coverage of pixel (dx, dy) of a circle of radius `rad` (filled, or a 1 px ring). */
static inline double circle_cov(int dx, int dy, double rad, int filled) {
double dist = sqrt((double)(dx * dx + dy * dy));
double outer = rad + 0.5 - dist;
double cov = outer > 1.0 ? 1.0 : outer;
if (!filled) {
double inner = dist - (rad - 1.0 - 0.5);
double ic = inner > 1.0 ? 1.0 : inner;
if (ic < cov) cov = ic;
}
return cov;
}
/* Row by row: the antialiased edge pixel by pixel, a filled circle's solid middle as one span and
* a ring's empty middle skipped (big translucent discs, like the starfield's nebulae, cost a
* sqrt per pixel otherwise). The same pixels as testing every pixel of the bounding box. */
void rs_circle(int32_t cx, int32_t cy, int32_t radius, int32_t cr, int32_t cg, int32_t cb, int32_t ca,
int32_t filled) {
if (!fb || radius <= 0) return;
double rad = radius;
/* Fully covered (filled) when dist <= rad - 0.5; certainly empty (ring) when dist <= rad - 2. */
double solid = filled ? (rad - 0.5) * (rad - 0.5) : (rad >= 2 ? (rad - 2.0) * (rad - 2.0) : -1.0);
for (int dy = -radius - 1; dy <= radius + 1; dy++) {
int y = cy + dy;
if (y < 0 || y >= fb_h || (clip_on && (y < clip_y || y >= clip_y + clip_h))) continue;
/* The middle run |dx| <= m is solid (or empty); m = -1 when there is none. */
int m = -1;
double left = solid - (double)dy * dy;
if (left >= 0) {
m = (int)sqrt(left);
while ((double)(m + 1) * (m + 1) <= left) m++;
while (m >= 0 && (double)m * m > left) m--;
}
for (int dx = -radius - 1; dx <= radius + 1; dx++) {
if (m >= 0 && dx == -m) {
if (filled) {
int xa = imax(cx - m, 0), xb = imin(cx + m + 1, fb_w);
if (clip_on) { xa = imax(xa, clip_x); xb = imin(xb, clip_x + clip_w); }
blend_span(y, xa, xb, cr, cg, cb, ca);
}
dx = m;
continue;
}
double cov = circle_cov(dx, dy, rad, filled);
if (cov > 0.02) blend_pixel(cx + dx, y, cr, cg, cb, (int)round(ca * cov));
}
}
}
/* ------------------------------------------------------------------ glyphs */
typedef struct Glyph {
int32_t slot, cp, size;
int32_t w, h, xoff, yoff, advance;
uint8_t *coverage;
struct Glyph *next;
} Glyph;
#define GLYPH_BUCKETS 4096
static Glyph *glyphs[GLYPH_BUCKETS];
static int font_loaded[4];
static Glyph *glyph(int32_t slot, int32_t cp, int32_t size) {
uint32_t hsh = ((uint32_t)slot * 2654435761u) ^ ((uint32_t)cp * 40503u) ^ ((uint32_t)size * 977u);
Glyph **b = &glyphs[hsh % GLYPH_BUCKETS];
for (Glyph *g = *b; g; g = g->next)
if (g->slot == slot && g->cp == cp && g->size == size) return g;
Glyph *g = calloc(1, sizeof *g);
g->slot = slot; g->cp = cp; g->size = size;
int32_t info[5] = {0};
if (slot >= 0 && slot < 4 && font_loaded[slot]) mp_font_metrics(slot, cp, size, info);
g->w = info[0]; g->h = info[1]; g->xoff = info[2]; g->yoff = info[3]; g->advance = info[4];
if (g->w > 0 && g->h > 0) {
/* The shim checks the buffer's MoonBit length: hand it a real MoonBit byte string. */
moonbit_bytes_t buf = moonbit_make_bytes(g->w * g->h, 0);
mp_font_bitmap(slot, cp, size, g->w, g->h, buf);
g->coverage = malloc((size_t)g->w * g->h);
memcpy(g->coverage, buf, (size_t)g->w * g->h);
moonbit_decref(buf);
} else {
g->w = g->h = 0;
}
g->next = *b;
*b = g;
return g;
}
static void drop_glyphs(int32_t slot) {
for (int i = 0; i < GLYPH_BUCKETS; i++) {
Glyph **p = &glyphs[i];
while (*p) {
Glyph *g = *p;
if (g->slot == slot) { *p = g->next; free(g->coverage); free(g); }
else p = &g->next;
}
}
}
/* Slot `slot` now holds a newly loaded face (raster.mbt loads it with mp_font_load, which also
* links compositor/font's shim in). */
void rs_font_loaded(int32_t slot) {
if (slot < 0 || slot >= 4) return;
font_loaded[slot] = 1;
drop_glyphs(slot);
}
int32_t rs_font_has(int32_t slot) { return slot >= 0 && slot < 4 && font_loaded[slot]; }
/* Metrics into info: width, height, xoff, yoff, advance. */
void rs_glyph_info(int32_t slot, int32_t cp, int32_t size, int32_t *info) {
Glyph *g = glyph(slot, cp, size);
info[0] = g->w; info[1] = g->h; info[2] = g->xoff; info[3] = g->yoff; info[4] = g->advance;
}
/* The coverage bitmap (w * h bytes) into `out`. */
void rs_glyph_coverage(int32_t slot, int32_t cp, int32_t size, moonbit_bytes_t out) {
Glyph *g = glyph(slot, cp, size);
size_t n = (size_t)g->w * g->h, cap = (size_t)Moonbit_array_length(out);
if (g->coverage && n <= cap) memcpy(out, g->coverage, n);
}
void rs_draw_glyph(int32_t slot, int32_t cp, int32_t size, int32_t pen, int32_t baseline, int32_t cr, int32_t cg,
int32_t cb, int32_t ca, int32_t embolden) {
if (!fb) return;
Glyph *g = glyph(slot, cp, size);
for (int row = 0; row < g->h; row++) {
for (int col = 0; col < g->w; col++) {
int cov = g->coverage[row * g->w + col];
if (cov > 0) {
int px = pen + g->xoff + col, py = baseline + g->yoff + row;
blend_pixel(px, py, cr, cg, cb, ca * cov / 255);
if (embolden) blend_pixel(px + 1, py, cr, cg, cb, ca * cov / 255);
}
}
}
}
/* ------------------------------------------------------------------ images */
#define MAX_IMAGE 16384
typedef struct Sized { int32_t w, h; uint8_t *rgba; struct Sized *next; } Sized;
typedef struct {
int used;
int32_t w, h;
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) */
uint32_t resized_at; /* the frame it was last drawn at a new large size */
int preview; /* a window preview (rs_thumbnail): drawn sampled at any other size */
} Image;
static Image *images;
static int32_t n_images, cap_images;
/* Scale RGBA src (sw x sh) to w x h: average of the covered source pixels (alpha weighted), the
* nearest one when enlarging. Same as the software renderer. Each output row sums its source
* rows per column first (32-bit sums; a column of up to 4096 rows of 255 * 255 fits), then each
* output pixel sums its columns: one pass over the source, row by row. */
static uint8_t *scale_rgba(const uint8_t *src, int sw, int sh, int w, int h) {
uint8_t *out = calloc((size_t)w * h, 4);
uint32_t *col = malloc(sizeof(uint32_t) * 5 * (size_t)sw); /* r*a, g*a, b*a, a, n per column */
for (int y = 0; y < h; y++) {
int y0 = y * sh / h, y1 = imax((y + 1) * sh / h, y0 + 1);
int x_hi = 0; /* columns summed so far for this row (they are needed left to right) */
for (int x = 0; x < w; x++) {
int x0 = x * sw / w, x1 = imax((x + 1) * sw / w, x0 + 1);
for (; x_hi < x1; x_hi++) {
uint32_t r = 0, g = 0, b = 0, a = 0;
const uint8_t *p = src + ((size_t)y0 * sw + x_hi) * 4;
for (int sy = y0; sy < y1; sy++, p += (size_t)sw * 4) {
uint32_t pa = p[3];
r += p[0] * pa; g += p[1] * pa; b += p[2] * pa; a += pa;
}
uint32_t *c = col + (size_t)x_hi * 5;
c[0] = r; c[1] = g; c[2] = b; c[3] = a; c[4] = (uint32_t)(y1 - y0);
}
uint8_t *o = out + ((size_t)y * w + x) * 4;
if ((int64_t)(x1 - x0) * (y1 - y0) <= 66000) {
/* The sums fit 32 bits (255 * 255 per pixel), and 32-bit division is much quicker. */
uint32_t r = 0, g = 0, b = 0, a = 0, n = 0;
for (int sx = x0; sx < x1; sx++) {
const uint32_t *c = col + (size_t)sx * 5;
r += c[0]; g += c[1]; b += c[2]; a += c[3]; n += c[4];
}
if (a > 0) { o[0] = (uint8_t)(r / a); o[1] = (uint8_t)(g / a); o[2] = (uint8_t)(b / a); o[3] = (uint8_t)(a / n); }
continue;
}
int64_t r = 0, g = 0, b = 0, a = 0, n = 0;
for (int sx = x0; sx < x1; sx++) {
const uint32_t *c = col + (size_t)sx * 5;
r += c[0]; g += c[1]; b += c[2]; a += c[3]; n += c[4];
}
if (a > 0) { o[0] = (uint8_t)(r / a); o[1] = (uint8_t)(g / a); o[2] = (uint8_t)(b / a); o[3] = (uint8_t)(a / n); }
}
}
free(col);
return out;
}
static void image_reset(Image *im) {
free(im->rgba);
if (im->svg) nsvgDelete(im->svg);
for (Sized *s = im->sized; s;) { Sized *n = s->next; free(s->rgba); free(s); s = n; }
memset(im, 0, sizeof *im);
}
static int32_t image_slot(int32_t reuse) {
if (reuse > 0 && reuse <= n_images) {
image_reset(&images[reuse - 1]);
images[reuse - 1].used = 1;
return reuse;
}
if (n_images == cap_images) {
cap_images = cap_images ? cap_images * 2 : 64;
images = realloc(images, sizeof(Image) * (size_t)cap_images);
}
memset(&images[n_images], 0, sizeof(Image));
images[n_images].used = 1;
return ++n_images;
}
/* Store w x h RGBA pixels as an image: overwrite `reuse` when it is an earlier handle, else add one. */
int32_t rs_image_put(int32_t reuse, int32_t w, int32_t h, moonbit_bytes_t rgba) {
if (w <= 0 || h <= 0 || w > MAX_IMAGE || h > MAX_IMAGE) return 0;
if ((size_t)Moonbit_array_length(rgba) < (size_t)w * h * 4) return 0;
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;
}
/* An SVG document (its bytes) as an image, rendered sharp at each size it is drawn at. 0 when it
* doesn't parse. */
int32_t rs_image_svg(moonbit_bytes_t data) {
size_t n = (size_t)Moonbit_array_length(data);
char *text = malloc(n + 1);
memcpy(text, data, n);
text[n] = 0;
NSVGimage *svg = nsvgParse(text, "px", 96.0f);
free(text);
if (!svg) return 0;
if (svg->width <= 0 || svg->height <= 0 || !svg->shapes) { nsvgDelete(svg); return 0; }
int32_t id = image_slot(0);
images[id - 1].svg = svg;
return id;
}
/* Rasterise just the shapes `list[0..n)` (relinked into a list for the call) into `dst`, which
* nanosvg clears first: straight (not premultiplied) RGBA. */
static void svg_raster_list(NSVGrasterizer *rast, NSVGimage *svg, NSVGshape **list, int n, float dx, float dy,
float k, uint8_t *dst, int w, int h) {
NSVGshape **next = malloc(sizeof *next * (size_t)(n ? n : 1));
for (int i = 0; i < n; i++) { next[i] = list[i]->next; list[i]->next = i + 1 < n ? list[i + 1] : NULL; }
NSVGimage part = { svg->width, svg->height, n ? list[0] : NULL };
nsvgRasterize(rast, &part, dx, dy, k, dst, w, h, w * 4);
for (int i = 0; i < n; i++) list[i]->next = next[i];
free(next);
}
/* The coverage of clip path or mask `id` as w * h alpha bytes: a clip path's shapes filled
* opaque; a mask's shapes as drawn, by luminance times alpha (content under a filter counts as
* white: the masks Inkscape writes turn theirs white with a colour-matrix filter). */
static uint8_t *svg_clip_mask(NSVGrasterizer *rast, NSVGimage *svg, NSVGshape **all, int n, const char *id,
float dx, float dy, float k, int w, int h) {
NSVGshape **clip = malloc(sizeof *clip * (size_t)n);
NSVGpaint *fill = malloc(sizeof *fill * (size_t)n), *stroke = malloc(sizeof *stroke * (size_t)n);
int m = 0;
for (int i = 0; i < n; i++)
if ((all[i]->flags & NSVG_FLAGS_CLIP) && strcmp(all[i]->clipOf, id) == 0) clip[m++] = all[i];
if (!m) { free(clip); free(fill); free(stroke); return NULL; } /* no such clip: not clipped */
unsigned char *flags = malloc((size_t)m + 1);
for (int i = 0; i < m; i++) {
fill[i] = clip[i]->fill; stroke[i] = clip[i]->stroke; flags[i] = clip[i]->flags;
int is_mask = clip[i]->flags & NSVG_FLAGS_MASK;
if (!is_mask || (clip[i]->flags & NSVG_FLAGS_FILTERED)) {
/* White, keeping a mask's alpha (a plain colour's; a gradient's counts as opaque). */
unsigned a = is_mask && clip[i]->fill.type == NSVG_PAINT_COLOR ? clip[i]->fill.color >> 24 : 0xff;
if (clip[i]->fill.type != NSVG_PAINT_NONE || !is_mask) { clip[i]->fill.type = NSVG_PAINT_COLOR; clip[i]->fill.color = (a << 24) | 0xffffffu; }
if (!is_mask) clip[i]->stroke.type = NSVG_PAINT_NONE;
else if (clip[i]->stroke.type == NSVG_PAINT_COLOR) clip[i]->stroke.color |= 0xffffffu;
}
clip[i]->flags = (unsigned char)(clip[i]->flags | NSVG_FLAGS_VISIBLE);
}
uint8_t *rgba = malloc((size_t)w * h * 4), *mask = malloc((size_t)w * h);
svg_raster_list(rast, svg, clip, m, dx, dy, k, rgba, w, h);
for (size_t i = 0; i < (size_t)w * h; i++) {
const uint8_t *q = rgba + i * 4;
unsigned lum = (54u * q[0] + 183u * q[1] + 19u * q[2]) >> 8; /* Rec. 709 luminance */
mask[i] = (uint8_t)(q[3] * lum / 255);
}
for (int i = 0; i < m; i++) { clip[i]->fill = fill[i]; clip[i]->stroke = stroke[i]; clip[i]->flags = flags[i]; }
free(flags);
free(rgba); free(clip); free(fill); free(stroke);
return mask;
}
/* `src` over `dst`, both straight RGBA, with src's alpha scaled by `mask` (NULL: none). */
static void svg_over(uint8_t *dst, const uint8_t *src, const uint8_t *mask, size_t npx) {
for (size_t i = 0; i < npx; i++) {
const uint8_t *s = src + i * 4;
uint8_t *d = dst + i * 4;
unsigned sa = mask ? (unsigned)s[3] * mask[i] / 255 : s[3];
if (!sa) continue;
unsigned da = d[3], oa = sa + da * (255 - sa) / 255;
for (int c = 0; c < 3; c++) d[c] = (uint8_t)((s[c] * sa + d[c] * da * (255 - sa) / 255) / oa);
d[3] = (uint8_t)oa;
}
}
/* The SVG drawn into a new w x h straight RGBA buffer, fitted and centred. Shapes under a
* clip-path (or mask) are drawn in runs, each cut to its clip's coverage (nanosvg itself has no
* clipping; the vendored parser collects the clip shapes, see NSVG_FLAGS_CLIP). */
static uint8_t *render_svg(NSVGimage *svg, int w, int h) {
static NSVGrasterizer *rast;
if (!rast) rast = nsvgCreateRasterizer();
uint8_t *out = calloc((size_t)w * h, 4);
float k = fminf((float)w / svg->width, (float)h / svg->height);
float dx = ((float)w - svg->width * k) / 2.0f, dy = ((float)h - svg->height * k) / 2.0f;
int n = 0, clipped = 0;
for (NSVGshape *sh = svg->shapes; sh; sh = sh->next) { n++; if (sh->clipId[0] && (sh->flags & NSVG_FLAGS_VISIBLE)) clipped = 1; }
if (!clipped) {
nsvgRasterize(rast, svg, dx, dy, k, out, w, h, w * 4);
return out;
}
NSVGshape **all = malloc(sizeof *all * (size_t)n);
int i = 0;
for (NSVGshape *sh = svg->shapes; sh; sh = sh->next) all[i++] = sh;
uint8_t *tmp = malloc((size_t)w * h * 4);
for (int a = 0; a < n;) {
int b = a + 1;
while (b < n && strcmp(all[b]->clipId, all[a]->clipId) == 0) b++;
svg_raster_list(rast, svg, all + a, b - a, dx, dy, k, tmp, w, h);
uint8_t *mask = all[a]->clipId[0] ? svg_clip_mask(rast, svg, all, n, all[a]->clipId, dx, dy, k, w, h) : NULL;
svg_over(out, tmp, mask, (size_t)w * h);
free(mask);
a = b;
}
free(tmp); free(all);
return out;
}
/* The largest size an image is drawn at (a window preview gliding to its window's size). */
#define MAX_DRAW 4096
/* Sizes past which only one scaled copy of an image is kept (icons are drawn at a few small
* sizes; previews at one large one, or a new one each frame while they move). */
static int big_size(int w, int h) { return w * h > 128 * 128; }
/* Frames submitted so far (rs_frame_begin): tells a moving image from one drawn at a new size once. */
static uint32_t frame_seq = 1;
void rs_frame_begin(void) { frame_seq++; }
/* Image `handle` at w x h, cached. NULL for an unknown handle or a silly size, and for a window
* preview at another size or a large image that was drawn at another new size in the frame
* before: it is moving (the overview's gliding previews), so rs_draw_image samples it instead of
* filtering it and keeping a copy at a size used once. */
static const uint8_t *image_sized(int32_t handle, int w, int h) {
if (w <= 0 || h <= 0 || w > MAX_DRAW || h > MAX_DRAW) return NULL;
if (handle <= 0 || handle > n_images || !images[handle - 1].used) return NULL;
Image *im = &images[handle - 1];
if (im->rgba && im->w == w && im->h == h) return im->rgba;
for (Sized *s = im->sized; s; s = s->next)
if (s->w == w && s->h == h) return s->rgba;
int big = big_size(w, h);
if (im->preview) return NULL; /* made at the size it settles at; stretched only while moving */
if (big && im->rgba) {
int moving = im->resized_at + 1 >= frame_seq;
im->resized_at = frame_seq;
if (moving) return NULL;
}
uint8_t *px = im->svg ? render_svg(im->svg, w, h) : im->rgba ? scale_rgba(im->rgba, im->w, im->h, w, h) : NULL;
if (!px) return NULL;
if (big) {
/* Keep one large size: drop the other large copies. */
for (Sized **pp = &im->sized; *pp;) {
Sized *s = *pp;
if (big_size(s->w, s->h)) { *pp = s->next; free(s->rgba); free(s); }
else pp = &s->next;
}
}
Sized *s = malloc(sizeof *s);
s->w = w; s->h = h; s->rgba = px; s->next = im->sized;
im->sized = s;
return px;
}
/* Blend straight-RGBA pixels `px` (w x h, row `stride` pixels) at (x0, y0), clipped. When `sx` /
* `sy` are given, destination column x / row y takes source column sx[x] / row sy[y] (sampling). */
static void blend_image(const uint8_t *px, int stride, int x0, int y0, int w, int h, const int *sx, const int *sy) {
int xa, ya, xb, yb;
if (!visible(x0, y0, w, h, &xa, &ya, &xb, &yb)) return;
for (int y = ya; y < yb; y++) {
int row = sy ? sy[y - y0] : y - y0;
const uint8_t *src = px + (size_t)row * stride * 4;
uint8_t *d = fb + ((size_t)y * fb_w + xa) * 4;
for (int x = xa; x < xb; x++, d += 4) {
const uint8_t *p = src + (size_t)(sx ? sx[x - x0] : x - x0) * 4;
int a = p[3];
if (a <= 0) continue;
if (a >= 255) { *(uint32_t *)d = opaque32(p[0], p[1], p[2]); continue; }
BLEND_ADDS(p[0], p[1], p[2], a);
*(uint32_t *)d = blend32(*(uint32_t *)d, 255u - (uint32_t)a, rbadd, agadd);
}
}
}
void rs_draw_image(int32_t handle, int32_t x0, int32_t y0, int32_t w, int32_t h) {
if (!fb) return;
const uint8_t *px = image_sized(handle, w, h);
if (px) { blend_image(px, w, x0, y0, w, h, NULL, NULL); return; }
/* A moving large image: each pixel from the nearest source pixel, nothing kept. */
if (w <= 0 || h <= 0 || w > MAX_DRAW || h > MAX_DRAW || handle <= 0 || handle > n_images) return;
Image *im = &images[handle - 1];
if (!im->used || !im->rgba) return;
int *sx = malloc(sizeof(int) * (size_t)(w + h)), *sy = sx + w;
for (int x = 0; x < w; x++) sx[x] = (int)(((int64_t)x * 2 + 1) * im->w / (2 * w));
for (int y = 0; y < h; y++) sy[y] = (int)(((int64_t)y * 2 + 1) * im->h / (2 * h));
blend_image(im->rgba, im->w, x0, y0, w, h, sx, sy);
free(sx);
}
/* ------------------------------------------------------------------ surfaces */
typedef struct Surface {
uint32_t id;
int32_t w, h;
uint8_t *rgba;
int opaque; /* every pixel has alpha 255: blits copy rows */
struct Surface *next;
} Surface;
#define SURF_BUCKETS 256
static Surface *surfaces[SURF_BUCKETS];
static uint32_t next_surface;
static Surface *surface(uint32_t id) {
for (Surface *s = surfaces[id % SURF_BUCKETS]; s; s = s->next)
if (s->id == id) return s;
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). */
static void rs_mem_log(void);
void rs_maps_gc(void) {
pool_maps_gc(mono_ms());
rs_mem_log();
}
/* 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) {
if (fd < 0 || offset < 0 || stride <= 0 || w <= 0 || h <= 0 || stride < w * 4) return 0;
int64_t len = (int64_t)stride * h, end = offset + len;
struct stat st;
if (fstat(fd, &st) < 0 || st.st_size < end) return 0;
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;
sf->next = surfaces[sf->id % SURF_BUCKETS];
surfaces[sf->id % SURF_BUCKETS] = sf;
return sf->id;
}
void rs_release(uint32_t id) {
Surface **p = &surfaces[id % SURF_BUCKETS];
while (*p) {
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;
}
}
int32_t rs_surface_count(void) {
int n = 0;
for (int i = 0; i < SURF_BUCKETS; i++) for (Surface *s = surfaces[i]; s; s = s->next) n++;
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;
Surface *s = surface(id);
if (!s) return 0;
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;
images[img - 1].preview = 1;
return img;
}
/* Draw surface `id` into (x, y, w, h). While a client catches up with a resize its buffer is
* smaller than the window: the buffer's bottom-right colour is extended over the rest.
* 0 when there is no such surface. */
int32_t rs_blit_surface(uint32_t id, int32_t dx, int32_t dy, int32_t dw, int32_t dh) {
Surface *s = surface(id);
if (!s) return 0;
if (!fb || s->w <= 0 || s->h <= 0 || dw <= 0 || dh <= 0) return 1;
if (s->w < dw || s->h < dh) {
const uint8_t *o = s->rgba + ((size_t)(s->h - 1) * s->w + (s->w - 1)) * 4;
rs_fill_rect(dx, dy, dw, dh, o[0], o[1], o[2], o[3], 0);
}
int copy_w = imin(s->w, dw), copy_h = imin(s->h, dh);
int c0 = imax(-dx, 0), c1 = imin(copy_w, fb_w - dx);
int r0 = imax(-dy, 0), r1 = imin(copy_h, fb_h - dy);
if (clip_on) {
c0 = imax(c0, clip_x - dx); c1 = imin(c1, clip_x + clip_w - dx);
r0 = imax(r0, clip_y - dy); r1 = imin(r1, clip_y + clip_h - dy);
}
if (c0 >= c1 || r0 >= r1) return 1;
for (int row = r0; row < r1; row++) {
const uint8_t *src = s->rgba + ((size_t)row * s->w + c0) * 4;
uint8_t *dst = fb + ((size_t)(dy + row) * fb_w + dx + c0) * 4;
size_t n = (size_t)(c1 - c0) * 4;
if (s->opaque) { memcpy(dst, src, n); continue; }
for (size_t i = 0; i < n; i += 4) {
int a = src[i + 3];
if (a >= 255) memcpy(dst + i, src + i, 4);
else if (a > 0) {
/* wl_shm ARGB8888 is premultiplied: the colour already carries its alpha. */
int inv = 255 - a;
dst[i] = (uint8_t)clamp_u8(src[i] + (dst[i] * inv + 127) / 255);
dst[i + 1] = (uint8_t)clamp_u8(src[i + 1] + (dst[i + 1] * inv + 127) / 255);
dst[i + 2] = (uint8_t)clamp_u8(src[i + 2] + (dst[i + 2] * inv + 127) / 255);
dst[i + 3] = (uint8_t)clamp_u8(a + (dst[i + 3] * inv + 127) / 255);
}
}
}
return 1;
}
/* ------------------------------------------------------------------ memory log */
/* A line of what the host holds, in the session log: once a minute (CHANDRA_MEM_LOG_SECS), so a
* session that grows until the machine swaps leaves a record of what grew. */
static void rs_mem_log(void) {
static int64_t last;
static int every_s = -1;
if (every_s < 0) {
const char *e = getenv("CHANDRA_MEM_LOG_SECS");
every_s = e && atoi(e) > 0 ? atoi(e) : 60;
}
int64_t now = mono_ms();
if (last && now - last < (int64_t)every_s * 1000) return;
last = now;
long rss = 0, swap = 0;
FILE *f = fopen("/proc/self/status", "r");
if (f) {
char line[128];
while (fgets(line, sizeof line, f)) {
sscanf(line, "VmRSS: %ld", &rss);
sscanf(line, "VmSwap: %ld", &swap);
}
fclose(f);
}
int surf_n = 0, img_n = 0;
size_t surf_bytes = 0, img_bytes = 0;
for (int i = 0; i < SURF_BUCKETS; i++)
for (Surface *s = surfaces[i]; s; s = s->next) { surf_n++; surf_bytes += (size_t)s->w * s->h * 4; }
for (int i = 0; i < n_images; i++) {
if (!images[i].used) continue;
img_n++;
if (images[i].rgba) img_bytes += (size_t)images[i].w * images[i].h * 4;
for (Sized *s = images[i].sized; s; s = s->next) img_bytes += (size_t)s->w * s->h * 4;
}
time_t wall = time(NULL);
struct tm tm;
char when[32] = "";
if (localtime_r(&wall, &tm)) strftime(when, sizeof when, "%F %T", &tm);
fprintf(stderr, "%s chandra-host: memory %ld MB resident, %ld MB swapped; %d window buffers (%zu MB), %d images (%zu MB)\n",
when, rss / 1024, swap / 1024, surf_n, surf_bytes >> 20, img_n, img_bytes >> 20);
}
/* ------------------------------------------------------------------ backdrop and output */
static uint8_t *backdrop;
static int32_t backdrop_w, backdrop_h;
/* Keep the framebuffer as the backdrop (wallpaper and desktop card). */
void rs_save_backdrop(void) {
free(backdrop);
backdrop = malloc((size_t)fb_w * fb_h * 4);
memcpy(backdrop, fb, (size_t)fb_w * fb_h * 4);
backdrop_w = fb_w;
backdrop_h = fb_h;
}
/* 1 when a backdrop of the framebuffer's size is kept. */
int32_t rs_has_backdrop(void) { return backdrop && backdrop_w == fb_w && backdrop_h == fb_h; }
/* Copy the backdrop back into the clip (or everywhere). */
void rs_copy_backdrop(void) {
if (!rs_has_backdrop()) return;
if (!clip_on) { memcpy(fb, backdrop, (size_t)fb_w * fb_h * 4); return; }
int x0 = imax(clip_x, 0), x1 = imin(clip_x + clip_w, fb_w);
int y0 = imax(clip_y, 0), y1 = imin(clip_y + clip_h, fb_h);
if (x0 >= x1) return;
for (int y = y0; y < y1; y++) {
size_t a = ((size_t)y * fb_w + x0) * 4;
memcpy(fb + a, backdrop + a, (size_t)(x1 - x0) * 4);
}
}
int32_t rs_width(void) { return fb_w; }
int32_t rs_height(void) { return fb_h; }
uint8_t *rs_pixels(void) { return fb; }
/* The framebuffer as RGBA8888 into `out` (w * h * 4 bytes). */
void rs_read_frame(moonbit_bytes_t out) {
size_t n = (size_t)fb_w * fb_h * 4;
if (fb && (size_t)Moonbit_array_length(out) >= n) memcpy(out, fb, n);
}
/* ---- 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];
static Box shm_slot_dmg[2];
static Box shm_pub_dmg;
/* 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);
box_add(&shm_slot_dmg[0], x, y, x + w, y + h);
box_add(&shm_slot_dmg[1], x, y, x + w, y + h);
box_add(&shm_pub_dmg, 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;
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 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, 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) 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: a short queue of frames and a writer thread ----
* rs_grab_recording copies a frame into a free slot (a Matroska Cluster header with the time it
* was taken, then the pixels; recorder.mbt's mkv_frame_header writes the same 42 bytes) and the
* writer thread sends the slots to ffmpeg's socket in order, so a frame never waits on the main
* loop. A full queue means ffmpeg is behind: that frame is not taken. */
#define REC_SLOTS 3
#define REC_HEAD 42
static uint8_t *rec_slot[REC_SLOTS];
static size_t rec_cap[REC_SLOTS], rec_size[REC_SLOTS];
static int rec_first, rec_count; /* the queue: slots rec_first.. (mod REC_SLOTS), rec_count of them */
static int rec_fd = -1, rec_running, rec_stop, rec_failed;
static pthread_t rec_thread;
static pthread_mutex_t rec_mu = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t rec_cv = PTHREAD_COND_INITIALIZER;
static uint8_t *rec_px;
static void rec_fill(int32_t w, int32_t h, int32_t x, int32_t y, int32_t rw, int32_t rh, uint8_t v) {
for (int32_t j = imax(y, 0); j < imin(y + rh, h); j++)
for (int32_t i = imax(x, 0); i < imin(x + rw, w); i++) {
uint8_t *p = rec_px + ((size_t)j * w + i) * 4;
p[0] = p[1] = p[2] = v; p[3] = 0xff;
}
}
/* The arrow pointer with its tip at (x, y), as recorder.mbt's draw_pointer draws it: a black body
* widening over 13 rows and a short tail, then the white inside. */
static void rec_pointer(int32_t w, int32_t h, int32_t x, int32_t y) {
for (int i = 0; i < 17; i++) {
int l = i < 13 ? 0 : 3 + (i - 13), bw = i < 13 ? i * 2 / 3 + 1 : 3;
rec_fill(w, h, x + l - 1, y + i - 1, bw + 2, 3, 0);
}
for (int i = 1; i < 16; i++) {
int l = i < 13 ? 0 : 4 + (i - 13), bw = i < 13 ? i * 2 / 3 - 1 : 1;
if (bw > 0) rec_fill(w, h, x + l + 1, y + i, bw, 1, 0xff);
}
}
/* An EBML ID and an 8-byte size. */
static uint8_t *rec_id_size(uint8_t *o, const uint8_t *id, int idn, uint64_t n) {
memcpy(o, id, idn); o += idn;
*o++ = 0x01;
for (int i = 6; i >= 0; i--) *o++ = (uint8_t)(n >> (i * 8));
return o;
}
static void rec_frame_header(uint8_t *o, uint64_t ms, size_t n) {
static const uint8_t cluster[] = { 0x1f, 0x43, 0xb6, 0x75 }, tc[] = { 0xe7 }, block[] = { 0xa3 };
o = rec_id_size(o, cluster, 4, 30 + n);
o = rec_id_size(o, tc, 1, 8);
for (int i = 7; i >= 0; i--) *o++ = (uint8_t)(ms >> (i * 8));
o = rec_id_size(o, block, 1, 4 + n);
o[0] = 0x81; o[1] = 0; o[2] = 0; o[3] = 0x80;
}
static uint64_t rec_now_ms(void) {
struct timespec ts;
clock_gettime(CLOCK_MONOTONIC, &ts);
return (uint64_t)ts.tv_sec * 1000 + (uint64_t)ts.tv_nsec / 1000000;
}
/* Write all of buf; ffmpeg not taking anything for 5 s counts as a failure (so stopping never
* hangs on a stuck encoder). */
static int rec_write_all(int fd, const uint8_t *buf, size_t len) {
size_t done = 0;
while (done < len) {
ssize_t w = send(fd, buf + done, len - done, MSG_NOSIGNAL);
if (w < 0 && errno == ENOTSOCK) w = write(fd, buf + done, len - done);
if (w < 0) {
if (errno == EINTR) continue;
if (errno == EAGAIN || errno == EWOULDBLOCK) {
struct pollfd p = { .fd = fd, .events = POLLOUT };
int r = poll(&p, 1, 5000);
if (r < 0 && errno == EINTR) continue;
if (r <= 0) { fprintf(stderr, "recording: ffmpeg took nothing for 5 s\n"); return -1; }
continue;
}
fprintf(stderr, "recording: writing to ffmpeg failed: %s\n", strerror(errno));
return -1;
}
done += (size_t)w;
}
return 0;
}
static void *rec_writer(void *arg) {
(void)arg;
pthread_mutex_lock(&rec_mu);
for (;;) {
while (rec_count == 0 && !rec_stop) pthread_cond_wait(&rec_cv, &rec_mu);
if (rec_count == 0) break; /* stopping, and all of it went out */
int i = rec_first;
pthread_mutex_unlock(&rec_mu);
int bad = rec_write_all(rec_fd, rec_slot[i], rec_size[i]) < 0;
pthread_mutex_lock(&rec_mu);
if (bad) { rec_failed = 1; break; }
rec_first = (rec_first + 1) % REC_SLOTS;
rec_count--;
}
pthread_mutex_unlock(&rec_mu);
return NULL;
}
int32_t rs_grab_recording(int32_t x, int32_t y, int32_t w, int32_t h, int32_t pointer, int32_t px, int32_t py) {
if (!fb || w <= 0 || h <= 0 || x < 0 || y < 0 || x + w > fb_w || y + h > fb_h) return 0;
pthread_mutex_lock(&rec_mu);
int full = rec_count == REC_SLOTS || rec_failed;
int i = (rec_first + rec_count) % REC_SLOTS;
pthread_mutex_unlock(&rec_mu);
if (full) return 0;
/* Slot i is not in the queue, so the writer doesn't touch it while it is filled. */
size_t n = (size_t)w * h * 4;
if (rec_cap[i] < REC_HEAD + n) {
free(rec_slot[i]);
rec_slot[i] = malloc(REC_HEAD + n);
if (!rec_slot[i]) { rec_cap[i] = 0; fprintf(stderr, "recording: out of memory for a frame\n"); return 0; }
rec_cap[i] = REC_HEAD + n;
}
rec_frame_header(rec_slot[i], rec_now_ms(), n);
rec_px = rec_slot[i] + REC_HEAD;
/* Copy and make opaque in one pass (alpha is the high byte of each little-endian pixel). */
for (int32_t j = 0; j < h; j++) {
const uint8_t *src = fb + ((size_t)(y + j) * fb_w + x) * 4;
uint8_t *dst = rec_px + (size_t)j * w * 4;
for (int32_t k = 0; k < w; k++) {
uint32_t v;
memcpy(&v, src + (size_t)k * 4, 4);
v |= 0xff000000u;
memcpy(dst + (size_t)k * 4, &v, 4);
}
}
if (pointer) rec_pointer(w, h, px - x, py - y);
rec_size[i] = REC_HEAD + n;
pthread_mutex_lock(&rec_mu);
rec_count++;
pthread_cond_signal(&rec_cv);
pthread_mutex_unlock(&rec_mu);
return 1;
}
/* fd >= 0: the writer sends to fd (started on the first call): the frames still queued, or -1
* once a write failed. fd < 0: send what is queued, stop the writer (0, or -1 when it failed). */
int32_t rs_send_recording(int32_t fd) {
if (fd >= 0) {
if (!rec_running) {
rec_fd = fd; rec_stop = 0; rec_failed = 0; rec_first = 0; rec_count = 0;
int fl = fcntl(fd, F_GETFL);
if (fl >= 0 && !(fl & O_NONBLOCK)) fcntl(fd, F_SETFL, fl | O_NONBLOCK);
if (pthread_create(&rec_thread, NULL, rec_writer, NULL) != 0) {
fprintf(stderr, "recording: can't start the writer thread\n");
return -1;
}
rec_running = 1;
} else if (fd != rec_fd) {
fprintf(stderr, "recording: a second stream while one is running\n");
return -1;
}
pthread_mutex_lock(&rec_mu);
int32_t r = rec_failed ? -1 : rec_count;
pthread_mutex_unlock(&rec_mu);
return r;
}
if (!rec_running) return 0;
pthread_mutex_lock(&rec_mu);
rec_stop = 1;
pthread_cond_signal(&rec_cv);
pthread_mutex_unlock(&rec_mu);
pthread_join(rec_thread, NULL);
rec_running = 0;
rec_fd = -1;
int32_t r = rec_failed ? -1 : 0;
rec_count = 0;
return r;
}
/* ---- screenshots: the frozen screen stays here ---- */
static uint8_t *snap;
static int32_t snap_w, snap_h;
int32_t rs_snapshot(void) {
if (!fb) return 0;
size_t n = (size_t)fb_w * fb_h * 4;
if (!snap || snap_w != fb_w || snap_h != fb_h) { free(snap); snap = malloc(n); snap_w = fb_w; snap_h = fb_h; }
memcpy(snap, fb, n);
return 1;
}
int32_t rs_snapshot_w(void) { return snap ? snap_w : 0; }
int32_t rs_snapshot_h(void) { return snap ? snap_h : 0; }
/* `x`, `y`, `w` x `h` of the snapshot scaled (nearest) to `ow` x `oh` into `out` (ow * oh * 4
* bytes), opaque; off the snapshot is black. */
void rs_snapshot_pixels(int32_t x, int32_t y, int32_t w, int32_t h, int32_t ow, int32_t oh, moonbit_bytes_t out) {
if ((size_t)Moonbit_array_length(out) < (size_t)ow * oh * 4 || ow <= 0 || oh <= 0) return;
for (int32_t ty = 0; ty < oh; ty++) {
int32_t sy = y + (int32_t)((int64_t)ty * h / oh);
for (int32_t tx = 0; tx < ow; tx++) {
int32_t sx = x + (int32_t)((int64_t)tx * w / ow);
uint8_t *d = out + ((size_t)ty * ow + tx) * 4;
if (snap && sx >= 0 && sy >= 0 && sx < snap_w && sy < snap_h) memcpy(d, snap + ((size_t)sy * snap_w + sx) * 4, 3);
else d[0] = d[1] = d[2] = 0;
d[3] = 0xff;
}
}
}
/* ---- live shared-memory framebuffer mirror (for chandra-remote) ---- */
static int shm_fd = -1;
static ChandraFbHeader *shm_hdr;
static int32_t shm_w, shm_h;
static int shm_init_tried;
static void shm_ensure_open(void) {
if (shm_init_tried) return;
shm_init_tried = 1;
char path[512];
const char *env = getenv("CHANDRA_FB_SHM");
if (env && env[0]) {
snprintf(path, sizeof path, "%s", env);
} else {
const char *tc = getenv("CHANDRA_TEST_CONFIG");
if (tc && tc[0]) return;
const char *rt = getenv("XDG_RUNTIME_DIR");
if (!rt || !rt[0]) return;
char dir[512];
snprintf(dir, sizeof dir, "%s/chandra", rt);
mkdir(dir, 0700);
snprintf(path, sizeof path, "%s/fb.shm", dir);
}
int fd = open(path, O_RDWR | O_CREAT | O_CLOEXEC, 0600);
if (fd < 0) return;
struct stat st;
size_t need = (size_t)CHANDRA_FB_TOTAL_BYTES;
if (fstat(fd, &st) < 0 || (size_t)st.st_size < need) {
if (ftruncate(fd, (off_t)need) < 0) {
close(fd);
return;
}
}
void *m = mmap(NULL, need, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
if (m == MAP_FAILED) {
close(fd);
return;
}
shm_fd = fd;
shm_hdr = (ChandraFbHeader *)m;
uint64_t saved_ping = 0;
if (shm_hdr->magic == CHANDRA_FB_MAGIC && shm_hdr->version == CHANDRA_FB_VERSION &&
shm_hdr->slot_bytes == CHANDRA_FB_SLOT_BYTES) {
saved_ping = __atomic_load_n(&shm_hdr->consumer_ping_ms, __ATOMIC_ACQUIRE);
} else {
memset(shm_hdr, 0, sizeof *shm_hdr);
}
shm_hdr->magic = CHANDRA_FB_MAGIC;
shm_hdr->version = CHANDRA_FB_VERSION;
shm_hdr->slot_bytes = CHANDRA_FB_SLOT_BYTES;
shm_hdr->active_slot = 0;
shm_hdr->width = 0;
shm_hdr->height = 0;
shm_hdr->dmg_x0 = shm_hdr->dmg_y0 = shm_hdr->dmg_x1 = shm_hdr->dmg_y1 = 0;
shm_hdr->frame_ms = 0;
__atomic_store_n(&shm_hdr->consumer_ping_ms, saved_ping, __ATOMIC_RELEASE);
__atomic_store_n(&shm_hdr->seq, 0, __ATOMIC_RELEASE);
}
void rs_publish_frame(void) {
if (!fb || fb_w <= 0 || fb_h <= 0) return;
if ((size_t)fb_w * (size_t)fb_h * 4 > CHANDRA_FB_SLOT_BYTES) return;
shm_ensure_open();
if (!shm_hdr) return;
uint64_t now = rec_now_ms();
uint64_t ping = __atomic_load_n(&shm_hdr->consumer_ping_ms, __ATOMIC_ACQUIRE);
uint64_t cur_seq = __atomic_load_n(&shm_hdr->seq, __ATOMIC_RELAXED);
if (cur_seq > 0 && (ping == 0 || now > ping + 5000)) return;
if (fb_w != shm_w || fb_h != shm_h || cur_seq == 0) {
shm_slot_dmg[0] = (Box){ 0, 0, fb_w, fb_h };
shm_slot_dmg[1] = (Box){ 0, 0, fb_w, fb_h };
shm_pub_dmg = (Box){ 0, 0, fb_w, fb_h };
shm_w = fb_w;
shm_h = fb_h;
}
Box pb = box_fb(shm_pub_dmg);
if (pb.x0 >= pb.x1 || pb.y0 >= pb.y1) {
if (cur_seq == 0) pb = (Box){ 0, 0, fb_w, fb_h };
else return;
}
uint32_t next = 1u - (__atomic_load_n(&shm_hdr->active_slot, __ATOMIC_RELAXED) & 1u);
uint8_t *dst = chandra_fb_slot_ptr(shm_hdr, next, shm_hdr->slot_bytes);
Box sb = box_fb(shm_slot_dmg[next]);
if (sb.x0 < sb.x1 && sb.y0 < sb.y1) {
if (sb.x0 == 0 && sb.x1 == fb_w) {
size_t off = (size_t)sb.y0 * (size_t)fb_w * 4;
size_t bytes = (size_t)(sb.y1 - sb.y0) * (size_t)fb_w * 4;
memcpy(dst + off, fb + off, bytes);
} else {
size_t span = (size_t)(sb.x1 - sb.x0) * 4;
for (int y = sb.y0; y < sb.y1; y++) {
size_t off = ((size_t)y * (size_t)fb_w + (size_t)sb.x0) * 4;
memcpy(dst + off, fb + off, span);
}
}
}
shm_slot_dmg[next] = (Box){ 0, 0, 0, 0 };
shm_pub_dmg = (Box){ 0, 0, 0, 0 };
shm_hdr->width = (uint32_t)fb_w;
shm_hdr->height = (uint32_t)fb_h;
shm_hdr->dmg_x0 = pb.x0;
shm_hdr->dmg_y0 = pb.y0;
shm_hdr->dmg_x1 = pb.x1;
shm_hdr->dmg_y1 = pb.y1;
shm_hdr->frame_ms = now;
__atomic_store_n(&shm_hdr->active_slot, next, __ATOMIC_RELEASE);
__atomic_store_n(&shm_hdr->seq, cur_seq + 1, __ATOMIC_RELEASE);
}