Files
top-octane/src/audio/audio_engine.cpp
T

522 lines
21 KiB
C++
Raw Normal View History

2026-11-30 22:31:51 +02:00
#include "audio/audio_engine.hpp"
#include "core/log.hpp"
#include <algorithm>
#include <cctype>
#include <cmath>
#include <cstring>
namespace top_octane::audio {
namespace {
int map_track_slot(MusicTrackId id) {
// MUSIC.DAT ordering: 0=TGAME1, 1=TGAME2, 2=TGAME4, 3=TINTRO2, 4=TGAME3
switch (id) {
case MusicTrackId::Game1: return 0;
case MusicTrackId::Game2: return 1;
case MusicTrackId::Game4: return 2;
case MusicTrackId::TitleIntro: return 3;
case MusicTrackId::Game3: return 4;
case MusicTrackId::Menu: return 3;
2026-11-30 22:31:51 +02:00
}
return 0;
}
const char* track_stem(MusicTrackId id) {
switch (id) {
case MusicTrackId::TitleIntro: return "tintro2";
case MusicTrackId::Game1: return "tgame1";
case MusicTrackId::Game2: return "tgame2";
case MusicTrackId::Game3: return "tgame3";
case MusicTrackId::Game4: return "tgame4";
case MusicTrackId::Menu: return "tmenu";
2026-11-30 22:31:51 +02:00
}
return "tgame1";
}
bool eq_icase(const std::string& a, const std::string& b) {
if (a.size() != b.size()) return false;
for (size_t i = 0; i < a.size(); ++i) {
if (std::tolower(static_cast<unsigned char>(a[i])) !=
std::tolower(static_cast<unsigned char>(b[i]))) {
return false;
}
}
return true;
}
} // namespace
AudioEngine::~AudioEngine() {
shutdown();
}
bool AudioEngine::init(const Vfs& vfs, const GameConfig& cfg, bool open_device) {
if (initialized_) return true;
if (!sound_bank_.load(vfs) || !music_archive_.load(vfs) ||
!opl_bank_.load(vfs) || !sf_bank_.load(vfs)) {
return false;
}
// Pre-parse all 5 tracks for OPL3 (.XMI bank 2) and SoundFont (.WTB bank 3)
for (int i = 0; i < 5; ++i) {
const auto& xmi_raw = music_archive_.banks[static_cast<size_t>(assets::MusicBankType::AdlibOpl)][i];
assets::parse_xmi_sequence(xmi_raw.data.data(), xmi_raw.data.size(), xmi_raw.name, opl_seqs_[i]);
const auto& wtb_raw = music_archive_.banks[static_cast<size_t>(assets::MusicBankType::Awe32Wt)][i];
assets::parse_xmi_sequence(wtb_raw.data.data(), wtb_raw.data.size(), wtb_raw.name, wt_seqs_[i]);
}
// Optional external SoundFont (.sf2)
has_custom_sf_ = false;
loaded_custom_sf_path_.clear();
2026-11-30 22:31:51 +02:00
if (!cfg.custom_soundfont_path.empty()) {
std::vector<uint8_t> sf_bytes;
if (Vfs::read_raw_file(cfg.custom_soundfont_path, sf_bytes) &&
custom_sf_bank_.load_from_bytes(sf_bytes.data(), sf_bytes.size())) {
has_custom_sf_ = true;
loaded_custom_sf_path_ = cfg.custom_soundfont_path;
2026-11-30 22:31:51 +02:00
}
}
// Optional custom WAV music tracks in <pref_dir>/music/*.wav (including optional tmenu.wav)
for (int i = 0; i < 6; ++i) {
2026-11-30 22:31:51 +02:00
MusicTrackId tid = static_cast<MusicTrackId>(i);
std::filesystem::path wp = vfs.pref_dir() / "music" / (std::string(track_stem(tid)) + ".wav");
std::vector<uint8_t> wdata;
if (Vfs::read_raw_file(wp, wdata)) {
assets::decode_wav_bytes(wdata.data(), wdata.size(), custom_wav_tracks_[i]);
}
}
if (custom_wav_tracks_[static_cast<int>(MusicTrackId::Menu)].pcm_mono.empty() &&
!custom_wav_tracks_[static_cast<int>(MusicTrackId::TitleIntro)].pcm_mono.empty()) {
custom_wav_tracks_[static_cast<int>(MusicTrackId::Menu)] =
custom_wav_tracks_[static_cast<int>(MusicTrackId::TitleIntro)];
}
2026-11-30 22:31:51 +02:00
opl_synth_.set_timbre_bank(&opl_bank_);
opl_synth_.set_sample_rate(kSampleRate);
sf_synth_.set_soundfont(has_custom_sf_ ? &custom_sf_bank_ : &sf_bank_);
sf_synth_.set_opl_fallback(&opl_bank_);
sf_synth_.set_sample_rate(kSampleRate);
xmi_player_.set_sample_rate(kSampleRate);
engine_sample_ = sound_bank_.find_gameplay("ENGINE1.WAV");
if (!engine_sample_) engine_sample_ = sound_bank_.find_gameplay("TESTENG3.WAV");
scrape_sample_ = sound_bank_.find_gameplay("SCRAPE2.WAV");
active_backend_ = cfg.music_backend;
requested_backend_ = cfg.music_backend;
master_vol_.store(cfg.master_volume, std::memory_order_relaxed);
sfx_vol_.store(cfg.sfx_volume, std::memory_order_relaxed);
music_vol_.store(cfg.music_volume, std::memory_order_relaxed);
mix_sample_clock_ = static_cast<uint64_t>(kSampleRate) * 60ull;
voice_seq_ = 0;
last_play_sample_gameplay_.fill(0);
last_play_sample_intro_.fill(0);
for (auto& v : sfx_voices_) v = SfxVoice{};
if (open_device) {
if (SDL_WasInit(SDL_INIT_AUDIO) == 0) {
if (SDL_InitSubSystem(SDL_INIT_AUDIO) != 0) {
LOG_WARN("SDL audio init failed (%s); continuing silent", SDL_GetError());
}
}
if (SDL_WasInit(SDL_INIT_AUDIO) != 0) {
SDL_AudioSpec want{}, have{};
want.freq = kSampleRate;
want.format = AUDIO_F32SYS;
want.channels = 2;
want.samples = 1024;
want.callback = &AudioEngine::sdl_audio_callback;
want.userdata = this;
dev_id_ = SDL_OpenAudioDevice(nullptr, 0, &want, &have, 0);
if (dev_id_ == 0) {
LOG_WARN("SDL_OpenAudioDevice failed (%s); continuing silent", SDL_GetError());
} else {
SDL_PauseAudioDevice(dev_id_, 0);
LOG_INFO("SDL2 Audio opened: %d Hz, float32 stereo", have.freq);
}
}
}
initialized_ = true;
return true;
}
void AudioEngine::shutdown() {
if (!initialized_) return;
if (dev_id_ != 0) {
SDL_CloseAudioDevice(dev_id_);
dev_id_ = 0;
}
initialized_ = false;
}
void AudioEngine::apply_config(const GameConfig& cfg, bool window_focused) {
master_vol_.store(cfg.master_volume, std::memory_order_relaxed);
sfx_vol_.store(cfg.sfx_volume, std::memory_order_relaxed);
music_vol_.store(cfg.music_volume, std::memory_order_relaxed);
muted_.store(cfg.mute_on_focus_loss && !window_focused, std::memory_order_relaxed);
if (cfg.custom_soundfont_path != loaded_custom_sf_path_) {
assets::SoundFontBank next_sf;
bool ok = false;
if (!cfg.custom_soundfont_path.empty()) {
std::vector<uint8_t> sf_bytes;
if (Vfs::read_raw_file(cfg.custom_soundfont_path, sf_bytes) &&
next_sf.load_from_bytes(sf_bytes.data(), sf_bytes.size())) {
ok = true;
}
}
if (dev_id_ != 0) SDL_LockAudioDevice(dev_id_);
if (ok) {
custom_sf_bank_ = std::move(next_sf);
has_custom_sf_ = true;
} else {
custom_sf_bank_ = assets::SoundFontBank{};
has_custom_sf_ = false;
}
loaded_custom_sf_path_ = cfg.custom_soundfont_path;
sf_synth_.reset();
sf_synth_.set_soundfont(has_custom_sf_ ? &custom_sf_bank_ : &sf_bank_);
if (dev_id_ != 0) SDL_UnlockAudioDevice(dev_id_);
}
2026-11-30 22:31:51 +02:00
if (cfg.music_backend != requested_backend_) {
requested_backend_ = cfg.music_backend;
AudioCommand cmd;
cmd.type = CmdType::SetBackend;
cmd.backend = cfg.music_backend;
push_command(cmd);
}
}
void AudioEngine::play_music(MusicTrackId track, bool loop) {
AudioCommand cmd;
cmd.type = CmdType::PlayMusic;
cmd.track = track;
cmd.loop = loop;
push_command(cmd);
}
void AudioEngine::stop_music() {
AudioCommand cmd;
cmd.type = CmdType::StopMusic;
push_command(cmd);
}
int AudioEngine::find_sfx_index(const std::string& name, bool intro_bank) const {
const auto& vec = intro_bank ? sound_bank_.intro_sfx : sound_bank_.gameplay_sfx;
for (size_t i = 0; i < vec.size(); ++i) {
if (eq_icase(vec[i].name, name)) return static_cast<int>(i);
}
return -1;
}
void AudioEngine::play_sfx(const std::string& wav_name, float gain, float pitch,
float pan, bool is_intro_bank, float min_interval_sec) {
int idx = find_sfx_index(wav_name, is_intro_bank);
if (idx < 0 && is_intro_bank) {
is_intro_bank = false;
idx = find_sfx_index(wav_name, false);
}
if (idx < 0) return;
AudioCommand cmd;
cmd.type = CmdType::PlaySfx;
cmd.sample_idx = idx;
cmd.intro_bank = is_intro_bank;
cmd.gain = std::clamp(gain, 0.0f, 2.0f);
cmd.pitch = std::clamp(pitch, 0.25f, 3.0f);
cmd.pan = std::clamp(pan, -1.0f, 1.0f);
cmd.min_interval_sec = std::max(0.0f, min_interval_sec);
push_command(cmd);
}
void AudioEngine::play_sfx_3d(const std::string& wav_name, const Vec3& src_pos,
const Vec3& listener_pos, const Vec3& listener_right,
float gain, float pitch, float min_interval_sec) {
Vec3 d = src_pos - listener_pos;
float dist = d.len();
if (dist > 28.0f) return;
float atten = 1.0f / (1.0f + dist * 0.22f + dist * dist * 0.025f);
float pan = (dist > 0.1f) ? std::clamp((d / dist).dot(listener_right), -1.0f, 1.0f) : 0.0f;
play_sfx(wav_name, gain * atten, pitch, pan, false, min_interval_sec);
}
void AudioEngine::set_engine_state(bool active, float speed_ratio, bool boosting, float scrape_amount) {
engine_active_.store(active, std::memory_order_relaxed);
engine_speed_ratio_.store(std::clamp(speed_ratio, 0.0f, 1.5f), std::memory_order_relaxed);
engine_boosting_.store(boosting, std::memory_order_relaxed);
scrape_amount_.store(std::clamp(scrape_amount, 0.0f, 1.0f), std::memory_order_relaxed);
}
const assets::XmiSequence& AudioEngine::xmi_sequence(MusicBackend b, MusicTrackId t) const {
int slot = map_track_slot(t);
return (b == MusicBackend::SoundFont) ? wt_seqs_[slot] : opl_seqs_[slot];
}
bool AudioEngine::push_command(const AudioCommand& cmd) {
uint32_t head = cmd_head_.load(std::memory_order_relaxed);
uint32_t next = (head + 1u) % kCmdQueueSize;
if (next == cmd_tail_.load(std::memory_order_acquire)) {
return false; // full
}
cmd_ring_[head] = cmd;
cmd_head_.store(next, std::memory_order_release);
return true;
}
void AudioEngine::start_active_track() {
opl_synth_.reset();
sf_synth_.reset();
custom_music_playing_ = false;
custom_music_pos_ = 0.0;
int idx = std::clamp(static_cast<int>(active_track_), 0, 5);
int slot = map_track_slot(active_track_);
if (active_backend_ == MusicBackend::Custom && !custom_wav_tracks_[idx].pcm_mono.empty()) {
xmi_player_.stop();
custom_music_playing_ = true;
} else {
uint32_t start_tick = (active_track_ == MusicTrackId::Menu) ? 1610u : 0u;
const assets::XmiSequence* seq = (active_backend_ == MusicBackend::SoundFont)
? &wt_seqs_[slot]
: &opl_seqs_[slot];
xmi_player_.set_sequence(seq, active_loop_, start_tick);
}
}
2026-11-30 22:31:51 +02:00
void AudioEngine::drain_commands() {
uint32_t tail = cmd_tail_.load(std::memory_order_relaxed);
uint32_t head = cmd_head_.load(std::memory_order_acquire);
while (tail != head) {
const AudioCommand& cmd = cmd_ring_[tail];
switch (cmd.type) {
case CmdType::PlaySfx: {
const auto& vec = cmd.intro_bank ? sound_bank_.intro_sfx : sound_bank_.gameplay_sfx;
if (cmd.sample_idx >= 0 && static_cast<size_t>(cmd.sample_idx) < vec.size()) {
const assets::SoundSample* smp = &vec[cmd.sample_idx];
if (smp->pcm_mono.empty()) break;
auto& last_arr = cmd.intro_bank ? last_play_sample_intro_ : last_play_sample_gameplay_;
if (static_cast<size_t>(cmd.sample_idx) < last_arr.size()) {
uint64_t min_samples = static_cast<uint64_t>(cmd.min_interval_sec * static_cast<float>(kSampleRate));
if (mix_sample_clock_ - last_arr[cmd.sample_idx] < min_samples) {
break;
}
last_arr[cmd.sample_idx] = mix_sample_clock_;
}
int same_count = 0;
SfxVoice* oldest_same = nullptr;
SfxVoice* free_slot = nullptr;
SfxVoice* oldest_any = nullptr;
for (auto& v : sfx_voices_) {
if (!v.active) {
if (!free_slot) free_slot = &v;
continue;
}
if (!oldest_any || v.start_seq < oldest_any->start_seq) {
oldest_any = &v;
}
if (v.sample_idx == cmd.sample_idx && v.intro_bank == cmd.intro_bank) {
++same_count;
if (!oldest_same || v.start_seq < oldest_same->start_seq) {
oldest_same = &v;
}
}
}
SfxVoice* target = (same_count >= kMaxSameSampleVoices && oldest_same)
? oldest_same
: (free_slot ? free_slot : oldest_any);
if (target) {
target->active = true;
target->sample = smp;
target->sample_idx = cmd.sample_idx;
target->intro_bank = cmd.intro_bank;
target->start_seq = ++voice_seq_;
target->pos = 0.0;
target->step = (static_cast<double>(smp->sample_rate) / kSampleRate) * cmd.pitch;
target->gain_l = cmd.gain * std::sqrt(0.5f * (1.0f - cmd.pan));
target->gain_r = cmd.gain * std::sqrt(0.5f * (1.0f + cmd.pan));
}
}
break;
}
case CmdType::PlayMusic: {
active_track_ = cmd.track;
active_loop_ = cmd.loop;
start_active_track();
2026-11-30 22:31:51 +02:00
break;
}
case CmdType::StopMusic:
xmi_player_.stop();
2026-11-30 23:22:00 +02:00
opl_synth_.reset();
sf_synth_.reset();
2026-11-30 22:31:51 +02:00
custom_music_playing_ = false;
break;
case CmdType::SetBackend:
if (cmd.backend != active_backend_) {
bool was_playing = xmi_player_.is_playing() || custom_music_playing_;
active_backend_ = cmd.backend;
2026-11-30 23:22:00 +02:00
opl_synth_.reset();
sf_synth_.reset();
2026-11-30 22:31:51 +02:00
custom_music_playing_ = false;
if (was_playing) {
start_active_track();
2026-11-30 22:31:51 +02:00
}
}
break;
}
tail = (tail + 1u) % kCmdQueueSize;
}
cmd_tail_.store(tail, std::memory_order_release);
}
void AudioEngine::render_internal(float* stereo_out, int frames) {
if (frames <= 0) return;
std::memset(stereo_out, 0, static_cast<size_t>(frames) * 2u * sizeof(float));
drain_commands();
const float master = muted_.load(std::memory_order_relaxed) ? 0.0f : master_vol_.load(std::memory_order_relaxed);
const float mvol = music_vol_.load(std::memory_order_relaxed) * master;
const float svol = sfx_vol_.load(std::memory_order_relaxed) * master;
constexpr int kChunk = 512;
std::array<float, kChunk * 2> sfx_bus;
for (int off = 0; off < frames; off += kChunk) {
int cur = std::min(kChunk, frames - off);
float* out_ptr = stereo_out + off * 2;
// 1. Render Music into output chunk
if (mvol > 0.001f) {
if (custom_music_playing_) {
int tidx = std::clamp(static_cast<int>(active_track_), 0, 5);
const auto& tr = custom_wav_tracks_[tidx];
2026-11-30 22:31:51 +02:00
if (!tr.pcm_mono.empty()) {
double step = static_cast<double>(tr.sample_rate) / kSampleRate;
for (int f = 0; f < cur; ++f) {
size_t i0 = static_cast<size_t>(custom_music_pos_);
if (i0 + 1 >= tr.pcm_mono.size()) {
if (active_loop_) {
custom_music_pos_ = 0.0;
i0 = 0;
} else {
custom_music_playing_ = false;
break;
}
}
float s = tr.pcm_mono[i0] * mvol;
out_ptr[f * 2 + 0] += s;
out_ptr[f * 2 + 1] += s;
custom_music_pos_ += step;
}
}
} else if (xmi_player_.is_playing()) {
if (active_backend_ == MusicBackend::SoundFont) {
xmi_player_.render(out_ptr, cur, sf_synth_);
} else {
xmi_player_.render(out_ptr, cur, opl_synth_);
}
for (int i = 0; i < cur * 2; ++i) {
out_ptr[i] *= mvol;
}
}
}
// 2. Render SFX + Continuous Engine & Scrape Loops into isolated SFX bus + soft compressor
if (svol > 0.001f) {
std::fill_n(sfx_bus.data(), cur * 2, 0.0f);
for (auto& v : sfx_voices_) {
if (!v.active || !v.sample) continue;
const auto& pcm = v.sample->pcm_mono;
for (int f = 0; f < cur; ++f) {
size_t i0 = static_cast<size_t>(v.pos);
if (i0 + 1 >= pcm.size()) {
v.active = false;
break;
}
float frac = static_cast<float>(v.pos - static_cast<double>(i0));
float s = (pcm[i0] + (pcm[i0 + 1] - pcm[i0]) * frac) * svol;
sfx_bus[f * 2 + 0] += s * v.gain_l;
sfx_bus[f * 2 + 1] += s * v.gain_r;
v.pos += v.step;
}
}
if (engine_active_.load(std::memory_order_relaxed) && engine_sample_ &&
!engine_sample_->pcm_mono.empty()) {
float spd = engine_speed_ratio_.load(std::memory_order_relaxed);
bool bst = engine_boosting_.load(std::memory_order_relaxed);
double pitch = 0.65 + 0.65 * spd + (bst ? 0.28 : 0.0);
double step = (static_cast<double>(engine_sample_->sample_rate) / kSampleRate) * pitch;
float egain = (0.13f + 0.11f * std::min(spd, 1.0f)) * svol;
const auto& pcm = engine_sample_->pcm_mono;
size_t len = pcm.size();
for (int f = 0; f < cur; ++f) {
size_t i0 = static_cast<size_t>(engine_pos_) % len;
size_t i1 = (i0 + 1) % len;
float frac = static_cast<float>(engine_pos_ - std::floor(engine_pos_));
float s = (pcm[i0] + (pcm[i1] - pcm[i0]) * frac) * egain;
sfx_bus[f * 2 + 0] += s;
sfx_bus[f * 2 + 1] += s;
engine_pos_ += step;
if (engine_pos_ >= static_cast<double>(len)) {
engine_pos_ -= static_cast<double>(len);
}
}
}
float scrape = scrape_amount_.load(std::memory_order_relaxed);
if (scrape > 0.02f && scrape_sample_ && !scrape_sample_->pcm_mono.empty()) {
const auto& pcm = scrape_sample_->pcm_mono;
size_t len = pcm.size();
double step = static_cast<double>(scrape_sample_->sample_rate) / kSampleRate;
float sgain = scrape * 0.22f * svol;
for (int f = 0; f < cur; ++f) {
size_t i0 = static_cast<size_t>(scrape_pos_) % len;
float s = pcm[i0] * sgain;
sfx_bus[f * 2 + 0] += s;
sfx_bus[f * 2 + 1] += s;
scrape_pos_ += step;
if (scrape_pos_ >= static_cast<double>(len)) scrape_pos_ -= static_cast<double>(len);
}
}
for (int i = 0; i < cur * 2; ++i) {
out_ptr[i] += std::tanh(sfx_bus[i] * 1.1f) * 0.88f;
}
}
}
mix_sample_clock_ += static_cast<uint64_t>(frames);
// Outer soft limiter against clipping
for (int i = 0; i < frames * 2; ++i) {
float x = stereo_out[i];
if (x > 0.96f || x < -0.96f) {
stereo_out[i] = std::tanh(x) * 0.985f;
}
}
}
void AudioEngine::mix_offline(float* stereo_out, int frames) {
render_internal(stereo_out, frames);
}
void AudioEngine::sdl_audio_callback(void* userdata, uint8_t* stream, int len) {
auto* self = static_cast<AudioEngine*>(userdata);
int frames = len / static_cast<int>(sizeof(float) * 2);
self->render_internal(reinterpret_cast<float*>(stream), frames);
}
} // namespace top_octane::audio