// 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"; import { type LibraryFiles, open_library } from "./libraries.ts"; const LIBRARY: LibraryFiles = { linux: "libopenal.so.1", windows: "OpenAL32.dll", darwin: "libopenal.1.dylib" }; 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() { this.#al = open_library("openal", LIBRARY, 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); } }