init commit
This commit is contained in:
commit
15ab48343a
187 files changed
+12644
No files matched your search
@@ -0,0 +1,491 @@
|
||||
#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;
|
||||
}
|
||||
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";
|
||||
}
|
||||
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;
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
// Optional custom WAV music tracks in <pref_dir>/music/*.wav
|
||||
for (int i = 0; i < 5; ++i) {
|
||||
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]);
|
||||
}
|
||||
}
|
||||
|
||||
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.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::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;
|
||||
int slot = map_track_slot(cmd.track);
|
||||
opl_synth_.all_notes_off();
|
||||
sf_synth_.all_notes_off();
|
||||
custom_music_playing_ = false;
|
||||
custom_music_pos_ = 0.0;
|
||||
if (active_backend_ == MusicBackend::Custom &&
|
||||
!custom_wav_tracks_[static_cast<int>(cmd.track)].pcm_mono.empty()) {
|
||||
xmi_player_.stop();
|
||||
custom_music_playing_ = true;
|
||||
} else if (active_backend_ == MusicBackend::SoundFont) {
|
||||
xmi_player_.set_sequence(&wt_seqs_[slot], cmd.loop);
|
||||
} else {
|
||||
xmi_player_.set_sequence(&opl_seqs_[slot], cmd.loop);
|
||||
}
|
||||
break;
|
||||
}
|
||||
case CmdType::StopMusic:
|
||||
xmi_player_.stop();
|
||||
opl_synth_.all_notes_off();
|
||||
sf_synth_.all_notes_off();
|
||||
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;
|
||||
opl_synth_.all_notes_off();
|
||||
sf_synth_.all_notes_off();
|
||||
custom_music_playing_ = false;
|
||||
if (was_playing) {
|
||||
int slot = map_track_slot(active_track_);
|
||||
if (active_backend_ == MusicBackend::Custom &&
|
||||
!custom_wav_tracks_[static_cast<int>(active_track_)].pcm_mono.empty()) {
|
||||
xmi_player_.stop();
|
||||
custom_music_playing_ = true;
|
||||
custom_music_pos_ = 0.0;
|
||||
} else if (active_backend_ == MusicBackend::SoundFont) {
|
||||
xmi_player_.set_sequence(&wt_seqs_[slot], active_loop_);
|
||||
} else {
|
||||
xmi_player_.set_sequence(&opl_seqs_[slot], active_loop_);
|
||||
}
|
||||
}
|
||||
}
|
||||
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_) {
|
||||
const auto& tr = custom_wav_tracks_[static_cast<int>(active_track_)];
|
||||
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
|
||||
@@ -0,0 +1,160 @@
|
||||
#pragma once
|
||||
|
||||
#include "assets/music_bank.hpp"
|
||||
#include "assets/sound_bank.hpp"
|
||||
#include "audio/opl3_synth.hpp"
|
||||
#include "audio/sf_synth.hpp"
|
||||
#include "audio/xmidi_player.hpp"
|
||||
#include "core/config.hpp"
|
||||
#include "core/math.hpp"
|
||||
#include "core/vfs.hpp"
|
||||
|
||||
#include <SDL.h>
|
||||
#include <array>
|
||||
#include <atomic>
|
||||
#include <cstdint>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace top_octane::audio {
|
||||
|
||||
enum class MusicTrackId {
|
||||
TitleIntro = 0, // TINTRO2
|
||||
Game1 = 1, // TGAME1
|
||||
Game2 = 2, // TGAME2
|
||||
Game3 = 3, // TGAME3
|
||||
Game4 = 4, // TGAME4
|
||||
};
|
||||
|
||||
class AudioEngine {
|
||||
public:
|
||||
static constexpr int kSampleRate = 48000;
|
||||
static constexpr int kMaxSfxVoices = 32;
|
||||
static constexpr int kMaxSameSampleVoices = 3;
|
||||
static constexpr int kCmdQueueSize = 256;
|
||||
|
||||
AudioEngine() = default;
|
||||
~AudioEngine();
|
||||
|
||||
AudioEngine(const AudioEngine&) = delete;
|
||||
AudioEngine& operator=(const AudioEngine&) = delete;
|
||||
|
||||
// Loads assets (SOUND.DAT, MUSIC.DAT, SAMPLE.OPL, BULLFROG.SBK) & opens SDL audio if open_device==true
|
||||
bool init(const Vfs& vfs, const GameConfig& cfg, bool open_device = true);
|
||||
void shutdown();
|
||||
|
||||
void apply_config(const GameConfig& cfg, bool window_focused = true);
|
||||
|
||||
void play_music(MusicTrackId track, bool loop = true);
|
||||
void stop_music();
|
||||
|
||||
// Gameplay / intro SFX triggers (thread-safe lock-free push)
|
||||
void play_sfx(const std::string& wav_name, float gain = 1.0f, float pitch = 1.0f,
|
||||
float pan = 0.0f, bool is_intro_bank = false, float min_interval_sec = 0.05f);
|
||||
void play_sfx_3d(const std::string& wav_name, const Vec3& src_pos,
|
||||
const Vec3& listener_pos, const Vec3& listener_right,
|
||||
float gain = 1.0f, float pitch = 1.0f, float min_interval_sec = 0.05f);
|
||||
|
||||
// Continuous player engine pitch/volume modulation
|
||||
void set_engine_state(bool active, float speed_ratio, bool boosting, float scrape_amount);
|
||||
|
||||
// Offline render hook for deterministic unit testing
|
||||
void mix_offline(float* stereo_out, int frames);
|
||||
|
||||
const assets::SoundBank& sound_bank() const { return sound_bank_; }
|
||||
const assets::OplTimbreBank& opl_bank() const { return opl_bank_; }
|
||||
const assets::SoundFontBank& sf_bank() const { return sf_bank_; }
|
||||
const assets::XmiSequence& xmi_sequence(MusicBackend b, MusicTrackId t) const;
|
||||
|
||||
private:
|
||||
enum class CmdType : uint8_t {
|
||||
PlaySfx = 0,
|
||||
PlayMusic,
|
||||
StopMusic,
|
||||
SetBackend,
|
||||
};
|
||||
|
||||
struct AudioCommand {
|
||||
CmdType type = CmdType::PlaySfx;
|
||||
int sample_idx = -1;
|
||||
bool intro_bank = false;
|
||||
float gain = 1.0f;
|
||||
float pitch = 1.0f;
|
||||
float pan = 0.0f;
|
||||
float min_interval_sec = 0.05f;
|
||||
MusicTrackId track = MusicTrackId::Game1;
|
||||
bool loop = true;
|
||||
MusicBackend backend = MusicBackend::Opl3;
|
||||
};
|
||||
|
||||
struct SfxVoice {
|
||||
bool active = false;
|
||||
const assets::SoundSample* sample = nullptr;
|
||||
int sample_idx = -1;
|
||||
bool intro_bank = false;
|
||||
uint64_t start_seq = 0;
|
||||
double pos = 0.0;
|
||||
double step = 1.0;
|
||||
float gain_l = 0.0f;
|
||||
float gain_r = 0.0f;
|
||||
};
|
||||
|
||||
bool push_command(const AudioCommand& cmd);
|
||||
void drain_commands();
|
||||
void render_internal(float* stereo_out, int frames);
|
||||
int find_sfx_index(const std::string& name, bool intro_bank) const;
|
||||
static void sdl_audio_callback(void* userdata, uint8_t* stream, int len);
|
||||
|
||||
SDL_AudioDeviceID dev_id_ = 0;
|
||||
bool initialized_ = false;
|
||||
|
||||
assets::SoundBank sound_bank_;
|
||||
assets::MusicArchive music_archive_;
|
||||
assets::OplTimbreBank opl_bank_;
|
||||
assets::SoundFontBank sf_bank_;
|
||||
assets::SoundFontBank custom_sf_bank_;
|
||||
bool has_custom_sf_ = false;
|
||||
|
||||
// Pre-parsed sequences for 2 banks (Adlib .XMI and AWE32 .WTB) x 5 songs
|
||||
std::array<assets::XmiSequence, 5> opl_seqs_{};
|
||||
std::array<assets::XmiSequence, 5> wt_seqs_{};
|
||||
std::array<assets::SoundSample, 5> custom_wav_tracks_{};
|
||||
|
||||
Opl3Synth opl_synth_;
|
||||
SfSynth sf_synth_;
|
||||
XmidiPlayer xmi_player_;
|
||||
|
||||
MusicBackend active_backend_ = MusicBackend::Opl3;
|
||||
MusicBackend requested_backend_ = MusicBackend::Opl3;
|
||||
MusicTrackId active_track_ = MusicTrackId::TitleIntro;
|
||||
bool active_loop_ = true;
|
||||
double custom_music_pos_ = 0.0;
|
||||
bool custom_music_playing_ = false;
|
||||
|
||||
std::array<SfxVoice, kMaxSfxVoices> sfx_voices_{};
|
||||
uint64_t mix_sample_clock_ = static_cast<uint64_t>(kSampleRate) * 60ull;
|
||||
uint64_t voice_seq_ = 0;
|
||||
std::array<uint64_t, 64> last_play_sample_gameplay_{};
|
||||
std::array<uint64_t, 64> last_play_sample_intro_{};
|
||||
const assets::SoundSample* engine_sample_ = nullptr;
|
||||
const assets::SoundSample* scrape_sample_ = nullptr;
|
||||
double engine_pos_ = 0.0;
|
||||
double scrape_pos_ = 0.0;
|
||||
|
||||
// Lock-free SPSC command ring buffer (game thread -> audio thread)
|
||||
std::array<AudioCommand, kCmdQueueSize> cmd_ring_{};
|
||||
std::atomic<uint32_t> cmd_head_{0};
|
||||
std::atomic<uint32_t> cmd_tail_{0};
|
||||
|
||||
// Atomic mix parameters
|
||||
std::atomic<float> master_vol_{0.85f};
|
||||
std::atomic<float> sfx_vol_{0.80f};
|
||||
std::atomic<float> music_vol_{0.75f};
|
||||
std::atomic<bool> muted_{false};
|
||||
std::atomic<bool> engine_active_{false};
|
||||
std::atomic<float> engine_speed_ratio_{0.0f};
|
||||
std::atomic<bool> engine_boosting_{false};
|
||||
std::atomic<float> scrape_amount_{0.0f};
|
||||
};
|
||||
|
||||
} // namespace top_octane::audio
|
||||
@@ -0,0 +1,319 @@
|
||||
#include "audio/opl3_synth.hpp"
|
||||
#include "core/math.hpp"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
|
||||
namespace top_octane::audio {
|
||||
|
||||
namespace {
|
||||
|
||||
constexpr double kMultTable[16] = {
|
||||
0.5, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0,
|
||||
8.0, 9.0, 10.0, 10.0, 12.0, 12.0, 15.0, 15.0
|
||||
};
|
||||
|
||||
float rate_to_sec(int rate_4bit, bool is_attack) {
|
||||
if (rate_4bit <= 0) return 8.0f;
|
||||
if (rate_4bit >= 15) return 0.002f;
|
||||
// Exponential OPL rate curve mapping 1..14 cleanly to seconds
|
||||
float norm = static_cast<float>(15 - rate_4bit);
|
||||
float base = is_attack ? 0.0025f : 0.008f;
|
||||
return base * std::pow(1.62f, norm);
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
Opl3Synth::Opl3Synth(const assets::OplTimbreBank* bank, int sample_rate)
|
||||
: bank_(bank), sample_rate_(std::max(sample_rate, 8000)) {
|
||||
for (int i = 0; i < kNumChannels; ++i) {
|
||||
channels_[i] = ChannelState{};
|
||||
channels_[i].bank = (i == 9) ? 127 : 0;
|
||||
}
|
||||
}
|
||||
|
||||
void Opl3Synth::set_sample_rate(int sample_rate) {
|
||||
sample_rate_ = std::max(sample_rate, 8000);
|
||||
}
|
||||
|
||||
void Opl3Synth::setup_operator(Operator& op, uint8_t reg20, uint8_t reg40, uint8_t reg60,
|
||||
uint8_t reg80, uint8_t regE0, float base_freq,
|
||||
float vel_scale, bool is_carrier) {
|
||||
double mult = kMultTable[reg20 & 0x0Fu];
|
||||
op.phase = 0.0;
|
||||
op.phase_inc = (static_cast<double>(base_freq) * mult) / static_cast<double>(sample_rate_);
|
||||
op.am = (reg20 & 0x80u) != 0;
|
||||
op.vib = (reg20 & 0x40u) != 0;
|
||||
op.sustain_hold = (reg20 & 0x20u) != 0;
|
||||
op.wave = regE0 & 7u;
|
||||
|
||||
// Total Level (6-bit, 0 = max, 63 = -47.25 dB)
|
||||
int tl = reg40 & 0x3Fu;
|
||||
float tl_gain = std::pow(10.0f, (-0.75f * static_cast<float>(tl)) / 20.0f);
|
||||
op.total_level = tl_gain * (is_carrier ? vel_scale : 1.0f);
|
||||
|
||||
int ar = (reg60 >> 4) & 0x0Fu;
|
||||
int dr = reg60 & 0x0Fu;
|
||||
int sl = (reg80 >> 4) & 0x0Fu;
|
||||
int rr = reg80 & 0x0Fu;
|
||||
|
||||
op.attack_rate = 1.0f / rate_to_sec(ar, true);
|
||||
op.decay_rate = 1.0f / rate_to_sec(dr, false);
|
||||
op.sustain_level = (sl == 15) ? 0.0f : std::pow(10.0f, (-3.0f * static_cast<float>(sl)) / 20.0f);
|
||||
op.release_rate = 1.0f / rate_to_sec(rr, false);
|
||||
op.env = 0.0f;
|
||||
op.stage = EnvStage::Attack;
|
||||
}
|
||||
|
||||
void Opl3Synth::update_voice_freq(Voice& v) {
|
||||
float bend = channels_[v.channel].pitch_bend_semitones;
|
||||
float f = v.base_freq * std::pow(2.0f, bend / 12.0f);
|
||||
const assets::OplPatch* patch = bank_ ? bank_->find(
|
||||
v.channel == 9 ? v.key : channels_[v.channel].program,
|
||||
v.channel == 9 ? 127 : channels_[v.channel].bank) : nullptr;
|
||||
double m0 = patch ? kMultTable[patch->regs[3] & 0x0Fu] : 1.0;
|
||||
double m1 = patch ? kMultTable[patch->regs[9] & 0x0Fu] : 1.0;
|
||||
v.op_mod.phase_inc = (static_cast<double>(f) * m0) / static_cast<double>(sample_rate_);
|
||||
v.op_car.phase_inc = (static_cast<double>(f) * m1) / static_cast<double>(sample_rate_);
|
||||
}
|
||||
|
||||
void Opl3Synth::note_on(uint8_t ch, uint8_t key, uint8_t vel) {
|
||||
if (ch >= kNumChannels) return;
|
||||
if (vel == 0) {
|
||||
note_off(ch, key);
|
||||
return;
|
||||
}
|
||||
|
||||
// Allocate free or oldest voice
|
||||
int slot = -1;
|
||||
uint32_t oldest_age = 0xFFFFFFFFu;
|
||||
int oldest_idx = 0;
|
||||
for (int i = 0; i < kNumVoices; ++i) {
|
||||
if (!voices_[i].active) {
|
||||
slot = i;
|
||||
break;
|
||||
}
|
||||
if (voices_[i].age < oldest_age) {
|
||||
oldest_age = voices_[i].age;
|
||||
oldest_idx = i;
|
||||
}
|
||||
}
|
||||
if (slot < 0) slot = oldest_idx;
|
||||
|
||||
Voice& v = voices_[slot];
|
||||
v = Voice{};
|
||||
v.active = true;
|
||||
v.channel = ch;
|
||||
v.key = key;
|
||||
v.velocity = vel;
|
||||
v.age = ++voice_counter_;
|
||||
|
||||
bool is_drum = (ch == 9);
|
||||
uint8_t lookup_patch = is_drum ? key : channels_[ch].program;
|
||||
uint8_t lookup_bank = is_drum ? 127 : channels_[ch].bank;
|
||||
const assets::OplPatch* patch = bank_ ? bank_->find(lookup_patch, lookup_bank) : nullptr;
|
||||
|
||||
float midi_note = static_cast<float>(key);
|
||||
if (patch && is_drum && patch->regs[2] > 0) {
|
||||
midi_note = static_cast<float>(patch->regs[2]);
|
||||
} else if (patch && !is_drum) {
|
||||
midi_note += static_cast<float>(static_cast<int8_t>(patch->regs[2]));
|
||||
}
|
||||
v.base_freq = 440.0f * std::pow(2.0f, (midi_note - 69.0f) / 12.0f);
|
||||
float vel_scale = std::clamp(static_cast<float>(vel) / 127.0f, 0.08f, 1.0f);
|
||||
|
||||
if (patch) {
|
||||
uint8_t c0 = patch->regs[8];
|
||||
int fb = (c0 >> 1) & 7;
|
||||
v.feedback = (fb == 0) ? 0.0f : (static_cast<float>(1 << fb) / 64.0f);
|
||||
v.additive = (c0 & 1u) != 0;
|
||||
|
||||
setup_operator(v.op_mod, patch->regs[3], patch->regs[4], patch->regs[5],
|
||||
patch->regs[6], patch->regs[7], v.base_freq,
|
||||
v.additive ? vel_scale : 1.0f, v.additive);
|
||||
setup_operator(v.op_car, patch->regs[9], patch->regs[10], patch->regs[11],
|
||||
patch->regs[12], patch->regs[13], v.base_freq,
|
||||
vel_scale, true);
|
||||
} else {
|
||||
v.feedback = 0.0f;
|
||||
v.additive = false;
|
||||
setup_operator(v.op_mod, 0x21, 0x18, 0xF2, 0x45, 0x00, v.base_freq, 1.0f, false);
|
||||
setup_operator(v.op_car, 0x21, 0x08, 0xF4, 0x36, 0x00, v.base_freq, vel_scale, true);
|
||||
}
|
||||
update_voice_freq(v);
|
||||
}
|
||||
|
||||
void Opl3Synth::note_off(uint8_t ch, uint8_t key) {
|
||||
for (auto& v : voices_) {
|
||||
if (v.active && v.channel == ch && v.key == key) {
|
||||
if (v.op_car.stage != EnvStage::Off) v.op_car.stage = EnvStage::Release;
|
||||
if (v.op_mod.stage != EnvStage::Off) v.op_mod.stage = EnvStage::Release;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void Opl3Synth::program_change(uint8_t ch, uint8_t program) {
|
||||
if (ch < kNumChannels) channels_[ch].program = program;
|
||||
}
|
||||
|
||||
void Opl3Synth::control_change(uint8_t ch, uint8_t cc, uint8_t val) {
|
||||
if (ch >= kNumChannels) return;
|
||||
switch (cc) {
|
||||
case 0: // Bank Select MSB
|
||||
channels_[ch].bank = (ch == 9) ? 127 : val;
|
||||
break;
|
||||
case 7: // Volume
|
||||
channels_[ch].volume = static_cast<float>(val) / 127.0f;
|
||||
break;
|
||||
case 10: // Pan
|
||||
channels_[ch].pan = (static_cast<float>(val) - 64.0f) / 64.0f;
|
||||
break;
|
||||
case 11: // Expression
|
||||
channels_[ch].expression = static_cast<float>(val) / 127.0f;
|
||||
break;
|
||||
case 120:
|
||||
case 123: // All Sound/Notes Off
|
||||
for (auto& v : voices_) {
|
||||
if (v.channel == ch) v.active = false;
|
||||
}
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
void Opl3Synth::pitch_bend(uint8_t ch, int16_t bend14) {
|
||||
if (ch >= kNumChannels) return;
|
||||
channels_[ch].pitch_bend_semitones = (static_cast<float>(bend14) / 8192.0f) * 2.0f;
|
||||
for (auto& v : voices_) {
|
||||
if (v.active && v.channel == ch) update_voice_freq(v);
|
||||
}
|
||||
}
|
||||
|
||||
void Opl3Synth::all_notes_off() {
|
||||
for (auto& v : voices_) {
|
||||
v = Voice{};
|
||||
}
|
||||
}
|
||||
|
||||
void Opl3Synth::step_envelope(Operator& op, float dt) {
|
||||
switch (op.stage) {
|
||||
case EnvStage::Off:
|
||||
op.env = 0.0f;
|
||||
break;
|
||||
case EnvStage::Attack:
|
||||
op.env += op.attack_rate * dt;
|
||||
if (op.env >= 1.0f) {
|
||||
op.env = 1.0f;
|
||||
op.stage = EnvStage::Decay;
|
||||
}
|
||||
break;
|
||||
case EnvStage::Decay:
|
||||
op.env -= op.decay_rate * dt;
|
||||
if (op.env <= op.sustain_level) {
|
||||
op.env = op.sustain_level;
|
||||
op.stage = op.sustain_hold ? EnvStage::Sustain : EnvStage::Release;
|
||||
}
|
||||
break;
|
||||
case EnvStage::Sustain:
|
||||
op.env = op.sustain_level;
|
||||
break;
|
||||
case EnvStage::Release:
|
||||
op.env -= op.release_rate * dt;
|
||||
if (op.env <= 0.0005f) {
|
||||
op.env = 0.0f;
|
||||
op.stage = EnvStage::Off;
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
float Opl3Synth::eval_waveform(uint8_t wave, double phase) {
|
||||
double p = phase - std::floor(phase);
|
||||
switch (wave & 7u) {
|
||||
case 0: // Full sine
|
||||
return static_cast<float>(std::sin(p * kTwoPi));
|
||||
case 1: // Half-sine
|
||||
return p < 0.5 ? static_cast<float>(std::sin(p * kTwoPi)) : 0.0f;
|
||||
case 2: // Abs-sine
|
||||
return static_cast<float>(std::abs(std::sin(p * kTwoPi)));
|
||||
case 3: // Quarter-pulse sine
|
||||
return (p < 0.25 || (p >= 0.5 && p < 0.75)) ?
|
||||
static_cast<float>(std::abs(std::sin(p * kTwoPi))) : 0.0f;
|
||||
case 4: // Alternating double-freq sine
|
||||
return p < 0.5 ? static_cast<float>(std::sin(p * 2.0 * kTwoPi)) : 0.0f;
|
||||
case 5: // Alternating double-freq abs-sine
|
||||
return p < 0.5 ? static_cast<float>(std::abs(std::sin(p * 2.0 * kTwoPi))) : 0.0f;
|
||||
case 6: // Square
|
||||
return p < 0.5 ? 1.0f : -1.0f;
|
||||
case 7: // Derived exponential/saw
|
||||
return p < 0.5 ? static_cast<float>(1.0 - p * 4.0) : static_cast<float>((p - 0.5) * 4.0 - 1.0);
|
||||
default:
|
||||
return 0.0f;
|
||||
}
|
||||
}
|
||||
|
||||
void Opl3Synth::render(float* stereo_out, int frames) {
|
||||
const float dt = 1.0f / static_cast<float>(sample_rate_);
|
||||
const double lfo_inc = 6.0 / static_cast<double>(sample_rate_);
|
||||
|
||||
for (int f = 0; f < frames; ++f) {
|
||||
lfo_phase_ += lfo_inc;
|
||||
if (lfo_phase_ >= 1.0) lfo_phase_ -= 1.0;
|
||||
float lfo = static_cast<float>(std::sin(lfo_phase_ * kTwoPi));
|
||||
|
||||
float left = 0.0f;
|
||||
float right = 0.0f;
|
||||
|
||||
for (auto& v : voices_) {
|
||||
if (!v.active) continue;
|
||||
|
||||
step_envelope(v.op_mod, dt);
|
||||
step_envelope(v.op_car, dt);
|
||||
if (v.op_car.stage == EnvStage::Off && (!v.additive || v.op_mod.stage == EnvStage::Off)) {
|
||||
v.active = false;
|
||||
continue;
|
||||
}
|
||||
|
||||
float vib0 = v.op_mod.vib ? (1.0f + 0.008f * lfo) : 1.0f;
|
||||
float vib1 = v.op_car.vib ? (1.0f + 0.008f * lfo) : 1.0f;
|
||||
|
||||
v.op_mod.phase += v.op_mod.phase_inc * vib0;
|
||||
v.op_mod.phase -= std::floor(v.op_mod.phase);
|
||||
float fb_mod = 0.5f * (v.prev_mod0 + v.prev_mod1) * v.feedback;
|
||||
float m_raw = eval_waveform(v.op_mod.wave, v.op_mod.phase + fb_mod);
|
||||
v.prev_mod1 = v.prev_mod0;
|
||||
v.prev_mod0 = m_raw;
|
||||
|
||||
float am0 = v.op_mod.am ? (1.0f - 0.12f * (0.5f + 0.5f * lfo)) : 1.0f;
|
||||
float mod_out = m_raw * v.op_mod.env * v.op_mod.total_level * am0;
|
||||
|
||||
v.op_car.phase += v.op_car.phase_inc * vib1;
|
||||
v.op_car.phase -= std::floor(v.op_car.phase);
|
||||
|
||||
float am1 = v.op_car.am ? (1.0f - 0.12f * (0.5f + 0.5f * lfo)) : 1.0f;
|
||||
float sample = 0.0f;
|
||||
if (v.additive) {
|
||||
float car_raw = eval_waveform(v.op_car.wave, v.op_car.phase);
|
||||
sample = (mod_out + car_raw * v.op_car.env * v.op_car.total_level * am1) * 0.5f;
|
||||
} else {
|
||||
// FM phase modulation depth
|
||||
float car_raw = eval_waveform(v.op_car.wave, v.op_car.phase + static_cast<double>(mod_out * 1.15f));
|
||||
sample = car_raw * v.op_car.env * v.op_car.total_level * am1;
|
||||
}
|
||||
|
||||
const ChannelState& cs = channels_[v.channel];
|
||||
float ch_gain = cs.volume * cs.expression * 0.55f;
|
||||
float pan_norm = std::clamp(cs.pan, -1.0f, 1.0f);
|
||||
float gl = std::sqrt(0.5f * (1.0f - pan_norm));
|
||||
float gr = std::sqrt(0.5f * (1.0f + pan_norm));
|
||||
left += sample * ch_gain * gl;
|
||||
right += sample * ch_gain * gr;
|
||||
}
|
||||
|
||||
stereo_out[f * 2 + 0] += std::tanh(left * 0.9f);
|
||||
stereo_out[f * 2 + 1] += std::tanh(right * 0.9f);
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace top_octane::audio
|
||||
@@ -0,0 +1,100 @@
|
||||
#pragma once
|
||||
|
||||
#include "assets/music_bank.hpp"
|
||||
|
||||
#include <array>
|
||||
#include <cstdint>
|
||||
|
||||
namespace top_octane::audio {
|
||||
|
||||
// Abstract MIDI synthesizer interface used by XmidiPlayer
|
||||
class IMidiSynth {
|
||||
public:
|
||||
virtual ~IMidiSynth() = default;
|
||||
virtual void set_sample_rate(int sample_rate) = 0;
|
||||
virtual void note_on(uint8_t ch, uint8_t key, uint8_t vel) = 0;
|
||||
virtual void note_off(uint8_t ch, uint8_t key) = 0;
|
||||
virtual void program_change(uint8_t ch, uint8_t program) = 0;
|
||||
virtual void control_change(uint8_t ch, uint8_t cc, uint8_t val) = 0;
|
||||
virtual void pitch_bend(uint8_t ch, int16_t bend14) = 0; // -8192..+8191
|
||||
virtual void all_notes_off() = 0;
|
||||
virtual void render(float* stereo_out, int frames) = 0;
|
||||
};
|
||||
|
||||
// Self-contained Yamaha OPL3 FM synthesizer driven by Miles SAMPLE.OPL timbres
|
||||
class Opl3Synth final : public IMidiSynth {
|
||||
public:
|
||||
static constexpr int kNumVoices = 18;
|
||||
static constexpr int kNumChannels = 16;
|
||||
|
||||
explicit Opl3Synth(const assets::OplTimbreBank* bank = nullptr, int sample_rate = 48000);
|
||||
|
||||
void set_timbre_bank(const assets::OplTimbreBank* bank) { bank_ = bank; }
|
||||
void set_sample_rate(int sample_rate) override;
|
||||
void note_on(uint8_t ch, uint8_t key, uint8_t vel) override;
|
||||
void note_off(uint8_t ch, uint8_t key) override;
|
||||
void program_change(uint8_t ch, uint8_t program) override;
|
||||
void control_change(uint8_t ch, uint8_t cc, uint8_t val) override;
|
||||
void pitch_bend(uint8_t ch, int16_t bend14) override;
|
||||
void all_notes_off() override;
|
||||
void render(float* stereo_out, int frames) override;
|
||||
|
||||
private:
|
||||
enum class EnvStage { Off = 0, Attack, Decay, Sustain, Release };
|
||||
|
||||
struct Operator {
|
||||
double phase = 0.0;
|
||||
double phase_inc = 0.0;
|
||||
float env = 0.0f; // 0..1 linear amplitude
|
||||
EnvStage stage = EnvStage::Off;
|
||||
float attack_rate = 0.0f;
|
||||
float decay_rate = 0.0f;
|
||||
float sustain_level = 0.5f;
|
||||
float release_rate = 0.0f;
|
||||
float total_level = 1.0f; // linear scale from TL + KSL + vel
|
||||
uint8_t wave = 0;
|
||||
bool am = false;
|
||||
bool vib = false;
|
||||
bool sustain_hold = true;
|
||||
};
|
||||
|
||||
struct Voice {
|
||||
bool active = false;
|
||||
uint8_t channel = 0;
|
||||
uint8_t key = 0;
|
||||
uint8_t velocity = 100;
|
||||
uint32_t age = 0;
|
||||
float base_freq = 440.0f;
|
||||
float feedback = 0.0f;
|
||||
bool additive = false;
|
||||
float prev_mod0 = 0.0f;
|
||||
float prev_mod1 = 0.0f;
|
||||
Operator op_mod{};
|
||||
Operator op_car{};
|
||||
};
|
||||
|
||||
struct ChannelState {
|
||||
uint8_t program = 0;
|
||||
uint8_t bank = 0;
|
||||
float volume = 1.0f;
|
||||
float expression = 1.0f;
|
||||
float pan = 0.0f; // -1..+1
|
||||
float pitch_bend_semitones = 0.0f;
|
||||
};
|
||||
|
||||
void setup_operator(Operator& op, uint8_t reg20, uint8_t reg40, uint8_t reg60,
|
||||
uint8_t reg80, uint8_t regE0, float base_freq, float vel_scale, bool is_carrier);
|
||||
void step_envelope(Operator& op, float dt);
|
||||
static float eval_waveform(uint8_t wave, double phase);
|
||||
void update_voice_freq(Voice& v);
|
||||
|
||||
const assets::OplTimbreBank* bank_ = nullptr;
|
||||
int sample_rate_ = 48000;
|
||||
uint32_t voice_counter_ = 0;
|
||||
double lfo_phase_ = 0.0;
|
||||
|
||||
std::array<Voice, kNumVoices> voices_{};
|
||||
std::array<ChannelState, kNumChannels> channels_{};
|
||||
};
|
||||
|
||||
} // namespace top_octane::audio
|
||||
@@ -0,0 +1,254 @@
|
||||
#include "audio/sf_synth.hpp"
|
||||
#include "core/math.hpp"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
|
||||
namespace top_octane::audio {
|
||||
|
||||
SfSynth::SfSynth(const assets::SoundFontBank* sf,
|
||||
const assets::OplTimbreBank* opl_fallback, int sample_rate)
|
||||
: sf_(sf), opl_fallback_(opl_fallback, sample_rate),
|
||||
sample_rate_(std::max(sample_rate, 8000)) {
|
||||
for (int i = 0; i < 16; ++i) {
|
||||
channels_[i].bank = (i == 9) ? 128 : 0;
|
||||
}
|
||||
}
|
||||
|
||||
void SfSynth::set_sample_rate(int sample_rate) {
|
||||
sample_rate_ = std::max(sample_rate, 8000);
|
||||
opl_fallback_.set_sample_rate(sample_rate_);
|
||||
}
|
||||
|
||||
SfSynth::RomWaveKind SfSynth::classify_rom_sample(const std::string& name) {
|
||||
if (name.find("Square") != std::string::npos) return RomWaveKind::Square;
|
||||
if (name.find("Saw") != std::string::npos) return RomWaveKind::Saw;
|
||||
if (name.find("Bass") != std::string::npos) return RomWaveKind::SynthBass;
|
||||
if (name.find("Glass") != std::string::npos || name.find("Xylo") != std::string::npos ||
|
||||
name.find("Marimba") != std::string::npos) {
|
||||
return RomWaveKind::Bell;
|
||||
}
|
||||
if (name.find("Bongo") != std::string::npos || name.find("Click") != std::string::npos) {
|
||||
return RomWaveKind::Perc;
|
||||
}
|
||||
return RomWaveKind::Sine;
|
||||
}
|
||||
|
||||
void SfSynth::note_on(uint8_t ch, uint8_t key, uint8_t vel) {
|
||||
if (ch >= 16) return;
|
||||
if (vel == 0) {
|
||||
note_off(ch, key);
|
||||
return;
|
||||
}
|
||||
|
||||
const ChState& cs = channels_[ch];
|
||||
const assets::SoundFontPreset* preset = sf_ ? sf_->find_preset(cs.bank, cs.program) : nullptr;
|
||||
if (!preset && sf_ && cs.bank != 0) {
|
||||
preset = sf_->find_preset(0, cs.program);
|
||||
}
|
||||
|
||||
const assets::SoundFontZone* matched = nullptr;
|
||||
if (preset) {
|
||||
for (const auto& z : preset->zones) {
|
||||
if (key >= z.key_lo && key <= z.key_hi && vel >= z.vel_lo && vel <= z.vel_hi) {
|
||||
matched = &z;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!matched || matched->sample_id < 0 ||
|
||||
static_cast<size_t>(matched->sample_id) >= sf_->samples.size()) {
|
||||
// Delegate unmapped GM/drum presets to OPL3 fallback seamlessly
|
||||
opl_fallback_.note_on(ch, key, vel);
|
||||
return;
|
||||
}
|
||||
|
||||
const assets::SoundFontSample& smp = sf_->samples[matched->sample_id];
|
||||
int slot = -1;
|
||||
uint32_t oldest = 0xFFFFFFFFu;
|
||||
int oldest_idx = 0;
|
||||
for (int i = 0; i < kMaxVoices; ++i) {
|
||||
if (!voices_[i].active) {
|
||||
slot = i;
|
||||
break;
|
||||
}
|
||||
if (voices_[i].age < oldest) {
|
||||
oldest = voices_[i].age;
|
||||
oldest_idx = i;
|
||||
}
|
||||
}
|
||||
if (slot < 0) slot = oldest_idx;
|
||||
|
||||
WtVoice& v = voices_[slot];
|
||||
v = WtVoice{};
|
||||
v.active = true;
|
||||
v.channel = ch;
|
||||
v.key = key;
|
||||
v.age = ++age_counter_;
|
||||
v.sample_idx = matched->sample_id;
|
||||
v.loop = (matched->sample_mode & 1) != 0;
|
||||
v.env = 1.0f;
|
||||
|
||||
int root = (matched->root_key_override >= 0) ? matched->root_key_override : smp.root_key;
|
||||
float pitch_ratio = std::pow(2.0f, (static_cast<float>(key) - static_cast<float>(root) +
|
||||
static_cast<float>(smp.fine_tune) / 100.0f) / 12.0f);
|
||||
|
||||
if (smp.in_ram) {
|
||||
v.rom_kind = RomWaveKind::None;
|
||||
v.pos = static_cast<double>(smp.start);
|
||||
v.step = (static_cast<double>(smp.sample_rate) / static_cast<double>(sample_rate_)) * pitch_ratio;
|
||||
} else {
|
||||
v.rom_kind = classify_rom_sample(smp.name);
|
||||
double freq = 440.0 * std::pow(2.0, (static_cast<double>(key) - 69.0) / 12.0);
|
||||
v.step = freq / static_cast<double>(sample_rate_);
|
||||
v.pos = 0.0;
|
||||
v.loop = (v.rom_kind != RomWaveKind::Perc && v.rom_kind != RomWaveKind::Bell);
|
||||
}
|
||||
|
||||
float atten = std::pow(10.0f, -matched->attenuation_db / 20.0f);
|
||||
v.gain = (static_cast<float>(vel) / 127.0f) * atten * 0.95f;
|
||||
v.pan = std::clamp(cs.pan + static_cast<float>(matched->pan_tenths_pct) / 500.0f, -1.0f, 1.0f);
|
||||
}
|
||||
|
||||
void SfSynth::note_off(uint8_t ch, uint8_t key) {
|
||||
opl_fallback_.note_off(ch, key);
|
||||
for (auto& v : voices_) {
|
||||
if (v.active && v.channel == ch && v.key == key) {
|
||||
v.releasing = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void SfSynth::program_change(uint8_t ch, uint8_t program) {
|
||||
opl_fallback_.program_change(ch, program);
|
||||
if (ch < 16) channels_[ch].program = program;
|
||||
}
|
||||
|
||||
void SfSynth::control_change(uint8_t ch, uint8_t cc, uint8_t val) {
|
||||
opl_fallback_.control_change(ch, cc, val);
|
||||
if (ch >= 16) return;
|
||||
switch (cc) {
|
||||
case 0:
|
||||
channels_[ch].bank = (ch == 9) ? 128 : val;
|
||||
break;
|
||||
case 7:
|
||||
channels_[ch].volume = static_cast<float>(val) / 127.0f;
|
||||
break;
|
||||
case 10:
|
||||
channels_[ch].pan = (static_cast<float>(val) - 64.0f) / 64.0f;
|
||||
break;
|
||||
case 11:
|
||||
channels_[ch].expression = static_cast<float>(val) / 127.0f;
|
||||
break;
|
||||
case 120:
|
||||
case 123:
|
||||
for (auto& v : voices_) {
|
||||
if (v.channel == ch) v.active = false;
|
||||
}
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
void SfSynth::pitch_bend(uint8_t ch, int16_t bend14) {
|
||||
opl_fallback_.pitch_bend(ch, bend14);
|
||||
if (ch < 16) {
|
||||
channels_[ch].pitch_bend_semitones = (static_cast<float>(bend14) / 8192.0f) * 2.0f;
|
||||
}
|
||||
}
|
||||
|
||||
void SfSynth::all_notes_off() {
|
||||
opl_fallback_.all_notes_off();
|
||||
for (auto& v : voices_) v = WtVoice{};
|
||||
}
|
||||
|
||||
float SfSynth::sample_voice(WtVoice& v) {
|
||||
float bend_mul = std::pow(2.0f, channels_[v.channel].pitch_bend_semitones / 12.0f);
|
||||
if (v.rom_kind != RomWaveKind::None) {
|
||||
v.pos += v.step * bend_mul;
|
||||
double ph = v.pos - std::floor(v.pos);
|
||||
float out = 0.0f;
|
||||
switch (v.rom_kind) {
|
||||
case RomWaveKind::Saw:
|
||||
out = static_cast<float>(2.0 * ph - 1.0);
|
||||
break;
|
||||
case RomWaveKind::Square:
|
||||
out = (ph < 0.5) ? 0.8f : -0.8f;
|
||||
break;
|
||||
case RomWaveKind::SynthBass:
|
||||
out = static_cast<float>(0.65 * std::sin(ph * kTwoPi) + 0.35 * (2.0 * ph - 1.0));
|
||||
break;
|
||||
case RomWaveKind::Bell:
|
||||
out = static_cast<float>(std::sin(ph * kTwoPi + 0.6 * std::sin(ph * 3.5 * kTwoPi)));
|
||||
v.env *= 0.9994f;
|
||||
break;
|
||||
case RomWaveKind::Perc:
|
||||
out = static_cast<float>(std::sin(ph * kTwoPi));
|
||||
v.env *= 0.9985f;
|
||||
break;
|
||||
default:
|
||||
out = static_cast<float>(std::sin(ph * kTwoPi));
|
||||
break;
|
||||
}
|
||||
return out * v.env;
|
||||
}
|
||||
|
||||
if (!sf_ || v.sample_idx < 0 || static_cast<size_t>(v.sample_idx) >= sf_->samples.size()) {
|
||||
v.active = false;
|
||||
return 0.0f;
|
||||
}
|
||||
const assets::SoundFontSample& smp = sf_->samples[v.sample_idx];
|
||||
uint32_t i0 = static_cast<uint32_t>(v.pos);
|
||||
if (i0 + 1 >= smp.end || i0 + 1 >= sf_->sample_pool.size()) {
|
||||
if (v.loop && smp.loop_end > smp.loop_start) {
|
||||
v.pos = static_cast<double>(smp.loop_start);
|
||||
i0 = smp.loop_start;
|
||||
} else {
|
||||
v.active = false;
|
||||
return 0.0f;
|
||||
}
|
||||
}
|
||||
float frac = static_cast<float>(v.pos - static_cast<double>(i0));
|
||||
float s0 = static_cast<float>(sf_->sample_pool[i0]) / 32768.0f;
|
||||
float s1 = static_cast<float>(sf_->sample_pool[i0 + 1]) / 32768.0f;
|
||||
float out = (s0 + (s1 - s0) * frac) * v.env;
|
||||
|
||||
v.pos += v.step * bend_mul;
|
||||
if (v.loop && smp.loop_end > smp.loop_start && v.pos >= static_cast<double>(smp.loop_end)) {
|
||||
v.pos -= static_cast<double>(smp.loop_end - smp.loop_start);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
void SfSynth::render(float* stereo_out, int frames) {
|
||||
opl_fallback_.render(stereo_out, frames);
|
||||
|
||||
const float rel_decay = 1.0f / (0.12f * static_cast<float>(sample_rate_));
|
||||
for (int f = 0; f < frames; ++f) {
|
||||
float l = 0.0f, r = 0.0f;
|
||||
for (auto& v : voices_) {
|
||||
if (!v.active) continue;
|
||||
if (v.releasing) {
|
||||
v.env -= rel_decay;
|
||||
if (v.env <= 0.001f) {
|
||||
v.active = false;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
float s = sample_voice(v);
|
||||
if (!v.active) continue;
|
||||
const ChState& cs = channels_[v.channel];
|
||||
float g = v.gain * cs.volume * cs.expression;
|
||||
float gl = std::sqrt(0.5f * (1.0f - v.pan));
|
||||
float gr = std::sqrt(0.5f * (1.0f + v.pan));
|
||||
l += s * g * gl;
|
||||
r += s * g * gr;
|
||||
}
|
||||
stereo_out[f * 2 + 0] = std::tanh(stereo_out[f * 2 + 0] + l);
|
||||
stereo_out[f * 2 + 1] = std::tanh(stereo_out[f * 2 + 1] + r);
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace top_octane::audio
|
||||
@@ -0,0 +1,72 @@
|
||||
#pragma once
|
||||
|
||||
#include "assets/music_bank.hpp"
|
||||
#include "audio/opl3_synth.hpp"
|
||||
|
||||
#include <array>
|
||||
#include <cstdint>
|
||||
#include <vector>
|
||||
|
||||
namespace top_octane::audio {
|
||||
|
||||
// Creative SoundFont 1.0 (BULLFROG.SBK) & 2.0 (.sf2) wavetable synthesizer with OPL3 fallback
|
||||
class SfSynth final : public IMidiSynth {
|
||||
public:
|
||||
static constexpr int kMaxVoices = 32;
|
||||
|
||||
SfSynth(const assets::SoundFontBank* sf = nullptr,
|
||||
const assets::OplTimbreBank* opl_fallback = nullptr,
|
||||
int sample_rate = 48000);
|
||||
|
||||
void set_soundfont(const assets::SoundFontBank* sf) { sf_ = sf; }
|
||||
void set_opl_fallback(const assets::OplTimbreBank* opl) { opl_fallback_.set_timbre_bank(opl); }
|
||||
|
||||
void set_sample_rate(int sample_rate) override;
|
||||
void note_on(uint8_t ch, uint8_t key, uint8_t vel) override;
|
||||
void note_off(uint8_t ch, uint8_t key) override;
|
||||
void program_change(uint8_t ch, uint8_t program) override;
|
||||
void control_change(uint8_t ch, uint8_t cc, uint8_t val) override;
|
||||
void pitch_bend(uint8_t ch, int16_t bend14) override;
|
||||
void all_notes_off() override;
|
||||
void render(float* stereo_out, int frames) override;
|
||||
|
||||
private:
|
||||
enum class RomWaveKind { None, Saw, Square, Sine, SynthBass, Bell, Perc };
|
||||
|
||||
struct WtVoice {
|
||||
bool active = false;
|
||||
bool releasing = false;
|
||||
uint8_t channel = 0;
|
||||
uint8_t key = 0;
|
||||
uint32_t age = 0;
|
||||
int sample_idx = -1;
|
||||
RomWaveKind rom_kind = RomWaveKind::None;
|
||||
bool loop = false;
|
||||
double pos = 0.0;
|
||||
double step = 1.0;
|
||||
float gain = 0.0f;
|
||||
float env = 0.0f;
|
||||
float pan = 0.0f;
|
||||
};
|
||||
|
||||
struct ChState {
|
||||
uint8_t program = 0;
|
||||
uint16_t bank = 0;
|
||||
float volume = 1.0f;
|
||||
float expression = 1.0f;
|
||||
float pan = 0.0f;
|
||||
float pitch_bend_semitones = 0.0f;
|
||||
};
|
||||
|
||||
static RomWaveKind classify_rom_sample(const std::string& name);
|
||||
float sample_voice(WtVoice& v);
|
||||
|
||||
const assets::SoundFontBank* sf_ = nullptr;
|
||||
Opl3Synth opl_fallback_;
|
||||
int sample_rate_ = 48000;
|
||||
uint32_t age_counter_ = 0;
|
||||
std::array<WtVoice, kMaxVoices> voices_{};
|
||||
std::array<ChState, 16> channels_{};
|
||||
};
|
||||
|
||||
} // namespace top_octane::audio
|
||||
@@ -0,0 +1,117 @@
|
||||
#include "audio/xmidi_player.hpp"
|
||||
|
||||
#include <algorithm>
|
||||
|
||||
namespace top_octane::audio {
|
||||
|
||||
void XmidiPlayer::set_sample_rate(int sample_rate) {
|
||||
sample_rate_ = std::max(sample_rate, 8000);
|
||||
samples_per_tick_ = static_cast<double>(sample_rate_) / 120.0;
|
||||
}
|
||||
|
||||
void XmidiPlayer::set_sequence(const assets::XmiSequence* seq, bool loop) {
|
||||
seq_ = seq;
|
||||
loop_ = loop;
|
||||
playing_ = (seq != nullptr && !seq->events.empty());
|
||||
event_cursor_ = 0;
|
||||
current_tick_ = 0;
|
||||
sample_accum_ = 0.0;
|
||||
samples_per_tick_ = static_cast<double>(sample_rate_) / 120.0;
|
||||
for (auto& n : note_offs_) n = PendingNoteOff{};
|
||||
}
|
||||
|
||||
void XmidiPlayer::stop() {
|
||||
playing_ = false;
|
||||
seq_ = nullptr;
|
||||
for (auto& n : note_offs_) n = PendingNoteOff{};
|
||||
}
|
||||
|
||||
void XmidiPlayer::process_tick(IMidiSynth& synth) {
|
||||
if (!seq_ || !playing_) return;
|
||||
|
||||
// Fire due note-offs
|
||||
for (auto& n : note_offs_) {
|
||||
if (n.active && current_tick_ >= n.off_tick) {
|
||||
synth.note_off(n.channel, n.key);
|
||||
n.active = false;
|
||||
}
|
||||
}
|
||||
|
||||
// Fire events at or before current_tick_
|
||||
const auto& evs = seq_->events;
|
||||
while (event_cursor_ < evs.size() && evs[event_cursor_].tick <= current_tick_) {
|
||||
const auto& ev = evs[event_cursor_++];
|
||||
if (ev.status == 0xFFu) {
|
||||
// Miles XMIDI stays anchored at 120 ticks/sec; tempo meta adjusts subtly if needed
|
||||
continue;
|
||||
}
|
||||
uint8_t hi = ev.status & 0xF0u;
|
||||
uint8_t ch = ev.status & 0x0Fu;
|
||||
switch (hi) {
|
||||
case 0x80u:
|
||||
synth.note_off(ch, ev.data1);
|
||||
break;
|
||||
case 0x90u:
|
||||
if (ev.data2 == 0) {
|
||||
synth.note_off(ch, ev.data1);
|
||||
} else {
|
||||
synth.note_on(ch, ev.data1, ev.data2);
|
||||
if (ev.duration_ticks > 0) {
|
||||
for (auto& n : note_offs_) {
|
||||
if (!n.active) {
|
||||
n.active = true;
|
||||
n.off_tick = current_tick_ + ev.duration_ticks;
|
||||
n.channel = ch;
|
||||
n.key = ev.data1;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
break;
|
||||
case 0xB0u:
|
||||
synth.control_change(ch, ev.data1, ev.data2);
|
||||
break;
|
||||
case 0xC0u:
|
||||
synth.program_change(ch, ev.data1);
|
||||
break;
|
||||
case 0xE0u: {
|
||||
int16_t bend14 = static_cast<int16_t>(((ev.data2 & 0x7Fu) << 7) | (ev.data1 & 0x7Fu)) - 8192;
|
||||
synth.pitch_bend(ch, bend14);
|
||||
break;
|
||||
}
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
++current_tick_;
|
||||
if (event_cursor_ >= evs.size() && current_tick_ > seq_->total_ticks) {
|
||||
if (loop_) {
|
||||
synth.all_notes_off();
|
||||
event_cursor_ = 0;
|
||||
current_tick_ = 0;
|
||||
for (auto& n : note_offs_) n = PendingNoteOff{};
|
||||
} else {
|
||||
playing_ = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void XmidiPlayer::render(float* stereo_out, int frames, IMidiSynth& synth) {
|
||||
if (!playing_ || !seq_) return;
|
||||
|
||||
int offset = 0;
|
||||
while (offset < frames && playing_) {
|
||||
if (sample_accum_ <= 0.0) {
|
||||
process_tick(synth);
|
||||
sample_accum_ += samples_per_tick_;
|
||||
}
|
||||
int step = std::min(frames - offset, std::max(1, static_cast<int>(sample_accum_)));
|
||||
synth.render(stereo_out + offset * 2, step);
|
||||
sample_accum_ -= static_cast<double>(step);
|
||||
offset += step;
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace top_octane::audio
|
||||
@@ -0,0 +1,47 @@
|
||||
#pragma once
|
||||
|
||||
#include "assets/music_bank.hpp"
|
||||
#include "audio/opl3_synth.hpp"
|
||||
|
||||
#include <array>
|
||||
#include <cstdint>
|
||||
|
||||
namespace top_octane::audio {
|
||||
|
||||
// Sample-accurate 120 Hz Miles XMIDI sequencer with fixed-size active note-off table
|
||||
class XmidiPlayer {
|
||||
public:
|
||||
static constexpr int kMaxActiveNotes = 128;
|
||||
|
||||
void set_sample_rate(int sample_rate);
|
||||
void set_sequence(const assets::XmiSequence* seq, bool loop = true);
|
||||
void stop();
|
||||
bool is_playing() const { return seq_ != nullptr && playing_; }
|
||||
|
||||
// Advances sequencer and synthesizes `frames` stereo samples into `stereo_out` (adds/writes)
|
||||
void render(float* stereo_out, int frames, IMidiSynth& synth);
|
||||
|
||||
private:
|
||||
struct PendingNoteOff {
|
||||
bool active = false;
|
||||
uint32_t off_tick = 0;
|
||||
uint8_t channel = 0;
|
||||
uint8_t key = 0;
|
||||
};
|
||||
|
||||
void process_tick(IMidiSynth& synth);
|
||||
|
||||
const assets::XmiSequence* seq_ = nullptr;
|
||||
bool loop_ = true;
|
||||
bool playing_ = false;
|
||||
int sample_rate_ = 48000;
|
||||
|
||||
size_t event_cursor_ = 0;
|
||||
uint32_t current_tick_ = 0;
|
||||
double samples_per_tick_ = 400.0; // 48000 / 120 Hz default
|
||||
double sample_accum_ = 0.0;
|
||||
|
||||
std::array<PendingNoteOff, kMaxActiveNotes> note_offs_{};
|
||||
};
|
||||
|
||||
} // namespace top_octane::audio
|
||||
Reference in new issue
Block a user