From cfb25fe6995fd1e3ca30c21241f3e2ed74dd2b2c Mon Sep 17 00:00:00 2001 From: nandithebull Date: Mon, 30 Nov 2026 16:42:22 -0800 Subject: [PATCH 1/3] Draw on the GPU: the desktop with OpenGL ES, apps through linux-dmabuf The host's rasteriser has a GPU half (raster_gpu.c): the same primitives, drawn the same way, on machines with a real GPU and OpenGL ES 3, straight into the display's buffers in a login session. EGL and GLES are loaded at run time; without them everything is drawn on the CPU as before (CHANDRA_GPU=0 does that too). zwp_linux_dmabuf_v1 lets apps draw on the GPU as well. Co-Authored-By: Claude Opus 5.5 --- README.md | 5 +- compositor/host/dmabuf_test.mbt | 106 ++ compositor/kms/kms_stub.c | 51 +- compositor/shell/render_mode.mbt | 7 +- compositor/sys/sys_native.mbt | 27 + compositor/sys/sys_wasm.mbt | 31 + compositor/wayland/dmabuf.mbt | 296 +++++ compositor/wayland/dnd.mbt | 2 +- compositor/wayland/server.mbt | 46 +- docs/rendering.md | 50 +- interface/chandra/host/raster/ffi.mbt | 60 +- interface/chandra/host/raster/native_stub.mbt | 87 +- .../chandra/host/raster/pkg.generated.mbti | 24 + interface/chandra/host/raster/top.mbt | 69 ++ justfile | 4 + scripts/test-gpu.sh | 18 + scripts/test.sh | 3 + wasmhost/README.md | 4 +- wasmhost/bin/main.mbt | 1 + wasmhost/bin/moon.pkg | 2 +- wasmhost/bin/raster.mbt | 80 ++ wasmhost/bin/raster_gpu.c | 1019 +++++++++++++++++ wasmhost/bin/raster_gpu.h | 54 + wasmhost/bin/raster_stub.c | 229 +++- wasmhost/test/gpu_test.c | 300 +++++ wit/host/raster.wit | 15 + 26 files changed, 2485 insertions(+), 105 deletions(-) create mode 100644 compositor/host/dmabuf_test.mbt create mode 100644 compositor/wayland/dmabuf.mbt create mode 100755 scripts/test-gpu.sh create mode 100644 wasmhost/bin/raster_gpu.c create mode 100644 wasmhost/bin/raster_gpu.h create mode 100644 wasmhost/test/gpu_test.c diff --git a/README.md b/README.md index f5d53fc..dc2b471 100644 --- a/README.md +++ b/README.md @@ -89,8 +89,9 @@ session), `--x11` (on Xorg; `--fullscreen` under a window manager, `--login-sess desktop session), `--theme PATH`, `--no-restore`, `--profile`, `--size WxH` and `--gfx-out frame.png` (render to a PNG, headless; add `--serve` to keep refreshing it). `WASMHOST_PROFILE=1` prints the time spent in each host function every 5 seconds; `WASMHOST_TRACE=1` logs every host call. -No GPU? Chandra detects it and asks less of the CPU; `CHANDRA_RENDER=software|hardware` or -Settings > Session > Lighter animations overrides it, and `CHANDRA_FRAME_TRACE=1` logs frame times +With a GPU (OpenGL ES 3) the host draws the desktop on it and apps draw on it too (linux-dmabuf); +`CHANDRA_GPU=0` keeps the desktop on the CPU. No GPU? Chandra draws on the CPU and asks less of it; +`CHANDRA_RENDER=software|hardware` or Settings > Session > Lighter animations overrides that, and `CHANDRA_FRAME_TRACE=1` logs frame times ([docs/rendering.md](docs/rendering.md)). `CHANDRA_DEBUG_CONFIGURE=1` (any host) logs each window's configures, acks and committed buffer diff --git a/compositor/host/dmabuf_test.mbt b/compositor/host/dmabuf_test.mbt new file mode 100644 index 0000000..95a5a7f --- /dev/null +++ b/compositor/host/dmabuf_test.mbt @@ -0,0 +1,106 @@ +///| zwp_linux_dmabuf_v1: what an app that draws on the GPU asks for, against a pretend GPU. + +///| +struct FakeGpu { + imported : Array[(Int, UInt64, Int, Int, UInt, Bool)] + captured : Array[UInt] + released : Array[UInt] +} + +///| +const XR24 : UInt = 0x34325258U + +///| +fn with_fake_gpu(comp : @host.ChandraCompositor) -> FakeGpu { + let g : FakeGpu = { imported: [], captured: [], released: [] } + comp.server.dmabuf_host = { + support: () => (0xe280UL, [(XR24, 0UL), (XR24, 0x0100000000000001UL)]), + import_buffer: (planes, modifier, w, h, fourcc, flip) => { + g.imported.push((planes.length(), modifier, w, h, fourcc, flip)) + if fourcc == XR24 { 40U + g.imported.length().reinterpret_as_uint() } else { 0U } + }, + capture: id => { + g.captured.push(id) + 7000U + g.captured.length().reinterpret_as_uint() + }, + release: id => g.released.push(id), + } + g +} + +///| create_params, add one plane, create_immed: the wl_buffer. +fn dmabuf_buffer(c : TestWaylandClient, dmabuf : UInt, fourcc : UInt, flags : UInt) -> UInt { + let params = c.alloc_id() + let a = @wayland.WireWriter::new() + a.u32(params) + c.send(a.finish_msg(dmabuf, 1U)) + let fd = @sys.memfd_create("plane", 4096) + let p = @wayland.WireWriter::new() + p.u32(0U) + p.u32(0U) + p.u32(1280U) + p.u32(0x01000000U) + p.u32(1U) + c.send(p.finish_msg(params, 1U), send_fd=fd) + @sys.close_fd(fd) + let buf = c.alloc_id() + let b = @wayland.WireWriter::new() + b.u32(buf) + b.i32(320) + b.i32(200) + b.u32(fourcc) + b.u32(flags) + c.send(b.finish_msg(params, 3U)) + c.send(@wayland.WireWriter::new().finish_msg(params, 0U)) + buf +} + +///| +test "dmabuf buffers show their window and are released at once" { + let socket_path = "/tmp/wayland-moon-dmabuf-" + @sys.getpid().to_string() + ".sock" + let comp = @host.ChandraCompositor::new(socket_path, @scene.ThemeTokens::moon_night(), 1280, 720).unwrap() + let gpu = with_fake_gpu(comp) + let (c, shm, surf, xdg, _tl, _deco) = open_and_configure_client(comp, socket_path, "T", "t") + commit_shm_frame(comp, c, shm, surf, xdg, 1UL) + let dmabuf = bind_global(c, 2U, "zwp_linux_dmabuf_v1", 4U) + let buf = dmabuf_buffer(c, dmabuf, XR24, 1U) + attach_commit(comp, c, surf, Some(buf)) + pump(comp, 3) + assert_eq(gpu.imported.length(), 1) + let (planes, modifier, w, h, fourcc, flip) = gpu.imported[0] + assert_eq(planes, 1) + assert_eq(modifier, 0x0100000000000001UL) + assert_eq((w, h), (320, 200)) + assert_eq(fourcc, XR24) + assert_true(flip) + assert_eq(gpu.captured, [41U]) + let s = comp.windows.get(1UL).unwrap().surface.unwrap() + assert_eq((s.width, s.height, s.format, s.host_id), (320, 200, 1, 7001U)) + // Destroying the wl_buffer forgets the import. + c.send(@wayland.WireWriter::new().finish_msg(buf, 0U)) + pump(comp, 2) + assert_eq(gpu.released, [41U]) + // A buffer the GPU can't read shows nothing and breaks nothing. + let bad = dmabuf_buffer(c, dmabuf, 0x3231564eU, 0U) + attach_commit(comp, c, surf, Some(bad)) + pump(comp, 3) + assert_eq(gpu.imported.length(), 2) + assert_eq(gpu.captured.length(), 1) + assert_eq(comp.windows.get(1UL).unwrap().surface.unwrap().host_id, 7001U) + // The client going away releases what it left. + ignore(dmabuf_buffer(c, dmabuf, XR24, 0U)) + pump(comp, 2) + assert_eq(gpu.imported.length(), 3) + @sys.close_fd(c.fd) + pump(comp, 3) + assert_eq(gpu.released, [41U, 43U]) + comp.close() +} + +///| +test "no dmabuf global without a GPU" { + let socket_path = "/tmp/wayland-moon-nodmabuf-" + @sys.getpid().to_string() + ".sock" + let comp = @host.ChandraCompositor::new(socket_path, @scene.ThemeTokens::moon_night(), 1280, 720).unwrap() + assert_eq(comp.server.dmabuf_formats().1.length(), 0) + comp.close() +} diff --git a/compositor/kms/kms_stub.c b/compositor/kms/kms_stub.c index 774d89c..9cbca69 100644 --- a/compositor/kms/kms_stub.c +++ b/compositor/kms/kms_stub.c @@ -130,6 +130,7 @@ struct fbuf { uint32_t handle, fb, pitch; size_t size; uint8_t *map; + int dmabuf; /* 1 + its fd as a dmabuf (for a GPU to draw into), 0 not exported yet, -1 can't be */ }; static int g_drm = -1; @@ -792,6 +793,9 @@ static void copy_rows(struct fbuf *b, const uint8_t *src, int w, int x0, int y0, MOONBIT_FFI_EXPORT int32_t mp_kms_present(moonbit_bytes_t pixels, int32_t w, int32_t h); +/* Show the back buffer (below). */ +int32_t mp_kms_flip(void); + /* Show an RGBA8888 frame of which only (dx, dy, dw, dh) changed since the last call: only what the * back buffer is missing is copied into it (the change now, and the one shown last time). */ MOONBIT_FFI_EXPORT @@ -810,10 +814,53 @@ int32_t mp_kms_present_damage(moonbit_bytes_t pixels, int32_t w, int32_t h, int3 int sx0 = s[0] < 0 ? 0 : s[0], sy0 = s[1] < 0 ? 0 : s[1]; int sx1 = s[2] > cw ? cw : s[2], sy1 = s[3] > ch ? ch : s[3]; if (sx0 < sx1 && sy0 < sy1) copy_rows(b, (const uint8_t *)pixels, w, sx0, sy0, sx1, sy1); + return mp_kms_flip(); +} + +/* ---- frames drawn by the GPU straight into the scanout buffers (the wasm host's rasteriser) ---- */ + +/* The frame changed there: every buffer is now missing it. */ +MOONBIT_FFI_EXPORT +void mp_kms_add_damage(int32_t x, int32_t y, int32_t w, int32_t h) { + if (w > 0 && h > 0) stale_add(x, y, x + w, y + h); +} + +/* The buffer to draw the next w x h frame into. Returns its index (0 or 1), -1 when no frame can be + * shown now, -2 when the display's buffers can't be shared with a GPU. info: dmabuf fd, pitch, + * width and height in pixels, scale, rotation; missing: x0, y0, x1, y1 of the frame it lacks. */ +MOONBIT_FFI_EXPORT +int32_t mp_kms_back_buffer(int32_t w, int32_t h, int32_t *info, int32_t *missing) { + if (w != g_width || h != g_height) return -1; + if (!g_seat_enabled || g_flip_pending || g_blank) return -1; + int back = 1 - g_front; + struct fbuf *b = &g_fb[back]; + if (b->dmabuf == 0) { + int fd = -1; + if (drmPrimeHandleToFD(g_drm, b->handle, DRM_CLOEXEC | DRM_RDWR, &fd) < 0) { + fprintf(stderr, "kms: cannot share the framebuffers with the GPU: %s\n", strerror(errno)); + b->dmabuf = -1; + } else { + b->dmabuf = fd + 1; + } + } + if (b->dmabuf < 0) return -2; + info[0] = b->dmabuf - 1; info[1] = (int32_t)b->pitch; info[2] = g_phys_w; info[3] = g_phys_h; + info[4] = g_scale > 1 ? g_scale : 1; info[5] = g_rot; + const int *s = g_stale[back]; + missing[0] = s[0] < 0 ? 0 : s[0]; missing[1] = s[1] < 0 ? 0 : s[1]; + missing[2] = s[2] > w ? w : s[2]; missing[3] = s[3] > h ? h : s[3]; + return back; +} + +/* Show the buffer mp_kms_back_buffer gave. */ +MOONBIT_FFI_EXPORT +int32_t mp_kms_flip(void) { + int back = 1 - g_front; + int *s = g_stale[back]; s[0] = s[1] = s[2] = s[3] = 0; - if (drmModePageFlip(g_drm, g_crtc, b->fb, DRM_MODE_PAGE_FLIP_EVENT, NULL) < 0) { + if (drmModePageFlip(g_drm, g_crtc, g_fb[back].fb, DRM_MODE_PAGE_FLIP_EVENT, NULL) < 0) { /* Fall back to a synchronous set. */ - if (drmModeSetCrtc(g_drm, g_crtc, b->fb, 0, 0, &g_conn, 1, &g_mode) < 0) return -1; + if (drmModeSetCrtc(g_drm, g_crtc, g_fb[back].fb, 0, 0, &g_conn, 1, &g_mode) < 0) return -1; } else { g_flip_pending = 1; } diff --git a/compositor/shell/render_mode.mbt b/compositor/shell/render_mode.mbt index a7cfc65..51ab06c 100644 --- a/compositor/shell/render_mode.mbt +++ b/compositor/shell/render_mode.mbt @@ -1,9 +1,8 @@ ///| Software or hardware rendering: whether this machine has a GPU that apps can draw with. /// -/// Chandra itself always draws the desktop on the CPU (the host's rasteriser), so the GPU never -/// makes the compositor's own frames cheaper. What it changes is how much CPU is left over: with -/// a GPU, apps (browsers, video, games) draw there; without one they draw with llvmpipe or their -/// own software paths on the same cores as Chandra. So in software mode the desktop asks for +/// The host draws the desktop on the GPU when it can (wasmhost/bin/raster_gpu.c decides that on its +/// own, docs/rendering.md) and apps draw there too; without one both are software on the same +/// cores. So in software mode the desktop asks for /// less: window previews are remade less often while they are on screen, and a desktop module /// (Live Starfield) gets at most 30 frames a second. /// diff --git a/compositor/sys/sys_native.mbt b/compositor/sys/sys_native.mbt index f0180c4..d6c1649 100644 --- a/compositor/sys/sys_native.mbt +++ b/compositor/sys/sys_native.mbt @@ -353,6 +353,33 @@ pub fn surface_capture(_fd : Int, _offset : Int, _stride : Int, _width : Int, _h 0U } +///| No GPU buffers on the native build, which draws on the CPU. +pub fn dmabuf_support() -> (UInt64, Array[(UInt, UInt64)]) { + (0UL, []) +} + +///| +pub fn dmabuf_import( + _planes : Array[(Int, UInt, UInt)], + _modifier : UInt64, + _width : Int, + _height : Int, + _fourcc : UInt, + _y_invert : Bool, +) -> UInt { + 0U +} + +///| +pub fn dmabuf_capture(_id : UInt) -> UInt { + 0U +} + +///| +pub fn dmabuf_release(_id : UInt) -> Unit { + () +} + ///| pub fn surface_release(_id : UInt) -> Unit { () diff --git a/compositor/sys/sys_wasm.mbt b/compositor/sys/sys_wasm.mbt index 1bca4ce..add503a 100644 --- a/compositor/sys/sys_wasm.mbt +++ b/compositor/sys/sys_wasm.mbt @@ -255,6 +255,37 @@ pub fn surface_capture(fd : Int, offset : Int, stride : Int, width : Int, height @hostraster.capture(fd, offset, stride, width, height, format) } +///| The GPU clients should draw on (its dev_t) and the buffers (DRM fourcc, modifier) the host takes +/// from it; none when the host draws on the CPU. +pub fn dmabuf_support() -> (UInt64, Array[(UInt, UInt64)]) { + let s = @hostraster.dmabufs() + (s.device, s.formats.map(f => (f.fourcc, f.modifier))) +} + +///| Import a client's GPU buffer (planes: fd, offset, stride; the fds stay the caller's). 0 when the +/// GPU can't read it. +pub fn dmabuf_import( + planes : Array[(Int, UInt, UInt)], + modifier : UInt64, + width : Int, + height : Int, + fourcc : UInt, + y_invert : Bool, +) -> UInt { + let planes : Array[@hostraster.DmabufPlane] = planes.map(p => { fd: p.0, offset: p.1, stride: p.2 }) + @hostraster.import_dmabuf(planes, modifier, width, height, fourcc, y_invert) +} + +///| What an imported buffer holds now, as a surface (like `surface_capture`). 0 on failure. +pub fn dmabuf_capture(id : UInt) -> UInt { + @hostraster.capture_dmabuf(id) +} + +///| +pub fn dmabuf_release(id : UInt) -> Unit { + @hostraster.release_dmabuf(id) +} + ///| Forget a captured surface. pub fn surface_release(id : UInt) -> Unit { @hostraster.release(id) diff --git a/compositor/wayland/dmabuf.mbt b/compositor/wayland/dmabuf.mbt new file mode 100644 index 0000000..d505ffa --- /dev/null +++ b/compositor/wayland/dmabuf.mbt @@ -0,0 +1,296 @@ +///| zwp_linux_dmabuf_v1 (version 4): apps that draw on the GPU hand over the buffer they drew into, +/// and never copy a frame through shared memory. Without it Mesa's EGL and Vulkan fall back to +/// drawing on the CPU, whatever GPU the machine has. +/// +/// The buffers live in the host (`@sys.dmabuf_*`); here are only ids. At each commit the host +/// copies the buffer on the GPU and it is released at once, as an shm buffer is. The global is +/// only advertised when the host draws on a GPU that reads such buffers. + +///| What the server needs of the host's GPU (a fake one in tests). +pub(all) struct DmabufHost { + /// The dev_t of the GPU clients should draw on, and the (fourcc, modifier) pairs it reads; no + /// pairs when there is none. + support : () -> (UInt64, Array[(UInt, UInt64)]) + /// (planes as (fd, offset, stride), modifier, width, height, fourcc, upside down) -> id, 0 when + /// the GPU can't read it. The fds stay the caller's. + import_buffer : (Array[(Int, UInt, UInt)], UInt64, Int, Int, UInt, Bool) -> UInt + /// What the buffer holds now, as a host surface id; 0 on failure. + capture : (UInt) -> UInt + release : (UInt) -> Unit +} + +///| +fn DmabufHost::system() -> DmabufHost { + { + support: () => @sys.dmabuf_support(), + import_buffer: (p, m, w, h, f, y) => @sys.dmabuf_import(p, m, w, h, f, y), + capture: id => @sys.dmabuf_capture(id), + release: id => @sys.dmabuf_release(id), + } +} + +///| A zwp_linux_buffer_params_v1: the planes added so far (fd, plane, offset, stride). +struct DmabufParams { + planes : Array[(Int, UInt, UInt, UInt)] + mut modifier : UInt64 + mut used : Bool +} + +///| A wl_buffer made from dmabufs. `id` is the host's (0: the GPU can't read it, it shows nothing). +struct DmabufBuffer { + id : UInt + width : Int + height : Int + opaque : Bool +} + +///| DRM_FORMAT_XRGB8888 and XBGR8888: no alpha. +fn fourcc_opaque(f : UInt) -> Bool { + f == 0x34325258U || f == 0x34324258U +} + +///| +fn DmabufParams::close_fds(self : DmabufParams) -> Unit { + for p in self.planes { + @sys.close_fd(p.0) + } + self.planes.clear() +} + +///| +fn ClientConn::drop_dmabufs(self : ClientConn, host : DmabufHost) -> Unit { + for _, p in self.dmabuf_params { + p.close_fds() + } + for _, b in self.dmabuf_buffers { + if b.id != 0U { + (host.release)(b.id) + } + } + self.dmabuf_params.clear() + self.dmabuf_buffers.clear() +} + +///| The formats the GPU reads, asked of the host once. +pub fn WaylandServer::dmabuf_formats(self : WaylandServer) -> (UInt64, Array[(UInt, UInt64)]) { + match self.dmabuf_support { + Some(s) => s + None => { + let s = (self.dmabuf_host.support)() + self.dmabuf_support = Some(s) + s + } + } +} + +///| What a client that bound the global learns: before version 4 the formats right away (after it +/// a feedback object tells, below). +fn WaylandServer::dmabuf_bound(self : WaylandServer, c : ClientConn, id : UInt, ver : UInt) -> Unit { + if ver >= 4U { + return + } + let told : Map[UInt, Bool] = {} + for f in self.dmabuf_formats().1 { + if ver >= 3U { + let w = WireWriter::new() + w.u32(f.0) + w.u32((f.1 >> 32).to_uint()) + w.u32((f.1 & 0xffffffffUL).to_uint()) + c.send_msg(w.finish_msg(id, 1U)) // modifier + } else if !told.contains(f.0) { + told.set(f.0, true) + let w = WireWriter::new() + w.u32(f.0) + c.send_msg(w.finish_msg(id, 0U)) // format + } + } +} + +///| +fn dev_array(dev : UInt64) -> Array[Byte] { + Array::makei(8, i => ((dev >> (i * 8)) & 0xffUL).to_byte()) +} + +///| zwp_linux_dmabuf_feedback_v1: the GPU to draw on and the formats to draw in, one tranche. The +/// same for every surface. +fn WaylandServer::dmabuf_feedback(self : WaylandServer, c : ClientConn, id : UInt) -> Unit { + let (dev, formats) = self.dmabuf_formats() + let table : Array[Byte] = [] + let indices : Array[Byte] = [] + for i, f in formats { + for k = 0; k < 4; k = k + 1 { + table.push(((f.0 >> (k * 8)) & 0xffU).to_byte()) + } + for _ in 0..<4 { + table.push(b'\x00') + } + table.append(dev_array(f.1)) + indices.push((i & 0xff).to_byte()) + indices.push((i >> 8).to_byte()) + } + let fd = @sys.memfd_create("chandra-dmabuf-formats", table.length()) + if fd < 0 { + return + } + ignore(@sys.pwrite_bytes(fd, Bytes::from_array(table), 0)) + let w = WireWriter::new() + w.u32(table.length().reinterpret_as_uint()) + if c.alive { + ignore(@sys.sendmsg_fd(c.fd, w.finish_msg(id, 1U), fd)) // format_table + } + @sys.close_fd(fd) + let w = WireWriter::new() + w.array(dev_array(dev)) + c.send_msg(w.finish_msg(id, 2U)) // main_device + let w = WireWriter::new() + w.array(dev_array(dev)) + c.send_msg(w.finish_msg(id, 4U)) // tranche_target_device + let w = WireWriter::new() + w.u32(0U) + c.send_msg(w.finish_msg(id, 6U)) // tranche_flags + let w = WireWriter::new() + w.array(indices) + c.send_msg(w.finish_msg(id, 5U)) // tranche_formats + c.send_msg(WireWriter::new().finish_msg(id, 3U)) // tranche_done + c.send_msg(WireWriter::new().finish_msg(id, 0U)) // done +} + +///| A request on the zwp_linux_dmabuf_v1 `obj_id`. +fn WaylandServer::dmabuf_request( + self : WaylandServer, + c : ClientConn, + obj_id : UInt, + opcode : UInt, + reader : WireReader, +) -> Unit { + match opcode { + 0U => { + c.objects.remove(obj_id) + send_delete_id(c, obj_id) + } + 1U => { + // create_params(id) + let id = reader.u32() + c.objects.set(id, ObjDmabufParams(id)) + c.dmabuf_params.set(id, { planes: [], modifier: 0UL, used: false }) + } + 2U | 3U => { + // get_default_feedback(id), get_surface_feedback(id, surface) + let id = reader.u32() + c.objects.set(id, ObjDmabufFeedback) + self.dmabuf_feedback(c, id) + } + _ => () + } +} + +///| A request on the zwp_linux_buffer_params_v1 `id`. +fn WaylandServer::dmabuf_params_request( + self : WaylandServer, + c : ClientConn, + id : UInt, + opcode : UInt, + reader : WireReader, +) -> Unit { + guard c.dmabuf_params.get(id) is Some(p) else { return } + match opcode { + 0U => { + p.close_fds() + c.dmabuf_params.remove(id) + c.objects.remove(id) + send_delete_id(c, id) + } + 1U => { + // add(fd: out-of-band, plane_idx, offset, stride, modifier_hi, modifier_lo) + let fd = c.take_fd() + let plane = reader.u32() + let offset = reader.u32() + let stride = reader.u32() + let hi = reader.u32() + let lo = reader.u32() + if fd < 0 { + return + } + if p.used || plane > 3U || p.planes.iter().any(q => q.1 == plane) { + @sys.close_fd(fd) + return + } + p.planes.push((fd, plane, offset, stride)) + p.modifier = (hi.to_uint64() << 32) | lo.to_uint64() + } + 2U | 3U => { + // create(width, height, format, flags), create_immed(buffer_id, width, height, format, flags) + let immed = opcode == 3U + let want = if immed { reader.u32() } else { 0U } + let width = reader.i32() + let height = reader.i32() + let fourcc = reader.u32() + let flags = reader.u32() + p.planes.sort_by((a, b) => a.1.compare(b.1)) + let planes = p.planes.map(q => (q.0, q.2, q.3)) + let contiguous = p.planes.length() > 0 && + p.planes[p.planes.length() - 1].1.reinterpret_as_int() == p.planes.length() - 1 + // flags: 1 upside down, 2 interlaced, 4 bottom field first. + let got = if p.used || !contiguous || width <= 0 || height <= 0 || (flags & 6U) != 0U { + 0U + } else { + (self.dmabuf_host.import_buffer)(planes, p.modifier, width, height, fourcc, (flags & 1U) != 0U) + } + p.used = true + p.close_fds() + if got == 0U { + @sys.log( + "dmabuf: can't use a client's buffer (\{width}x\{height}, format 0x\{fourcc.to_string(radix=16)}, modifier 0x\{p.modifier.to_string(radix=16)}, \{planes.length()} planes)", + ) + if !immed { + c.send_msg(WireWriter::new().finish_msg(id, 1U)) // failed + return + } + } + let buf = if immed { + want + } else { + let b = c.next_offer // any id of the server's + c.next_offer = b + 1U + b + } + c.objects.set(buf, ObjBuffer(buf)) + c.dmabuf_buffers.set(buf, { id: got, width, height, opaque: fourcc_opaque(fourcc) }) + if !immed { + let w = WireWriter::new() + w.u32(buf) + c.send_msg(w.finish_msg(id, 0U)) // created + } + } + _ => () + } +} + +///| The wl_buffer `buf_id` was destroyed. +fn WaylandServer::dmabuf_buffer_gone(self : WaylandServer, c : ClientConn, buf_id : UInt) -> Unit { + match c.dmabuf_buffers.get(buf_id) { + Some(b) => { + if b.id != 0U { + (self.dmabuf_host.release)(b.id) + } + c.dmabuf_buffers.remove(buf_id) + } + None => () + } +} + +///| What the dmabuf buffer `b` holds now, as `snapshot_buffer` gives it. +fn WaylandServer::snapshot_dmabuf(self : WaylandServer, b : DmabufBuffer) -> @scene.ShmBufferSnapshot? { + let id = if b.id == 0U { 0U } else { (self.dmabuf_host.capture)(b.id) } + if id == 0U { + return None + } + Some({ + width: b.width, + height: b.height, + stride: b.width * 4, + format: if b.opaque { 1 } else { 0 }, + bytes: Bytes::make(0, b'\x00'), + host_id: id, + }) +} diff --git a/compositor/wayland/dnd.mbt b/compositor/wayland/dnd.mbt index 05fc6c6..59fad2f 100644 --- a/compositor/wayland/dnd.mbt +++ b/compositor/wayland/dnd.mbt @@ -509,7 +509,7 @@ fn WaylandServer::dnd_icon_commit( } match surf.attached_buffer { Some(bid) => - match snapshot_shm_buffer(c, bid) { + match self.snapshot_buffer(c, bid) { Some(snap) => events.push(DragIcon(Some(snap), d.icon_x, d.icon_y)) None => () } diff --git a/compositor/wayland/server.mbt b/compositor/wayland/server.mbt index a1e102d..75c6d18 100644 --- a/compositor/wayland/server.mbt +++ b/compositor/wayland/server.mbt @@ -106,6 +106,10 @@ enum ObjKind { /// zwp_text_input_manager_v3 and its zwp_text_input_v3 objects (text_input.mbt). ObjTextInputMgr ObjTextInput + /// zwp_linux_dmabuf_v1, a zwp_linux_buffer_params_v1 and a feedback object (dmabuf.mbt). + ObjDmabuf + ObjDmabufParams(UInt) + ObjDmabufFeedback } ///| @@ -223,6 +227,8 @@ struct ClientConn { surfaces : Map[UInt, SurfaceState] shm_pools : Map[UInt, ShmPoolState] shm_buffers : Map[UInt, ShmBufferState] + dmabuf_params : Map[UInt, DmabufParams] + dmabuf_buffers : Map[UInt, DmabufBuffer] xdg_surfaces : Map[UInt, XdgSurfaceState] subsurfaces : Map[UInt, SubState] toplevels : Map[UInt64, ToplevelState] @@ -267,6 +273,8 @@ fn ClientConn::new(client_id : UInt, fd : Int) -> ClientConn { surfaces: {}, shm_pools: {}, shm_buffers: {}, + dmabuf_params: {}, + dmabuf_buffers: {}, xdg_surfaces: {}, subsurfaces: {}, toplevels: {}, @@ -384,6 +392,9 @@ pub(all) struct WaylandServer { /// so clients stop drawing frames nobody sees: (client id, callback id), sent on release. mut hold_frames : Bool held_frames : Array[(UInt, UInt)] + /// Client buffers on the GPU (dmabuf.mbt): the host's side, and what it supports once asked. + mut dmabuf_host : DmabufHost + mut dmabuf_support : (UInt64, Array[(UInt, UInt64)])? } ///| @@ -422,6 +433,8 @@ pub fn WaylandServer::listen( drop_pending: None, hold_frames: false, held_frames: [], + dmabuf_host: DmabufHost::system(), + dmabuf_support: None, }) } @@ -456,6 +469,7 @@ pub fn WaylandServer::close(self : WaylandServer) -> Unit { } self.transfers.clear() for c in self.clients { + c.drop_dmabufs(self.dmabuf_host) c.close_all() } self.clients.clear() @@ -471,7 +485,7 @@ fn WaylandServer::next_serial(self : WaylandServer) -> UInt { } ///| -fn emit_registry_globals(c : ClientConn, reg_id : UInt) -> Unit { +fn emit_registry_globals(c : ClientConn, reg_id : UInt, dmabuf : Bool) -> Unit { let globals : Array[(UInt, String, UInt)] = [ (1U, "wl_compositor", 5U), (2U, "wl_shm", 1U), @@ -486,6 +500,9 @@ fn emit_registry_globals(c : ClientConn, reg_id : UInt) -> Unit { (11U, "zwp_primary_selection_device_manager_v1", 1U), (12U, "zwp_text_input_manager_v3", 1U), ] + if dmabuf { + globals.push((13U, "zwp_linux_dmabuf_v1", 4U)) + } for g in globals { let w = WireWriter::new() w.u32(g.0) @@ -602,10 +619,15 @@ fn send_decoration_mode(c : ClientConn, deco_id : UInt, mode : UInt) -> Unit { } ///| -fn snapshot_shm_buffer( +fn WaylandServer::snapshot_buffer( + self : WaylandServer, c : ClientConn, buf_id : UInt, ) -> @scene.ShmBufferSnapshot? { + match c.dmabuf_buffers.get(buf_id) { + Some(b) => return self.snapshot_dmabuf(b) + None => () + } let buf = match c.shm_buffers.get(buf_id) { Some(b) => b None => return None @@ -676,7 +698,7 @@ fn WaylandServer::dispatch_msg( // get_registry(registry: new_id) let reg_id = reader.u32() c.objects.set(reg_id, ObjRegistry) - emit_registry_globals(c, reg_id) + emit_registry_globals(c, reg_id, self.dmabuf_formats().1.length() > 0) } ObjRegistry => if opcode == 0U { @@ -713,6 +735,9 @@ fn WaylandServer::dispatch_msg( c.objects.set(new_id, ObjPrimaryManager) } else if iface == "zwp_text_input_manager_v3" { c.objects.set(new_id, ObjTextInputMgr) + } else if iface == "zwp_linux_dmabuf_v1" { + c.objects.set(new_id, ObjDmabuf) + self.dmabuf_bound(c, new_id, ver) } else if iface == "wl_subcompositor" { c.objects.set(new_id, ObjSubcompositor) } else if iface == "wl_output" { @@ -798,7 +823,7 @@ fn WaylandServer::dispatch_msg( } else { match surf.attached_buffer { Some(bid) => - match snapshot_shm_buffer(c, bid) { + match self.snapshot_buffer(c, bid) { Some(snap) => events.push(SubsurfaceCommitted(wid, sid, ax, ay, Some(snap))) None => () } @@ -815,7 +840,7 @@ fn WaylandServer::dispatch_msg( Some(tl) => if tl.popup_parent is Some(_) { let snap = match surf.attached_buffer { - Some(bid) => snapshot_shm_buffer(c, bid) + Some(bid) => self.snapshot_buffer(c, bid) None => None } events.push(PopupCommitted(wid, snap)) @@ -832,7 +857,7 @@ fn WaylandServer::dispatch_msg( ) } else { let snap = match surf.attached_buffer { - Some(bid) => snapshot_shm_buffer(c, bid) + Some(bid) => self.snapshot_buffer(c, bid) None => None } if snap is Some(_) { @@ -1213,6 +1238,7 @@ fn WaylandServer::dispatch_msg( None => None } c.shm_buffers.remove(buf_id) + self.dmabuf_buffer_gone(c, buf_id) c.objects.remove(buf_id) send_delete_id(c, buf_id) match pool_id { @@ -1220,6 +1246,13 @@ fn WaylandServer::dispatch_msg( None => () } } + ObjDmabuf => self.dmabuf_request(c, obj_id, opcode, reader) + ObjDmabufParams(id) => self.dmabuf_params_request(c, id, opcode, reader) + ObjDmabufFeedback => + if opcode == 0U { + c.objects.remove(obj_id) + send_delete_id(c, obj_id) + } ObjXdgWmBase => if opcode == 0U { c.objects.remove(obj_id) @@ -1723,6 +1756,7 @@ pub fn WaylandServer::poll_events( self.win_to_client.remove(wid) events.push(ToplevelClosed(wid)) } + c.drop_dmabufs(self.dmabuf_host) c.close_all() self.dnd_client_gone(c.client_id, events) if self.kbd_client == Some(c.client_id) { diff --git a/docs/rendering.md b/docs/rendering.md index d1d1835..025d6db 100644 --- a/docs/rendering.md +++ b/docs/rendering.md @@ -1,14 +1,52 @@ # Rendering, animations and machines without a GPU -Chandra draws the desktop on the CPU on every machine: the host (build/wasmhost) -rasterises each frame into its own framebuffer and hands it to the display (KMS, X11, a -nested Wayland window). A GPU never makes Chandra's own frames cheaper. What it changes is how -much CPU is left: with a GPU, apps (browsers, video, games) draw there; without one they draw -with llvmpipe or their own software paths on the same cores as Chandra. +On a machine with a GPU the host (build/wasmhost) draws the desktop on it, and apps hand over the +buffers they drew on it. Anywhere else the host rasterises each frame on the CPU and apps use shared +memory, as before. The component never knows the difference: it sends the same draw operations. + +## Drawing on the GPU + +At start the host looks for a GPU and logs it (or why there is none): + + gpu: drawing on Mesa Intel(R) HD Graphics 4600 (HSW GT2) + +- **The desktop** (`wasmhost/bin/raster_gpu.c`): OpenGL ES 3 on a DRM render node, with libEGL and + libGLESv2 loaded at run time, so neither is needed to build or to run without a GPU. It takes + raster_stub.c's calls and draws the same shapes (within rounding), into a texture that keeps its + contents, so only damage is redrawn. +- **The display** (`--drm`): the finished frame is drawn into the display's own buffers (the DRM dumb + buffers, shared as dmabufs), scaled and turned as the output is. When the GPU can't draw there, + the frame is read back and copied, which works on any display. +- **A nested window, X11, screenshots, recordings, the remote mirror** need the pixels on the CPU: the + part that changed is read back when one of them asks. +- **Apps** (`compositor/wayland/dmabuf.mbt`): `zwp_linux_dmabuf_v1` version 4. Without it Mesa's EGL and + Vulkan draw on the CPU whatever GPU there is. A committed buffer is copied on the GPU and + released at once. Formats: 8-bit RGB with or without alpha, in every layout the driver samples. + +Which GPU: the first render node whose driver is a real one (the list below), or the one +`CHANDRA_RENDER_NODE` names. `CHANDRA_GPU=0`, `CHANDRA_RENDER=software` and `LIBGL_ALWAYS_SOFTWARE=1` +keep to the CPU. `CHANDRA_GPU=1` takes whatever OpenGL there is (a virtual machine's, llvmpipe, +NVIDIA's). NVIDIA's proprietary driver is not used by itself: the code relies on implicit sync +(the kernel ordering buffer use), which that driver lacks. + +If a login session dies within seconds of first drawing on the display with the GPU, the next one +keeps to the CPU once (`~/.local/state/chandra/gpu-starting`). + +Not done: handing an app's buffer to the display without any copy, dmabufs to the host compositor +when nested, recovering from a GPU reset, OpenGL ES 2 only GPUs (they use the CPU). + +`scripts/test-gpu.sh` (`just test-gpu`) compares both rasterisers on this machine's GPU and draws +through real display buffers, without needing a free display. + +On an HD 4600 (Haswell), 1920x1080, median time to rasterise a frame, CPU then GPU: the overview +gliding with four windows 8 ms, 1 ms; a full-screen terminal scrolling 8 ms, 3 ms. alacritty (OpenGL) +scrolling: 7 frames a second drawing in software, 42 on the GPU. vkcube (Vulkan) showed +no frames at all without dmabufs, and 57 a second with them. ## Software or hardware mode -At start Chandra looks for a GPU and logs what it decided: +Apart from where the pixels are drawn, the shell asks less of a machine without a GPU. At start it +looks for one and logs what it decided: rendering: software (no GPU found) rendering: hardware (GPU: amdgpu) diff --git a/interface/chandra/host/raster/ffi.mbt b/interface/chandra/host/raster/ffi.mbt index 90f8c48..6fb80be 100644 --- a/interface/chandra/host/raster/ffi.mbt +++ b/interface/chandra/host/raster/ffi.mbt @@ -6,6 +6,18 @@ fn wasmImportCapture(p0 : Int, p1 : Int, p2 : Int, p3 : Int, p4 : Int, p5 : Int) ///| fn wasmImportRelease(p0 : Int) = "chandra:host/raster@0.1.0" "release" +///| +fn wasmImportDmabufs(p0 : Int) = "chandra:host/raster@0.1.0" "dmabufs" + +///| +fn wasmImportImportDmabuf(p0 : Int, p1 : Int, p2 : Int64, p3 : Int, p4 : Int, p5 : Int, p6 : Int) -> Int = "chandra:host/raster@0.1.0" "import-dmabuf" + +///| +fn wasmImportCaptureDmabuf(p0 : Int) -> Int = "chandra:host/raster@0.1.0" "capture-dmabuf" + +///| +fn wasmImportReleaseDmabuf(p0 : Int) = "chandra:host/raster@0.1.0" "release-dmabuf" + ///| fn wasmImportLoadImage(p0 : Int, p1 : Int) -> Int = "chandra:host/raster@0.1.0" "load-image" @@ -51,33 +63,19 @@ fn wasmImportSnapshotPng(p0 : Int, p1 : Int, p2 : Int, p3 : Int, p4 : Int) = "c ///| fn wasmImportSnapshotPixels(p0 : Int, p1 : Int, p2 : Int, p3 : Int, p4 : Int, p5 : Int, p6 : Int) = "chandra:host/raster@0.1.0" "snapshot-pixels" -///| -extern "wasm" fn mbt_ffi_free(position : Int) = -#|(func (param i32) local.get 0 call $moonbit.decref) - -///| -extern "wasm" fn mbt_ffi_ptr2str(ptr : Int, len : Int) -> String = -#|(func (param i32) (param i32) (result i32) -#| local.get 0 -#| local.get 1 call $moonbit.init_array16 -#| local.get 0) - ///| #owned(bytes) extern "wasm" fn mbt_ffi_bytes2ptr(bytes : FixedArray[Byte]) -> Int = #|(func (param i32) (result i32) local.get 0) ///| -extern "wasm" fn mbt_ffi_load8_u(offset : Int) -> Int = -#|(func (param i32) (result i32) local.get 0 i32.load8_u) +extern "wasm" fn mbt_ffi_load64(offset : Int) -> Int64 = +#|(func (param i32) (result i64) local.get 0 i64.load) ///| -extern "wasm" fn mbt_ffi_store8(offset : Int, value : Int) = -#|(func (param i32) (param i32) local.get 0 local.get 1 i32.store8) - -///| -extern "wasm" fn mbt_ffi_store32(offset : Int, value : Int) = -#|(func (param i32) (param i32) local.get 0 local.get 1 i32.store) +#owned(str) +extern "wasm" fn mbt_ffi_str2ptr(str : String) -> Int = +#|(func (param i32) (result i32) local.get 0) ///| extern "wasm" fn mbt_ffi_malloc(size : Int) -> Int = @@ -86,14 +84,25 @@ extern "wasm" fn mbt_ffi_malloc(size : Int) -> Int = #| local.tee 1 i32.const 0 call $moonbit.init_array8 #| local.get 1) +///| +extern "wasm" fn mbt_ffi_store8(offset : Int, value : Int) = +#|(func (param i32) (param i32) local.get 0 local.get 1 i32.store8) + +///| +extern "wasm" fn mbt_ffi_free(position : Int) = +#|(func (param i32) local.get 0 call $moonbit.decref) + ///| extern "wasm" fn mbt_ffi_load32(offset : Int) -> Int = #|(func (param i32) (result i32) local.get 0 i32.load) ///| -#owned(str) -extern "wasm" fn mbt_ffi_str2ptr(str : String) -> Int = -#|(func (param i32) (result i32) local.get 0) +extern "wasm" fn mbt_ffi_store32(offset : Int, value : Int) = +#|(func (param i32) (param i32) local.get 0 local.get 1 i32.store) + +///| +extern "wasm" fn mbt_ffi_load8_u(offset : Int) -> Int = +#|(func (param i32) (result i32) local.get 0 i32.load8_u) ///| extern "wasm" fn mbt_ffi_ptr2bytes(ptr : Int, len : Int) -> FixedArray[Byte] = @@ -102,3 +111,10 @@ extern "wasm" fn mbt_ffi_ptr2bytes(ptr : Int, len : Int) -> FixedArray[Byte] = #| local.get 1 call $moonbit.init_array8 #| local.get 0) +///| +extern "wasm" fn mbt_ffi_ptr2str(ptr : Int, len : Int) -> String = +#|(func (param i32) (param i32) (result i32) +#| local.get 0 +#| local.get 1 call $moonbit.init_array16 +#| local.get 0) + diff --git a/interface/chandra/host/raster/native_stub.mbt b/interface/chandra/host/raster/native_stub.mbt index f8ee8d9..064b2af 100644 --- a/interface/chandra/host/raster/native_stub.mbt +++ b/interface/chandra/host/raster/native_stub.mbt @@ -10,6 +10,26 @@ fn wasmImportRelease(p0 : Int) -> Unit { abort("wasm-only host import") } +///| +fn wasmImportDmabufs(p0 : Int) -> Unit { + abort("wasm-only host import") +} + +///| +fn wasmImportImportDmabuf(p0 : Int, p1 : Int, p2 : Int64, p3 : Int, p4 : Int, p5 : Int, p6 : Int) -> Int { + abort("wasm-only host import") +} + +///| +fn wasmImportCaptureDmabuf(p0 : Int) -> Int { + abort("wasm-only host import") +} + +///| +fn wasmImportReleaseDmabuf(p0 : Int) -> Unit { + abort("wasm-only host import") +} + ///| fn wasmImportLoadImage(p0 : Int, p1 : Int) -> Int { abort("wasm-only host import") @@ -85,43 +105,13 @@ fn wasmImportSnapshotPixels(p0 : Int, p1 : Int, p2 : Int, p3 : Int, p4 : Int, p5 abort("wasm-only host import") } -///| -fn mbt_ffi_free(position : Int) -> Unit { - abort("wasm-only") -} - -///| -fn mbt_ffi_ptr2str(ptr : Int, len : Int) -> String { - abort("wasm-only") -} - ///| fn mbt_ffi_bytes2ptr(bytes : FixedArray[Byte]) -> Int { abort("wasm-only") } ///| -fn mbt_ffi_load8_u(offset : Int) -> Int { - abort("wasm-only") -} - -///| -fn mbt_ffi_store8(offset : Int, value : Int) -> Unit { - abort("wasm-only") -} - -///| -fn mbt_ffi_store32(offset : Int, value : Int) -> Unit { - abort("wasm-only") -} - -///| -fn mbt_ffi_malloc(size : Int) -> Int { - abort("wasm-only") -} - -///| -fn mbt_ffi_load32(offset : Int) -> Int { +fn mbt_ffi_load64(offset : Int) -> Int64 { abort("wasm-only") } @@ -130,7 +120,42 @@ fn mbt_ffi_str2ptr(str : String) -> Int { abort("wasm-only") } +///| +fn mbt_ffi_malloc(size : Int) -> Int { + abort("wasm-only") +} + +///| +fn mbt_ffi_store8(offset : Int, value : Int) -> Unit { + abort("wasm-only") +} + +///| +fn mbt_ffi_free(position : Int) -> Unit { + abort("wasm-only") +} + +///| +fn mbt_ffi_load32(offset : Int) -> Int { + abort("wasm-only") +} + +///| +fn mbt_ffi_store32(offset : Int, value : Int) -> Unit { + abort("wasm-only") +} + +///| +fn mbt_ffi_load8_u(offset : Int) -> Int { + abort("wasm-only") +} + ///| fn mbt_ffi_ptr2bytes(ptr : Int, len : Int) -> FixedArray[Byte] { abort("wasm-only") } + +///| +fn mbt_ffi_ptr2str(ptr : Int, len : Int) -> String { + abort("wasm-only") +} diff --git a/interface/chandra/host/raster/pkg.generated.mbti b/interface/chandra/host/raster/pkg.generated.mbti index a78fea8..673e459 100644 --- a/interface/chandra/host/raster/pkg.generated.mbti +++ b/interface/chandra/host/raster/pkg.generated.mbti @@ -4,6 +4,10 @@ package "chandra/desktop/interface/chandra/host/raster" // Values pub fn capture(Int32, Int32, Int32, Int32, Int32, Int32) -> UInt32 +pub fn capture_dmabuf(UInt32) -> UInt32 + +pub fn dmabufs() -> DmabufSupport + pub fn emoji_font() -> Result[String, String] pub fn emoji_has(Array[String]) -> Array[Bool] @@ -16,12 +20,16 @@ pub fn grab_recording_frame(Int32, Int32, Int32, Int32, Bool, Int32, Int32) -> B pub fn image_pixels(Int32, Int32, FixedArray[Byte], UInt32) -> UInt32 +pub fn import_dmabuf(Array[DmabufPlane], UInt64, Int32, Int32, UInt32, Bool) -> UInt32 + pub fn load_image(String) -> UInt32 pub fn read_frame() -> FixedArray[Byte] pub fn release(UInt32) -> Unit +pub fn release_dmabuf(UInt32) -> Unit + pub fn send_recording_frame(Int32) -> Int32 pub fn snapshot_frame() -> Bool @@ -54,6 +62,22 @@ pub(all) struct Disc { filled : Bool } +pub(all) struct DmabufFormat { + fourcc : UInt32 + modifier : UInt64 +} + +pub(all) struct DmabufPlane { + fd : Int32 + offset : UInt32 + stride : UInt32 +} + +pub(all) struct DmabufSupport { + device : UInt64 + formats : Array[DmabufFormat] +} + pub(all) struct Fill { area : Rect color : Color diff --git a/interface/chandra/host/raster/top.mbt b/interface/chandra/host/raster/top.mbt index afdf799..36418e3 100644 --- a/interface/chandra/host/raster/top.mbt +++ b/interface/chandra/host/raster/top.mbt @@ -58,6 +58,22 @@ pub(all) struct Frame { width : Int; height : Int; wallpaper : Array[Op]?; background : Array[Op]; windows : Array[Window]; panel : Array[Op]; popups : Array[Popup] } ///| +/// Client buffers that live on the GPU (linux-dmabuf). A pixel format (DRM fourcc) and layout +/// (DRM modifier) the GPU reads. +pub(all) struct DmabufFormat { + fourcc : UInt; modifier : UInt64 +} +///| +/// `device`: the `dev_t` of the GPU clients should draw on. No formats: the host draws on the +/// CPU and takes no such buffers. +pub(all) struct DmabufSupport { + device : UInt64; formats : Array[DmabufFormat] +} +///| +pub(all) struct DmabufPlane { + fd : Int; offset : UInt; stride : UInt +} +///| /// Copy a client buffer (`stride * height` bytes at `offset` of the file behind `fd`) into a /// host surface. `format` is the wl_shm format (0 ARGB8888, 1 XRGB8888). 0 on failure. pub fn capture(fd : Int, offset : Int, stride : Int, width : Int, height : Int, format : Int) -> UInt { @@ -72,6 +88,59 @@ pub fn release(id : UInt) -> Unit { wasmImportRelease((id).reinterpret_as_int()); +} +///| +pub fn dmabufs() -> DmabufSupport { + + let return_area = mbt_ffi_malloc(16) + wasmImportDmabufs(return_area); + + let array : Array[DmabufFormat] = []; + for index = 0; index < (mbt_ffi_load32((return_area) + 12)); index = index + 1 { + let iter_base = (mbt_ffi_load32((return_area) + 8)) + (index * 16) + + array.push(DmabufFormat::{fourcc : (mbt_ffi_load32((iter_base) + 0)).reinterpret_as_uint(), modifier : (mbt_ffi_load64((iter_base) + 8)).reinterpret_as_uint64()}) + } + mbt_ffi_free(mbt_ffi_load32((return_area) + 8)) + let ret = DmabufSupport::{device : (mbt_ffi_load64((return_area) + 0)).reinterpret_as_uint64(), formats : array} + mbt_ffi_free(return_area) + return ret + +} +///| +/// Import a buffer (the fds stay the caller's to close). 0 when the GPU can't read it. +pub fn import_dmabuf(planes : Array[DmabufPlane], modifier : UInt64, width : Int, height : Int, fourcc : UInt, y_invert : Bool) -> UInt { + + let address = mbt_ffi_malloc((planes).length() * 12); + for index = 0; index < (planes).length(); index = index + 1 { + let iter_elem : DmabufPlane = (planes)[(index)] + let iter_base = address + (index * 12); + mbt_ffi_store32((iter_base) + 0, (iter_elem).fd) + mbt_ffi_store32((iter_base) + 4, ((iter_elem).offset).reinterpret_as_int()) + mbt_ffi_store32((iter_base) + 8, ((iter_elem).stride).reinterpret_as_int()) + + } + let result : Int = wasmImportImportDmabuf(address, (planes).length(), (modifier).reinterpret_as_int64(), width, height, (fourcc).reinterpret_as_int(), (if y_invert { 1 } else { 0 })); + let ret = (result).reinterpret_as_uint() + mbt_ffi_free(address) + return ret + +} +///| +/// What the buffer holds now as a surface, like `capture` (a copy on the GPU: the client may +/// draw into its buffer again at once). 0 on failure. +pub fn capture_dmabuf(id : UInt) -> UInt { + + let result : Int = wasmImportCaptureDmabuf((id).reinterpret_as_int()); + let ret = (result).reinterpret_as_uint() + return ret + +} +///| +pub fn release_dmabuf(id : UInt) -> Unit { + + wasmImportReleaseDmabuf((id).reinterpret_as_int()); + } ///| /// Decode the PNG or SVG file at `path` into a host image (an app icon), for `draw-image`. diff --git a/justfile b/justfile index dbf4c26..96a911e 100644 --- a/justfile +++ b/justfile @@ -162,6 +162,10 @@ test: modules emoji-font t *words: scripts/test-native.py {{words}} +# The GPU rasteriser against the CPU one on this machine's GPU (a few seconds; skips without one). +test-gpu: + scripts/test-gpu.sh + # Render one composed frame to _build/e2e_frame.png (via the e2e test). frame: modules scripts/test-native.py -p compositor/host e2e_test diff --git a/scripts/test-gpu.sh b/scripts/test-gpu.sh new file mode 100755 index 0000000..4bd42a0 --- /dev/null +++ b/scripts/test-gpu.sh @@ -0,0 +1,18 @@ +#!/usr/bin/env bash +# The GPU rasteriser (wasmhost/bin/raster_gpu.c) against the CPU one, on this machine's GPU; a few +# seconds. Skips (exit 0, saying so) on machines without one; CHANDRA_GPU=1 takes llvmpipe too. +# scripts/test-gpu.sh +set -euo pipefail +ROOT="$(cd "$(dirname "$0")/.." && pwd)"; cd "$ROOT" +PIXI="$ROOT/.pixi/envs/default" +mkdir -p _build +# raster_gpu.c is included, not linked: the test looks inside it. +cat > _build/gpu_test_all.c </dev/null; then done fi +step "the GPU rasteriser against the CPU one (skipped without a GPU)" +scripts/test-gpu.sh + step "face unlock (chandra-face with a fake camera; the PAM module through pamtester as root)" python3 face/test_face.py --pam diff --git a/wasmhost/README.md b/wasmhost/README.md index f3ab186..8faf9df 100644 --- a/wasmhost/README.md +++ b/wasmhost/README.md @@ -22,7 +22,9 @@ build/wasmhost build/compositor.wasm --socket PATH --gfx-out frame.png (`snapshot-*`, `*-recording-frame`, `write-frame-png` in `wit/host/raster.wit`). - `bin/`: the interfaces of `wit/host`. Most of it is the native compositor's own packages: `sys` is compositor/sys, glyphs come from compositor/font (stb_truetype). The rasteriser - (`raster.mbt`, pixel work in `raster_stub.c`) is a port of compositor/renderer; SVG icons + (`raster.mbt`, pixel work in `raster_stub.c`) is a port of compositor/renderer; with a GPU the + same calls draw on it (`raster_gpu.c`, OpenGL ES 3 loaded at run time; `scripts/test-gpu.sh` + compares the two; docs/rendering.md). SVG icons use nanosvg (`third_party/nanosvg`, patched for clip paths and masks). `plasmoids.mbt` runs panel modules through compositor/wasm (wasm.h, which libwasmtime provides); `display.mbt` is the login session's DRM/KMS output and input (compositor/kms). diff --git a/wasmhost/bin/main.mbt b/wasmhost/bin/main.mbt index 45f5c05..5617bb1 100644 --- a/wasmhost/bin/main.mbt +++ b/wasmhost/bin/main.mbt @@ -70,6 +70,7 @@ fn main { args.remove(0) |> ignore } c_ignore_sigchld() + ignore(rs_gpu_init(if args.contains("--drm") { 1 } else { 0 })) match @wt.load(path) { Ok(_) => () Err(e) => { diff --git a/wasmhost/bin/moon.pkg b/wasmhost/bin/moon.pkg index c0f4122..f18fe1e 100644 --- a/wasmhost/bin/moon.pkg +++ b/wasmhost/bin/moon.pkg @@ -24,7 +24,7 @@ pkgtype(kind: "executable") // looks for it there too (the rpath is relative to build/), not through LD_LIBRARY_PATH, which // apps started by the compositor would inherit. options( - "native-stub": [ "host_stub.c", "raster_stub.c" ], + "native-stub": [ "host_stub.c", "raster_stub.c", "raster_gpu.c" ], link: { "native": { "cc-link-flags": "-l:libwasmtime.a -lpthread -ldl -lm -ldrm -linput -lseat -lxkbcommon -ludev -Wl,-rpath,$ORIGIN/../.pixi/envs/default/lib", diff --git a/wasmhost/bin/raster.mbt b/wasmhost/bin/raster.mbt index c971ef3..81b21f3 100644 --- a/wasmhost/bin/raster.mbt +++ b/wasmhost/bin/raster.mbt @@ -2,6 +2,76 @@ /// surface ids; the pixels live here (raster_stub.c) and never cross the component boundary. /// What to draw where (layers, the wallpaper cache, damage) is decided here. +///| Look for a GPU to draw on (raster_gpu.c): 1 when there is one. Before anything else here. +/// `session` is 1 for a login session (--drm). +extern "C" fn rs_gpu_init(session : Int) -> Int = "rs_gpu_init" + +///| +extern "C" fn rs_dmabuf_device() -> UInt64 = "rs_dmabuf_device" + +///| +#borrow(out) +extern "C" fn rs_dmabuf_format(i : Int, out : FixedArray[Int]) -> Int = "rs_dmabuf_format" + +///| +#borrow(planes) +extern "C" fn rs_dmabuf_import( + n : Int, + planes : FixedArray[Int], + modifier : UInt64, + w : Int, + h : Int, + fourcc : UInt, + y_invert : Int, +) -> UInt = "rs_dmabuf_import" + +///| +extern "C" fn rs_dmabuf_release(id : UInt) = "rs_dmabuf_release" + +///| +extern "C" fn rs_dmabuf_capture(id : UInt) -> UInt = "rs_dmabuf_capture" + +///| `dmabufs`: the GPU clients should draw on and the buffers it reads. +fn dmabuf_support() -> @wt.Val { + let formats : Array[@wt.Val] = [] + let f = FixedArray::make(3, 0) + while rs_dmabuf_format(formats.length(), f) != 0 { + let modifier = f[1].reinterpret_as_uint().to_uint64() | + (f[2].reinterpret_as_uint().to_uint64() << 32) + formats.push( + Record([ + ("fourcc", U32(f[0].reinterpret_as_uint())), + ("modifier", U64(modifier)), + ]), + ) + } + Record([("device", U64(rs_dmabuf_device())), ("formats", List(formats))]) +} + +///| +fn import_dmabuf(a : Array[@wt.Val]) -> UInt { + let planes = a[0].to_list() + if planes.length() < 1 || planes.length() > 4 { + return 0U + } + let flat = FixedArray::make(planes.length() * 3, 0) + for i, p in planes { + flat[i * 3] = p.field("fd").to_int() + flat[i * 3 + 1] = p.field("offset").to_uint().reinterpret_as_int() + flat[i * 3 + 2] = p.field("stride").to_uint().reinterpret_as_int() + } + guard a[1] is U64(modifier) else { return 0U } + rs_dmabuf_import( + planes.length(), + flat, + modifier, + a[2].to_int(), + a[3].to_int(), + a[4].to_uint(), + if a[5].to_bool() { 1 } else { 0 }, + ) +} + ///| extern "C" fn rs_resize(w : Int, h : Int) -> Int = "rs_resize" @@ -991,6 +1061,16 @@ fn raster_funcs() -> Array[(String, (Array[@wt.Val]) -> Array[@wt.Val])] { none }, ), + ("dmabufs", _ => [dmabuf_support()]), + ("import-dmabuf", a => [U32(import_dmabuf(a))]), + ("capture-dmabuf", a => [U32(rs_dmabuf_capture(a[0].to_uint()))]), + ( + "release-dmabuf", + a => { + rs_dmabuf_release(a[0].to_uint()) + none + }, + ), ("load-image", a => [U32(load_image(a[0].to_string()).reinterpret_as_uint())]), ( "emoji-font", diff --git a/wasmhost/bin/raster_gpu.c b/wasmhost/bin/raster_gpu.c new file mode 100644 index 0000000..a5eaed4 --- /dev/null +++ b/wasmhost/bin/raster_gpu.c @@ -0,0 +1,1019 @@ +/* The host's rasteriser on the GPU (OpenGL ES 3): the same primitives as raster_stub.c, drawn the + * same way, into a texture that stays on the GPU. + * + * EGL and GLES are loaded with dlopen, so the host starts (and draws on the CPU) on machines + * without them, and building needs no GL headers. No window system is involved: the context is + * surfaceless on a DRM render node, and finished frames go to the display's own scanout buffers + * (gpu_scanout) or are read back (nested window, X11, screenshots). + * + * Every primitive is one instanced quad; what it looks like is decided per pixel from its integer + * coordinates, with the same tests the CPU rasteriser makes, so both draw the same shapes. Quads + * are cut to the clip here, so a clip costs no draw call; a batch ends only when the next image + * uses another texture. */ +#define _GNU_SOURCE +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "raster_gpu.h" + +int gpu_on; + +/* ------------------------------------------------------------------ EGL and GL, as used here */ + +typedef void *EGLDisplay, *EGLContext, *EGLConfig, *EGLSurface, *EGLImage, *EGLDeviceEXT; +typedef int32_t EGLint; +typedef uint32_t GLenum, GLuint; +typedef int32_t GLint, GLsizei; + +#define EGL_EXTENSIONS 0x3055 +#define EGL_NONE 0x3038 +#define EGL_WIDTH 0x3057 +#define EGL_HEIGHT 0x3056 +#define EGL_OPENGL_ES_API 0x30A0 +#define EGL_CONTEXT_MAJOR_VERSION 0x3098 +#define EGL_CONTEXT_PRIORITY_LEVEL_IMG 0x3100 +#define EGL_CONTEXT_PRIORITY_HIGH_IMG 0x3101 +#define EGL_PLATFORM_DEVICE_EXT 0x313F +#define EGL_DRM_DEVICE_FILE_EXT 0x3233 +#define EGL_DRM_RENDER_NODE_FILE_EXT 0x3377 +#define EGL_LINUX_DMA_BUF_EXT 0x3270 +#define EGL_LINUX_DRM_FOURCC_EXT 0x3271 + +#define GL_TEXTURE_2D 0x0DE1 +#define GL_TEXTURE0 0x84C0 +#define GL_RGBA 0x1908 +#define GL_RED 0x1903 +#define GL_GREEN 0x1904 +#define GL_BLUE 0x1905 +#define GL_ALPHA 0x1906 +#define GL_ONE 1 +#define GL_RGBA8 0x8058 +#define GL_R8 0x8229 +#define GL_UNSIGNED_BYTE 0x1401 +#define GL_FLOAT 0x1406 +#define GL_FRAMEBUFFER 0x8D40 +#define GL_RENDERBUFFER 0x8D41 +#define GL_COLOR_ATTACHMENT0 0x8CE0 +#define GL_FRAMEBUFFER_COMPLETE 0x8CD5 +#define GL_COLOR_BUFFER_BIT 0x4000 +#define GL_BLEND 0x0BE2 +#define GL_DITHER 0x0BD0 +#define GL_SCISSOR_TEST 0x0C11 +#define GL_ONE_MINUS_SRC_ALPHA 0x0303 +#define GL_TRIANGLE_STRIP 5 +#define GL_ARRAY_BUFFER 0x8892 +#define GL_STREAM_DRAW 0x88E0 +#define GL_PIXEL_UNPACK_BUFFER 0x88EC +#define GL_MAP_WRITE_BIT 0x0002 +#define GL_MAP_INVALIDATE_BUFFER_BIT 0x0008 +#define GL_VERTEX_SHADER 0x8B31 +#define GL_FRAGMENT_SHADER 0x8B30 +#define GL_COMPILE_STATUS 0x8B81 +#define GL_LINK_STATUS 0x8B82 +#define GL_TEXTURE_MIN_FILTER 0x2801 +#define GL_TEXTURE_MAG_FILTER 0x2800 +#define GL_TEXTURE_WRAP_S 0x2802 +#define GL_TEXTURE_WRAP_T 0x2803 +#define GL_NEAREST 0x2600 +#define GL_LINEAR 0x2601 +#define GL_CLAMP_TO_EDGE 0x812F +#define GL_TEXTURE_SWIZZLE_R 0x8E42 +#define GL_TEXTURE_SWIZZLE_B 0x8E44 +#define GL_TEXTURE_SWIZZLE_A 0x8E45 +#define GL_UNPACK_ROW_LENGTH 0x0CF2 +#define GL_UNPACK_ALIGNMENT 0x0CF5 +#define GL_PACK_ROW_LENGTH 0x0D02 +#define GL_MAX_TEXTURE_SIZE 0x0D33 +#define GL_VENDOR 0x1F00 +#define GL_RENDERER 0x1F01 +#define GL_EXTENSIONS 0x1F03 + +#define EGL_FNS(F) \ + F(const char *, eglQueryString, (EGLDisplay, EGLint)) \ + F(uint32_t, eglInitialize, (EGLDisplay, EGLint *, EGLint *)) \ + F(uint32_t, eglTerminate, (EGLDisplay)) \ + F(uint32_t, eglBindAPI, (GLenum)) \ + F(EGLContext, eglCreateContext, (EGLDisplay, EGLConfig, EGLContext, const EGLint *)) \ + F(uint32_t, eglMakeCurrent, (EGLDisplay, EGLSurface, EGLSurface, EGLContext)) \ + F(EGLint, eglGetError, (void)) \ + F(EGLDisplay, eglGetPlatformDisplayEXT, (GLenum, void *, const EGLint *)) \ + F(uint32_t, eglQueryDevicesEXT, (EGLint, EGLDeviceEXT *, EGLint *)) \ + F(const char *, eglQueryDeviceStringEXT, (EGLDeviceEXT, EGLint)) + +/* Only needed for dmabufs (client buffers and scanout). */ +#define EGL_OPT_FNS(F) \ + F(EGLImage, eglCreateImageKHR, (EGLDisplay, EGLContext, GLenum, void *, const EGLint *)) \ + F(uint32_t, eglDestroyImageKHR, (EGLDisplay, EGLImage)) \ + F(uint32_t, eglQueryDmaBufFormatsEXT, (EGLDisplay, EGLint, EGLint *, EGLint *)) \ + F(uint32_t, eglQueryDmaBufModifiersEXT, (EGLDisplay, EGLint, EGLint, uint64_t *, uint32_t *, EGLint *)) \ + F(void, glEGLImageTargetTexture2DOES, (GLenum, EGLImage)) \ + F(void, glEGLImageTargetRenderbufferStorageOES, (GLenum, EGLImage)) + +#define GL_FNS(F) \ + F(const uint8_t *, glGetString, (GLenum)) \ + F(void, glGetIntegerv, (GLenum, GLint *)) \ + F(GLenum, glGetError, (void)) \ + F(void, glEnable, (GLenum)) \ + F(void, glDisable, (GLenum)) \ + F(void, glBlendFunc, (GLenum, GLenum)) \ + F(void, glViewport, (GLint, GLint, GLsizei, GLsizei)) \ + F(void, glScissor, (GLint, GLint, GLsizei, GLsizei)) \ + F(void, glClearColor, (float, float, float, float)) \ + F(void, glClear, (GLenum)) \ + F(void, glFinish, (void)) \ + F(void, glFlush, (void)) \ + F(void, glPixelStorei, (GLenum, GLint)) \ + F(void, glReadPixels, (GLint, GLint, GLsizei, GLsizei, GLenum, GLenum, void *)) \ + F(void, glGenTextures, (GLsizei, GLuint *)) \ + F(void, glDeleteTextures, (GLsizei, const GLuint *)) \ + F(void, glActiveTexture, (GLenum)) \ + F(void, glBindTexture, (GLenum, GLuint)) \ + F(void, glTexParameteri, (GLenum, GLenum, GLint)) \ + F(void, glTexStorage2D, (GLenum, GLsizei, GLenum, GLsizei, GLsizei)) \ + F(void, glTexSubImage2D, (GLenum, GLint, GLint, GLint, GLsizei, GLsizei, GLenum, GLenum, const void *)) \ + F(void, glCopyTexSubImage2D, (GLenum, GLint, GLint, GLint, GLint, GLint, GLsizei, GLsizei)) \ + F(void, glGenFramebuffers, (GLsizei, GLuint *)) \ + F(void, glDeleteFramebuffers, (GLsizei, const GLuint *)) \ + F(void, glBindFramebuffer, (GLenum, GLuint)) \ + F(void, glFramebufferTexture2D, (GLenum, GLenum, GLenum, GLuint, GLint)) \ + F(GLenum, glCheckFramebufferStatus, (GLenum)) \ + F(void, glGenRenderbuffers, (GLsizei, GLuint *)) \ + F(void, glDeleteRenderbuffers, (GLsizei, const GLuint *)) \ + F(void, glBindRenderbuffer, (GLenum, GLuint)) \ + F(void, glFramebufferRenderbuffer, (GLenum, GLenum, GLenum, GLuint)) \ + F(GLuint, glCreateShader, (GLenum)) \ + F(void, glShaderSource, (GLuint, GLsizei, const char *const *, const GLint *)) \ + F(void, glCompileShader, (GLuint)) \ + F(void, glGetShaderiv, (GLuint, GLenum, GLint *)) \ + F(void, glGetShaderInfoLog, (GLuint, GLsizei, GLsizei *, char *)) \ + F(GLuint, glCreateProgram, (void)) \ + F(void, glAttachShader, (GLuint, GLuint)) \ + F(void, glLinkProgram, (GLuint)) \ + F(void, glGetProgramiv, (GLuint, GLenum, GLint *)) \ + F(void, glUseProgram, (GLuint)) \ + F(GLint, glGetUniformLocation, (GLuint, const char *)) \ + F(void, glUniform1i, (GLint, GLint)) \ + F(void, glUniform2f, (GLint, float, float)) \ + F(void, glUniform4i, (GLint, GLint, GLint, GLint, GLint)) \ + F(void, glGenVertexArrays, (GLsizei, GLuint *)) \ + F(void, glBindVertexArray, (GLuint)) \ + F(void, glGenBuffers, (GLsizei, GLuint *)) \ + F(void, glBindBuffer, (GLenum, GLuint)) \ + F(void, glBufferData, (GLenum, intptr_t, const void *, GLenum)) \ + F(void *, glMapBufferRange, (GLenum, intptr_t, intptr_t, GLenum)) \ + F(uint8_t, glUnmapBuffer, (GLenum)) \ + F(void, glEnableVertexAttribArray, (GLuint)) \ + F(void, glVertexAttribPointer, (GLuint, GLint, GLenum, uint8_t, GLsizei, const void *)) \ + F(void, glVertexAttribDivisor, (GLuint, GLuint)) \ + F(void, glDrawArrays, (GLenum, GLint, GLsizei)) \ + F(void, glDrawArraysInstanced, (GLenum, GLint, GLsizei, GLsizei)) + +#define DECL(ret, name, args) static ret(*p_##name) args; +EGL_FNS(DECL) +EGL_OPT_FNS(DECL) +GL_FNS(DECL) +#undef DECL + +static EGLDisplay dpy; +static EGLContext ctx; +static uint64_t device; /* the render node's dev_t */ +static int has_modifiers, can_import; +static GLint max_tex; + +static int has_ext(const char *list, const char *name) { + size_t n = strlen(name); + for (const char *p = list; p && (p = strstr(p, name)); p += n) + if ((p == list || p[-1] == ' ') && (p[n] == ' ' || p[n] == 0)) return 1; + return 0; +} + +/* ------------------------------------------------------------------ shaders */ + +static const char *VS = + "#version 300 es\n" + "precision highp float; precision highp int;\n" + "uniform vec2 size;\n" + "layout(location=0) in vec4 quad;\n" /* x0 y0 x1 y1, already clipped */ + "layout(location=1) in vec4 a_p;\n" + "layout(location=2) in vec4 a_q;\n" + "layout(location=3) in vec4 a_color;\n" + "flat out vec4 p; flat out vec4 q; flat out vec4 color;\n" + "void main() {\n" + " vec2 c = vec2((gl_VertexID & 1) == 0 ? quad.x : quad.z, (gl_VertexID & 2) == 0 ? quad.y : quad.w);\n" + " p = a_p; q = a_q; color = a_color;\n" + " gl_Position = vec4(c / size * 2.0 - 1.0, 0.0, 1.0);\n" + "}\n"; + +enum { K_SOLID, K_ROUND, K_STROKE, K_DISC, K_RING, K_GLYPH, K_IMAGE, K_IMAGE_PM, K_SURFACE, K_TEXEL }; + +/* The frame texture's row 0 is the top row, so gl_FragCoord is the pixel as the CPU counts it. */ +static const char *FS = + "#version 300 es\n" + "precision highp float; precision highp int; precision highp sampler2D;\n" + "uniform sampler2D atlas; uniform sampler2D img;\n" + "flat in vec4 p; flat in vec4 q; flat in vec4 color;\n" + "out vec4 o;\n" + "bool inside(ivec2 c, ivec4 b, int rad) {\n" + " if (c.x < b.x || c.y < b.y || c.x >= b.x + b.z || c.y >= b.y + b.w) return false;\n" + " int r = min(rad, min(b.z, b.w) / 2);\n" + " if (r <= 0) return true;\n" + " int dx = max(max(b.x + r - c.x, c.x - (b.x + b.z - r - 1)), 0);\n" + " int dy = max(max(b.y + r - c.y, c.y - (b.y + b.w - r - 1)), 0);\n" + " return dx == 0 || dy == 0 || dx * dx + dy * dy <= r * r;\n" + "}\n" + "void main() {\n" + " ivec2 c = ivec2(gl_FragCoord.xy);\n" + " int kind = int(q.w);\n" + " vec4 s = color;\n" + " if (kind == 0) {\n" + " } else if (kind == 1) {\n" + " if (!inside(c, ivec4(p), int(q.x))) discard;\n" + " } else if (kind == 2) {\n" + " ivec4 b = ivec4(p); int w = int(q.x);\n" + " if (!inside(c, b, int(q.y))) discard;\n" + " ivec4 n = ivec4(b.x + w, b.y + w, b.z - 2 * w, b.w - 2 * w);\n" + " if (n.z > 0 && n.w > 0 && inside(c, n, max(int(q.y) - w, 0))) discard;\n" + " } else if (kind == 3 || kind == 4) {\n" + " float d = length(vec2(c - ivec2(p.xy)));\n" + " float cov = min(p.z + 0.5 - d, 1.0);\n" + " if (kind == 4) cov = min(cov, d - (p.z - 1.5));\n" + " if (cov <= 0.02) discard;\n" + " s.a *= cov;\n" + " } else if (kind == 5) {\n" + " s.a *= texelFetch(atlas, c - ivec2(p.xy) + ivec2(p.zw), 0).r;\n" + " } else if (kind == 6) {\n" + " s = texture(img, (gl_FragCoord.xy - p.xy) / p.zw);\n" + " } else if (kind == 7) {\n" + " o = texture(img, (gl_FragCoord.xy - p.xy) / p.zw); return;\n" + " } else if (kind == 8) {\n" + " o = texelFetch(img, c - ivec2(p.xy), 0); return;\n" + " } else {\n" + " o = texelFetch(img, ivec2(p.xy), 0); return;\n" + " }\n" + " o = vec4(s.rgb * s.a, s.a);\n" + "}\n"; + +/* Copies (gl_VertexID makes the one triangle). */ +static const char *VS_COPY = + "#version 300 es\n" + "void main() { gl_Position = vec4(gl_VertexID == 1 ? 3.0 : -1.0, gl_VertexID == 2 ? 3.0 : -1.0, 0.0, 1.0); }\n"; + +/* A scaled copy, the average of a 4 x 4 grid of bilinear samples per pixel; `flip` upside down. */ +static const char *FS_SCALE = + "#version 300 es\n" + "precision highp float; precision highp sampler2D;\n" + "uniform sampler2D img; uniform vec2 size; uniform int flip; uniform int one;\n" + "out vec4 o;\n" + "void main() {\n" + " if (one != 0) {\n" + " ivec2 c = ivec2(gl_FragCoord.xy);\n" + " if (flip != 0) c.y = int(size.y) - 1 - c.y;\n" + " o = texelFetch(img, c, 0); return;\n" + " }\n" + " vec4 t = vec4(0.0);\n" + " for (int y = 0; y < 4; y++) for (int x = 0; x < 4; x++)\n" + " t += texture(img, (floor(gl_FragCoord.xy) + (vec2(x, y) + 0.5) / 4.0) / size);\n" + " o = t / 16.0;\n" + "}\n"; + +/* The frame onto a scanout buffer: whole-number scale and quarter turns, one texel per pixel (what + * kms_stub.c's copy_rows does). turn = rotation, scale, the unrotated frame's size. */ +static const char *FS_SCAN = + "#version 300 es\n" + "precision highp float; precision highp int; precision highp sampler2D;\n" + "uniform sampler2D img; uniform ivec4 turn;\n" + "out vec4 o;\n" + "void main() {\n" + " ivec2 b = turn.zw - 1;\n" + " ivec2 u = min(ivec2(gl_FragCoord.xy) / turn.y, b);\n" + " ivec2 c = u;\n" + " if (turn.x == 1) c = ivec2(u.y, b.x - u.x);\n" + " else if (turn.x == 2) c = b - u;\n" + " else if (turn.x == 3) c = ivec2(b.y - u.y, u.x);\n" + " o = vec4(texelFetch(img, c, 0).rgb, 1.0);\n" + "}\n"; + +static GLuint compile(GLenum type, const char *src) { + GLuint s = p_glCreateShader(type); + p_glShaderSource(s, 1, &src, NULL); + p_glCompileShader(s); + GLint ok = 0; + p_glGetShaderiv(s, GL_COMPILE_STATUS, &ok); + if (!ok) { + char log[1024] = ""; + p_glGetShaderInfoLog(s, sizeof log, NULL, log); + fprintf(stderr, "gpu: shader: %s\n", log); + } + return ok ? s : 0; +} + +static GLuint program(const char *vs, const char *fs) { + GLuint v = compile(GL_VERTEX_SHADER, vs), f = compile(GL_FRAGMENT_SHADER, fs); + if (!v || !f) return 0; + GLuint pr = p_glCreateProgram(); + p_glAttachShader(pr, v); + p_glAttachShader(pr, f); + p_glLinkProgram(pr); + GLint ok = 0; + p_glGetProgramiv(pr, GL_LINK_STATUS, &ok); + if (!ok) fprintf(stderr, "gpu: shaders don't link\n"); + return ok ? pr : 0; +} + +/* ------------------------------------------------------------------ batching */ + +typedef struct { + float quad[4], p[4], q[4]; /* q.w: the kind */ + uint8_t color[4]; +} Inst; + +#define BATCH 4096 +static Inst batch[BATCH]; +static int batch_n; +static GLuint batch_tex; /* the image texture the batch uses, 0 for none yet */ + +static GLuint prog, prog_scale, prog_scan, vao, vao_empty, vbo; +static GLint u_size, u_scale_size, u_scale_flip, u_scale_one, u_turn; +static int fb_w, fb_h; +static GLuint fb_tex, fb_fbo, back_tex, tmp_fbo; + +#define ATLAS 2048 +static GLuint atlas_tex; +static uint32_t atlas_gen = 1; +static int atlas_x, atlas_y, atlas_row; + +static int clip_on, clip_x0, clip_y0, clip_x1, clip_y1; + +static GLuint tex_new(GLenum format, int w, int h, int filter) { + GLuint t; + p_glGenTextures(1, &t); + p_glActiveTexture(GL_TEXTURE0 + 1); + p_glBindTexture(GL_TEXTURE_2D, t); + p_glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, filter); + p_glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, filter); + p_glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); + p_glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); + if (format) p_glTexStorage2D(GL_TEXTURE_2D, 1, format, w, h); + return t; +} + +static int attach(GLuint fbo, GLuint tex) { + p_glBindFramebuffer(GL_FRAMEBUFFER, fbo); + p_glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, tex, 0); + return p_glCheckFramebufferStatus(GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE; +} + +void gpu_flush(void) { + if (!batch_n) return; + p_glBindFramebuffer(GL_FRAMEBUFFER, fb_fbo); + p_glViewport(0, 0, fb_w, fb_h); + p_glUseProgram(prog); + p_glUniform2f(u_size, (float)fb_w, (float)fb_h); + p_glActiveTexture(GL_TEXTURE0); + p_glBindTexture(GL_TEXTURE_2D, atlas_tex); + p_glActiveTexture(GL_TEXTURE0 + 1); + p_glBindTexture(GL_TEXTURE_2D, batch_tex ? batch_tex : atlas_tex); + p_glBindVertexArray(vao); + p_glBindBuffer(GL_ARRAY_BUFFER, vbo); + p_glBufferData(GL_ARRAY_BUFFER, (intptr_t)sizeof(Inst) * batch_n, batch, GL_STREAM_DRAW); + p_glEnable(GL_BLEND); + p_glDrawArraysInstanced(GL_TRIANGLE_STRIP, 0, 4, batch_n); + batch_n = 0; + batch_tex = 0; +} + +void gpu_submit(void) { + gpu_flush(); + p_glFlush(); +} + +void gpu_clip(int on, int x, int y, int w, int h) { + clip_on = on; + clip_x0 = x; clip_y0 = y; clip_x1 = x + w; clip_y1 = y + h; +} + +/* One quad over (x, y, w, h) cut to the frame and the clip; NULL when nothing is left of it. */ +static Inst *quad(int kind, GLuint tex, int x, int y, int w, int h, int r, int g, int b, int a) { + int x0 = x > 0 ? x : 0, y0 = y > 0 ? y : 0; + int x1 = x + w < fb_w ? x + w : fb_w, y1 = y + h < fb_h ? y + h : fb_h; + if (clip_on) { + if (clip_x0 > x0) x0 = clip_x0; + if (clip_y0 > y0) y0 = clip_y0; + if (clip_x1 < x1) x1 = clip_x1; + if (clip_y1 < y1) y1 = clip_y1; + } + if (x0 >= x1 || y0 >= y1) return NULL; + if (batch_n == BATCH || (tex && batch_tex && tex != batch_tex)) gpu_flush(); + if (tex) batch_tex = tex; + Inst *i = &batch[batch_n++]; + *i = (Inst){ { (float)x0, (float)y0, (float)x1, (float)y1 }, + { (float)x, (float)y, (float)w, (float)h }, + { 0, 0, 0, (float)kind }, + { (uint8_t)r, (uint8_t)g, (uint8_t)b, (uint8_t)(a < 0 ? 0 : a > 255 ? 255 : a) } }; + return i; +} + +void gpu_fill(int x, int y, int w, int h, int r, int g, int b, int a, int radius) { + if (w <= 0 || h <= 0 || a <= 0) return; + Inst *i = quad(radius > 0 ? K_ROUND : K_SOLID, 0, x, y, w, h, r, g, b, a); + if (i) i->q[0] = (float)radius; +} + +void gpu_stroke(int x, int y, int w, int h, int r, int g, int b, int a, int width, int radius) { + if (w <= 0 || h <= 0 || width <= 0 || a <= 0) return; + Inst *i = quad(K_STROKE, 0, x, y, w, h, r, g, b, a); + if (i) { i->q[0] = (float)width; i->q[1] = (float)radius; } +} + +void gpu_circle(int cx, int cy, int radius, int r, int g, int b, int a, int filled) { + if (radius <= 0 || a <= 0) return; + Inst *i = quad(filled ? K_DISC : K_RING, 0, cx - radius - 1, cy - radius - 1, 2 * radius + 3, 2 * radius + 3, r, g, b, a); + if (i) { i->p[0] = (float)cx; i->p[1] = (float)cy; i->p[2] = (float)radius; } +} + +void gpu_glyph(const uint8_t *cov, int w, int h, int *ax, int *ay, uint32_t *gen, int x, int y, int r, int g, int b, + int a) { + if (w <= 0 || h <= 0 || w >= ATLAS || h >= ATLAS || a <= 0) return; + if (*gen != atlas_gen) { + if (atlas_x + w > ATLAS) { atlas_x = 0; atlas_y += atlas_row; atlas_row = 0; } + if (atlas_y + h > ATLAS) { /* full: start over, every glyph is put in again when next drawn */ + gpu_flush(); + atlas_gen++; + atlas_x = atlas_y = atlas_row = 0; + } + p_glActiveTexture(GL_TEXTURE0); + p_glBindTexture(GL_TEXTURE_2D, atlas_tex); + p_glPixelStorei(GL_UNPACK_ALIGNMENT, 1); + p_glTexSubImage2D(GL_TEXTURE_2D, 0, atlas_x, atlas_y, w, h, GL_RED, GL_UNSIGNED_BYTE, cov); + p_glPixelStorei(GL_UNPACK_ALIGNMENT, 4); + *ax = atlas_x; *ay = atlas_y; *gen = atlas_gen; + atlas_x += w; + if (h > atlas_row) atlas_row = h; + } + Inst *i = quad(K_GLYPH, 0, x, y, w, h, r, g, b, a); + if (i) { i->p[2] = (float)*ax; i->p[3] = (float)*ay; } +} + +void gpu_image(uint32_t tex, int x, int y, int w, int h, int premultiplied) { + if (tex && w > 0 && h > 0) quad(premultiplied ? K_IMAGE_PM : K_IMAGE, tex, x, y, w, h, 0, 0, 0, 0); +} + +void gpu_surface(uint32_t tex, int tw, int th, int x, int y, int w, int h) { + if (!tex || w <= 0 || h <= 0) return; + int cw = tw < w ? tw : w, ch = th < h ? th : h; + if (cw < w || ch < h) { + Inst *i = quad(K_TEXEL, tex, x, y, w, h, 0, 0, 0, 0); + if (i) { i->p[0] = (float)(tw - 1); i->p[1] = (float)(th - 1); } + } + quad(K_SURFACE, tex, x, y, cw, ch, 0, 0, 0, 0); +} + +/* ------------------------------------------------------------------ the frame */ + +int gpu_resize(int w, int h) { + gpu_flush(); + if (w > max_tex || h > max_tex) return 0; + if (fb_tex) p_glDeleteTextures(1, &fb_tex); + if (back_tex) p_glDeleteTextures(1, &back_tex); + back_tex = 0; + if (!fb_fbo) p_glGenFramebuffers(1, &fb_fbo); + fb_tex = tex_new(GL_RGBA8, w, h, GL_NEAREST); + if (!attach(fb_fbo, fb_tex)) return 0; + fb_w = w; fb_h = h; + gpu_clear(); + return 1; +} + +void gpu_clear(void) { + batch_n = 0; + batch_tex = 0; + p_glBindFramebuffer(GL_FRAMEBUFFER, fb_fbo); + p_glClearColor(0, 0, 0, 0); + p_glClear(GL_COLOR_BUFFER_BIT); +} + +void gpu_read(uint8_t *fb, int stride_px, int x0, int y0, int x1, int y1) { + gpu_flush(); + p_glBindFramebuffer(GL_FRAMEBUFFER, fb_fbo); + p_glPixelStorei(GL_PACK_ROW_LENGTH, stride_px); + p_glReadPixels(x0, y0, x1 - x0, y1 - y0, GL_RGBA, GL_UNSIGNED_BYTE, fb + ((size_t)y0 * stride_px + x0) * 4); + p_glPixelStorei(GL_PACK_ROW_LENGTH, 0); +} + +void gpu_save_backdrop(void) { + gpu_flush(); + if (!back_tex) back_tex = tex_new(GL_RGBA8, fb_w, fb_h, GL_NEAREST); + p_glBindFramebuffer(GL_FRAMEBUFFER, fb_fbo); + p_glActiveTexture(GL_TEXTURE0 + 1); + p_glBindTexture(GL_TEXTURE_2D, back_tex); + p_glCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, 0, 0, fb_w, fb_h); +} + +void gpu_copy_backdrop(void) { + if (back_tex) quad(K_SURFACE, back_tex, 0, 0, fb_w, fb_h, 0, 0, 0, 0); +} + +/* ------------------------------------------------------------------ textures */ + +/* Textures of released surfaces, for the next capture of the same size (a client that redraws + * every frame goes round two or three of them). */ +#define SPARE 8 +static struct { GLuint tex; int w, h; } spare[SPARE]; + +static GLuint tex_take(int w, int h) { + for (int i = 0; i < SPARE; i++) + if (spare[i].tex && spare[i].w == w && spare[i].h == h) { + GLuint t = spare[i].tex; + memmove(spare + i, spare + i + 1, (size_t)(SPARE - 1 - i) * sizeof spare[0]); + spare[SPARE - 1].tex = 0; + return t; + } + if (w > max_tex || h > max_tex) return 0; + return tex_new(GL_RGBA8, w, h, GL_LINEAR); +} + +void gpu_tex_free(uint32_t tex, int w, int h) { + if (!tex) return; + if (batch_tex == tex) gpu_flush(); + int i = 0; + while (i < SPARE && spare[i].tex) i++; + if (i == SPARE) { + p_glDeleteTextures(1, &spare[0].tex); + memmove(spare, spare + 1, (SPARE - 1) * sizeof spare[0]); + i = SPARE - 1; + } + spare[i].tex = tex; spare[i].w = w; spare[i].h = h; +} + +static void tex_swizzle(int bgr, int opaque) { + p_glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_R, bgr ? GL_BLUE : GL_RED); + p_glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_B, bgr ? GL_RED : GL_BLUE); + p_glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_A, opaque ? GL_ONE : GL_ALPHA); +} + +/* Large uploads go through a buffer the GPU then copies from in its own time: writing into a + * texture directly waits for the GPU, or converts its layout on the CPU (8 ms against 3 for a + * 1080p window on Haswell). */ +static int upload_buffered(const uint8_t *px, int stride_px, int w, int h) { + static GLuint pbo; + intptr_t n = (intptr_t)w * h * 4; + if (!pbo) p_glGenBuffers(1, &pbo); + p_glBindBuffer(GL_PIXEL_UNPACK_BUFFER, pbo); + p_glBufferData(GL_PIXEL_UNPACK_BUFFER, n, NULL, GL_STREAM_DRAW); + uint8_t *m = p_glMapBufferRange(GL_PIXEL_UNPACK_BUFFER, 0, n, GL_MAP_WRITE_BIT | GL_MAP_INVALIDATE_BUFFER_BIT); + int ok = m != NULL; + if (ok) { + if (stride_px == w) memcpy(m, px, (size_t)n); + else for (int y = 0; y < h; y++) memcpy(m + (size_t)y * w * 4, px + (size_t)y * stride_px * 4, (size_t)w * 4); + ok = p_glUnmapBuffer(GL_PIXEL_UNPACK_BUFFER); + if (ok) p_glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, w, h, GL_RGBA, GL_UNSIGNED_BYTE, NULL); + } + p_glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0); + return ok; +} + +static GLuint tex_upload(const uint8_t *px, int stride_px, int w, int h, int bgr, int opaque) { + GLuint t = tex_take(w, h); + if (!t) return 0; + p_glActiveTexture(GL_TEXTURE0 + 1); + p_glBindTexture(GL_TEXTURE_2D, t); + tex_swizzle(bgr, opaque); + if (w * h >= 256 * 256 && upload_buffered(px, stride_px, w, h)) return t; + p_glPixelStorei(GL_UNPACK_ROW_LENGTH, stride_px); + p_glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, w, h, GL_RGBA, GL_UNSIGNED_BYTE, px); + p_glPixelStorei(GL_UNPACK_ROW_LENGTH, 0); + return t; +} + +uint32_t gpu_tex_rgba(const uint8_t *px, int w, int h) { return tex_upload(px, w, w, h, 0, 0); } + +uint32_t gpu_tex_shm(const uint8_t *px, int stride, int w, int h, int opaque) { + if (stride % 4 == 0) return tex_upload(px, stride / 4, w, h, 1, opaque); + /* Rows at odd strides: packed first. */ + uint8_t *tight = malloc((size_t)w * h * 4); + if (!tight) return 0; + for (int y = 0; y < h; y++) memcpy(tight + (size_t)y * w * 4, px + (size_t)y * stride, (size_t)w * 4); + GLuint t = tex_upload(tight, w, w, h, 1, opaque); + free(tight); + return t; +} + +/* Draw `src` into a texture of w x h: one to one (`one`, upside down when `flip`) or scaled. */ +static GLuint tex_copy(GLuint src, int w, int h, int one, int flip) { + GLuint t = tex_take(w, h); + if (!t) return 0; + p_glActiveTexture(GL_TEXTURE0 + 1); + p_glBindTexture(GL_TEXTURE_2D, t); + tex_swizzle(0, 0); + if (!attach(tmp_fbo, t)) { p_glDeleteTextures(1, &t); return 0; } + p_glViewport(0, 0, w, h); + p_glDisable(GL_BLEND); + p_glUseProgram(prog_scale); + p_glUniform2f(u_scale_size, (float)w, (float)h); + p_glUniform1i(u_scale_flip, flip); + p_glUniform1i(u_scale_one, one); + p_glBindTexture(GL_TEXTURE_2D, src); + p_glBindVertexArray(vao_empty); + p_glDrawArrays(GL_TRIANGLE_STRIP, 0, 3); + return t; +} + +uint32_t gpu_tex_scaled(uint32_t src, int sw, int sh, int w, int h) { + gpu_flush(); + return tex_copy(src, w, h, sw == w && sh == h, 0); +} + +/* ------------------------------------------------------------------ dmabufs */ + +#define FOURCC(a, b, c, d) ((uint32_t)(a) | (uint32_t)(b) << 8 | (uint32_t)(c) << 16 | (uint32_t)(d) << 24) +#define DRM_XRGB FOURCC('X', 'R', '2', '4') +#define DRM_ARGB FOURCC('A', 'R', '2', '4') +#define DRM_XBGR FOURCC('X', 'B', '2', '4') +#define DRM_ABGR FOURCC('A', 'B', '2', '4') +#define MOD_INVALID 0x00ffffffffffffffull + +static int fourcc_known(uint32_t f) { return f == DRM_XRGB || f == DRM_ARGB || f == DRM_XBGR || f == DRM_ABGR; } + +uint64_t gpu_device(void) { return gpu_on && can_import ? device : 0; } + +int gpu_dmabuf_formats(uint32_t *fourcc, uint64_t *modifier, int cap) { + if (!gpu_on || !can_import) return 0; + EGLint formats[256], nf = 0; + if (!p_eglQueryDmaBufFormatsEXT(dpy, 256, formats, &nf)) return 0; + int n = 0; + for (int i = 0; i < nf; i++) { + uint32_t f = (uint32_t)formats[i]; + if (!fourcc_known(f)) continue; + uint64_t mods[128]; + uint32_t external[128]; + EGLint nm = 0; + if (has_modifiers && p_eglQueryDmaBufModifiersEXT(dpy, formats[i], 128, mods, external, &nm)) + for (int m = 0; m < nm && n < cap; m++) + if (!external[m]) { fourcc[n] = f; modifier[n++] = mods[m]; } + /* And a buffer whose layout the driver keeps to itself (clients that know no modifiers). */ + if (n < cap) { fourcc[n] = f; modifier[n++] = MOD_INVALID; } + } + return n; +} + +static EGLImage image_import(int n, const int *fd, const uint32_t *offset, const uint32_t *stride, uint64_t modifier, + int w, int h, uint32_t fourcc) { + static const EGLint plane_fd[4] = { 0x3272, 0x3275, 0x3278, 0x3440 }; + static const EGLint plane_mod[4] = { 0x3443, 0x3445, 0x3447, 0x3449 }; + EGLint a[64]; + int k = 0; + a[k++] = EGL_WIDTH; a[k++] = w; + a[k++] = EGL_HEIGHT; a[k++] = h; + a[k++] = EGL_LINUX_DRM_FOURCC_EXT; a[k++] = (EGLint)fourcc; + for (int i = 0; i < n; i++) { + a[k++] = plane_fd[i]; a[k++] = fd[i]; + a[k++] = plane_fd[i] + 1; a[k++] = (EGLint)offset[i]; + a[k++] = plane_fd[i] + 2; a[k++] = (EGLint)stride[i]; + if (has_modifiers && modifier != MOD_INVALID) { + a[k++] = plane_mod[i]; a[k++] = (EGLint)(uint32_t)modifier; + a[k++] = plane_mod[i] + 1; a[k++] = (EGLint)(uint32_t)(modifier >> 32); + } + } + a[k] = EGL_NONE; + return p_eglCreateImageKHR(dpy, NULL, EGL_LINUX_DMA_BUF_EXT, NULL, a); +} + +typedef struct { + EGLImage image; + GLuint tex; + int w, h, opaque, flip; +} Dmabuf; +static Dmabuf *dmabufs; +static int n_dmabufs; + +uint32_t gpu_dmabuf_import(int n, const int *fd, const uint32_t *offset, const uint32_t *stride, uint64_t modifier, + int w, int h, uint32_t fourcc, int y_invert) { + if (!gpu_on || !can_import || n < 1 || n > 4 || w <= 0 || h <= 0 || w > max_tex || h > max_tex) return 0; + if (!fourcc_known(fourcc)) return 0; + EGLImage im = image_import(n, fd, offset, stride, modifier, w, h, fourcc); + if (!im) return 0; + while (p_glGetError()) {} + GLuint t = tex_new(0, 0, 0, GL_NEAREST); + p_glEGLImageTargetTexture2DOES(GL_TEXTURE_2D, im); + if (p_glGetError()) { + p_glDeleteTextures(1, &t); + p_eglDestroyImageKHR(dpy, im); + return 0; + } + int i = 0; + while (i < n_dmabufs && dmabufs[i].image) i++; + if (i == n_dmabufs) { + Dmabuf *grown = realloc(dmabufs, sizeof *dmabufs * (size_t)(n_dmabufs + 16)); + if (!grown) { p_glDeleteTextures(1, &t); p_eglDestroyImageKHR(dpy, im); return 0; } + dmabufs = grown; + memset(dmabufs + n_dmabufs, 0, sizeof *dmabufs * 16); + n_dmabufs += 16; + } + dmabufs[i] = (Dmabuf){ im, t, w, h, fourcc == DRM_XRGB || fourcc == DRM_XBGR, y_invert }; + return (uint32_t)i + 1; +} + +static Dmabuf *dmabuf(uint32_t id) { + return id >= 1 && id <= (uint32_t)n_dmabufs && dmabufs[id - 1].image ? &dmabufs[id - 1] : NULL; +} + +void gpu_dmabuf_free(uint32_t id) { + Dmabuf *d = dmabuf(id); + if (!d) return; + p_glDeleteTextures(1, &d->tex); + p_eglDestroyImageKHR(dpy, d->image); + memset(d, 0, sizeof *d); +} + +/* The client may draw into its buffer again as soon as this returns: the copy is handed to the GPU + * here, and the kernel orders the client's next drawing after it (implicit sync). */ +uint32_t gpu_dmabuf_copy(uint32_t id, int *w, int *h, int *opaque) { + Dmabuf *d = dmabuf(id); + if (!d) return 0; + gpu_flush(); + p_glActiveTexture(GL_TEXTURE0 + 1); + p_glBindTexture(GL_TEXTURE_2D, d->tex); + p_glEGLImageTargetTexture2DOES(GL_TEXTURE_2D, d->image); /* what the client drew since */ + GLuint t = tex_copy(d->tex, d->w, d->h, 1, d->flip); + if (!t) return 0; + p_glFlush(); + *w = d->w; *h = d->h; *opaque = d->opaque; + return t; +} + +/* ------------------------------------------------------------------ the crash guard */ + +/* A login session that dies while it starts drawing on the display with the GPU must not do so at + * every login: it leaves this file, and the next session keeps to the CPU once (and removes it). */ +static char guard_path[512]; +static int64_t guard_since; /* when the file was made; 0: there is none */ + +static int64_t now_ms(void) { + struct timespec t; + clock_gettime(CLOCK_MONOTONIC, &t); + return (int64_t)t.tv_sec * 1000 + t.tv_nsec / 1000000; +} + +/* 0 when the last session died at it. */ +static int guard_check(void) { + const char *state = getenv("XDG_STATE_HOME"), *home = getenv("HOME"); + if (state && *state) snprintf(guard_path, sizeof guard_path, "%s/chandra/gpu-starting", state); + else if (home && *home) snprintf(guard_path, sizeof guard_path, "%s/.local/state/chandra/gpu-starting", home); + return !(guard_path[0] && unlink(guard_path) == 0); +} + +/* An orderly end within those seconds is no crash. */ +static void guard_exit(void) { + if (guard_since) unlink(guard_path); +} + +static void guard_start(void) { + if (!guard_path[0] || guard_since) return; + int fd = open(guard_path, O_WRONLY | O_CREAT | O_CLOEXEC, 0600); + if (fd < 0) { guard_path[0] = 0; return; } + close(fd); + guard_since = now_ms(); + atexit(guard_exit); +} + +/* Frames have been shown for a while: all is well. */ +static void guard_done(void) { + if (!guard_since || now_ms() - guard_since < 5000) return; + unlink(guard_path); + guard_path[0] = 0; + guard_since = 0; +} + +/* ------------------------------------------------------------------ scanout */ + +static struct { EGLImage image; GLuint rbo, fbo; int state, w, h; } scan[2]; /* state: 1 works, -1 doesn't */ + +static int scan_setup(int slot, int fd, uint32_t pitch, int pw, int ph) { + if (scan[slot].state && scan[slot].w == pw && scan[slot].h == ph) return scan[slot].state > 0; + if (scan[slot].fbo) p_glDeleteFramebuffers(1, &scan[slot].fbo); + if (scan[slot].rbo) p_glDeleteRenderbuffers(1, &scan[slot].rbo); + if (scan[slot].image) p_eglDestroyImageKHR(dpy, scan[slot].image); + memset(&scan[slot], 0, sizeof scan[slot]); + scan[slot].state = -1; + scan[slot].w = pw; scan[slot].h = ph; + if (!can_import || fd < 0) return 0; + uint32_t zero = 0; + EGLImage im = image_import(1, &fd, &zero, &pitch, 0 /* linear */, pw, ph, DRM_XRGB); + if (!im) { fprintf(stderr, "gpu: can't draw into the display's buffers (EGL error 0x%x)\n", p_eglGetError()); return 0; } + p_glGenRenderbuffers(1, &scan[slot].rbo); + p_glBindRenderbuffer(GL_RENDERBUFFER, scan[slot].rbo); + while (p_glGetError()) {} + p_glEGLImageTargetRenderbufferStorageOES(GL_RENDERBUFFER, im); + p_glGenFramebuffers(1, &scan[slot].fbo); + p_glBindFramebuffer(GL_FRAMEBUFFER, scan[slot].fbo); + p_glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, scan[slot].rbo); + scan[slot].image = im; + if (p_glGetError() || p_glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) { + fprintf(stderr, "gpu: the display's buffers can't be drawn into\n"); + return 0; + } + scan[slot].state = 1; + return 1; +} + +int gpu_scanout(int slot, int fd, uint32_t pitch, int pw, int ph, int scale, int rot, int x0, int y0, int x1, int y1) { + guard_start(); + guard_done(); + if (!scan_setup(slot, fd, pitch, pw, ph)) return 0; + gpu_flush(); + if (x0 < x1 && y0 < y1) { + p_glBindFramebuffer(GL_FRAMEBUFFER, scan[slot].fbo); + p_glViewport(0, 0, pw, ph); + p_glDisable(GL_BLEND); + if (rot == 0) { /* turned screens are copied whole */ + p_glEnable(GL_SCISSOR_TEST); + p_glScissor(x0 * scale, y0 * scale, (x1 - x0) * scale, (y1 - y0) * scale); + } + p_glUseProgram(prog_scan); + p_glUniform4i(u_turn, rot, scale, rot & 1 ? fb_h : fb_w, rot & 1 ? fb_w : fb_h); + p_glActiveTexture(GL_TEXTURE0 + 1); + p_glBindTexture(GL_TEXTURE_2D, fb_tex); + p_glBindVertexArray(vao_empty); + p_glDrawArrays(GL_TRIANGLE_STRIP, 0, 3); + p_glDisable(GL_SCISSOR_TEST); + } + p_glFlush(); /* the page flip waits for the drawing (implicit sync) */ + return 1; +} + +/* ------------------------------------------------------------------ setup */ + +/* Display-only and virtual DRM drivers (compositor/shell/render_mode.mbt has the same list). */ +static int driver_is_gpu(const char *node) { + static const char *const not_gpus[] = { + "simpledrm", "simple-framebuffer", "efifb", "vesafb", "vkms", "vgem", "virtio_gpu", "virtio-gpu", "qxl", "bochs", + "bochs-drm", "cirrus", "cirrus-qemu", "vboxvideo", "vmwgfx", "hyperv_drm", "udl", "gud", "ast", "mgag200", + "xen-front", + }; + char path[128], line[256], drv[128] = ""; + snprintf(path, sizeof path, "/sys/class/drm/%s/device/uevent", node); + FILE *f = fopen(path, "r"); + if (!f) return 0; + while (fgets(line, sizeof line, f)) + if (sscanf(line, "DRIVER=%127s", drv) == 1) break; + fclose(f); + for (size_t i = 0; i < sizeof not_gpus / sizeof not_gpus[0]; i++) + if (!strcmp(drv, not_gpus[i])) return 0; + return drv[0] != 0; +} + +static int env_is(const char *name, const char *const *values) { + const char *e = getenv(name); + for (; e && *values; values++) + if (!strcasecmp(e, *values)) return 1; + return 0; +} + +static int load_functions(void) { + void *egl = dlopen("libEGL.so.1", RTLD_NOW | RTLD_LOCAL); + void *gl = egl ? dlopen("libGLESv2.so.2", RTLD_NOW | RTLD_LOCAL) : NULL; + if (!egl || !gl) { fprintf(stderr, "gpu: no %s on this machine\n", egl ? "libGLESv2.so.2" : "libEGL.so.1"); return 0; } + void *(*get)(const char *) = (void *(*)(const char *))dlsym(egl, "eglGetProcAddress"); + if (!get) return 0; +#define LOAD(lib, name) \ + *(void **)&p_##name = dlsym(lib, #name); \ + if (!p_##name) *(void **)&p_##name = get(#name); +#define NEED_EGL(ret, name, args) LOAD(egl, name) if (!p_##name) { fprintf(stderr, "gpu: EGL has no " #name "\n"); return 0; } +#define NEED_GL(ret, name, args) LOAD(gl, name) if (!p_##name) { fprintf(stderr, "gpu: GLES has no " #name "\n"); return 0; } +#define WANT(ret, name, args) *(void **)&p_##name = get(#name); + EGL_FNS(NEED_EGL) + GL_FNS(NEED_GL) + EGL_OPT_FNS(WANT) + return 1; +} + +/* The EGL device of the first real GPU (or of CHANDRA_RENDER_NODE), and its node's dev_t. */ +static EGLDeviceEXT pick_device(int forced) { + EGLDeviceEXT devs[16]; + EGLint n = 0; + if (!p_eglQueryDevicesEXT(16, devs, &n)) return NULL; + const char *want = getenv("CHANDRA_RENDER_NODE"); + EGLDeviceEXT best = NULL; + char best_path[64] = ""; + for (int i = 0; i < n; i++) { + const char *path = p_eglQueryDeviceStringEXT(devs[i], EGL_DRM_RENDER_NODE_FILE_EXT); + if (!path) path = p_eglQueryDeviceStringEXT(devs[i], EGL_DRM_DEVICE_FILE_EXT); + if (!path) continue; /* Mesa's software device */ + const char *base = strrchr(path, '/'); + if (want && *want) { if (strcmp(path, want)) continue; } + else if (!driver_is_gpu(base ? base + 1 : path) && !forced) continue; + /* The lowest node, the order the kernel found them in. */ + if (best && strcmp(path, best_path) >= 0) continue; + struct stat st; + if (stat(path, &st) < 0) continue; + best = devs[i]; + device = (uint64_t)st.st_rdev; + snprintf(best_path, sizeof best_path, "%s", path); + } + return best; +} + +static int setup(int forced) { + if (!load_functions()) return 0; + EGLDeviceEXT dev = pick_device(forced); + if (!dev) { fprintf(stderr, "gpu: no GPU found\n"); return 0; } + dpy = p_eglGetPlatformDisplayEXT(EGL_PLATFORM_DEVICE_EXT, dev, NULL); + if (!dpy || !p_eglInitialize(dpy, NULL, NULL)) { fprintf(stderr, "gpu: can't open the GPU (EGL error 0x%x)\n", p_eglGetError()); return 0; } + const char *ext = p_eglQueryString(dpy, EGL_EXTENSIONS); + if (!has_ext(ext, "EGL_KHR_surfaceless_context") || !has_ext(ext, "EGL_KHR_no_config_context")) { + fprintf(stderr, "gpu: EGL can't draw without a window\n"); + return 0; + } + p_eglBindAPI(EGL_OPENGL_ES_API); + /* Ahead of the apps' drawing, where the driver allows it. */ + EGLint attrs[] = { EGL_CONTEXT_MAJOR_VERSION, 3, EGL_NONE, EGL_NONE, EGL_NONE }; + if (has_ext(ext, "EGL_IMG_context_priority")) { + attrs[2] = EGL_CONTEXT_PRIORITY_LEVEL_IMG; + attrs[3] = EGL_CONTEXT_PRIORITY_HIGH_IMG; + } + ctx = p_eglCreateContext(dpy, NULL, NULL, attrs); + if (!ctx && attrs[2] != EGL_NONE) { + attrs[2] = EGL_NONE; + ctx = p_eglCreateContext(dpy, NULL, NULL, attrs); + } + if (!ctx || !p_eglMakeCurrent(dpy, NULL, NULL, ctx)) { fprintf(stderr, "gpu: no OpenGL ES 3\n"); return 0; } + const char *vendor = (const char *)p_glGetString(GL_VENDOR), *renderer = (const char *)p_glGetString(GL_RENDERER); + if (!vendor) vendor = ""; + if (!renderer) renderer = ""; + if (!forced && (strstr(renderer, "llvmpipe") || strstr(renderer, "softpipe") || strstr(renderer, "SWR"))) { + fprintf(stderr, "gpu: %s is not a GPU\n", renderer); + return 0; + } + if (!forced && !strncmp(vendor, "NVIDIA", 6)) { + /* No implicit sync: frames could be shown, and buffers reused, before they are drawn. */ + fprintf(stderr, "gpu: NVIDIA's own driver is not used (CHANDRA_GPU=1 to try)\n"); + return 0; + } + p_glGetIntegerv(GL_MAX_TEXTURE_SIZE, &max_tex); + has_modifiers = has_ext(ext, "EGL_EXT_image_dma_buf_import_modifiers") && p_eglQueryDmaBufModifiersEXT; + can_import = has_ext(ext, "EGL_EXT_image_dma_buf_import") && has_modifiers && p_eglCreateImageKHR && p_eglDestroyImageKHR && + p_eglQueryDmaBufFormatsEXT && p_glEGLImageTargetTexture2DOES && p_glEGLImageTargetRenderbufferStorageOES && + has_ext((const char *)p_glGetString(GL_EXTENSIONS), "GL_OES_EGL_image"); + + prog = program(VS, FS); + prog_scale = program(VS_COPY, FS_SCALE); + prog_scan = program(VS_COPY, FS_SCAN); + if (!prog || !prog_scale || !prog_scan) return 0; + p_glUseProgram(prog); + p_glUniform1i(p_glGetUniformLocation(prog, "atlas"), 0); + p_glUniform1i(p_glGetUniformLocation(prog, "img"), 1); + u_size = p_glGetUniformLocation(prog, "size"); + p_glUseProgram(prog_scale); + p_glUniform1i(p_glGetUniformLocation(prog_scale, "img"), 1); + u_scale_size = p_glGetUniformLocation(prog_scale, "size"); + u_scale_flip = p_glGetUniformLocation(prog_scale, "flip"); + u_scale_one = p_glGetUniformLocation(prog_scale, "one"); + p_glUseProgram(prog_scan); + p_glUniform1i(p_glGetUniformLocation(prog_scan, "img"), 1); + u_turn = p_glGetUniformLocation(prog_scan, "turn"); + + p_glGenVertexArrays(1, &vao_empty); + p_glGenVertexArrays(1, &vao); + p_glBindVertexArray(vao); + p_glGenBuffers(1, &vbo); + p_glBindBuffer(GL_ARRAY_BUFFER, vbo); + static const size_t at[4] = { offsetof(Inst, quad), offsetof(Inst, p), offsetof(Inst, q), offsetof(Inst, color) }; + for (GLuint i = 0; i < 4; i++) { + p_glEnableVertexAttribArray(i); + p_glVertexAttribPointer(i, 4, i == 3 ? GL_UNSIGNED_BYTE : GL_FLOAT, i == 3, sizeof(Inst), (const void *)at[i]); + p_glVertexAttribDivisor(i, 1); + } + p_glGenFramebuffers(1, &tmp_fbo); + atlas_tex = tex_new(GL_R8, ATLAS, ATLAS, GL_NEAREST); + p_glDisable(GL_DITHER); + p_glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA); + if (p_glGetError()) { fprintf(stderr, "gpu: OpenGL setup failed\n"); return 0; } + fprintf(stderr, "gpu: drawing on %s%s\n", renderer, can_import ? "" : " (no dmabufs)"); + return 1; +} + +/* Find the GPU and get ready to draw on it. CHANDRA_GPU=0 (or CHANDRA_RENDER=software, + * LIBGL_ALWAYS_SOFTWARE) keeps to the CPU; CHANDRA_GPU=1 takes whatever OpenGL there is, a virtual + * machine's or llvmpipe too. */ +int gpu_init(int session) { + static const char *const yes[] = { "1", "yes", "on", "true", NULL }, *const no[] = { "0", "no", "off", "false", NULL }, + *const soft[] = { "software", "sw", "cpu", NULL }; + int forced = env_is("CHANDRA_GPU", yes); + if (env_is("CHANDRA_GPU", no)) return 0; + const char *ls = getenv("LIBGL_ALWAYS_SOFTWARE"); + if (!forced && (env_is("CHANDRA_RENDER", soft) || (ls && *ls && strcmp(ls, "0") && strcmp(ls, "false")))) return 0; + if (session && !guard_check() && !forced) { + fprintf(stderr, "gpu: the last session died starting to draw on the GPU: this one uses the CPU\n"); + return 0; + } + gpu_on = setup(forced); + return gpu_on; +} diff --git a/wasmhost/bin/raster_gpu.h b/wasmhost/bin/raster_gpu.h new file mode 100644 index 0000000..5b2b15a --- /dev/null +++ b/wasmhost/bin/raster_gpu.h @@ -0,0 +1,54 @@ +/* The GPU half of the host's rasteriser (raster_stub.c calls these when gpu_on). */ +#ifndef CHANDRA_RASTER_GPU_H +#define CHANDRA_RASTER_GPU_H +#include + +/* 1 once gpu_init found a GPU: every drawing call then goes to it. */ +extern int gpu_on; +/* `session`: for a login session on the display itself (the crash guard). */ +int gpu_init(int session); + +/* The frame: a texture of w x h that keeps its contents between frames (so damage works). */ +int gpu_resize(int w, int h); /* 0 when the GPU can't */ +void gpu_clear(void); +void gpu_clip(int on, int x, int y, int w, int h); +void gpu_flush(void); /* send what was batched to GL */ +void gpu_submit(void); /* and start the GPU on it */ +void gpu_read(uint8_t *fb, int stride_px, int x0, int y0, int x1, int y1); /* RGBA rows, at their place in fb */ + +void gpu_fill(int x, int y, int w, int h, int r, int g, int b, int a, int radius); +void gpu_stroke(int x, int y, int w, int h, int r, int g, int b, int a, int width, int radius); +void gpu_circle(int cx, int cy, int radius, int r, int g, int b, int a, int filled); +/* A glyph's coverage (w * h bytes). *ax, *ay, *gen: where the atlas holds it, kept by the caller. */ +void gpu_glyph(const uint8_t *cov, int w, int h, int *ax, int *ay, uint32_t *gen, int x, int y, int r, int g, int b, + int a); + +/* Textures. Straight-alpha RGBA pixels, or (gpu_tex_shm) a client's B, G, R, A/X rows. */ +uint32_t gpu_tex_rgba(const uint8_t *px, int w, int h); +uint32_t gpu_tex_shm(const uint8_t *px, int stride, int w, int h, int opaque); +void gpu_tex_free(uint32_t tex, int w, int h); /* w, h: its size, to reuse it */ +/* A copy of texture `src` (sw x sh, premultiplied) scaled to w x h. */ +uint32_t gpu_tex_scaled(uint32_t src, int sw, int sh, int w, int h); +/* Draw `tex` stretched over (x, y, w, h). */ +void gpu_image(uint32_t tex, int x, int y, int w, int h, int premultiplied); +/* Draw `tex` (tw x th, premultiplied) unscaled at (x, y), cut to w x h; the part past the + * texture takes its bottom-right pixel. */ +void gpu_surface(uint32_t tex, int tw, int th, int x, int y, int w, int h); + +void gpu_save_backdrop(void); +void gpu_copy_backdrop(void); + +/* Client buffers on the GPU (linux-dmabuf). */ +uint64_t gpu_device(void); /* the render node's dev_t; 0 without dmabuf support */ +int gpu_dmabuf_formats(uint32_t *fourcc, uint64_t *modifier, int cap); /* how many there are */ +uint32_t gpu_dmabuf_import(int n, const int *fd, const uint32_t *offset, const uint32_t *stride, uint64_t modifier, + int w, int h, uint32_t fourcc, int y_invert); +void gpu_dmabuf_free(uint32_t id); +/* A copy of the buffer as it is now, as a texture. *opaque: its format has no alpha. */ +uint32_t gpu_dmabuf_copy(uint32_t id, int *w, int *h, int *opaque); + +/* Draw the frame into scanout buffer `slot` (0 or 1), a dmabuf of pw x ph XRGB8888: the frame's + * x0..y1, at `scale` and turned by `rot` quarters. `fd` is only used the first time (and not + * closed). 0 when the GPU can't draw there. */ +int gpu_scanout(int slot, int fd, uint32_t pitch, int pw, int ph, int scale, int rot, int x0, int y0, int x1, int y1); +#endif diff --git a/wasmhost/bin/raster_stub.c b/wasmhost/bin/raster_stub.c index ed53c6f..654f8b0 100644 --- a/wasmhost/bin/raster_stub.c +++ b/wasmhost/bin/raster_stub.c @@ -4,6 +4,10 @@ * 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. * + * With a GPU (raster_gpu.c) every primitive is drawn there instead, into a frame that stays on the + * GPU; `fb` is then only a copy, read back (fb_sync) when something needs the pixels here: + * screenshots, recordings, the remote mirror, a nested or X11 window. + * * Glyphs come from stb_truetype through compositor/font's shim (mp_font_*); SVG icons from * nanosvg (third_party/nanosvg). */ #define _GNU_SOURCE @@ -23,6 +27,7 @@ #include #include "moonbit.h" #include "../../remote/chandra_fb_shm.h" +#include "raster_gpu.h" #define NANOSVG_IMPLEMENTATION #define NANOSVGRAST_IMPLEMENTATION @@ -38,7 +43,8 @@ int32_t mp_font_has_glyph(int32_t slot, int32_t cp); /* ------------------------------------------------------------------ canvas */ static int32_t fb_w, fb_h; -static uint8_t *fb; /* RGBA8888 */ +static uint8_t *fb; /* RGBA8888; with a GPU a copy, see fb_sync */ +static int canvas_bad; /* the frame is too big for the GPU */ static int clip_on; static int32_t clip_x, clip_y, clip_w, clip_h; @@ -47,11 +53,26 @@ 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; } +/* Find the GPU, before anything is drawn or captured. 1 when there is one to draw on. */ +int32_t rs_gpu_init(int32_t session) { return gpu_init(session); } + +static void gpu_stale_all(void); + /* 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; + if (w == fb_w && h == fb_h && (fb || gpu_on)) return 0; + if (gpu_on) { + free(fb); + fb = NULL; + fb_w = w; + fb_h = h; + canvas_bad = !gpu_resize(w, h); + if (canvas_bad) fprintf(stderr, "gpu: no %d x %d frame\n", w, h); + gpu_stale_all(); + return 1; + } free(fb); fb = calloc((size_t)w * h, 4); fb_w = w; @@ -59,11 +80,15 @@ int32_t rs_resize(int32_t w, int32_t h) { return 1; } -void rs_clear(void) { if (fb) memset(fb, 0, (size_t)fb_w * fb_h * 4); } +void rs_clear(void) { + if (gpu_on) { gpu_clear(); return; } + 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; + if (gpu_on) gpu_clip(on, x, y, w, h); } /* Colour (r, g, b) at alpha a over the RGBA8888 pixel at p: two channels at a time in 16-bit @@ -138,6 +163,7 @@ static int visible(int x, int y, int w, int h, int *x0, int *y0, int *x1, int *y 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 (gpu_on) { gpu_fill(x, y, w, h, cr, cg, cb, ca, radius); return; } 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; @@ -166,6 +192,7 @@ void rs_fill_rect(int32_t x, int32_t y, int32_t w, int32_t h, int32_t cr, int32_ 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 (gpu_on) { gpu_stroke(x, y, w, h, cr, cg, cb, ca, width, radius); return; } 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; @@ -193,13 +220,14 @@ void rs_stroke_rect(int32_t x, int32_t y, int32_t w, int32_t h, int32_t cr, int3 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; + if (!fb && !gpu_on) 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++) + if (gpu_on) gpu_fill(x0 - half, y0 - half, 2 * half + 1, 2 * half + 1, cr, cg, cb, ca, 0); + else 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; @@ -226,6 +254,7 @@ static inline double circle_cov(int dx, int dy, double rad, int filled) { * 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 (gpu_on) { gpu_circle(cx, cy, radius, cr, cg, cb, ca, filled); return; } if (!fb || radius <= 0) return; double rad = radius; /* Fully covered (filled) when dist <= rad - 0.5; certainly empty (ring) when dist <= rad - 2. */ @@ -263,6 +292,8 @@ typedef struct Glyph { int32_t slot, cp, size; int32_t w, h, xoff, yoff, advance; uint8_t *coverage; + int ax, ay; /* its place in the GPU's glyph atlas, */ + uint32_t gen; /* when this is the atlas's generation */ struct Glyph *next; } Glyph; @@ -336,8 +367,14 @@ void rs_glyph_coverage(int32_t slot, int32_t cp, int32_t size, moonbit_bytes_t o 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; + if (!fb && !gpu_on) return; Glyph *g = glyph(slot, cp, size); + if (gpu_on) { + if (!g->coverage) return; + for (int k = 0; k <= (embolden ? 1 : 0); k++) + gpu_glyph(g->coverage, g->w, g->h, &g->ax, &g->ay, &g->gen, pen + g->xoff + k, baseline + g->yoff, cr, cg, cb, ca); + return; + } for (int row = 0; row < g->h; row++) { for (int col = 0; col < g->w; col++) { int cov = g->coverage[row * g->w + col]; @@ -354,11 +391,12 @@ void rs_draw_glyph(int32_t slot, int32_t cp, int32_t size, int32_t pen, int32_t #define MAX_IMAGE 16384 -typedef struct Sized { int32_t w, h; uint8_t *rgba; struct Sized *next; } Sized; +typedef struct Sized { int32_t w, h; uint8_t *rgba; uint32_t tex; struct Sized *next; } Sized; typedef struct { int used; int32_t w, h; - uint8_t *rgba; /* pixels, or NULL for an SVG */ + uint8_t *rgba; /* pixels, or NULL for an SVG (or a preview made on the GPU) */ + uint32_t tex; /* the pixels on the GPU, once drawn there */ 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) */ @@ -414,10 +452,17 @@ static uint8_t *scale_rgba(const uint8_t *src, int sw, int sh, int w, int h) { return out; } +static void sized_free(Sized *s) { + gpu_tex_free(s->tex, s->w, s->h); + free(s->rgba); + free(s); +} + static void image_reset(Image *im) { free(im->rgba); + gpu_tex_free(im->tex, im->w, im->h); if (im->svg) nsvgDelete(im->svg); - for (Sized *s = im->sized; s;) { Sized *n = s->next; free(s->rgba); free(s); s = n; } + for (Sized *s = im->sized; s;) { Sized *n = s->next; sized_free(s); s = n; } memset(im, 0, sizeof *im); } @@ -594,12 +639,12 @@ static const uint8_t *image_sized(int32_t handle, int w, int h) { /* 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); } + if (big_size(s->w, s->h)) { *pp = s->next; sized_free(s); } else pp = &s->next; } } Sized *s = malloc(sizeof *s); - s->w = w; s->h = h; s->rgba = px; s->next = im->sized; + s->w = w; s->h = h; s->rgba = px; s->tex = 0; s->next = im->sized; im->sized = s; return px; } @@ -624,7 +669,28 @@ static void blend_image(const uint8_t *px, int stride, int x0, int y0, int w, in } } +static void draw_image_gpu(int32_t handle, int x0, int y0, int w, int h) { + 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) return; + if (im->preview) { gpu_image(im->tex, x0, y0, w, h, 1); return; } /* filtered at any size */ + const uint8_t *px = image_sized(handle, w, h); + if (px && px != im->rgba) { + Sized *s = im->sized; + while (s && s->rgba != px) s = s->next; + if (!s) return; + if (!s->tex) s->tex = gpu_tex_rgba(s->rgba, w, h); + gpu_image(s->tex, x0, y0, w, h, 0); + return; + } + /* At its own size, or a large one that is moving: the GPU scales it. */ + if (!im->rgba) return; + if (!im->tex) im->tex = gpu_tex_rgba(im->rgba, im->w, im->h); + gpu_image(im->tex, x0, y0, w, h, 0); +} + void rs_draw_image(int32_t handle, int32_t x0, int32_t y0, int32_t w, int32_t h) { + if (gpu_on) { draw_image_gpu(handle, x0, y0, w, h); return; } 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; } @@ -644,7 +710,8 @@ void rs_draw_image(int32_t handle, int32_t x0, int32_t y0, int32_t w, int32_t h) typedef struct Surface { uint32_t id; int32_t w, h; - uint8_t *rgba; + uint8_t *rgba; /* NULL with a GPU: */ + uint32_t tex; /* it is there */ int opaque; /* every pixel has alpha 255: blits copy rows */ struct Surface *next; } Surface; @@ -759,6 +826,15 @@ static const uint8_t *pool_map(int fd, const struct stat *st) { return p; } +static uint32_t surface_add(int32_t w, int32_t h, uint8_t *rgba, uint32_t tex, int opaque) { + 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->tex = tex; sf->opaque = opaque; + sf->next = surfaces[sf->id % SURF_BUCKETS]; + surfaces[sf->id % SURF_BUCKETS] = sf; + return sf->id; +} + /* 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) { @@ -768,15 +844,57 @@ uint32_t rs_capture(int32_t fd, int32_t offset, int32_t stride, int32_t w, int32 if (fstat(fd, &st) < 0 || st.st_size < end) return 0; const uint8_t *p = pool_map(fd, &st); if (!p) return 0; + if (gpu_on) { + /* Whether ARGB pixels are all opaque is not worth reading them for: the GPU blends. */ + uint32_t tex = gpu_tex_shm(p + offset, stride, w, h, format == 1); + return tex ? surface_add(w, h, NULL, tex, format == 1) : 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; + return surface_add(w, h, rgba, 0, opaque); +} + +/* ---- client buffers on the GPU (linux-dmabuf) ---- */ + +/* The device clients should draw on (its dev_t), 0 when there are no GPU buffers here. */ +uint64_t rs_dmabuf_device(void) { return gpu_device(); } + +#define DMABUF_FORMATS 512 +/* Format i as fourcc, modifier low, modifier high into `out`; 0 past the last one. */ +int32_t rs_dmabuf_format(int32_t i, int32_t *out) { + static uint32_t fourcc[DMABUF_FORMATS]; + static uint64_t modifier[DMABUF_FORMATS]; + static int n = -1; + if (n < 0) n = gpu_dmabuf_formats(fourcc, modifier, DMABUF_FORMATS); + if (i < 0 || i >= n) return 0; + out[0] = (int32_t)fourcc[i]; + out[1] = (int32_t)(uint32_t)modifier[i]; + out[2] = (int32_t)(uint32_t)(modifier[i] >> 32); + return 1; +} + +/* planes: fd, offset, stride of each of `n`. */ +uint32_t rs_dmabuf_import(int32_t n, const int32_t *planes, uint64_t modifier, int32_t w, int32_t h, uint32_t fourcc, + int32_t y_invert) { + int fd[4]; + uint32_t offset[4], stride[4]; + if (n < 1 || n > 4) return 0; + for (int i = 0; i < n; i++) { + fd[i] = planes[i * 3]; + offset[i] = (uint32_t)planes[i * 3 + 1]; + stride[i] = (uint32_t)planes[i * 3 + 2]; + } + return gpu_dmabuf_import(n, fd, offset, stride, modifier, w, h, fourcc, y_invert); +} + +void rs_dmabuf_release(uint32_t id) { gpu_dmabuf_free(id); } + +/* A dmabuf as it is now, as a surface (a copy on the GPU, so its client can have it back at once). */ +uint32_t rs_dmabuf_capture(uint32_t id) { + int w, h, opaque; + uint32_t tex = gpu_dmabuf_copy(id, &w, &h, &opaque); + return tex ? surface_add(w, h, NULL, tex, opaque) : 0; } void rs_release(uint32_t id) { @@ -785,6 +903,7 @@ void rs_release(uint32_t id) { if ((*p)->id == id) { Surface *s = *p; *p = s->next; px_free(s->rgba, (size_t)s->w * s->h * 4); + gpu_tex_free(s->tex, s->w, s->h); free(s); return; } @@ -818,9 +937,11 @@ 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); + uint8_t *px = gpu_on ? NULL : scale_rgba(s->rgba, s->w, s->h, w, h); + uint32_t tex = gpu_on ? gpu_tex_scaled(s->tex, s->w, s->h, w, h) : 0; + if (!px && !tex) return 0; int32_t img = image_slot(reuse); - images[img - 1].w = w; images[img - 1].h = h; images[img - 1].rgba = px; + images[img - 1].w = w; images[img - 1].h = h; images[img - 1].rgba = px; images[img - 1].tex = tex; images[img - 1].changed = img == reuse; images[img - 1].preview = 1; return img; @@ -832,6 +953,7 @@ int32_t rs_thumbnail(uint32_t id, int32_t w, int32_t h, int32_t reuse) { 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 (gpu_on) { gpu_surface(s->tex, s->w, s->h, dx, dy, dw, dh); return 1; } 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; @@ -915,6 +1037,7 @@ static int32_t backdrop_w, backdrop_h; /* Keep the framebuffer as the backdrop (wallpaper and desktop card). */ void rs_save_backdrop(void) { + if (gpu_on) { gpu_save_backdrop(); backdrop_w = fb_w; backdrop_h = fb_h; return; } free(backdrop); backdrop = malloc((size_t)fb_w * fb_h * 4); memcpy(backdrop, fb, (size_t)fb_w * fb_h * 4); @@ -923,11 +1046,12 @@ void rs_save_backdrop(void) { } /* 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; } +int32_t rs_has_backdrop(void) { return (backdrop || gpu_on) && 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 (gpu_on) { gpu_copy_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); @@ -940,12 +1064,13 @@ void rs_copy_backdrop(void) { int32_t rs_width(void) { return fb_w; } int32_t rs_height(void) { return fb_h; } -uint8_t *rs_pixels(void) { return fb; } + +static int fb_sync(void); /* 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); + if (fb_sync() && (size_t)Moonbit_array_length(out) >= n) memcpy(out, fb, n); } /* ---- damage: what changed in the framebuffer since each output last took it ---- */ @@ -965,6 +1090,27 @@ 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) }; } +/* What the CPU's copy of a frame on the GPU is missing. */ +static Box cpu_stale; + +static void gpu_stale_all(void) { cpu_stale = (Box){ 0, 0, fb_w, fb_h }; } + +/* Have the frame's pixels in `fb`: with a GPU, read back what changed since the last time. 0 when + * there is no frame. */ +static int fb_sync(void) { + if (!gpu_on) return fb != NULL; + if (fb_w <= 0 || fb_h <= 0 || canvas_bad) return 0; + if (!fb) { + fb = calloc((size_t)fb_w * fb_h, 4); + if (!fb) return 0; + gpu_stale_all(); + } + Box b = box_fb(cpu_stale); + if (b.x0 < b.x1 && b.y0 < b.y1) gpu_read(fb, fb_w, b.x0, b.y0, b.x1, b.y1); + cpu_stale = (Box){ 0, 0, 0, 0 }; + return 1; +} + #define EXPORT_SLOTS 3 static Box kms_damage; static Box slot_damage[EXPORT_SLOTS]; @@ -974,6 +1120,7 @@ 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); + box_add(&cpu_stale, 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); @@ -1014,7 +1161,7 @@ static void slots_drop(void) { /* 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; + if (!fb_sync()) return -1; size_t n = (size_t)fb_w * fb_h * 4; if (slot_w != fb_w || slot_h != fb_h) { slots_drop(); @@ -1041,10 +1188,32 @@ int32_t rs_export_memfd(void) { 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); +/* compositor/kms/kms_stub.c: the buffer to draw the next frame into (its index, -1 when no frame + * can be shown now), as a dmabuf with its layout, and the part of the frame it is missing; then + * show it. */ +int32_t mp_kms_back_buffer(int32_t w, int32_t h, int32_t *info, int32_t *missing); +int32_t mp_kms_flip(void); +void mp_kms_add_damage(int32_t x, int32_t y, int32_t w, int32_t h); + +/* 1 when the GPU drew the frame into the display's own buffer (or nothing can be shown now). */ +static int present_gpu(void) { + int32_t info[6], m[4]; + int32_t i = mp_kms_back_buffer(fb_w, fb_h, info, m); + if (i < 0) return i != -2; + if (!gpu_scanout(i, info[0], (uint32_t)info[1], info[2], info[3], info[4], info[5], m[0], m[1], m[2], m[3])) return 0; + mp_kms_flip(); + return 1; +} + void rs_present_kms(void) { - if (!fb) return; + if (!fb && !gpu_on) return; Box b = box_fb(kms_damage); if (b.x0 >= b.x1 || b.y0 >= b.y1) b = (Box){ 0, 0, 0, 0 }; + if (gpu_on && !canvas_bad) { + mp_kms_add_damage(b.x0, b.y0, b.x1 - b.x0, b.y1 - b.y0); + if (present_gpu()) { kms_damage = (Box){ 0, 0, 0, 0 }; return; } + } + if (!fb_sync()) return; /* 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 }; @@ -1154,12 +1323,12 @@ static void *rec_writer(void *arg) { } 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; + if (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; + if (full || !fb_sync()) 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) { @@ -1231,7 +1400,7 @@ static uint8_t *snap; static int32_t snap_w, snap_h; int32_t rs_snapshot(void) { - if (!fb) return 0; + if (!fb_sync()) 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); @@ -1318,7 +1487,8 @@ static void shm_ensure_open(void) { } void rs_publish_frame(void) { - if (!fb || fb_w <= 0 || fb_h <= 0) return; + if (gpu_on) gpu_submit(); /* the frame is drawn: start the GPU on it */ + if ((!fb && !gpu_on) || 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; @@ -1338,6 +1508,7 @@ void rs_publish_frame(void) { if (cur_seq == 0) pb = (Box){ 0, 0, fb_w, fb_h }; else return; } + if (!fb_sync()) 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]); diff --git a/wasmhost/test/gpu_test.c b/wasmhost/test/gpu_test.c new file mode 100644 index 0000000..57eb657 --- /dev/null +++ b/wasmhost/test/gpu_test.c @@ -0,0 +1,300 @@ +/* The GPU rasteriser against the CPU one: both draw the same scenes in this process and the frames + * are compared; then a frame goes through a display buffer (a DRM dumb buffer shared as a dmabuf, + * which needs no display) at every rotation, and a client's dmabuf is captured. + * scripts/test-gpu.sh exits 77 when there is no GPU */ +#include "../bin/raster_stub.c" +#include +#include +#include + +/* ---- what raster_stub.c takes from the rest of the host ---- */ + +/* MoonBit's runtime, as far as byte strings go. */ +moonbit_bytes_t moonbit_make_bytes(int32_t n, int c) { + struct moonbit_object *o = malloc(sizeof *o + (size_t)n + 1); + memset(o, 0, sizeof *o); + o->meta = (uint32_t)n; + memset(o + 1, c, (size_t)n + 1); + return (moonbit_bytes_t)(o + 1); +} +void moonbit_decref(void *p) { free((struct moonbit_object *)p - 1); } + +int32_t mp_font_load(int32_t slot, moonbit_bytes_t path) { (void)slot; (void)path; return 0; } +int32_t mp_font_has_glyph(int32_t slot, int32_t cp) { (void)slot; (void)cp; return 1; } +/* Glyphs: a gradient blob as big as the size asked for. */ +void mp_font_metrics(int32_t slot, int32_t cp, int32_t size, int32_t *info) { + (void)slot; + info[0] = size / 2 + cp % 7; info[1] = size; info[2] = 1; info[3] = -size; info[4] = size / 2 + 2; +} +void mp_font_bitmap(int32_t slot, int32_t cp, int32_t size, int32_t w, int32_t h, moonbit_bytes_t buf) { + (void)slot; (void)size; + for (int i = 0; i < w * h; i++) buf[i] = (uint8_t)((i * 37 + cp * 11) % 256); +} +int32_t mp_kms_back_buffer(int32_t w, int32_t h, int32_t *info, int32_t *missing) { (void)w; (void)h; (void)info; (void)missing; return -1; } +int32_t mp_kms_flip(void) { return 0; } +void mp_kms_add_damage(int32_t x, int32_t y, int32_t w, int32_t h) { (void)x; (void)y; (void)w; (void)h; } +int32_t mp_kms_present_damage(moonbit_bytes_t p, int32_t w, int32_t h, int32_t x, int32_t y, int32_t dw, int32_t dh) { + (void)p; (void)w; (void)h; (void)x; (void)y; (void)dw; (void)dh; return 0; +} + +/* ---- scenes ---- */ + +#define W 640 +#define H 480 +static int failures; + +static uint32_t rnd_state; +static int rnd(int lo, int hi) { /* [lo, hi] */ + rnd_state = rnd_state * 1664525u + 1013904223u; + return lo + (int)((rnd_state >> 8) % (uint32_t)(hi - lo + 1)); +} + +static moonbit_bytes_t pixels(int w, int h, int alpha) { + moonbit_bytes_t b = moonbit_make_bytes(w * h * 4, 0); + for (int i = 0; i < w * h; i++) { + int a = alpha ? rnd(0, 255) : 255; + b[i * 4] = (uint8_t)rnd(0, 255); b[i * 4 + 1] = (uint8_t)rnd(0, 255); b[i * 4 + 2] = (uint8_t)rnd(0, 255); + b[i * 4 + 3] = (uint8_t)a; + } + return b; +} + +static uint32_t capture(int w, int h, int format) { + int stride = w * 4 + 16; + int fd = memfd_create("client", MFD_CLOEXEC); + uint8_t *p = malloc((size_t)stride * h); + for (int i = 0; i < stride * h; i += 4) { /* premultiplied */ + int a = rnd(0, 255); + for (int c = 0; c < 3; c++) p[i + c] = (uint8_t)rnd(0, format == 1 ? 255 : a); + p[i + 3] = (uint8_t)a; + } + if (write(fd, p, (size_t)stride * h) < 0) perror("write"); + free(p); + uint32_t id = rs_capture(fd, 0, stride, w, h, format); + close(fd); + return id; +} + +/* A kind of drawing, repeated with random places and colours (also off the edges). */ +static void draw(int kind) { + int x = rnd(-40, W), y = rnd(-40, H), w = rnd(1, 200), h = rnd(1, 150); + int r = rnd(0, 255), g = rnd(0, 255), b = rnd(0, 255), a = rnd(0, 2) ? rnd(1, 254) : 255; + switch (kind) { + case 0: rs_fill_rect(x, y, w, h, r, g, b, a, 0); break; + case 1: rs_fill_rect(x, y, w, h, r, g, b, a, rnd(1, 60)); break; + case 2: rs_stroke_rect(x, y, w, h, r, g, b, a, rnd(1, 6), rnd(0, 40)); break; + case 3: rs_circle(x, y, rnd(1, 80), r, g, b, a, 1); break; + case 4: rs_circle(x, y, rnd(1, 80), r, g, b, a, 0); break; + case 5: rs_line(x, y, x + rnd(-90, 90), y + rnd(-90, 90), r, g, b, a, rnd(1, 5)); break; + case 6: rs_draw_glyph(0, rnd(32, 200), rnd(8, 40), x, y, r, g, b, a, rnd(0, 1)); break; + } +} + +static const char *const kinds[] = { "fill", "rounded fill", "stroke", "disc", "ring", "line", "glyph", "icon", "surface" }; +static int32_t icon; +static uint32_t surf_a, surf_x; + +static void scene(int kind) { + rnd_state = 1234u + (uint32_t)kind; + rs_frame_begin(); + rs_resize(W, H); + rs_set_clip(0, 0, 0, 0, 0); + rs_clear(); + for (int y = 0; y < H; y += 16) rs_fill_rect(0, y, W, 16, y / 2, 128, 255 - y / 2, 255, 0); + for (int i = 0; i < 60; i++) { + if (i % 4 == 3) rs_set_clip(1, rnd(0, W), rnd(0, H), rnd(1, W), rnd(1, H)); + else rs_set_clip(0, 0, 0, 0, 0); + if (kind == 7) { int s = rnd(0, 1) ? 32 : 20; rs_draw_image(icon, rnd(-20, W), rnd(-20, H), s, s); } + else if (kind == 8) { + /* Smaller than its window only when opaque: the corner pixel stretched over the rest is + * blended as straight alpha by the CPU. */ + int x = rnd(-60, W), y = rnd(-60, H); + if (rnd(0, 1)) rs_blit_surface(surf_a, x, y, rnd(1, 120), rnd(1, 80)); + else rs_blit_surface(surf_x, x, y, rnd(1, 140), rnd(1, 90)); + } + else draw(kind); + } + if (kind == 0) { /* the backdrop: kept, drawn over, copied back into a clip */ + rs_set_clip(0, 0, 0, 0, 0); + rs_save_backdrop(); + rs_fill_rect(0, 0, W, H, 1, 2, 3, 255, 0); + rs_set_clip(1, 50, 60, 300, 200); + rs_copy_backdrop(); + } + rs_damage(0, 0, W, H); + rs_publish_frame(); +} + +static uint8_t *render(int kind, int on) { + gpu_on = on; + free(fb); fb = NULL; fb_w = fb_h = 0; + rnd_state = 99; + icon = rs_image_put(0, 32, 32, pixels(32, 32, 1)); + surf_a = capture(120, 80, 0); + surf_x = capture(100, 60, 1); + scene(kind); + uint8_t *out = moonbit_make_bytes(W * H * 4, 0); + rs_read_frame(out); + rs_release(surf_a); + rs_release(surf_x); + return out; +} + +static void compare(int kind) { + uint8_t *cpu = render(kind, 0), *gpu = render(kind, 1); + int worst = 0, bad = 0; + for (int i = 0; i < W * H * 4; i++) { + int d = abs(cpu[i] - gpu[i]); + if (d > worst) worst = d; + if (d > 4) bad++; /* rounding; a circle's edge is a float */ + } + /* And that something was drawn over the background at all. */ + int drawn = 0; + for (int i = 0; i < W * H; i++) drawn += cpu[i * 4 + 1] != 128; + printf("%-12s worst difference %3d, pixels off %d (of %d drawn)\n", kinds[kind], worst, bad, drawn); + if (bad > 0 || drawn < 500) failures++; +} + +/* ---- the display's buffers ---- */ + +typedef struct { int fd; uint32_t handle, pitch; uint8_t *map; } Dumb; + +static int dumb_new(int drm, int w, int h, Dumb *d) { + struct drm_mode_create_dumb c = { .width = (uint32_t)w, .height = (uint32_t)h, .bpp = 32 }; + if (drmIoctl(drm, DRM_IOCTL_MODE_CREATE_DUMB, &c) < 0) return -1; + struct drm_mode_map_dumb m = { .handle = c.handle }; + if (drmPrimeHandleToFD(drm, c.handle, DRM_CLOEXEC | DRM_RDWR, &d->fd) < 0) return -1; + if (drmIoctl(drm, DRM_IOCTL_MODE_MAP_DUMB, &m) < 0) return -1; + d->handle = c.handle; d->pitch = c.pitch; + d->map = mmap(NULL, c.size, PROT_READ | PROT_WRITE, MAP_SHARED, drm, (off_t)m.offset); + return d->map == MAP_FAILED ? -1 : 0; +} + +/* What kms_stub.c's copy_rows shows at physical (px, py). */ +static const uint8_t *expected(const uint8_t *f, int px, int py, int sc, int rot) { + int lw = W, lh = H, bw = rot & 1 ? lh : lw, bh = rot & 1 ? lw : lh, ux = px / sc, uy = py / sc, x = ux, y = uy; + if (rot == 1) { x = uy; y = bw - 1 - ux; } + else if (rot == 2) { x = bw - 1 - ux; y = bh - 1 - uy; } + else if (rot == 3) { x = bh - 1 - uy; y = ux; } + return f + ((size_t)y * lw + x) * 4; +} + +static void scanout(int drm) { + uint8_t *frame = render(1, 1); + for (int rot = 0; rot < 4; rot++) + for (int sc = 1; sc <= 2; sc++) { + int pw = (rot & 1 ? H : W) * sc, ph = (rot & 1 ? W : H) * sc; + Dumb d; + if (dumb_new(drm, pw, ph, &d) < 0) { printf("scanout skipped (no dumb buffers: %s)\n", strerror(errno)); return; } + memset(d.map, 0x55, (size_t)d.pitch * ph); + scan[0].state = 0; /* a new buffer each time */ + int ok = gpu_scanout(0, d.fd, d.pitch, pw, ph, sc, rot, 0, 0, W, H); + p_glFinish(); + int bad = 0; + for (int y = 0; ok && y < ph; y++) + for (int x = 0; x < pw; x++) { + const uint8_t *e = expected(frame, x, y, sc, rot), *g = d.map + (size_t)y * d.pitch + x * 4; + if (g[0] != e[2] || g[1] != e[1] || g[2] != e[0]) bad++; + } + printf("scanout rotation %3d, scale %d: %s, %d pixels off\n", rot * 90, sc, ok ? "drawn" : "REFUSED", bad); + if (!ok || bad) failures++; + close(d.fd); + } + /* Only the damaged part is touched. */ + Dumb d; + if (dumb_new(drm, W, H, &d) < 0) return; + memset(d.map, 0x55, (size_t)d.pitch * H); + scan[0].state = 0; + gpu_scanout(0, d.fd, d.pitch, W, H, 1, 0, 100, 50, 200, 90); + p_glFinish(); + int bad = 0; + for (int y = 0; y < H; y++) + for (int x = 0; x < W; x++) { + int in = x >= 100 && x < 200 && y >= 50 && y < 90; + const uint8_t *e = expected(frame, x, y, 1, 0), *g = d.map + (size_t)y * d.pitch + x * 4; + if (in ? g[0] != e[2] || g[1] != e[1] || g[2] != e[0] : g[0] != 0x55 || g[1] != 0x55) bad++; + } + printf("scanout a damaged part only: %d pixels off\n", bad); + if (bad) failures++; +} + +static void client_dmabuf(int drm) { + Dumb d; + if (dumb_new(drm, 64, 32, &d) < 0) return; + for (int y = 0; y < 32; y++) + for (int x = 0; x < 64; x++) { + uint8_t *p = d.map + (size_t)y * d.pitch + x * 4; + p[0] = (uint8_t)(x * 4); p[1] = (uint8_t)(y * 8); p[2] = 77; p[3] = 0; + } + int32_t plane[3] = { d.fd, 0, (int32_t)d.pitch }; + for (int flip = 0; flip < 2; flip++) { + gpu_on = 1; + uint32_t id = rs_dmabuf_import(1, plane, 0, 64, 32, DRM_XRGB, flip); + uint32_t s = id ? rs_dmabuf_capture(id) : 0; + rs_dmabuf_release(id); + rs_resize(W, H); + rs_set_clip(0, 0, 0, 0, 0); + rs_clear(); + if (s) rs_blit_surface(s, 10, 20, 64, 32); + rs_damage(0, 0, W, H); + uint8_t *out = moonbit_make_bytes(W * H * 4, 0); + rs_read_frame(out); + int bad = 0; + for (int y = 0; y < 32; y++) + for (int x = 0; x < 64; x++) { + const uint8_t *p = out + ((size_t)(y + 20) * W + x + 10) * 4; + int sy = flip ? 31 - y : y; + if (p[0] != 77 || p[1] != sy * 8 || p[2] != x * 4 || p[3] != 255) bad++; + } + printf("dmabuf %s: %d pixels off\n", flip ? "upside down" : "upright", bad); + if (!s || bad) failures++; + if (s) rs_release(s); + } + int32_t junk[3] = { open("/dev/null", O_RDWR | O_CLOEXEC), 0, 256 }; + if (rs_dmabuf_import(1, junk, 0, 64, 32, DRM_XRGB, 0) || rs_dmabuf_capture(12345)) { + printf("dmabuf a buffer that is none was accepted\n"); + failures++; + } +} + +int main(void) { + setenv("CHANDRA_TEST_CONFIG", "1", 1); + rs_font_loaded(0); + /* The crash guard: a session that died starting on the GPU keeps the next one off it, once. */ + char dir[] = "/tmp/ct-gpu-XXXXXX", sub[64], mark[96]; + if (!mkdtemp(dir)) return 1; + snprintf(sub, sizeof sub, "%s/chandra", dir); + snprintf(mark, sizeof mark, "%s/gpu-starting", sub); + mkdir(sub, 0700); + setenv("XDG_STATE_HOME", dir, 1); + const char *forced = getenv("CHANDRA_GPU"); + forced = forced ? strdup(forced) : NULL; + unsetenv("CHANDRA_GPU"); + close(open(mark, O_CREAT | O_WRONLY, 0600)); + int kept_off = !rs_gpu_init(1) && access(mark, F_OK) != 0; + if (forced) setenv("CHANDRA_GPU", forced, 1); + if (!rs_gpu_init(1)) { printf("no GPU: skipped\n"); return 77; } + printf("crash guard %s\n", kept_off ? "ok" : "FAILED"); + failures += !kept_off; + for (int k = 0; k < 9; k++) compare(k); + int32_t f[3], n = 0; + while (rs_dmabuf_format(n, f)) n++; + printf("dmabuf %d format/modifier pairs\n", n); + if (!n) failures++; + /* The card node of the GPU. */ + int drm = -1; + for (int i = 0; i < 8 && drm < 0; i++) { + char path[32]; + snprintf(path, sizeof path, "/dev/dri/card%d", i); + drm = open(path, O_RDWR | O_CLOEXEC); + } + if (drm < 0) printf("scanout skipped (no card to open)\n"); + else { client_dmabuf(drm); scanout(drm); } + int marked = access(mark, F_OK) == 0; /* drawing on the display has begun */ + if (drm >= 0 && !marked) { printf("crash guard no mark while starting\n"); failures++; } + guard_exit(); + rmdir(sub); + rmdir(dir); + printf(failures ? "FAILED: %d\n" : "ok\n", failures); + return failures ? 1 : 0; +} diff --git a/wit/host/raster.wit b/wit/host/raster.wit index 6ab1866..841c669 100644 --- a/wit/host/raster.wit +++ b/wit/host/raster.wit @@ -55,6 +55,21 @@ interface raster { /// host surface. `format` is the wl_shm format (0 ARGB8888, 1 XRGB8888). 0 on failure. capture: func(fd: s32, offset: s32, stride: s32, width: s32, height: s32, format: s32) -> u32; release: func(id: u32); + + /// Client buffers that live on the GPU (linux-dmabuf). A pixel format (DRM fourcc) and layout + /// (DRM modifier) the GPU reads. + record dmabuf-format { fourcc: u32, modifier: u64 } + /// `device`: the `dev_t` of the GPU clients should draw on. No formats: the host draws on the + /// CPU and takes no such buffers. + record dmabuf-support { device: u64, formats: list } + dmabufs: func() -> dmabuf-support; + record dmabuf-plane { fd: s32, offset: u32, stride: u32 } + /// Import a buffer (the fds stay the caller's to close). 0 when the GPU can't read it. + import-dmabuf: func(planes: list, modifier: u64, width: s32, height: s32, fourcc: u32, y-invert: bool) -> u32; + /// What the buffer holds now as a surface, like `capture` (a copy on the GPU: the client may + /// draw into its buffer again at once). 0 on failure. + capture-dmabuf: func(id: u32) -> u32; + release-dmabuf: func(id: u32); /// Decode the PNG or SVG file at `path` into a host image (an app icon), for `draw-image`. /// Loading the same path again returns the same handle. 0 when it can't be read or decoded. load-image: func(path: string) -> u32; From b293ecb51ad9aef918d54cf75f504b5bea4010ad Mon Sep 17 00:00:00 2001 From: nandithebull Date: Mon, 30 Nov 2026 16:47:03 -0800 Subject: [PATCH 2/3] Backlight: don't ask the host for the environment while instantiating The wasm compositor trapped at start since e2dc2bb: a top-level value called getenv. Co-Authored-By: Claude Opus 5.5 --- compositor/shell/backlight.mbt | 33 ++++++++++++++++++++++++++++----- 1 file changed, 28 insertions(+), 5 deletions(-) diff --git a/compositor/shell/backlight.mbt b/compositor/shell/backlight.mbt index 1c90f72..bb86f89 100644 --- a/compositor/shell/backlight.mbt +++ b/compositor/shell/backlight.mbt @@ -1,6 +1,27 @@ ///| Linux backlight provider for the `power` capability (sysfs read + logind SetBrightness fallback). -let backlight_root : Ref[String] = { val: "/sys/class/backlight" } +///| Where backlight devices are: /sys/class/backlight, or $CHANDRA_BACKLIGHT_ROOT (the test runner +/// gives every test a fake one, so no test changes the real screen's brightness). +pub fn default_backlight_root() -> String { + let env = @sys.getenv("CHANDRA_BACKLIGHT_ROOT") + if env.length() > 0 { + env + } else { + "/sys/class/backlight" + } +} + +///| The directory in use; "" until it is first needed (a wasm component can't call the host while +/// it is being instantiated, which is when top-level values are made). +let backlight_root_set : Ref[String] = { val: "" } + +///| +fn backlight_root() -> String { + if backlight_root_set.val == "" { + backlight_root_set.val = default_backlight_root() + } + backlight_root_set.val +} let backlight_sample_sec : Ref[Int] = { val: -1 } @@ -8,7 +29,7 @@ let backlight_cached : Ref[Int] = { val: -1 } ///| Override /sys/class/backlight root for unit tests. pub fn set_backlight_root(dir : String) -> Unit { - backlight_root.val = dir + backlight_root_set.val = dir backlight_sample_sec.val = -1 backlight_cached.val = -1 } @@ -94,7 +115,7 @@ fn clamp_pct(pct : Int, lo : Int, hi : Int) -> Int { } ///| Read backlight brightness percentage in 0..100, or -1 if no backlight exists. -pub fn read_backlight_percent(root? : String = backlight_root.val) -> Int { +pub fn read_backlight_percent(root? : String = backlight_root()) -> Int { match find_backlight(root) { None => -1 Some(dev) => clamp_pct(((dev.cur * 100L + dev.max / 2L) / dev.max).to_int(), 0, 100) @@ -115,7 +136,7 @@ pub fn read_backlight_polled() -> Int { pub fn write_backlight_percent( pct : Int, display : String, - root? : String = backlight_root.val, + root? : String = backlight_root(), ) -> Int { match find_backlight(root) { None => -1 @@ -124,7 +145,9 @@ pub fn write_backlight_percent( let raw0 = (clamped.to_int64() * dev.max + 50L) / 100L let raw = if raw0 < 1L { 1L } else if raw0 > dev.max { dev.max } else { raw0 } let data = @utf8.encode(raw.to_string() + "\n") - if @sys.write_file_bytes(dev.path + "/brightness", data) < 0 { + // Under test (CHANDRA_TEST_CONFIG=1) never ask logind: that would change the real screen. + if @sys.write_file_bytes(dev.path + "/brightness", data) < 0 && + @sys.getenv("CHANDRA_TEST_CONFIG") != "1" { let sid = @sys.getenv("XDG_SESSION_ID").trim(chars=" \n\r\t").to_string() let sess = if sid.length() > 0 && safe_backlight_name(sid) { "/org/freedesktop/login1/session/" + sid From c5dbe028e649b9b2be3a8e302aa021afe28410d1 Mon Sep 17 00:00:00 2001 From: nandithebull Date: Mon, 30 Nov 2026 16:49:06 -0800 Subject: [PATCH 3/3] Panel: generate the Show Desktop interfaces and toggle request - Add generated .mbti interfaces for show-desktop, its plasmoid, and the show-desktop-widget world - Add a ToggleDesktop host request and publish_desktop_shown(Bool) for the panel to report desktop state --- .../desktop/plasmoid/pkg.generated.mbti | 42 +++++++++++++++++++ .../show-desktop/gen/pkg.generated.mbti | 13 ++++++ .../desktop/show-desktop/pkg.generated.mbti | 15 +++++++ .../chandra/host/plasmoids/pkg.generated.mbti | 3 ++ world/show-desktop-widget/pkg.generated.mbti | 12 ++++++ 5 files changed, 85 insertions(+) create mode 100644 components/show-desktop/gen/interface/chandra/desktop/plasmoid/pkg.generated.mbti create mode 100644 components/show-desktop/gen/pkg.generated.mbti create mode 100644 interface/chandra/desktop/show-desktop/pkg.generated.mbti create mode 100644 world/show-desktop-widget/pkg.generated.mbti diff --git a/components/show-desktop/gen/interface/chandra/desktop/plasmoid/pkg.generated.mbti b/components/show-desktop/gen/interface/chandra/desktop/plasmoid/pkg.generated.mbti new file mode 100644 index 0000000..f05063e --- /dev/null +++ b/components/show-desktop/gen/interface/chandra/desktop/plasmoid/pkg.generated.mbti @@ -0,0 +1,42 @@ +// Generated using `moon info`, DON'T EDIT IT +package "chandra/desktop/components/show-desktop/gen/interface/chandra/desktop/plasmoid" + +import { + "chandra/desktop/interface/chandra/desktop/types", +} + +// Values +pub fn info() -> PlasmoidInfo + +pub fn on_event(Surface, @types.InputEvent) -> Bool + +pub fn popup() -> PopupSurface? + +pub fn render(@types.Size) -> Array[@types.DrawOp] + +// Errors + +// Types and methods +pub(all) struct PlasmoidInfo { + id : String + name : String + preferred : @types.Size + min_width : UInt32 + stretch : Bool +} + +pub(all) struct PopupSurface { + size : @types.Size + ops : Array[@types.DrawOp] +} + +pub(all) enum Surface { + WIDGET + POPUP +} +pub fn Surface::from(Int32) -> Self +pub fn Surface::ordinal(Self) -> Int32 + +// Type aliases + +// Traits diff --git a/components/show-desktop/gen/pkg.generated.mbti b/components/show-desktop/gen/pkg.generated.mbti new file mode 100644 index 0000000..e6df652 --- /dev/null +++ b/components/show-desktop/gen/pkg.generated.mbti @@ -0,0 +1,13 @@ +// Generated using `moon info`, DON'T EDIT IT +package "chandra/desktop/components/show-desktop/gen" + +// Values +pub fn mbt_ffi_cabi_realloc(Int32, Int32, Int32, Int32) -> Int32 + +// Errors + +// Types and methods + +// Type aliases + +// Traits diff --git a/interface/chandra/desktop/show-desktop/pkg.generated.mbti b/interface/chandra/desktop/show-desktop/pkg.generated.mbti new file mode 100644 index 0000000..5619200 --- /dev/null +++ b/interface/chandra/desktop/show-desktop/pkg.generated.mbti @@ -0,0 +1,15 @@ +// Generated using `moon info`, DON'T EDIT IT +package "chandra/desktop/interface/chandra/desktop/show-desktop" + +// Values +pub fn is_shown() -> Bool + +pub fn toggle() -> Unit + +// Errors + +// Types and methods + +// Type aliases + +// Traits diff --git a/interface/chandra/host/plasmoids/pkg.generated.mbti b/interface/chandra/host/plasmoids/pkg.generated.mbti index d60949f..b10f346 100644 --- a/interface/chandra/host/plasmoids/pkg.generated.mbti +++ b/interface/chandra/host/plasmoids/pkg.generated.mbti @@ -35,6 +35,8 @@ pub fn publish_brightness(Int32) -> Unit pub fn publish_desktop(Int32) -> Unit +pub fn publish_desktop_shown(Bool) -> Unit + pub fn publish_osk(Bool) -> Unit pub fn publish_power(UInt32, UInt32) -> Unit @@ -139,6 +141,7 @@ pub(all) enum Request { SetBrightness(Int32) SetOskVisible(Bool) SetRotation(Int32) + ToggleDesktop } pub(all) struct SettingChange { diff --git a/world/show-desktop-widget/pkg.generated.mbti b/world/show-desktop-widget/pkg.generated.mbti new file mode 100644 index 0000000..28d0ce3 --- /dev/null +++ b/world/show-desktop-widget/pkg.generated.mbti @@ -0,0 +1,12 @@ +// Generated using `moon info`, DON'T EDIT IT +package "chandra/desktop/world/show-desktop-widget" + +// Values + +// Errors + +// Types and methods + +// Type aliases + +// Traits