mirror of
https://github.com/pithings/unkernel.git
synced 2026-12-02 00:39:40 +08:00
Microphone: kwsnd gains a capture substream fed by the host (SDK option soundIn, the page's Microphone setting and ?mic=0, the CLI's --sound-in-wav and --sound-in). Camera: kwcam is a V4L2 capture device (/dev/video0) fed by the host: I420, NV12 and YUYV at 320x240 to 1280x720, and H.264 encoded by the host's WebCodecs encoder where it has one, with bitrate, GOP and key frame controls (SDK option camera, the page's Camera setting and ?cam=0, the CLI's --camera). The base's rc writes the udev database entry of /dev/video*, so programs that list cameras through libudev find it. kwva (protocol 5): an encode whose input surface is a camera buffer's dma-buf names the frame to the host instead of sending its pixels, and pixels an app writes into an exported surface reach the host (put).
189 lines
7.6 KiB
TypeScript
189 lines
7.6 KiB
TypeScript
// SPDX-License-Identifier: MIT
|
|
// Copyright (C) 2026 Pooya Parsa <pooya@pi0.io>
|
|
// A kwsnd sink for Node: what the guest played, as a WAV file (the CLI's
|
|
// --sound-wav); and capture sources: a WAV file or a tone (--sound-in-wav,
|
|
// --sound-in). See core/sound.ts.
|
|
import fs from "node:fs";
|
|
import {
|
|
SOUND_FORMAT_S16_LE, SOUND_FORMAT_U8, convertPcm, pcmToFloat32, wavHeader,
|
|
type SoundEvent, type SoundFormat, type SoundInStats, type SoundSink, type SoundSource, type SoundState, type SoundStats,
|
|
} from "../core/sound.ts";
|
|
|
|
/**
|
|
* Write every chunk the guest plays to `file`, in the format of the first
|
|
* stream; later streams in another format are converted (core/sound.ts,
|
|
* convertPcm). Gaps (underruns, time between streams) are not recorded: the
|
|
* file is the samples back to back. The header is rewritten after every
|
|
* stream stop and by close(), so the file is valid while the guest runs.
|
|
*/
|
|
export class WavSink implements SoundSink {
|
|
readonly file: string;
|
|
format: SoundFormat | null = null;
|
|
bytes = 0;
|
|
#fd: number;
|
|
#log: (msg: string) => void;
|
|
onChunk: (chunk: { format: SoundFormat; data: Uint8Array }) => number;
|
|
onState: (state: SoundState, event: SoundEvent) => void;
|
|
|
|
constructor(file: string, opts: { log?: (msg: string) => void; onState?: (state: SoundState, event: SoundEvent) => void } = {}) {
|
|
this.file = file;
|
|
this.#log = opts.log ?? (() => {});
|
|
this.#fd = fs.openSync(file, "w");
|
|
this.onChunk = ({ format, data }) => {
|
|
if (!this.format) {
|
|
this.format = format;
|
|
fs.writeSync(this.#fd, wavHeader(format, 0), 0, 44, 0);
|
|
}
|
|
const out = convertPcm(data, format, this.format);
|
|
fs.writeSync(this.#fd, out, 0, out.length, 44 + this.bytes);
|
|
this.bytes += out.length;
|
|
return 0;
|
|
};
|
|
this.onState = (state, event) => {
|
|
if (event === "stop" || event === "drain" || event === "close") this.#writeHeader();
|
|
opts.onState?.(state, event);
|
|
};
|
|
}
|
|
|
|
#writeHeader(): void {
|
|
if (this.format) fs.writeSync(this.#fd, wavHeader(this.format, this.bytes), 0, 44, 0);
|
|
}
|
|
|
|
/** Finish the header and close the file (once). */
|
|
close(): void {
|
|
if (this.#fd < 0) return;
|
|
this.#writeHeader();
|
|
fs.closeSync(this.#fd);
|
|
this.#fd = -1;
|
|
const f = this.format;
|
|
this.#log(f ? `[host] sound: wrote ${this.file} (${f.rate} Hz, ${f.channels} ch, ${(f.frameBytes / f.channels) * 8} bit, ${(this.bytes / f.frameBytes / f.rate).toFixed(3)} s)`
|
|
: `[host] sound: nothing played, ${this.file} is empty`);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* The CLI's sound options: --sound-wav FILE (a card whose output goes to
|
|
* FILE) or --sound (a card whose output is dropped); neither: no card.
|
|
* Logs each state change; close() finishes the file and, given the stats
|
|
* (--stats), prints them.
|
|
*/
|
|
export function cliSound(wavFile: string | undefined, enabled: boolean, log: (msg: string) => void): {
|
|
option: boolean | SoundSink;
|
|
close: (stats?: SoundStats) => void;
|
|
} {
|
|
const onState = (s: SoundState, ev: SoundEvent): void => {
|
|
const f = s.format;
|
|
log(`[host] sound: ${ev}${ev === "prepare" && f ? ` ${f.rate} Hz, ${f.channels} ch, ${(f.frameBytes / f.channels) * 8} bit` : ""}`);
|
|
};
|
|
const wav = wavFile ? new WavSink(wavFile, { log, onState }) : undefined;
|
|
return {
|
|
option: wav ?? (enabled ? { onState } : false),
|
|
close: (stats) => {
|
|
wav?.close();
|
|
if (stats) log(`[host] sound: ${stats.opens} opens, ${stats.starts} starts, ${stats.stops} stops (not drains), ` +
|
|
`${stats.chunks} chunks, ${stats.frames} frames, max lag ${stats.maxLagMs.toFixed(1)} ms`);
|
|
},
|
|
};
|
|
}
|
|
|
|
/** A PCM WAV file (8 or 16 bit, any rate and channels) as mono samples at its rate. */
|
|
export function readWavMono(file: string): { rate: number; samples: Float32Array } {
|
|
const b = fs.readFileSync(file);
|
|
const dv = new DataView(b.buffer, b.byteOffset, b.byteLength);
|
|
const tag = (o: number) => b.toString("latin1", o, o + 4);
|
|
if (b.length < 12 || tag(0) !== "RIFF" || tag(8) !== "WAVE") throw new Error(`${file}: not a WAV file`);
|
|
let fmt: SoundFormat | null = null;
|
|
for (let o = 12; o + 8 <= b.length;) {
|
|
const id = tag(o), size = dv.getUint32(o + 4, true), body = o + 8;
|
|
if (id === "fmt ") {
|
|
const code = dv.getUint16(body, true), channels = dv.getUint16(body + 2, true), rate = dv.getUint32(body + 4, true), bits = dv.getUint16(body + 14, true);
|
|
// 1: PCM; 0xfffe: WAVE_FORMAT_EXTENSIBLE (PCM in practice for 8 and 16 bit).
|
|
if ((code !== 1 && code !== 0xfffe) || (bits !== 8 && bits !== 16) || !channels || !rate) throw new Error(`${file}: only 8 or 16 bit PCM WAV files (format ${code}, ${bits} bit)`);
|
|
fmt = { rate, channels, format: bits === 8 ? SOUND_FORMAT_U8 : SOUND_FORMAT_S16_LE, frameBytes: channels * bits / 8 };
|
|
} else if (id === "data") {
|
|
if (!fmt) throw new Error(`${file}: data before fmt`);
|
|
const data = new Uint8Array(b.buffer, b.byteOffset + body, Math.min(size, b.length - body) - (Math.min(size, b.length - body) % fmt.frameBytes));
|
|
const all = pcmToFloat32(data, fmt);
|
|
const ch = fmt.channels, samples = new Float32Array(all.length / ch);
|
|
for (let i = 0; i < samples.length; i++) {
|
|
let v = 0;
|
|
for (let c = 0; c < ch; c++) v += all[i * ch + c]!;
|
|
samples[i] = v / ch;
|
|
}
|
|
return { rate: fmt.rate, samples };
|
|
}
|
|
o = body + size + (size & 1);
|
|
}
|
|
throw new Error(`${file}: no data chunk`);
|
|
}
|
|
|
|
/**
|
|
* Play `samples` (mono, at `rate`) to the guest's capture once, from its
|
|
* first start on, across streams; silence once it has ended. A stream at
|
|
* another rate gets it resampled (linear).
|
|
*/
|
|
export function samplesSource(rate: number, samples: Float32Array, onEnd?: () => void): SoundSource {
|
|
let pos = 0; // in the samples' frames (fractional when resampling)
|
|
return {
|
|
read(out, want) {
|
|
const step = rate / want;
|
|
let i = 0;
|
|
for (; i < out.length; i++) {
|
|
const f = Math.floor(pos), t = pos - f;
|
|
if (f >= samples.length) break;
|
|
const a = samples[f]!, b = f + 1 < samples.length ? samples[f + 1]! : a;
|
|
out[i] = step === 1 ? a : a + (b - a) * t;
|
|
pos += step;
|
|
}
|
|
if (i < out.length && pos >= samples.length && onEnd) {
|
|
onEnd();
|
|
onEnd = undefined;
|
|
}
|
|
return i;
|
|
},
|
|
};
|
|
}
|
|
|
|
/** A sine of `hz` at `amplitude`, continuous across reads and streams. */
|
|
export function toneSource(hz = 440, amplitude = 0.25): SoundSource {
|
|
let phase = 0;
|
|
return {
|
|
read(out, rate) {
|
|
for (let i = 0; i < out.length; i++) {
|
|
out[i] = amplitude * Math.sin(2 * Math.PI * phase);
|
|
phase = (phase + hz / rate) % 1;
|
|
}
|
|
return out.length;
|
|
},
|
|
};
|
|
}
|
|
|
|
/**
|
|
* The CLI's capture options: --sound-in-wav FILE (the guest records FILE,
|
|
* once, then silence) or --sound-in (a 440 Hz tone); neither: no capture.
|
|
* Logs each state change; close() prints the stats it is given (--stats).
|
|
*/
|
|
export function cliSoundIn(wavFile: string | undefined, tone: boolean, log: (msg: string) => void): {
|
|
option: false | SoundSource;
|
|
close: (stats?: SoundInStats) => void;
|
|
} {
|
|
if (!wavFile && !tone) return { option: false, close: () => {} };
|
|
const onState = (s: SoundState, ev: SoundEvent): void => {
|
|
const f = s.format;
|
|
log(`[host] sound in: ${ev}${ev === "prepare" && f ? ` ${f.rate} Hz, ${f.channels} ch, ${(f.frameBytes / f.channels) * 8} bit` : ""}`);
|
|
};
|
|
let src: SoundSource;
|
|
if (wavFile) {
|
|
const { rate, samples } = readWavMono(wavFile);
|
|
log(`[host] sound in: ${wavFile} (${rate} Hz, ${(samples.length / rate).toFixed(3)} s, as mono) from the first capture on`);
|
|
src = samplesSource(rate, samples, () => log(`[host] sound in: ${wavFile} has ended; silence from now on`));
|
|
} else src = toneSource();
|
|
return {
|
|
option: { read: src.read, onState },
|
|
close: (stats) => {
|
|
if (stats) log(`[host] sound in: ${stats.opens} opens, ${stats.starts} starts, ${stats.stops} stops (not drains), ` +
|
|
`${stats.frames} frames, ${stats.silentFrames} of them silence`);
|
|
},
|
|
};
|
|
}
|