DoomAudio.ts
examples/doom/sim/DoomAudio.ts · raw · open the example · all examples · site home
Exports: DoomAudioOptionsDoomAudio
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329
// WebAudio backend for the sound and music modules of doom.wasm's host interface.
//
// Doom's s_sound.c has already done the positional mixdown, so SFX arrive as
// (channel, volume 0-127, separation 0-254) plus the raw DS* lump, which is
// decoded once per lump into an AudioBuffer. Music arrives as standard MIDI
// (MUS is converted in C) and is synthesized live by libADLMIDI's OPL3
// emulation (libadlmidi-js) in an AudioWorklet, using the embedded DMX bank
// so it sounds like Doom's GENMIDI on an Adlib/Sound Blaster. The synth's
// main-thread class is libadlmidi-js's bundled dist/libadlmidi.js, imported
// from oplModuleUrl at unlock (a static page has no package resolution).
import type { DoomModule, RadixAudioHooks } from "./DoomSim.js";
// libADLMIDI ADL_VolumeModels: DMX is Doom's volume curve.
const ADLMIDI_VOLUME_MODEL_DMX = 3;
// The subset of libadlmidi-js's AdlMidi used here
interface AdlMidi {
node: AudioWorkletNode;
init(processorUrl?: string, wasmUrl?: string): Promise<void>;
getEmbeddedBanks(): Promise<{ id: number; name: string }[]>;
setBank(bank: number): Promise<void>;
setVolumeModel(model: number): void;
setNumChips(chips: number): void;
loadMidi(data: ArrayBuffer): Promise<{ duration: number }>;
play(): void;
stop(): void;
setLoop(enabled: boolean): void;
}
export interface DoomAudioOptions {
// URLs of libadlmidi's ES module (dist/libadlmidi.js), AudioWorklet
// processor and core wasm. Omit the processor to disable music.
oplModuleUrl?: string;
oplProcessorUrl?: string;
oplWasmUrl?: string;
// Overall music gain applied on top of Doom's music volume (OPL output is
// hot compared with the 8-bit SFX).
musicGain?: number;
sfxGain?: number;
log?: (message: string) => void;
}
interface SfxChannel {
source: AudioBufferSourceNode;
gain: GainNode;
panner: StereoPannerNode;
lumpnum: number;
ended: boolean;
}
interface Song {
midi: Uint8Array;
}
export class DoomAudio {
readonly context: AudioContext;
private module?: DoomModule;
private readonly options: DoomAudioOptions;
private readonly log: (message: string) => void;
private readonly sfxMaster: GainNode;
private readonly buffers = new Map<number, AudioBuffer | null>();
private readonly channels = new Map<number, SfxChannel>();
private readonly musicMaster: GainNode;
private readonly songs = new Map<number, Song>();
private nextSongHandle = 1;
private synth?: AdlMidi;
private synthReady?: Promise<void>;
private musicVolume = 1;
private playing = false;
private playGeneration = 0;
currentSong?: { handle: number; looping: boolean };
constructor(options: DoomAudioOptions = {}) {
this.options = options;
this.log = options.log ?? (() => {});
this.context = new AudioContext({ sampleRate: 44100 });
this.sfxMaster = this.context.createGain();
this.sfxMaster.gain.value = options.sfxGain ?? 1;
this.sfxMaster.connect(this.context.destination);
this.musicMaster = this.context.createGain();
this.musicMaster.gain.value = options.musicGain ?? 0.6;
this.musicMaster.connect(this.context.destination);
}
// Must be called from a user gesture before anything is audible.
async unlock() {
if (this.context.state === "suspended") {
await this.context.resume();
}
if (this.options.oplProcessorUrl && !this.synthReady) {
this.synthReady = this.initSynth().catch((error) => {
this.log(`OPL music unavailable: ${error instanceof Error ? error.message : String(error)}`);
this.synth = undefined;
});
}
}
attach(module: DoomModule) {
this.module = module;
}
// The object to install as Module.radixAudio when the sim runs on this
// thread: reads lump/MIDI bytes from the module heap and forwards to the
// byte-based methods below (which a worker-hosted sim drives via messages,
// see ../simWorker.ts).
hooks(): RadixAudioHooks {
return {
sfxStart: (channel, lumpnum, ptr, len, vol, sep) => {
const bytes = this.buffers.has(lumpnum) ? null : this.module?.HEAPU8.subarray(ptr, ptr + len) ?? null;
return this.startSfx(channel, lumpnum, bytes, vol, sep);
},
sfxUpdate: (channel, vol, sep) => this.updateSfx(channel, vol, sep),
sfxStop: (channel) => this.stopSfx(channel),
sfxIsPlaying: (channel) => this.isSfxPlaying(channel),
musicRegister: (ptr, len, isMidi) => {
if (!this.module || isMidi === 0) return 0;
const handle = this.nextSongHandle++;
this.registerMusic(handle, this.module.HEAPU8.slice(ptr, ptr + len));
return handle;
},
musicUnregister: (handle) => this.unregisterMusic(handle),
musicPlay: (handle, looping) => this.playMusic(handle, looping !== 0),
musicStop: () => this.stopMusic(),
musicPause: () => this.pauseMusic(),
musicResume: () => this.resumeMusic(),
musicSetVolume: (volume) => this.setMusicVolume(volume),
musicIsPlaying: () => this.playing,
};
}
get musicBackend(): "opl3" | "none" {
return this.synth ? "opl3" : "none";
}
// ---- SFX ---------------------------------------------------------------
// Decodes a DMX lump once per lumpnum; `bytes` may be null once cached
private decodeLump(lumpnum: number, bytes: Uint8Array | null): AudioBuffer | null {
const cached = this.buffers.get(lumpnum);
if (cached !== undefined) {
return cached;
}
if (!bytes) {
return null;
}
// DMX sound lump: u16 format (3), u16 sample rate, u32 sample count,
// then 16 bytes of padding, samples, 16 bytes of padding.
const len = bytes.length;
let buffer: AudioBuffer | null = null;
if (len > 8 + 32) {
const format = bytes[0] | (bytes[1] << 8);
const rate = bytes[2] | (bytes[3] << 8);
const count = (bytes[4] | (bytes[5] << 8) | (bytes[6] << 16) | (bytes[7] << 24)) >>> 0;
if (format === 3 && rate > 0 && count > 32 && count <= len - 8) {
const samples = count - 32;
buffer = this.context.createBuffer(1, samples, rate);
const data = buffer.getChannelData(0);
const start = 8 + 16;
for (let i = 0; i < samples; i += 1) {
data[i] = (bytes[start + i] - 128) / 128;
}
}
}
this.buffers.set(lumpnum, buffer);
return buffer;
}
hasSfx(lumpnum: number) {
return this.buffers.has(lumpnum);
}
// Start a sound on a Doom channel; `bytes` is the DMX lump (needed only
// the first time a lumpnum is heard). Returns the channel or -1.
startSfx(channel: number, lumpnum: number, bytes: Uint8Array | null, vol: number, sep: number): number {
this.stopSfx(channel);
const buffer = this.decodeLump(lumpnum, bytes);
if (!buffer || this.context.state !== "running") {
return -1;
}
const source = this.context.createBufferSource();
source.buffer = buffer;
const gain = this.context.createGain();
const panner = this.context.createStereoPanner();
source.connect(gain).connect(panner).connect(this.sfxMaster);
const entry: SfxChannel = { source, gain, panner, lumpnum, ended: false };
applySfxParams(entry, vol, sep);
source.onended = () => {
entry.ended = true;
if (this.channels.get(channel) === entry) {
this.channels.delete(channel);
}
};
source.start();
this.channels.set(channel, entry);
return channel;
}
updateSfx(channel: number, vol: number, sep: number) {
const entry = this.channels.get(channel);
if (entry) {
applySfxParams(entry, vol, sep);
}
}
stopSfx(channel: number) {
const entry = this.channels.get(channel);
if (entry) {
this.channels.delete(channel);
try {
entry.source.stop();
} catch {
// already stopped
}
entry.source.disconnect();
}
}
isSfxPlaying(channel: number) {
const entry = this.channels.get(channel);
return entry !== undefined && !entry.ended;
}
// ---- music -------------------------------------------------------------
private async initSynth() {
if (!this.options.oplModuleUrl) {
throw new Error("no oplModuleUrl");
}
const { AdlMidi } = (await import(/* @vite-ignore */ this.options.oplModuleUrl)) as { AdlMidi: new (context: AudioContext) => AdlMidi };
const synth = new AdlMidi(this.context);
await synth.init(this.options.oplProcessorUrl, this.options.oplWasmUrl);
// Route through our gain instead of straight to the destination.
synth.node.disconnect();
synth.node.connect(this.musicMaster);
const banks = (await synth.getEmbeddedBanks()) as { id: number; name: string }[];
const dmx =
banks.find((bank) => /Bobby Prince v2/i.test(bank.name)) ??
banks.find((bank) => /default DMX/i.test(bank.name)) ??
banks.find((bank) => /DMX/i.test(bank.name));
if (dmx) {
await synth.setBank(dmx.id);
this.log(`OPL3 bank: ${dmx.name}`);
}
synth.setVolumeModel(ADLMIDI_VOLUME_MODEL_DMX);
synth.setNumChips(2);
this.synth = synth;
this.applyMusicVolume();
// A song may have been requested before the synth was ready.
if (this.currentSong) {
void this.startCurrentSong();
}
}
// Standard MIDI bytes (MUS is converted in C) under a caller-chosen handle
registerMusic(handle: number, midi: Uint8Array) {
this.songs.set(handle, { midi });
}
unregisterMusic(handle: number) {
this.songs.delete(handle);
if (this.currentSong?.handle === handle) {
this.stopMusic();
}
}
playMusic(handle: number, looping: boolean) {
this.currentSong = { handle, looping };
this.playing = true;
void this.startCurrentSong();
}
private async startCurrentSong() {
const synth = this.synth;
const song = this.currentSong ? this.songs.get(this.currentSong.handle) : undefined;
if (!synth || !song || !this.currentSong) {
return;
}
const generation = ++this.playGeneration;
const looping = this.currentSong.looping;
try {
synth.stop();
const midi = song.midi.slice();
await synth.loadMidi(midi.buffer as ArrayBuffer);
if (generation !== this.playGeneration) {
return; // superseded by a newer play/stop
}
synth.setLoop(looping);
synth.play();
} catch (error) {
this.log(`Music failed: ${error instanceof Error ? error.message : String(error)}`);
}
}
stopMusic() {
this.playGeneration += 1;
this.playing = false;
this.currentSong = undefined;
this.synth?.stop();
}
pauseMusic() {
this.synth?.stop();
}
resumeMusic() {
if (this.currentSong) {
this.synth?.play();
}
}
// Doom volume 0-127 (already scaled from the 0-15 menu setting).
setMusicVolume(volume: number) {
this.musicVolume = Math.max(0, Math.min(127, volume)) / 127;
this.applyMusicVolume();
}
private applyMusicVolume() {
this.musicMaster.gain.value = (this.options.musicGain ?? 0.6) * this.musicVolume;
}
}
function applySfxParams(entry: SfxChannel, vol: number, sep: number) {
entry.gain.gain.value = Math.max(0, Math.min(127, vol)) / 127;
entry.panner.pan.value = Math.max(-1, Math.min(1, (sep - 128) / 128));
}