Sound and Camera

A sound card with playback and capture, and a V4L2 camera, for guest programs.

import { createKernel, pcmToFloat32 } from "unkernel";

const vm = await createKernel({
  sound: { onChunk: ({ data, format }) => play(pcmToFloat32(data, format)) }, // ALSA hw:0,0 and /dev/dsp
});

sound gives the guest a sound card (ALSA hw:0,0 and OSS /dev/dsp): true drops what it plays, or a sink receives the PCM chunks with their format and the playback state.

#Sound in browsers

createAudioOut() plays the guest's sound with Web Audio:

import { createAudioOut, createKernel } from "unkernel/web";

button.hidden = true;
const audio = createAudioOut({
  onChange: (state) => {
    button.hidden = state !== "waiting"; // "click to play"
  },
});
const vm = await createKernel({ sound: audio });
button.onclick = () => audio.resume(); // or any other click or key press on the page

Browsers start sound only after a click, tap or key press on the page. Until then the latest holdSeconds (10) of what the guest plays are held: a clip that has ended by then plays whole, a stream joins live. audio.muted = true silences it.

One sink serves one kernel at a time, and outlives it: pass it to the next kernel, or close() it.

#Microphone

soundIn gives the sound card a capture substream: what arecord records, or a read of /dev/dsp. createAudioIn() from unkernel/web is the user's microphone. It is asked for only when a guest program starts recording and released when the program closes the device; until then the guest records silence. Anywhere else, true records silence, or a source's read(out, rate) fills out with mono samples in [-1, 1].

import { createAudioIn, createAudioOut, createKernel } from "unkernel/web";

const vm = await createKernel({ sound: createAudioOut(), soundIn: createAudioIn() });

#Camera

camera gives the guest /dev/video0, a V4L2 device with I420, NV12 and YUYV up to 1280x720 at 30 frames a second, for v4l2-ctl, ffmpeg, GStreamer or a browser in the guest. createCamera() from unkernel/web is the user's camera. It is asked for only when a guest program starts streaming and released when the program stops; until then the guest gets black frames. Anywhere else, true gives black frames, or a source's read(out, format) writes the current frame in the stream's format.

import { createCamera, createKernel } from "unkernel/web";

const vm = await createKernel({ camera: createCamera() });
// in the guest: ffmpeg -f v4l2 -input_format h264 -i /dev/video0 -c:v copy out.mkv

Where the browser's VideoEncoder makes H.264, the camera offers it too, encoded on the host, so the guest copies the stream instead of encoding it, as with a webcam that encodes. The CLI's --camera shows a test pattern, and --camera=h264 also offers it as H.264.