Files
bworld/client/native/web_audio.ts
T
2026-11-22 18:27:01 -03:00

361 lines
10 KiB
TypeScript

// 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();
}