From 0d770c7bc44587b04cf21f59f7aef1b7f01b5ec9 Mon Sep 17 00:00:00 2001 From: Paula Date: Sun, 22 Nov 2026 18:27:01 -0300 Subject: [PATCH] Audio on native --- client/audio_output.ts | 9 +- client/native/main.ts | 10 ++ client/native/messages.ts | 37 +++- client/native/web_audio.ts | 360 +++++++++++++++++++++++++++++++++++++ deno.json | 2 + deno.lock | 40 +++++ desktop/native.ts | 35 +++- desktop/openal.ts | 213 ++++++++++++++++++++++ tests/native_audio_test.ts | 94 ++++++++++ 9 files changed, 790 insertions(+), 10 deletions(-) create mode 100644 client/native/web_audio.ts create mode 100644 desktop/openal.ts create mode 100644 tests/native_audio_test.ts diff --git a/client/audio_output.ts b/client/audio_output.ts index 24ca517..ed8b2e5 100644 --- a/client/audio_output.ts +++ b/client/audio_output.ts @@ -15,8 +15,13 @@ export class WebAudioOutput implements SoundOutput { #buffers = new WeakMap>(); #volumes: Volumes | undefined; - constructor() { - // browsers keep audio off until the player clicks or presses a key, so it starts then + // browsers keep audio off until the player clicks or presses a key, so it starts then. the desktop app's web audio + // (client/native/web_audio.ts) has no such rule and starts right away + constructor(wait_for_input = true) { + if (!wait_for_input) { + this.#unlock(); + return; + } const unlock = () => { this.#unlock(); if (this.#context?.state === "running") { diff --git a/client/native/main.ts b/client/native/main.ts index f61d77a..c0bf0e0 100644 --- a/client/native/main.ts +++ b/client/native/main.ts @@ -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) { 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) => { asking.get(message.id)?.(message.yes); asking.delete(message.id); break; + case "audio_ended": + sources_ended(message.sources); + break; } }; diff --git a/client/native/messages.ts b/client/native/messages.ts index 3cc46ab..1710402 100644 --- a/client/native/messages.ts +++ b/client/native/messages.ts @@ -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; + // 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]; + }; diff --git a/client/native/web_audio.ts b/client/native/web_audio.ts new file mode 100644 index 0000000..b4f0161 --- /dev/null +++ b/client/native/web_audio.ts @@ -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(); + +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(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 { + 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(); +} diff --git a/deno.json b/deno.json index 190a93e..0e05308 100644 --- a/deno.json +++ b/deno.json @@ -26,6 +26,8 @@ }, "imports": { "@/": "./", + "@audio/decode-opus": "npm:@audio/decode-opus@^1.3.3", + "@audio/decode-vorbis": "npm:@audio/decode-vorbis@^1.3.4", "@std/msgpack": "jsr:@std/msgpack@^1.0.3", "cubi/server": "./common/mod_api/server.ts", "cubi/client": "./common/mod_api/client.ts", diff --git a/deno.lock b/deno.lock index cbd651b..deeb8ca 100644 --- a/deno.lock +++ b/deno.lock @@ -26,6 +26,8 @@ "jsr:@std/path@^1.1.4": "1.1.6", "jsr:@std/streams@^1.0.17": "1.1.2", "jsr:@zod/zod@^4.6.7": "4.6.7", + "npm:@audio/decode-opus@^1.3.3": "1.3.3", + "npm:@audio/decode-vorbis@^1.3.4": "1.3.4", "npm:fflate@~0.8.2": "0.8.3", "npm:gl-matrix@^3.4.4": "3.4.4", "npm:marked@^17.0.3": "17.0.3" @@ -129,6 +131,39 @@ } }, "npm": { + "@audio/decode-opus@1.3.3": { + "integrity": "sha512-/iykUcA9cgdqqj9pLwPjBkJ4z+WlpLIyWA4xGzvTBkHb1uWpMxYX5yoG+slw8HhmBmrBP2LxKqw6i779g4acVA==", + "dependencies": [ + "codec-parser" + ] + }, + "@audio/decode-vorbis@1.3.4": { + "integrity": "sha512-0bgH1zgLlpgjdHj9NWdiYkMeLyCz5w1UEuvg2qiwJFXbwYSvRhOcmeT82CQUlb8RZSblS3AWpDJzLnAmQJ2cgg==", + "dependencies": [ + "@wasm-audio-decoders/ogg-vorbis", + "codec-parser" + ] + }, + "@eshaz/web-worker@1.2.2": { + "integrity": "sha512-WxXiHFmD9u/owrzempiDlBB1ZYqiLnm9s6aPc8AlFQalq2tKmqdmMr9GXOupDgzXtqnBipj8Un0gkIm7Sjf8mw==" + }, + "@wasm-audio-decoders/common@9.0.7": { + "integrity": "sha512-WRaUuWSKV7pkttBygml/a6dIEpatq2nnZGFIoPTc5yPLkxL6Wk4YaslPM98OPQvWacvNZ+Py9xROGDtrFBDzag==", + "dependencies": [ + "@eshaz/web-worker", + "simple-yenc" + ] + }, + "@wasm-audio-decoders/ogg-vorbis@0.1.20": { + "integrity": "sha512-zaQPasU5usRjUDXtXOHYED5tfkR4QMXd+EH3Nrz1+4+M5pCsdD+s9YxJqb0oqnTyRu/KUujOmu5Z/m/NT47vwg==", + "dependencies": [ + "@wasm-audio-decoders/common", + "codec-parser" + ] + }, + "codec-parser@2.5.0": { + "integrity": "sha512-Ru9t80fV8B0ZiixQl8xhMTLru+dzuis/KQld32/x5T/+3LwZb0/YvQdSKytX9JqCnRdiupvAvyYJINKrXieziQ==" + }, "fflate@0.8.3": { "integrity": "sha512-tbZNuJrLwGUp3zshBtdy4W+ORxZuIh8a5ilyIEQDC5rY1f3U20JMry0Ll3WBzU58EZKsEuJFXhb5gwv8CsPvgA==" }, @@ -138,6 +173,9 @@ "marked@17.0.3": { "integrity": "sha512-jt1v2ObpyOKR8p4XaUJVk3YWRJ5n+i4+rjQopxvV32rSndTJXvIzuUdWWIy/1pFQMkQmvTXawzDNqOH/CUmx6A==", "bin": true + }, + "simple-yenc@1.0.4": { + "integrity": "sha512-5gvxpSd79e9a3V4QDYUqnqxeD4HGlhCakVpb6gMnDD7lexJggSBJRBO5h52y/iJrdXRilX9UCuDaIJhSWm5OWw==" } }, "remote": { @@ -154,6 +192,8 @@ "jsr:@std/msgpack@^1.0.3", "jsr:@std/path@1", "jsr:@zod/zod@^4.6.7", + "npm:@audio/decode-opus@^1.3.3", + "npm:@audio/decode-vorbis@^1.3.4", "npm:fflate@~0.8.2", "npm:gl-matrix@^3.4.4", "npm:marked@^17.0.3" diff --git a/desktop/native.ts b/desktop/native.ts index 9b590c3..34c4de9 100644 --- a/desktop/native.ts +++ b/desktop/native.ts @@ -8,13 +8,24 @@ import { join, toFileUrl } from "@std/path"; import { desktop_app } from "./app.ts"; import { SdlWindow } from "./sdl.ts"; +import { OpenAl } from "./openal.ts"; import type { ClientMessage, WindowMessage } from "../client/native/messages.ts"; // how often the window's events are looked at, in milliseconds const POLL_MS = 2; +// how often sounds are checked for having ended, in polls +const AUDIO_POLLS = 10; const game_window = new SdlWindow("bworld", 1280, 720); +// the game plays without sound when there's no openal +let audio: OpenAl | undefined; +try { + audio = new OpenAl(); +} catch (e) { + console.error(`No sound: ${(e as Error).message}`); +} + const app = desktop_app((message) => { console.error(message); game_window.show_error("bworld", `The singleplayer world stopped: ${message}`); @@ -37,11 +48,13 @@ try { } let client: Worker | undefined; +let closing = false; // a fresh client, like loading the page again. the old one is gone with everything it loaded async function start_client(page: URL) { client?.terminate(); game_window.set_grabbed(false); + audio?.reset(); const client_dir = await app.client_dir; const worker = new Worker(toFileUrl(join(client_dir, "client", "native.js")), { type: "module", @@ -61,6 +74,7 @@ async function start_client(page: URL) { surface: game_window.surface_handles(), ...game_window.pixel_size(), storage, + audio: audio !== undefined, }); } @@ -69,6 +83,8 @@ function send(message: WindowMessage) { } function handle(message: ClientMessage) { + // what it asks while the app closes, like sounds, would come after openal and the window are gone + if (closing) return; switch (message.type) { case "grab": game_window.set_grabbed(message.grab); @@ -102,6 +118,9 @@ function handle(message: ClientMessage) { case "write_clipboard": game_window.write_clipboard(message.text); break; + case "audio": + audio?.run(message.commands); + break; case "store": storage[message.key] = message.value; Deno.writeTextFileSync(STORAGE_FILE, JSON.stringify(storage, null, "\t")); @@ -109,18 +128,24 @@ function handle(message: ClientMessage) { } } -let closing = false; - -// the world gets saved before the app closes +// the world gets saved before the app closes. the client isn't terminated first, exiting while a terminated worker is +// still letting go of its webgpu surface can crash deno, exiting stops it as well async function close() { if (closing) return; closing = true; clearInterval(polling); - client?.terminate(); await app.singleplayer.stop(); + audio?.close(); game_window.close(); Deno.exit(0); } -const polling = setInterval(() => game_window.poll(send, close), POLL_MS); +let polls = 0; +const polling = setInterval(() => { + game_window.poll(send, close); + if (audio && ++polls % AUDIO_POLLS === 0) { + const ended = audio.ended(); + if (ended.length) send({ type: "audio_ended", sources: ended }); + } +}, POLL_MS); start_client(start_page); diff --git a/desktop/openal.ts b/desktop/openal.ts new file mode 100644 index 0000000..91d6ca0 --- /dev/null +++ b/desktop/openal.ts @@ -0,0 +1,213 @@ +// SPDX-FileCopyrightText: 2026 Paula Wisnievski +// SPDX-License-Identifier: AGPL-3.0-or-later + +// the desktop app's sound, with openal soft through ffi: plays what the client's web audio asks for (see +// client/native/web_audio.ts), each of its sources an openal source. openal mixes on a thread of its own, with hrtf +// like browsers' panners, and linear distance falloff the same as a web audio panner's +import type { AudioCommand, SourceSettings } from "../client/native/messages.ts"; + +const LIBRARY = + { linux: "libopenal.so.1", windows: "OpenAL32.dll", darwin: "libopenal.1.dylib" }[Deno.build.os as string]; + +const SYMBOLS = { + alcOpenDevice: { parameters: ["pointer"], result: "pointer" }, + alcCloseDevice: { parameters: ["pointer"], result: "u8" }, + alcCreateContext: { parameters: ["pointer", "buffer"], result: "pointer" }, + alcDestroyContext: { parameters: ["pointer"], result: "void" }, + alcMakeContextCurrent: { parameters: ["pointer"], result: "u8" }, + alIsExtensionPresent: { parameters: ["buffer"], result: "u8" }, + alDistanceModel: { parameters: ["i32"], result: "void" }, + alGenBuffers: { parameters: ["i32", "buffer"], result: "void" }, + alDeleteBuffers: { parameters: ["i32", "buffer"], result: "void" }, + alBufferData: { parameters: ["u32", "i32", "buffer", "i32", "i32"], result: "void" }, + alGenSources: { parameters: ["i32", "buffer"], result: "void" }, + alDeleteSources: { parameters: ["i32", "buffer"], result: "void" }, + alSourcei: { parameters: ["u32", "i32", "i32"], result: "void" }, + alSourcef: { parameters: ["u32", "i32", "f32"], result: "void" }, + alSource3f: { parameters: ["u32", "i32", "f32", "f32", "f32"], result: "void" }, + alGetSourcei: { parameters: ["u32", "i32", "buffer"], result: "void" }, + alSourcePlay: { parameters: ["u32"], result: "void" }, + alSourceStop: { parameters: ["u32"], result: "void" }, + alListener3f: { parameters: ["i32", "f32", "f32", "f32"], result: "void" }, + alListenerfv: { parameters: ["i32", "buffer"], result: "void" }, +} as const; + +const ALC_TRUE = 1; +const ALC_HRTF_SOFT = 0x1992; +const AL_SOURCE_RELATIVE = 0x202; +const AL_PITCH = 0x1003; +const AL_POSITION = 0x1004; +const AL_LOOPING = 0x1007; +const AL_BUFFER = 0x1009; +const AL_GAIN = 0x100a; +const AL_ORIENTATION = 0x100f; +const AL_SOURCE_STATE = 0x1010; +const AL_STOPPED = 0x1014; +const AL_REFERENCE_DISTANCE = 0x1020; +const AL_ROLLOFF_FACTOR = 0x1021; +const AL_MAX_DISTANCE = 0x1023; +const AL_SEC_OFFSET = 0x1024; +const AL_LINEAR_DISTANCE_CLAMPED = 0xd004; +const AL_FORMAT_MONO_FLOAT32 = 0x10010; +const AL_FORMAT_STEREO_FLOAT32 = 0x10011; + +// openal can't play at a pitch of 0 or less +const MIN_PITCH = 0.001; + +const c_string = (text: string) => new TextEncoder().encode(text + "\0"); + +// a decoded file, made into openal buffers as it's needed: mono for sounds placed somewhere, since openal only places +// mono ones, and as many channels as it has (up to stereo) for the rest +interface Decoded { + channels: Float32Array[]; + sample_rate: number; + mono?: number; + all?: number; +} + +export class OpenAl { + #al: Deno.DynamicLibrary["symbols"]; + #device: Deno.PointerObject; + #context: Deno.PointerObject; + #buffers = new Map(); + // the client's source ids, and the openal sources playing them + #sources = new Map(); + #name = new Uint32Array(1); + #state = new Int32Array(1); + + // throws when there's no openal or no sound device + constructor() { + if (!LIBRARY) throw new Error(`There's no openal for ${Deno.build.os}`); + this.#al = Deno.dlopen(LIBRARY, SYMBOLS).symbols; + const al = this.#al; + const device = al.alcOpenDevice(null); + if (!device) throw new Error("There's no sound device"); + // hrtf on speakers too, like a browser's panners + const context = al.alcCreateContext(device, new Int32Array([ALC_HRTF_SOFT, ALC_TRUE, 0])); + if (!context || !al.alcMakeContextCurrent(context)) { + al.alcCloseDevice(device); + throw new Error("Couldn't start openal"); + } + if (!al.alIsExtensionPresent(c_string("AL_EXT_FLOAT32"))) { + throw new Error("This openal can't play float samples"); + } + this.#device = device; + this.#context = context; + al.alDistanceModel(AL_LINEAR_DISTANCE_CLAMPED); + } + + run(commands: AudioCommand[]) { + const al = this.#al; + for (const command of commands) { + switch (command.op) { + case "buffer": + this.#buffers.set(command.id, { channels: command.channels, sample_rate: command.sample_rate }); + break; + case "play": { + const decoded = this.#buffers.get(command.buffer); + if (!decoded) break; + al.alGenSources(1, this.#name); + const name = this.#name[0]; + al.alSourcei(name, AL_BUFFER, this.#buffer(decoded, command.settings.at !== undefined)); + al.alSourcei(name, AL_LOOPING, command.loop ? 1 : 0); + al.alSourcef(name, AL_SEC_OFFSET, command.offset); + this.#set(name, command.settings); + al.alSourcePlay(name); + this.#sources.set(command.id, { name, loop: command.loop }); + break; + } + case "set": { + const source = this.#sources.get(command.id); + if (source) this.#set(source.name, command.settings); + break; + } + case "stop": + this.#delete_source(command.id); + break; + case "listener": + al.alListener3f(AL_POSITION, ...command.position); + al.alListenerfv(AL_ORIENTATION, new Float32Array([...command.forward, ...command.up])); + break; + } + } + } + + #set(name: number, settings: SourceSettings) { + const al = this.#al; + al.alSourcef(name, AL_GAIN, Math.max(0, settings.gain)); + al.alSourcef(name, AL_PITCH, Math.max(MIN_PITCH, settings.pitch)); + // one that isn't anywhere stays on the listener, at full volume + al.alSourcei(name, AL_SOURCE_RELATIVE, settings.at ? 0 : 1); + al.alSource3f(name, AL_POSITION, ...settings.at ?? [0, 0, 0]); + al.alSourcef(name, AL_ROLLOFF_FACTOR, settings.at ? settings.rolloff : 0); + al.alSourcef(name, AL_REFERENCE_DISTANCE, settings.ref_distance); + al.alSourcef(name, AL_MAX_DISTANCE, settings.max_distance); + } + + #buffer(decoded: Decoded, placed: boolean): number { + const key = placed || decoded.channels.length === 1 ? "mono" : "all"; + const made = decoded[key]; + if (made !== undefined) return made; + const { channels, sample_rate } = decoded; + const length = channels[0].length; + let samples: Float32Array; + if (key === "mono") { + samples = new Float32Array(length); + for (const channel of channels) { + for (let i = 0; i < length; i++) samples[i] += channel[i] / channels.length; + } + } else { + // past stereo only the first two, cubi's sounds are mono or stereo + samples = new Float32Array(length * 2); + for (let i = 0; i < length; i++) { + samples[i * 2] = channels[0][i]; + samples[i * 2 + 1] = channels[1][i]; + } + } + const al = this.#al; + al.alGenBuffers(1, this.#name); + const name = this.#name[0]; + const format = key === "mono" ? AL_FORMAT_MONO_FLOAT32 : AL_FORMAT_STEREO_FLOAT32; + al.alBufferData(name, format, samples, samples.byteLength, sample_rate); + decoded[key] = name; + return name; + } + + #delete_source(id: number) { + const source = this.#sources.get(id); + if (!source) return; + this.#sources.delete(id); + this.#al.alSourceStop(source.name); + this.#al.alDeleteSources(1, new Uint32Array([source.name])); + } + + // the sources that played to their end since the last call, by the client's ids. they're gone after + ended(): number[] { + const ended: number[] = []; + for (const [id, source] of this.#sources) { + if (source.loop) continue; + this.#al.alGetSourcei(source.name, AL_SOURCE_STATE, this.#state); + if (this.#state[0] === AL_STOPPED) ended.push(id); + } + for (const id of ended) this.#delete_source(id); + return ended; + } + + // everything the client had, for a client starting over + reset() { + for (const id of [...this.#sources.keys()]) this.#delete_source(id); + for (const decoded of this.#buffers.values()) { + for (const name of [decoded.mono, decoded.all]) { + if (name !== undefined) this.#al.alDeleteBuffers(1, new Uint32Array([name])); + } + } + this.#buffers.clear(); + } + + close() { + this.reset(); + this.#al.alcMakeContextCurrent(null); + this.#al.alcDestroyContext(this.#context); + this.#al.alcCloseDevice(this.#device); + } +} diff --git a/tests/native_audio_test.ts b/tests/native_audio_test.ts new file mode 100644 index 0000000..5c62e45 --- /dev/null +++ b/tests/native_audio_test.ts @@ -0,0 +1,94 @@ +// SPDX-FileCopyrightText: 2026 Paula Wisnievski +// SPDX-License-Identifier: AGPL-3.0-or-later + +import { assert, assertAlmostEquals, assertEquals } from "@std/assert"; +import { walk } from "@std/fs"; +import { install_web_audio, sources_ended } from "@/client/native/web_audio.ts"; +import { WebAudioOutput } from "@/client/audio_output.ts"; +import { SOUND_CATEGORIES } from "@/common/mod_data.ts"; +import type { Volumes } from "@/client/sounds.ts"; +import type { AudioCommand } from "@/client/native/messages.ts"; + +// any of the mods' sound files +async function some_ogg(): Promise { + for await (const entry of walk("mods", { exts: [".ogg"], includeDirs: false })) { + return await Deno.readFile(entry.path); + } + throw new Error("No .ogg in mods/"); +} + +// what the window was sent, once one of them is what's wanted +async function sent_until(sent: AudioCommand[], wanted: (command: AudioCommand) => boolean) { + for (let i = 0; i < 200 && !sent.some(wanted); i++) await new Promise((resolve) => setTimeout(resolve, 5)); + return sent.find(wanted); +} + +Deno.test("the desktop app's web audio plays a voice as one source: its gains multiplied, its pitch, where it is and its range", async () => { + const sent: AudioCommand[] = []; + install_web_audio((commands) => sent.push(...commands)); + const output = new WebAudioOutput(false); + const category = SOUND_CATEGORIES[0]; + const volumes = Object.fromEntries(SOUND_CATEGORIES.map((c) => [c, 1])) as Volumes; + output.set_volumes({ ...volumes, master: 0.5, [category]: 0.5 }); + + const voice = output.start({ id: "test:sound", bytes: await some_ogg() }, { + category, + at: { x: 1, y: 2, z: 3 }, + range: 16, + volume: 0.8, + pitch: 1.5, + loop: false, + offset: 0, + })!; + const play = await sent_until(sent, (command) => command.op === "play"); + assert(play?.op === "play"); + const buffer = sent.find((command) => command.op === "buffer"); + assert(buffer?.op === "buffer" && buffer.id === play.buffer, "the file goes before what plays it"); + assert(buffer.channels.length > 0 && buffer.channels[0].length > 0); + + const { gain, ...rest } = play.settings; + assertAlmostEquals(gain, 0.8 * 0.5 * 0.5); + assertEquals(rest, { pitch: 1.5, at: [1, 2, 3], ref_distance: 1, max_distance: 16, rolloff: 1 }); + + sent.length = 0; + voice.move({ x: 4, y: 5, z: 6 }); + const moved = await sent_until(sent, (command) => command.op === "set"); + assert(moved?.op === "set" && moved.id === play.id); + assertEquals(moved.settings.at, [4, 5, 6]); + + // the category's volume changes every sound in it + sent.length = 0; + output.set_volumes({ ...volumes, master: 0.5, [category]: 1 }); + const louder = await sent_until(sent, (command) => command.op === "set"); + assert(louder?.op === "set"); + assertAlmostEquals(louder.settings.gain, 0.8 * 0.5); + + sources_ended([play.id]); + await new Promise((resolve) => setTimeout(resolve, 0)); + assert(voice.ended); +}); + +Deno.test("the desktop app's web audio plays a sound from nowhere as it is, and stopping it stops the window's", async () => { + const sent: AudioCommand[] = []; + install_web_audio((commands) => sent.push(...commands)); + const output = new WebAudioOutput(false); + output.set_volumes(Object.fromEntries(["master", ...SOUND_CATEGORIES].map((c) => [c, 1])) as Volumes); + + const voice = output.start({ id: "test:sound", bytes: await some_ogg() }, { + category: undefined, + at: undefined, + range: 16, + volume: 1, + pitch: 1, + loop: true, + offset: 0, + })!; + const play = await sent_until(sent, (command) => command.op === "play"); + assert(play?.op === "play"); + assertEquals(play.settings.at, undefined); + assertEquals(play.loop, true); + + voice.stop(); + const stop = await sent_until(sent, (command) => command.op === "stop"); + assert(stop?.op === "stop" && stop.id === play.id); +});