Audio on native
This commit is contained in:
+30
-5
@@ -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);
|
||||
|
||||
@@ -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<typeof SYMBOLS>["symbols"];
|
||||
#device: Deno.PointerObject;
|
||||
#context: Deno.PointerObject;
|
||||
#buffers = new Map<number, Decoded>();
|
||||
// the client's source ids, and the openal sources playing them
|
||||
#sources = new Map<number, { name: number; loop: boolean }>();
|
||||
#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);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user