Guides

Embedding in a web page

Run Warm64 in a web worker, draw on a canvas, keep disks in OPFS, and enable multiple cores with cross-origin isolation.

Warm64 runs in any modern browser. For a responsive page, run it in a web worker and let the page handle the canvas, the keyboard and the pointer.

Why a worker

  • Speed. Warm64 starts faster in a worker. On a page's main thread, the browser holds back some of the work it needs to get going.
  • Responsiveness. The machine runs in slices on whatever thread it's given. In a worker, your page never has to wait for it.
  • Storage. Disks that persist need the Origin Private File System's synchronous handles, which only exist in workers.

Files to serve

Serve the package's wasm/ directory and its dist/ scripts together, laid out as they are in the package, because Warm64 starts its own workers from files next to its scripts. browserWARMHost({ base }) fetches the core from ${base}wasm/${kind}.wasm.

The worker

worker.js
import { WARM, browserWARMHost } from "/node_modules/@warm-virtual/warm64/dist/index.js";

let vm;
self.onmessage = async ({ data }) => {
  if (data.type === "start") {
    vm = await WARM.launch(data.args, {
      ...browserWARMHost({ base: "/node_modules/@warm-virtual/warm64/" }),
      display: data.canvas ? { canvas: data.canvas } : undefined,
    });
    vm.serial[0].onData((bytes) => self.postMessage({ type: "output", bytes }));
    await vm.qmp("cont");
  } else if (data.type === "input") {
    vm.serial[0].write(data.text);
  } else if (data.type === "qmp") {
    self.postMessage({ type: "reply", id: data.id, reply: await vm.qmpJson(data.json) });
  }
};

The page

main.js
const worker = new Worker("worker.js", { type: "module" });
const el = document.querySelector("canvas");
const canvas = el.transferControlToOffscreen();

worker.postMessage({
  type: "start",
  canvas,
  args: "-m 1G -cpu cortex-a76 -S -kernel /images/vmlinuz-virt -initrd /images/initramfs-virt -append console=ttyAMA0 " +
        "-accel wapi -display default,gl=on -device virtio-gpu-gl-pci -device virtio-keyboard-pci -device virtio-tablet-pci",
}, [canvas]);

const decoder = new TextDecoder();
worker.onmessage = ({ data }) => {
  if (data.type === "output") terminal.write(decoder.decode(data.bytes, { stream: true }));
};

transferControlToOffscreen() moves the canvas to the worker, and Warm64 passes it on to its GPU worker, which draws on it with WebGPU or WebGL2. -accel wapi lets it use those; under tcg it draws in software.

The command line starts the machine paused with -S, so the worker can attach its console listener before any output arrives. cont then sets it running.

Keyboard and pointer

Forward the page's events to the worker and turn them into QMP there. Pointer positions run from 0 to 32767 across the canvas:

main.js
el.addEventListener("pointermove", (e) => {
  const x = Math.round((e.offsetX / el.clientWidth) * 32767);
  const y = Math.round((e.offsetY / el.clientHeight) * 32767);
  worker.postMessage({ type: "qmp", id: 0, json: JSON.stringify({
    execute: "input-send-event",
    arguments: { events: [
      { type: "abs", data: { axis: "x", value: x } },
      { type: "abs", data: { axis: "y", value: y } },
    ] },
  }) });
});

Keys work the same way, with input-send-event and { type: "key", data: { down, key: { type: "qcode", data } } }. Map the browser's KeyboardEvent.code to QEMU's key names.

Leave the page's pointer visible over the canvas. With a tablet, it is the guest's cursor, and the display doesn't draw one.

With a relative mouse instead (-device virtio-mouse-pci and no tablet), the display draws the guest's cursor. The page captures the pointer on a click, as QEMU's window does, and sends its movement:

main.js
el.addEventListener("click", () => el.requestPointerLock());
el.addEventListener("pointermove", (e) => {
  if (document.pointerLockElement !== el) return;
  worker.postMessage({ type: "qmp", id: 0, json: JSON.stringify({
    execute: "input-send-event",
    arguments: { events: [
      { type: "rel", data: { axis: "x", value: e.movementX } },
      { type: "rel", data: { axis: "y", value: e.movementY } },
    ] },
  }) });
});

Buttons are sent as btn events, as with a tablet. The browser releases the pointer when you press Esc.

Cross-origin isolation

More than one core, and the fastest GPU module, need SharedArrayBuffer, which browsers only give to cross-origin-isolated pages. Serve the page with these headers:

Cross-Origin-Opener-Policy: same-origin
Cross-Origin-Embedder-Policy: require-corp

You can check it from script with self.crossOriginIsolated. Without it, a single core still runs, and the GPU falls back to its single-threaded module.

Disks that persist

The stock browser host reads each disk whole and keeps the guest's writes in memory. To keep the writes, open the disks in OPFS from the worker, as shown in openDisk.

Networking

Browsers can't open TCP connections, so the guest's connections go through a relay. See Networking in a browser.

Background tabs

A hidden tab gets far less CPU time, while the guest's clocks keep following the wall clock, so a machine in a background tab runs much slower. Keep the page visible while a guest boots.

See also