js: convert XRGB8888 framebuffer pixels with Wasm SIMD (#188)

* js: convert XRGB8888 framebuffer pixels with Wasm SIMD

* js: keep the pixel SIMD scratch buffer off address 0

* js: move the frame conversion test to test/display.test.ts and check the embedded module

The test needs no kernel. It now also covers readRGBA()'s packed and padded paths and a shared source, and rebuilds pixel-simd.zig where zig 0.16 is on PATH to compare it with the embedded bytes.

---------

Co-authored-by: Pooya Parsa <pooya@pi0.io>
This commit is contained in:
Kotaro Chikuba
2026-12-05 08:49:32 +09:00
committed by GitHub
parent f3fffb594f
commit c554197790
6 changed files with 188 additions and 3 deletions

View File

@@ -17,7 +17,7 @@ Run the row for what you changed, and no more.
| JIT control flow, regions, budget or polls | the row above; `zig build test -Dkwemu-a64-fuzz=20000` (the A64 block fuzz; a64/jit.md) |
| Base initramfs, kw layer, distro images (`guest/`) | `KW_BASE_OUT=/tmp/b kernel/build.sh base`, `KW_BASE_OUT=/tmp/b KW_DISTRO_OUT=/tmp/d guest/build.sh distro`, then `UNKERNEL_TEST_BASE_KERNEL=/tmp/b/unkernel.wasm UNKERNEL_TEST_DISTRO_DIR=/tmp/d pnpm test:distro` and `UNKERNEL_TEST_KERNEL=/tmp/b/unkernel.wasm UNKERNEL_TEST_DISTRO_DIR=/tmp/d pnpm test:api` (or the same in place: `kernel/build.sh base`, `kernel/build.sh distro`, `pnpm test:distro`, `pnpm test:api`); `UNKERNEL_TEST_DISTRO_FORMAT=ext4` for the ext4 images; optional: `node js/cli.ts --timeout 120 --input '{8}uname -a; apk --version\n{2}poweroff\n'` |
| distros.json, `fetchDistro()` (`guest/tools/distros-json.mjs`, `js/node/distro-fetch.ts`) | `guest/build.sh index` (with the same `KW_BASE_OUT`/`KW_DISTRO_OUT` as the build); `pnpm test:distro-fetch` (the downloader and its cache against a local server, no internet); `pnpm build`, then the downloader against a local copy of the release (below, SDK row) |
| Display, input, sound (kwfb, kwinput, kwsnd) | `pnpm test:api`; optional: `node test/glimmer-check.mjs --run`; for capture `node test/mic-check.mjs` (the page's microphone in headless Chromium) |
| Display, input, sound (kwfb, kwinput, kwsnd) | `pnpm test:display` (the frame conversion, no kernel); `pnpm test:api`; optional: `node test/glimmer-check.mjs --run`; for capture `node test/mic-check.mjs` (the page's microphone in headless Chromium) |
| Camera (kwcam, `js/core/camera*.ts`, `js/web/camera*.ts`) | `pnpm test:camera` (with `test/camera-h264.test.ts`: H.264, the chunk ring, the encoder driver on stand-ins); `node --test --test-name-pattern="camera\|H\.264" test/api.test.ts` (and with `UNKERNEL_TEST_CPUS=2`); `node test/camera-check.mjs` (the page's camera in headless Chromium, H.264 through its OpenH264 too; `KW_KERNEL=BUNDLE` for a bundle beside the main one); the camera to the VA-API encoder: `node --test test/va-camera.test.ts` and `node test/va/check.mjs --gl --camera --disk vendor/build/va/debian-va-apps.img --skip vainfo,vadecode,ffmpeg,recover,fps,mpv,h264,modes,av1,encode,export,wland,bgr0,mpvfps` (and `--worker`; va.md, Testing); a real consumer: `v4l2-compliance -s 10` from Alpine's v4l-utils (community) under `--camera` (57 of 57, 2026-11-29); H.264 under `--camera=h264` in a Debian guest (v4l-utils, ffmpeg, GStreamer's good and bad plugins): `v4l2-compliance -s 10` with YUYV and with H.264 set, and `-s 10 -f` (57 and 129 of 129), `ffmpeg -f v4l2 -input_format h264 -video_size 1280x720 -i /dev/video0 -t 5 -c:v copy out.mkv` (and to mp4, and with `-f alsa -i default -c:a aac` under `--sound-in`: the streams' durations agree) checked with `ffprobe -count_frames` and `ffmpeg -xerror -i out.mkv -f null -`, `gst-launch-1.0 v4l2src ! video/x-h264 ! h264parse ! matroskamux` |
| kwvirtio, virtio-gpu (`js/core/virtio*.ts`) | the kernel row; `node test/gpu/check.mjs` (a dumb-buffer KMS client against the host's frame, a refused and a restored snapshot, display size changes heard by `test/gpu/kms-hotplug.c` inline and in worker mode), `node test/gpu/flip-check.mjs BUNDLE 120 30` (page flips and DIRTYFB at 60 Hz, the idle tail); for SMP paths `--cpus 2 --pin 1`; 3D (`js/core/gl-gpu.ts`, `kw_vgpu_*`): `node test/gl/unkernel-check.mjs --drm` (headless Chromium; gl.md, Testing) |
| Bluetooth (kwbt, `js/core/bluetooth*.ts`, `js/web/bluetooth.ts`) | `pnpm typecheck`; `pnpm test:bluetooth` (the host's unit tests, then `test/bluetooth/kwbt.c` on the kernel, UP and 2 CPUs); BlueZ against the CLI's `--bluetooth` peripheral in Debian after `apt install bluez`: `bluetoothctl` scan on, connect, `menu gatt` list-attributes, read, write, notify on (kernel/devices.md, kwbt) |

View File

@@ -27,6 +27,8 @@
// guest when it changes (KernelInstance.updateDisplaySize(): a hotplug);
// kwfb takes it at the next first open.
import { simdXrgbToRgba } from "./pixel-simd.ts";
/** DRM fourcc of XRGB8888 ("XR24"): 32-bit pixels, little endian B, G, R, X. */
export const FOURCC_XRGB8888 = 0x34325258;
const ENODEV = 19;
@@ -259,6 +261,7 @@ export class DisplayHost {
const px = this.pixels();
if (!m || !px) return null;
const { width, height, stride } = m;
if (stride === width * 4) return { width, height, data: xrgbToRgba(px, width, height, out) };
const data = out && out.length === width * height * 4 ? out : new Uint8ClampedArray(width * height * 4);
const dst = new Uint32Array(data.buffer, data.byteOffset, width * height);
// Typed arrays use the platform byte order, which is little endian on
@@ -288,7 +291,7 @@ export function xrgbToRgba(src: Uint8Array, width: number, height: number, out?:
const dst = new Uint32Array(data.buffer, data.byteOffset, n);
// Little endian, as in readRGBA(): 0xXXRRGGBB in, 0xAABBGGRR out.
const s = new Uint32Array(src.buffer, src.byteOffset, n);
for (let i = 0; i < n; i++) {
for (let i = simdXrgbToRgba(s, dst); i < n; i++) {
const p = s[i]!;
dst[i] = 0xff000000 | ((p & 0xff) << 16) | (p & 0xff00) | ((p >>> 16) & 0xff);
}

67
js/core/pixel-simd.ts Normal file
View File

@@ -0,0 +1,67 @@
// SPDX-License-Identifier: MIT
// Copyright (C) 2026 mizchi
// Generated from pixel-simd.zig with Zig 0.16.0, from the repository root:
// zig build-exe js/core/pixel-simd.zig -target wasm32-freestanding -mcpu=mvp+simd128 \
// -O ReleaseFast -fno-entry -fstrip -rdynamic --stack 0 --global-base=16 \
// --max-memory=1114112 -femit-bin=/tmp/pixel-simd.wasm
// (--global-base keeps `scratch` off address 0, which Zig takes for null.)
// Embed the resulting bytes so the SDK can run directly from source;
// test/display.test.ts rebuilds them where zig is on PATH and compares.
/** @internal The helper module's bytes (exported for that test). */
export const pixelSimdWasm = new Uint8Array([
0, 97, 115, 109, 1, 0, 0, 0, 1, 9, 2, 96, 1, 127, 0, 96, 0, 1, 127, 3,
3, 2, 0, 1, 4, 5, 1, 112, 1, 1, 1, 5, 4, 1, 1, 17, 17, 6, 9, 1,
127, 1, 65, 144, 128, 192, 0, 11, 7, 33, 3, 6, 109, 101, 109, 111, 114, 121, 2, 0,
4, 114, 103, 98, 97, 0, 0, 13, 115, 99, 114, 97, 116, 99, 104, 79, 102, 102, 115, 101,
116, 0, 1, 10, 119, 2, 108, 2, 2, 127, 1, 123, 2, 64, 32, 0, 65, 127, 106, 65,
255, 255, 63, 75, 13, 0, 32, 0, 65, 15, 113, 13, 0, 65, 0, 33, 1, 3, 64, 32,
1, 65, 144, 128, 128, 128, 0, 106, 34, 2, 32, 2, 253, 0, 4, 0, 253, 12, 0, 0,
0, 255, 0, 0, 0, 255, 0, 0, 0, 255, 0, 0, 0, 255, 253, 80, 32, 3, 253, 13,
2, 1, 0, 3, 6, 5, 4, 7, 10, 9, 8, 11, 14, 13, 12, 15, 253, 11, 4, 0,
32, 1, 65, 16, 106, 34, 1, 32, 0, 73, 13, 0, 11, 11, 11, 8, 0, 65, 144, 128,
128, 128, 0, 11,
]);
interface Simd {
scratch: Uint8Array;
rgba(length: number): void;
}
let simd: Simd | null | undefined;
function getSimd(): Simd | null {
if (simd !== undefined) return simd;
try {
const { memory, scratchOffset, rgba } = new WebAssembly.Instance(new WebAssembly.Module(pixelSimdWasm)).exports as {
memory: WebAssembly.Memory;
scratchOffset(): number;
rgba(length: number): void;
};
simd = {
scratch: new Uint8Array(memory.buffer, scratchOffset(), 1024 * 1024),
rgba,
};
} catch {
simd = null;
}
return simd;
}
/** Convert whole vectors and return the number of pixels processed. */
export function simdXrgbToRgba(src: Uint32Array, dst: Uint32Array): number {
// The scalar loop also handles callers passing aliased input and output.
if (src.length < 1024 || src.buffer === dst.buffer) return 0;
const host = getSimd();
if (!host) return 0;
const length = src.byteLength - (src.byteLength % 16);
const input = new Uint8Array(src.buffer, src.byteOffset, length);
const output = new Uint8Array(dst.buffer, dst.byteOffset, length);
for (let i = 0; i < length; i += host.scratch.length) {
const chunk = input.subarray(i, i + host.scratch.length);
host.scratch.set(chunk);
host.rgba(chunk.length);
output.set(host.scratch.subarray(0, chunk.length), i);
}
return length / 4;
}

20
js/core/pixel-simd.zig Normal file
View File

@@ -0,0 +1,20 @@
// SPDX-License-Identifier: MIT
// Copyright (C) 2026 mizchi
const Bytes = @Vector(16, u8);
const rgba_order: @Vector(16, i32) = .{ 2, 1, 0, 3, 6, 5, 4, 7, 10, 9, 8, 11, 14, 13, 12, 15 };
const opaque_alpha: Bytes = .{ 0, 0, 0, 255, 0, 0, 0, 255, 0, 0, 0, 255, 0, 0, 0, 255 };
var scratch: [1024 * 1024]u8 align(16) = undefined;
export fn scratchOffset() usize {
return @intFromPtr(&scratch);
}
export fn rgba(length: usize) void {
if (length > scratch.len or length % @sizeOf(Bytes) != 0) return;
var i: usize = 0;
while (i < length) : (i += @sizeOf(Bytes)) {
const lanes: *Bytes = @ptrCast(@alignCast(&scratch[i]));
lanes.* = @shuffle(u8, lanes.*, undefined, rgba_order) | opaque_alpha;
}
}

View File

@@ -51,7 +51,7 @@
"scripts": {
"build": "obuild",
"typecheck": "tsc -p .",
"test": "pnpm typecheck && pnpm test:jit && pnpm test:block && pnpm test:net && pnpm test:tty && pnpm test:http && pnpm test:ws && pnpm test:9p && pnpm test:distro-fetch && pnpm test:distro && pnpm test:gl-gpu && pnpm test:vk && pnpm test:va && pnpm test:audio && pnpm test:serial-host && pnpm test:bluetooth-host && pnpm test:usb-host",
"test": "pnpm typecheck && pnpm test:jit && pnpm test:block && pnpm test:net && pnpm test:tty && pnpm test:http && pnpm test:ws && pnpm test:9p && pnpm test:distro-fetch && pnpm test:distro && pnpm test:gl-gpu && pnpm test:vk && pnpm test:va && pnpm test:audio && pnpm test:display && pnpm test:serial-host && pnpm test:bluetooth-host && pnpm test:usb-host",
"test:block": "node --test test/block.test.ts test/opfs-disk.test.ts",
"test:net": "node --test test/net.test.ts test/net-policy.test.ts",
"test:tty": "node --test test/tty.test.ts",
@@ -69,6 +69,7 @@
"test:vk": "node --test test/vk.test.ts",
"test:va": "node --test test/va.test.ts test/va-h264.test.ts test/va-decoders.test.ts test/va-av1.test.ts test/va-frames.test.ts test/va-enc.test.ts test/va-camera.test.ts",
"test:audio": "node --test test/audio.test.ts test/audio-in.test.ts",
"test:display": "node --test test/display.test.ts",
"test:camera": "node --test test/camera.test.ts test/camera-h264.test.ts",
"test:serial-host": "node --test test/serial-host.test.ts",
"test:serial": "node --test test/serial-host.test.ts test/serial.test.ts",

94
test/display.test.ts Normal file
View File

@@ -0,0 +1,94 @@
// SPDX-License-Identifier: MIT
// Copyright (C) 2026 mizchi
// Copyright (C) 2026 Pooya Parsa <pooya@pi0.io>
// XRGB8888 to RGBA conversion (js/core/display.ts, js/core/pixel-simd.ts)
// without a kernel, and the embedded SIMD module against its Zig source.
//
// node --test test/display.test.ts
import assert from "node:assert/strict";
import { spawnSync } from "node:child_process";
import { mkdtempSync, readFileSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import path from "node:path";
import { test } from "node:test";
import { fileURLToPath } from "node:url";
import { DisplayHost, FOURCC_XRGB8888, xrgbToRgba } from "../js/core/display.ts";
import { pixelSimdWasm } from "../js/core/pixel-simd.ts";
const root = fileURLToPath(new URL("..", import.meta.url));
/** Packed XRGB8888 pixels with distinct channels, and their RGBA. */
function pattern(width: number, height: number, buffer?: ArrayBufferLike, offset = 0): { input: Uint8Array; expected: Uint8ClampedArray } {
const n = width * height * 4;
const input = new Uint8Array(buffer ?? new ArrayBuffer(n), offset, n);
const expected = new Uint8ClampedArray(n);
for (let i = 0; i < n; i += 4) {
input[i] = (i >>> 2) & 255;
input[i + 1] = (i >>> 6) & 255;
input[i + 2] = (i >>> 12) & 255;
input[i + 3] = (i >>> 3) & 255;
expected[i] = input[i + 2]!;
expected[i + 1] = input[i + 1]!;
expected[i + 2] = input[i]!;
expected[i + 3] = 255;
}
return { input, expected };
}
test("packed framebuffer conversion covers a scratch boundary, tail pixels and in-place output", () => {
// 1025 x 257 pixels: more than the 1 MiB scratch, and not a multiple of 4.
const width = 1025, height = 257;
const { input, expected } = pattern(width, height);
assert.deepEqual(xrgbToRgba(input, width, height), expected);
const out = new Uint8ClampedArray(input.buffer);
assert.equal(xrgbToRgba(input, width, height, out), out);
assert.deepEqual(out, expected);
});
test("packed framebuffer conversion from a shared buffer at an offset, into a reused output at an offset", () => {
const width = 1023, height = 515;
const { input, expected } = pattern(width, height, new SharedArrayBuffer(width * height * 4 + 32), 12);
const out = new Uint8ClampedArray(new ArrayBuffer(expected.length + 16), 8, expected.length).fill(7);
assert.equal(xrgbToRgba(input, width, height, out), out);
assert.deepEqual(out, expected);
// Small frames take the scalar loop only.
const small = pattern(31, 3);
assert.deepEqual(xrgbToRgba(small.input, 31, 3), small.expected);
});
test("readRGBA() converts a packed scanout and one with padded rows", () => {
for (const pad of [0, 12]) {
const width = 1027, height = 300, stride = width * 4 + pad;
const { input, expected } = pattern(width, height);
const px = new Uint8Array(stride * height);
for (let y = 0; y < height; y++) px.set(input.subarray(y * width * 4, (y + 1) * width * 4), y * stride);
const display = new DisplayHost({ memory: () => new WebAssembly.Memory({ initial: 1 }) });
display.setScanout({ mode: { width, height, stride, format: FOURCC_XRGB8888 }, pixels: () => px });
const out = new Uint8ClampedArray(expected.length);
const frame = display.readRGBA(out);
assert.ok(frame, `pad ${pad}`);
assert.equal(frame.data, out);
assert.deepEqual([frame.width, frame.height], [width, height]);
assert.deepEqual(frame.data, expected, `pad ${pad}`);
}
});
const zig = process.env.ZIG ?? "zig";
const zigVersion = spawnSync(zig, ["version"], { encoding: "utf8" });
const noZig = zigVersion.status !== 0 ? `no ${zig} on PATH` :
!zigVersion.stdout.startsWith("0.16.") ? `zig ${zigVersion.stdout.trim()}, not 0.16` : false;
test("the embedded pixel SIMD module is the build of pixel-simd.zig", { skip: noZig }, () => {
const dir = mkdtempSync(path.join(tmpdir(), "pixel-simd-"));
try {
const out = path.join(dir, "pixel-simd.wasm");
// The command in js/core/pixel-simd.ts.
const r = spawnSync(zig, ["build-exe", "js/core/pixel-simd.zig", "-target", "wasm32-freestanding", "-mcpu=mvp+simd128",
"-O", "ReleaseFast", "-fno-entry", "-fstrip", "-rdynamic", "--stack", "0", "--global-base=16",
"--max-memory=1114112", `-femit-bin=${out}`], { cwd: root, encoding: "utf8" });
assert.equal(r.status, 0, r.stderr);
assert.deepEqual(new Uint8Array(readFileSync(out)), pixelSimdWasm);
} finally {
rmSync(dir, { recursive: true, force: true });
}
});