Audio on native

This commit is contained in:
2026-11-22 18:27:01 -03:00
parent a552883795
commit 0d770c7bc4
9 changed files with 790 additions and 10 deletions
+10
View File
@@ -10,6 +10,9 @@ import { init_window, resize_canvas } from "../renderer/mod.ts";
import { show_fatal_error } from "../fatal.ts";
import { start_client } from "../client_loop.ts";
import { TextCreditsScreen } from "./credits_screen.ts";
import { install_web_audio, sources_ended } from "./web_audio.ts";
import { sounds } from "../sounds.ts";
import { WebAudioOutput } from "../audio_output.ts";
import type { ClientMessage, WindowMessage } from "./messages.ts";
const post = (message: ClientMessage) => self.postMessage(message);
@@ -148,6 +151,10 @@ async function start(message: Extract<WindowMessage, { type: "start" }>) {
throw e;
}
resize_canvas(width, height);
if (message.audio) {
install_web_audio((commands) => post({ type: "audio", commands }));
sounds.set_output(new WebAudioOutput(false));
}
await start_client();
}
@@ -202,5 +209,8 @@ self.onmessage = (event: MessageEvent<WindowMessage>) => {
asking.get(message.id)?.(message.yes);
asking.delete(message.id);
break;
case "audio_ended":
sources_ended(message.sources);
break;
}
};
+34 -3
View File
@@ -18,8 +18,10 @@ export type WindowMessage =
surface: SurfaceHandles;
width: number;
height: number;
// what the client saved, see NativePlatform's storage
// what the client saved, see Platform.storage
storage: Record<string, string>;
// whether the window can play sound, see desktop/openal.ts
audio: boolean;
}
// in pixels, what's drawn to is this big now
| { type: "resize"; width: number; height: number }
@@ -40,7 +42,9 @@ export type WindowMessage =
| { type: "shown"; shown: boolean }
// answers, by the id they were asked with
| { type: "clipboard"; id: number; text: string }
| { type: "answer"; id: number; yes: boolean };
| { type: "answer"; id: number; yes: boolean }
// sources that played to their end, see web_audio.ts
| { type: "audio_ended"; sources: number[] };
export type ClientMessage =
| { type: "grab"; grab: boolean }
@@ -52,4 +56,31 @@ export type ClientMessage =
| { type: "ask"; id: number; title: string; text: string; yes: string; no: string }
| { type: "read_clipboard"; id: number }
| { type: "write_clipboard"; text: string }
| { type: "store"; key: string; value: string };
| { type: "store"; key: string; value: string }
| { type: "audio"; commands: AudioCommand[] };
// how a playing source sounds: everything between it and the speakers worked out, see web_audio.ts. gain 0 is silent
export interface SourceSettings {
gain: number;
pitch: number;
// where it is, with its distance falloff: full gain within ref_distance, fading linearly to 1 - rolloff at
// max_distance. undefined plays it as it is, not from anywhere
at: [number, number, number] | undefined;
ref_distance: number;
max_distance: number;
rolloff: number;
}
// what the client's web audio has the window's openal do. ids are the client's own
export type AudioCommand =
// a decoded file, one array of samples a channel
| { op: "buffer"; id: number; channels: Float32Array[]; sample_rate: number }
| { op: "play"; id: number; buffer: number; loop: boolean; offset: number; settings: SourceSettings }
| { op: "set"; id: number; settings: SourceSettings }
| { op: "stop"; id: number }
| {
op: "listener";
position: [number, number, number];
forward: [number, number, number];
up: [number, number, number];
};
+360
View File
@@ -0,0 +1,360 @@
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
// SPDX-License-Identifier: AGPL-3.0-or-later
// the web audio api for the desktop app's client, which runs in deno with no audio of its own. only what
// client/audio_output.ts uses: buffer sources, gains and panners connected in a chain to the destination, the
// listener, and decoding the ogg files mods' sounds are (vorbis or opus). the window plays it with openal
// (desktop/openal.ts): each playing source is one openal source, its chain worked out into one gain, pitch and place
// at the end of every task something changed in. panners are all hrtf with linear distance, like cubi makes them
import decode_vorbis from "@audio/decode-vorbis";
import decode_opus from "@audio/decode-opus";
import type { AudioCommand, SourceSettings } from "./messages.ts";
type Vector = [number, number, number];
// sends what changed to the window
let send: (commands: AudioCommand[]) => void = () => {};
let next_id = 0;
// what's been started and hasn't ended, by id
const playing = new Map<number, BufferSource>();
class Param {
#value: number;
#context: Context;
constructor(context: Context, value: number) {
this.#context = context;
this.#value = value;
}
get value() {
return this.#value;
}
set value(value: number) {
this.#value = value;
this.#context.changed();
}
}
class Node {
readonly context: Context;
// where it plays into, cubi connects each node to one other
output: Node | undefined;
constructor(context: Context) {
this.context = context;
}
connect<T extends Node>(destination: T): T {
this.output = destination;
this.context.changed();
return destination;
}
disconnect() {
this.output = undefined;
this.context.changed();
}
}
class Destination extends Node {}
class Gain extends Node {
readonly gain: Param;
constructor(context: Context, options: { gain?: number } = {}) {
super(context);
this.gain = new Param(context, options.gain ?? 1);
}
}
interface PannerOptions {
panningModel?: string;
distanceModel?: string;
refDistance?: number;
maxDistance?: number;
rolloffFactor?: number;
positionX?: number;
positionY?: number;
positionZ?: number;
}
class Panner extends Node {
readonly positionX: Param;
readonly positionY: Param;
readonly positionZ: Param;
// openal plays every panner like this, whatever it's set to
panningModel = "HRTF";
distanceModel = "linear";
#ref_distance: number;
#max_distance: number;
#rolloff: number;
constructor(context: Context, options: PannerOptions = {}) {
super(context);
this.positionX = new Param(context, options.positionX ?? 0);
this.positionY = new Param(context, options.positionY ?? 0);
this.positionZ = new Param(context, options.positionZ ?? 0);
this.#ref_distance = options.refDistance ?? 1;
this.#max_distance = options.maxDistance ?? 10000;
this.#rolloff = options.rolloffFactor ?? 1;
}
get refDistance() {
return this.#ref_distance;
}
set refDistance(value: number) {
this.#ref_distance = value;
this.context.changed();
}
get maxDistance() {
return this.#max_distance;
}
set maxDistance(value: number) {
this.#max_distance = value;
this.context.changed();
}
get rolloffFactor() {
return this.#rolloff;
}
set rolloffFactor(value: number) {
this.#rolloff = value;
this.context.changed();
}
}
class Buffer {
readonly sampleRate: number;
readonly length: number;
readonly numberOfChannels: number;
#channels: Float32Array[];
// once the window has it, see BufferSource.start
id: number | undefined;
constructor(channels: Float32Array[], sample_rate: number) {
this.#channels = channels;
this.sampleRate = sample_rate;
this.length = channels[0]?.length ?? 0;
this.numberOfChannels = channels.length;
}
get duration() {
return this.length / this.sampleRate;
}
getChannelData(channel: number) {
return this.#channels[channel];
}
}
class BufferSource extends Node {
readonly id = next_id++;
buffer: Buffer | null;
loop: boolean;
readonly playbackRate: Param;
onended: (() => void) | null = null;
// seconds into the buffer it starts at
offset = 0;
// what the window was last told, undefined before it was told to play it
sent: SourceSettings | undefined;
#started = false;
constructor(context: Context, options: { buffer?: Buffer; loop?: boolean; playbackRate?: number } = {}) {
super(context);
this.buffer = options.buffer ?? null;
this.loop = options.loop ?? false;
this.playbackRate = new Param(context, options.playbackRate ?? 1);
}
// it's always now, cubi starts sources as it makes them
start(_when = 0, offset = 0) {
if (this.#started) throw new Error("A source can only be started once");
this.#started = true;
this.offset = offset;
playing.set(this.id, this);
this.context.changed();
}
stop() {
if (!playing.has(this.id)) return;
if (this.sent) this.context.queue({ op: "stop", id: this.id });
this.end();
}
end() {
playing.delete(this.id);
queueMicrotask(() => this.onended?.());
}
}
class Listener {
readonly positionX: Param;
readonly positionY: Param;
readonly positionZ: Param;
readonly forwardX: Param;
readonly forwardY: Param;
readonly forwardZ: Param;
readonly upX: Param;
readonly upY: Param;
readonly upZ: Param;
constructor(context: Context) {
const param = (value: number) => new Param(context, value);
[this.positionX, this.positionY, this.positionZ] = [param(0), param(0), param(0)];
[this.forwardX, this.forwardY, this.forwardZ] = [param(0), param(0), param(-1)];
[this.upX, this.upY, this.upZ] = [param(0), param(1), param(0)];
}
setPosition(x: number, y: number, z: number) {
[this.positionX.value, this.positionY.value, this.positionZ.value] = [x, y, z];
}
setOrientation(x: number, y: number, z: number, up_x: number, up_y: number, up_z: number) {
[this.forwardX.value, this.forwardY.value, this.forwardZ.value] = [x, y, z];
[this.upX.value, this.upY.value, this.upZ.value] = [up_x, up_y, up_z];
}
command(): AudioCommand {
const values = (params: Param[]) => params.map((param) => param.value) as Vector;
return {
op: "listener",
position: values([this.positionX, this.positionY, this.positionZ]),
forward: values([this.forwardX, this.forwardY, this.forwardZ]),
up: values([this.upX, this.upY, this.upZ]),
};
}
}
class Context {
// there's no rule against playing before the player clicks, it plays right away
readonly state = "running";
readonly destination: Destination = new Destination(this);
readonly listener: Listener = new Listener(this);
#queued: AudioCommand[] = [];
#flushing = false;
#last_listener = "";
createGain() {
return new Gain(this);
}
resume() {
return Promise.resolve();
}
close() {
for (const source of playing.values()) source.stop();
return Promise.resolve();
}
// ogg vorbis or ogg opus, by the first packet: after the first page's 27 byte header and its segment table
async decodeAudioData(data: ArrayBuffer): Promise<Buffer> {
const bytes = new Uint8Array(data);
const packet = 27 + (bytes[26] ?? 0);
const head = new TextDecoder().decode(bytes.subarray(packet, packet + 8));
const decode = head.startsWith("OpusHead") ? decode_opus : head.includes("vorbis") ? decode_vorbis : undefined;
if (!decode) throw new Error("Only ogg vorbis and ogg opus can be decoded");
const { channelData, sampleRate } = await decode(bytes);
if (!channelData.length || !channelData[0].length) throw new Error("There's no audio in it");
return new Buffer(channelData, sampleRate);
}
queue(command: AudioCommand) {
this.#queued.push(command);
this.changed();
}
// something about what plays changed, the window hears about it once this task is done
changed() {
if (this.#flushing) return;
this.#flushing = true;
queueMicrotask(() => this.#flush());
}
#flush() {
this.#flushing = false;
const commands = this.#queued;
this.#queued = [];
const listener = this.listener.command();
const listener_key = JSON.stringify(listener);
if (listener_key !== this.#last_listener) {
this.#last_listener = listener_key;
commands.push(listener);
}
for (const source of playing.values()) {
if (source.context !== this) continue;
const settings = source_settings(source);
if (!source.sent) {
const buffer = source.buffer;
if (!buffer) continue;
if (buffer.id === undefined) {
buffer.id = next_id++;
const channels = Array.from(
{ length: buffer.numberOfChannels },
(_, i) => buffer.getChannelData(i),
);
commands.push({ op: "buffer", id: buffer.id, channels, sample_rate: buffer.sampleRate });
}
commands.push({
op: "play",
id: source.id,
buffer: buffer.id,
loop: source.loop,
offset: source.offset,
settings,
});
} else if (!same_settings(source.sent, settings)) {
commands.push({ op: "set", id: source.id, settings });
}
source.sent = settings;
}
if (commands.length) send(commands);
}
}
// the gains between source and destination multiplied, and the panner in between if there's one. silent when it
// isn't connected all the way
function source_settings(source: BufferSource): SourceSettings {
let gain = 1;
let panner: Panner | undefined;
let node = source.output;
while (node && !(node instanceof Destination)) {
if (node instanceof Gain) gain *= node.gain.value;
else if (node instanceof Panner) panner ??= node;
node = node.output;
}
return {
gain: node ? gain : 0,
pitch: source.playbackRate.value,
at: panner && [panner.positionX.value, panner.positionY.value, panner.positionZ.value],
ref_distance: panner?.refDistance ?? 1,
max_distance: panner?.maxDistance ?? 1,
rolloff: panner?.rolloffFactor ?? 0,
};
}
function same_settings(a: SourceSettings, b: SourceSettings) {
return a.gain === b.gain && a.pitch === b.pitch && a.at?.join() === b.at?.join() &&
a.ref_distance === b.ref_distance && a.max_distance === b.max_distance && a.rolloff === b.rolloff;
}
// makes AudioContext and its nodes globals, with to_window sending the window what to play
export function install_web_audio(to_window: (commands: AudioCommand[]) => void) {
send = to_window;
Object.assign(globalThis, {
AudioContext: Context,
GainNode: Gain,
PannerNode: Panner,
AudioBufferSourceNode: BufferSource,
AudioBuffer: Buffer,
AudioParam: Param,
});
}
// the window says these played to their end
export function sources_ended(ids: number[]) {
for (const id of ids) playing.get(id)?.end();
}