Add track recovery, fix Arctic Land bridge & 9-map sim/render, harden security & optimize runtime

- Add manual track recovery (R / Backspace / Gamepad Back), document controls in README.md, fix Track 8 (Arctic Land) bridge jump/clearance physics, and fix Track 5 respawn invincibility & Track 6 off-track AI recovery across all 9 maps
- Verify 9-map sector morphing, combat (swept projectiles/LOS), pitstop chargers, and overpass/bridge surface sampling
- Fix Overpass Bottom (-Y) diagonal split and AO, add TerrainChunk frustum culling, O(1) 3D Classic uPaletteLut, atlas gutter/bleed UVs, cached uniform locations, and reusable render scratch buffers
- Harden VFS path traversal, RNC decompression bombs/truncated headers, asset/WAV parsers, GameConfig, save loaders, CLI args, and FLIC lifecycle
- Optimize 48 kHz OPL3/SoundFont synthesis (trig LUTs, cached envelopes/filters), 64-bit XMI ticks, and audio parameter/thread safety
- Add security, rendering, physics, and gameplay regression tests across all test suites
This commit is contained in:
Luxferre committed 2026-12-01 18:50:29 +02:00
1 parent 5c2ac8e70f
commit db788a2739
50 files changed
+3522 -1100

No files matched your search

+76 -38
View File
@@ -60,13 +60,18 @@ bool AudioEngine::init(const Vfs& vfs, const GameConfig& cfg, bool open_device)
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]);
// Pre-parse up to 5 tracks for OPL3 (.XMI bank 2) and SoundFont (.WTB bank 3)
const auto& opl_bank_raw = music_archive_.banks[static_cast<size_t>(assets::MusicBankType::AdlibOpl)];
const auto& wt_bank_raw = music_archive_.banks[static_cast<size_t>(assets::MusicBankType::Awe32Wt)];
for (size_t i = 0; i < 5; ++i) {
if (i < opl_bank_raw.size()) {
assets::parse_xmi_sequence(opl_bank_raw[i].data.data(), opl_bank_raw[i].data.size(),
opl_bank_raw[i].name, opl_seqs_[i]);
}
if (i < wt_bank_raw.size()) {
assets::parse_xmi_sequence(wt_bank_raw[i].data.data(), wt_bank_raw[i].data.size(),
wt_bank_raw[i].name, wt_seqs_[i]);
}
}
// Optional external SoundFont (.sf2)
@@ -115,9 +120,10 @@ bool AudioEngine::init(const Vfs& vfs, const GameConfig& cfg, bool open_device)
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);
auto sane_vol = [](float v) { return std::isfinite(v) ? std::clamp(v, 0.0f, 1.0f) : 0.0f; };
master_vol_.store(sane_vol(cfg.master_volume), std::memory_order_relaxed);
sfx_vol_.store(sane_vol(cfg.sfx_volume), std::memory_order_relaxed);
music_vol_.store(sane_vol(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);
@@ -168,9 +174,10 @@ void AudioEngine::shutdown() {
}
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);
auto sane_vol = [](float v) { return std::isfinite(v) ? std::clamp(v, 0.0f, 1.0f) : 0.0f; };
master_vol_.store(sane_vol(cfg.master_volume), std::memory_order_relaxed);
sfx_vol_.store(sane_vol(cfg.sfx_volume), std::memory_order_relaxed);
music_vol_.store(sane_vol(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_) {
@@ -183,18 +190,20 @@ void AudioEngine::apply_config(const GameConfig& cfg, bool window_focused) {
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;
{
// Parse & build off-lock above, swap pointer/bank under device lock, free old bank after unlock
if (dev_id_ != 0) SDL_LockAudioDevice(dev_id_);
std::swap(custom_sf_bank_, next_sf);
has_custom_sf_ = ok;
loaded_custom_sf_path_ = cfg.custom_soundfont_path;
sf_synth_.set_soundfont(has_custom_sf_ ? &custom_sf_bank_ : &sf_bank_);
if (active_backend_ == MusicBackend::SoundFont && xmi_player_.is_playing()) {
start_active_track();
} else {
sf_synth_.reset();
}
if (dev_id_ != 0) SDL_UnlockAudioDevice(dev_id_);
}
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_);
}
if (cfg.music_backend != requested_backend_) {
@@ -230,6 +239,7 @@ int AudioEngine::find_sfx_index(const std::string& name, bool intro_bank) const
void AudioEngine::play_sfx(const std::string& wav_name, float gain, float pitch,
float pan, bool is_intro_bank, float min_interval_sec) {
if (!std::isfinite(gain) || !std::isfinite(pitch) || !std::isfinite(pan)) return;
int idx = find_sfx_index(wav_name, is_intro_bank);
if (idx < 0 && is_intro_bank) {
is_intro_bank = false;
@@ -244,23 +254,28 @@ void AudioEngine::play_sfx(const std::string& wav_name, float gain, float pitch,
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);
cmd.min_interval_sec = std::isfinite(min_interval_sec) ? std::max(0.0f, min_interval_sec) : 0.0f;
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) {
if (!std::isfinite(src_pos.x) || !std::isfinite(src_pos.y) || !std::isfinite(src_pos.z) ||
!std::isfinite(listener_pos.x) || !std::isfinite(listener_pos.y) || !std::isfinite(listener_pos.z) ||
!std::isfinite(listener_right.x) || !std::isfinite(listener_right.y) || !std::isfinite(listener_right.z)) {
return;
}
Vec3 d = src_pos - listener_pos;
float dist = d.len();
if (dist > 28.0f) return;
if (!std::isfinite(dist) || 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::play_intro_sfx(int sample_index_0based, float gain, bool loop) {
if (sample_index_0based < 0 ||
if (!std::isfinite(gain) || sample_index_0based < 0 ||
static_cast<size_t>(sample_index_0based) >= sound_bank_.intro_sfx.size()) {
return;
}
@@ -286,16 +301,19 @@ void AudioEngine::stop_intro_sfx(int sample_index_0based) {
}
void AudioEngine::set_engine_state(bool active, float speed_ratio, bool boosting, float scrape_amount) {
float sr = std::isfinite(speed_ratio) ? std::clamp(speed_ratio, 0.0f, 1.5f) : 0.0f;
float sc = std::isfinite(scrape_amount) ? std::clamp(scrape_amount, 0.0f, 1.0f) : 0.0f;
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_speed_ratio_.store(sr, 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);
scrape_amount_.store(sc, std::memory_order_relaxed);
}
void AudioEngine::set_pitstop_state(bool on_pad, bool charging, float fill_ratio) {
float fr = std::isfinite(fill_ratio) ? std::clamp(fill_ratio, 0.0f, 1.0f) : 1.0f;
pit_active_.store(on_pad, std::memory_order_relaxed);
pit_charging_.store(charging, std::memory_order_relaxed);
pit_fill_ratio_.store(std::clamp(fill_ratio, 0.0f, 1.0f), std::memory_order_relaxed);
pit_fill_ratio_.store(fr, std::memory_order_relaxed);
}
const assets::XmiSequence& AudioEngine::xmi_sequence(MusicBackend b, MusicTrackId t) const {
@@ -441,7 +459,7 @@ void AudioEngine::drain_commands() {
}
void AudioEngine::render_internal(float* stereo_out, int frames) {
if (frames <= 0) return;
if (!stereo_out || frames <= 0) return;
std::memset(stereo_out, 0, static_cast<size_t>(frames) * 2u * sizeof(float));
drain_commands();
@@ -492,25 +510,33 @@ void AudioEngine::render_internal(float* stereo_out, int frames) {
}
}
// 2. Render SFX + Continuous Engine & Scrape Loops into isolated SFX bus + soft compressor
// 2. Render SFX + Continuous Engine & Scrape Loops into isolated SFX bus + soft clipper
if (svol > 0.001f) {
std::fill_n(sfx_bus.data(), cur * 2, 0.0f);
bool sfx_any = false;
auto ensure_sfx_bus = [&]() {
if (!sfx_any) {
std::fill_n(sfx_bus.data(), cur * 2, 0.0f);
sfx_any = true;
}
};
for (auto& v : sfx_voices_) {
if (!v.active || !v.sample) continue;
const auto& pcm = v.sample->pcm_mono;
const size_t len = pcm.size();
if (len < 2) {
if (len < 2 || !std::isfinite(v.pos) || v.pos < 0.0 ||
!std::isfinite(v.step) || v.step <= 0.0) {
v.active = false;
v.loop = false;
continue;
}
ensure_sfx_bus();
for (int f = 0; f < cur; ++f) {
size_t i0 = 0;
size_t i1 = 0;
if (v.loop) {
while (v.pos >= static_cast<double>(len)) {
v.pos -= static_cast<double>(len);
if (v.pos >= static_cast<double>(len)) {
v.pos = std::fmod(v.pos, static_cast<double>(len));
}
i0 = static_cast<size_t>(v.pos);
i1 = (i0 + 1 < len) ? (i0 + 1) : 0;
@@ -532,6 +558,7 @@ void AudioEngine::render_internal(float* stereo_out, int frames) {
if (engine_active_.load(std::memory_order_relaxed) && engine_sample_ &&
!engine_sample_->pcm_mono.empty()) {
ensure_sfx_bus();
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);
@@ -556,6 +583,7 @@ void AudioEngine::render_internal(float* stereo_out, int frames) {
float scrape = scrape_amount_.load(std::memory_order_relaxed);
if (scrape > 0.02f && scrape_sample_ && !scrape_sample_->pcm_mono.empty()) {
ensure_sfx_bus();
const auto& pcm = scrape_sample_->pcm_mono;
size_t len = pcm.size();
double step = static_cast<double>(scrape_sample_->sample_rate) / kSampleRate;
@@ -576,6 +604,7 @@ void AudioEngine::render_internal(float* stereo_out, int frames) {
const float target_pit_env = pit_on ? (pit_chg ? 1.0f : 0.45f) : 0.0f;
if ((refuel_env_ > 0.001f || target_pit_env > 0.001f) && refuel_sample_ &&
!refuel_sample_->pcm_mono.empty()) {
ensure_sfx_bus();
const auto& pcm = refuel_sample_->pcm_mono;
const size_t len = pcm.size();
const double pitch = pit_chg ? (0.78 + 0.52 * static_cast<double>(pit_fill)) : 1.28;
@@ -601,8 +630,17 @@ void AudioEngine::render_internal(float* stereo_out, int frames) {
}
}
for (int i = 0; i < cur * 2; ++i) {
out_ptr[i] += std::tanh(sfx_bus[i] * 1.1f) * 0.88f;
if (sfx_any) {
for (int i = 0; i < cur * 2; ++i) {
float y = sfx_bus[i] * 0.968f;
float ay = std::abs(y);
if (ay <= 0.55f) {
out_ptr[i] += y;
} else {
float lim = 0.55f + 0.33f * std::tanh((ay - 0.55f) / 0.33f);
out_ptr[i] += (y >= 0.0f) ? lim : -lim;
}
}
}
}
}
+75 -48
View File
@@ -2,12 +2,33 @@
#include "core/math.hpp"
#include <algorithm>
#include <array>
#include <cmath>
namespace top_octane::audio {
namespace {
constexpr int kSinLutSize = 2048;
inline float fast_sin_phase(double p) {
static const std::array<float, kSinLutSize + 1> kLut = []() {
std::array<float, kSinLutSize + 1> t{};
for (int i = 0; i <= kSinLutSize; ++i) {
t[static_cast<size_t>(i)] = static_cast<float>(
std::sin((static_cast<double>(i) / static_cast<double>(kSinLutSize)) * kTwoPi));
}
return t;
}();
if (!std::isfinite(p)) return 0.0f;
p -= std::floor(p);
double fp = p * static_cast<double>(kSinLutSize);
int i0 = static_cast<int>(fp) & (kSinLutSize - 1);
float frac = static_cast<float>(fp - static_cast<double>(i0));
return kLut[static_cast<size_t>(i0)] +
(kLut[static_cast<size_t>(i0) + 1u] - kLut[static_cast<size_t>(i0)]) * frac;
}
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
@@ -48,15 +69,31 @@ void Opl3Synth::reset() {
}
void Opl3Synth::set_sample_rate(int sample_rate) {
sample_rate_ = std::max(sample_rate, 8000);
sample_rate_ = std::clamp(sample_rate, 8000, 192000);
for (auto& v : voices_) {
if (!v.active) continue;
update_operator_rates(v.op_mod);
update_operator_rates(v.op_car);
update_voice_freq(v);
}
}
void Opl3Synth::update_operator_rates(Operator& op) {
constexpr float kDbToLn = 0.11512925465f; // ln(10) / 20
const float dt = 1.0f / static_cast<float>(sample_rate_);
op.attack_alpha = (op.attack_rate > 0.0f) ? (1.0f - std::exp(-op.attack_rate * dt)) : 0.0f;
op.decay_mul = (op.decay_rate > 0.0f) ? std::exp(-op.decay_rate * dt * kDbToLn) : 1.0f;
op.sustain_lin = (op.sustain_db >= 90.0f) ? 0.0f : std::exp(-op.sustain_db * kDbToLn);
op.release_mul = std::exp(-op.release_rate * dt * kDbToLn);
}
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 midi_note,
float vel_scale, bool is_carrier) {
double mult = kMultTable[reg20 & 0x0Fu];
op.mult = kMultTable[reg20 & 0x0Fu];
op.phase = 0.0;
op.phase_inc = (static_cast<double>(base_freq) * mult) / static_cast<double>(sample_rate_);
op.phase_inc = std::clamp((static_cast<double>(base_freq) * op.mult) / static_cast<double>(sample_rate_),
0.0, 0.49);
op.am = (reg20 & 0x80u) != 0;
op.vib = (reg20 & 0x40u) != 0;
op.sustain_hold = (reg20 & 0x20u) != 0;
@@ -95,18 +132,16 @@ void Opl3Synth::setup_operator(Operator& op, uint8_t reg20, uint8_t reg40, uint8
op.env = 0.0f;
op.env_db = 96.0f;
op.stage = (op.attack_rate > 0.0f) ? EnvStage::Attack : EnvStage::Off;
update_operator_rates(op);
}
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_);
if (v.channel >= kNumChannels) return;
float f = v.base_freq * channels_[v.channel].bend_mul;
if (!std::isfinite(f) || f < 0.0f) f = 0.0f;
const double sr = static_cast<double>(sample_rate_);
v.op_mod.phase_inc = std::clamp((static_cast<double>(f) * v.op_mod.mult) / sr, 0.0, 0.49);
v.op_car.phase_inc = std::clamp((static_cast<double>(f) * v.op_car.mult) / sr, 0.0, 0.49);
}
void Opl3Synth::note_on(uint8_t ch, uint8_t key, uint8_t vel) {
@@ -207,7 +242,9 @@ void Opl3Synth::control_change(uint8_t ch, uint8_t cc, uint8_t val) {
cs.volume_target = std::clamp(static_cast<float>(val) / 127.0f, 0.0f, 1.0f);
break;
case 10: // Pan
cs.pan = (static_cast<float>(val) - 64.0f) / 64.0f;
cs.pan = std::clamp((static_cast<float>(val) - 64.0f) / 64.0f, -1.0f, 1.0f);
cs.pan_l = std::sqrt(0.5f * (1.0f - cs.pan));
cs.pan_r = std::sqrt(0.5f * (1.0f + cs.pan));
break;
case 11: // Expression
cs.expr_target = std::clamp(static_cast<float>(val) / 127.0f, 0.0f, 1.0f);
@@ -233,6 +270,7 @@ void Opl3Synth::control_change(uint8_t ch, uint8_t cc, uint8_t val) {
cs.expr_target = 1.0f;
cs.expr_smooth = 1.0f;
cs.pitch_bend_semitones = 0.0f;
cs.bend_mul = 1.0f;
cs.sustain_pedal = false;
for (auto& v : voices_) {
if (v.active && v.channel == ch) {
@@ -263,6 +301,7 @@ void Opl3Synth::control_change(uint8_t ch, uint8_t cc, uint8_t val) {
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;
channels_[ch].bend_mul = std::pow(2.0f, channels_[ch].pitch_bend_semitones / 12.0f);
for (auto& v : voices_) {
if (v.active && v.channel == ch) update_voice_freq(v);
}
@@ -274,52 +313,43 @@ void Opl3Synth::all_notes_off() {
}
}
void Opl3Synth::step_envelope(Operator& op, float dt) {
constexpr float kDbToLn = 0.11512925465f; // ln(10) / 20
void Opl3Synth::step_envelope(Operator& op) {
switch (op.stage) {
case EnvStage::Off:
op.env = 0.0f;
op.env_db = 96.0f;
break;
case EnvStage::Attack:
if (op.attack_rate <= 0.0f) {
if (op.attack_alpha <= 0.0f) {
op.env = 0.0f;
op.env_db = 96.0f;
op.stage = EnvStage::Off;
} else {
op.env += (1.05f - op.env) * (1.0f - std::exp(-op.attack_rate * dt));
op.env += (1.05f - op.env) * op.attack_alpha;
if (op.env >= 1.0f) {
op.env = 1.0f;
op.env_db = 0.0f;
op.stage = EnvStage::Decay;
}
}
break;
case EnvStage::Decay:
if (op.decay_rate > 0.0f) {
op.env_db += op.decay_rate * dt;
if (op.env_db >= op.sustain_db) {
op.env_db = op.sustain_db;
op.env *= op.decay_mul;
if (op.env <= op.sustain_lin || op.env <= 3.16228e-5f) {
op.env = op.sustain_lin;
op.stage = op.sustain_hold ? EnvStage::Sustain : EnvStage::Release;
}
} else if (op.sustain_db <= 0.01f) {
op.env_db = 0.0f;
op.env = 1.0f;
op.stage = op.sustain_hold ? EnvStage::Sustain : EnvStage::Release;
}
op.env = (op.env_db >= 90.0f) ? 0.0f : std::exp(-op.env_db * kDbToLn);
break;
case EnvStage::Sustain:
op.env_db = op.sustain_db;
op.env = (op.sustain_db >= 90.0f) ? 0.0f : std::exp(-op.env_db * kDbToLn);
op.env = op.sustain_lin;
break;
case EnvStage::Release:
op.env_db += op.release_rate * dt;
if (op.env_db >= 84.0f) {
op.env *= op.release_mul;
if (op.env <= 6.309573e-5f) {
op.env = 0.0f;
op.env_db = 96.0f;
op.stage = EnvStage::Off;
} else {
op.env = std::exp(-op.env_db * kDbToLn);
}
break;
}
@@ -329,18 +359,17 @@ 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));
return fast_sin_phase(p);
case 1: // Half-sine
return p < 0.5 ? static_cast<float>(std::sin(p * kTwoPi)) : 0.0f;
return p < 0.5 ? fast_sin_phase(p) : 0.0f;
case 2: // Abs-sine
return static_cast<float>(std::abs(std::sin(p * kTwoPi)));
return std::abs(fast_sin_phase(p));
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;
return (p < 0.25 || (p >= 0.5 && p < 0.75)) ? std::abs(fast_sin_phase(p)) : 0.0f;
case 4: // Alternating double-freq sine
return p < 0.5 ? static_cast<float>(std::sin(p * 2.0 * kTwoPi)) : 0.0f;
return p < 0.5 ? fast_sin_phase(p * 2.0) : 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;
return p < 0.5 ? std::abs(fast_sin_phase(p * 2.0)) : 0.0f;
case 6: // Square
return p < 0.5 ? 1.0f : -1.0f;
case 7: // Derived exponential/saw
@@ -351,6 +380,7 @@ float Opl3Synth::eval_waveform(uint8_t wave, double phase) {
}
void Opl3Synth::render(float* stereo_out, int frames) {
if (!stereo_out || frames <= 0) return;
const float dt = 1.0f / static_cast<float>(sample_rate_);
const float cc_alpha = 1.0f - std::exp(-dt / 0.005f);
const double lfo_inc = 6.0 / static_cast<double>(sample_rate_);
@@ -358,7 +388,7 @@ void Opl3Synth::render(float* stereo_out, int frames) {
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 lfo = fast_sin_phase(lfo_phase_);
for (int c = 0; c < kNumChannels; ++c) {
channels_[c].vol_smooth += (channels_[c].volume_target - channels_[c].vol_smooth) * cc_alpha;
@@ -369,10 +399,10 @@ void Opl3Synth::render(float* stereo_out, int frames) {
float right = 0.0f;
for (auto& v : voices_) {
if (!v.active) continue;
if (!v.active || v.channel >= kNumChannels) continue;
step_envelope(v.op_mod, dt);
step_envelope(v.op_car, dt);
step_envelope(v.op_mod);
step_envelope(v.op_car);
if (v.op_car.stage == EnvStage::Off && (!v.additive || v.op_mod.stage == EnvStage::Off)) {
v.active = false;
continue;
@@ -407,11 +437,8 @@ void Opl3Synth::render(float* stereo_out, int frames) {
const ChannelState& cs = channels_[v.channel];
float ch_gain = (cs.vol_smooth * cs.vol_smooth) * (cs.expr_smooth * cs.expr_smooth) * 0.28f;
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;
left += sample * ch_gain * cs.pan_l;
right += sample * ch_gain * cs.pan_r;
}
stereo_out[f * 2 + 0] += soft_limit_safety(left, 0.85f);
+10 -1
View File
@@ -47,6 +47,7 @@ private:
struct Operator {
double phase = 0.0;
double phase_inc = 0.0;
double mult = 1.0;
float env = 0.0f; // 0..1 linear amplitude
float env_db = 96.0f; // 0 dB = peak, 96 dB = silence
EnvStage stage = EnvStage::Off;
@@ -54,6 +55,10 @@ private:
float decay_rate = 0.0f; // dB/s
float sustain_db = 12.0f; // dB attenuation
float release_rate = 0.0f; // dB/s
float attack_alpha = 0.0f;
float decay_mul = 1.0f;
float sustain_lin = 0.0f;
float release_mul = 1.0f;
float total_level = 1.0f; // linear scale from TL + KSL + vel
uint8_t wave = 0;
bool am = false;
@@ -85,14 +90,18 @@ private:
float expr_target = 1.0f;
float expr_smooth = 1.0f;
float pan = 0.0f; // -1..+1
float pan_l = 0.70710678f;
float pan_r = 0.70710678f;
float pitch_bend_semitones = 0.0f;
float bend_mul = 1.0f;
bool sustain_pedal = false;
};
void setup_operator(Operator& op, uint8_t reg20, uint8_t reg40, uint8_t reg60,
uint8_t reg80, uint8_t regE0, float base_freq, float midi_note,
float vel_scale, bool is_carrier);
void step_envelope(Operator& op, float dt);
void update_operator_rates(Operator& op);
void step_envelope(Operator& op);
static float eval_waveform(uint8_t wave, double phase);
void update_voice_freq(Voice& v);
+117 -60
View File
@@ -2,12 +2,33 @@
#include "core/math.hpp"
#include <algorithm>
#include <array>
#include <cmath>
namespace top_octane::audio {
namespace {
constexpr int kSinLutSize = 2048;
inline float fast_sin_phase(double p) {
static const std::array<float, kSinLutSize + 1> kLut = []() {
std::array<float, kSinLutSize + 1> t{};
for (int i = 0; i <= kSinLutSize; ++i) {
t[static_cast<size_t>(i)] = static_cast<float>(
std::sin((static_cast<double>(i) / static_cast<double>(kSinLutSize)) * kTwoPi));
}
return t;
}();
if (!std::isfinite(p)) return 0.0f;
p -= std::floor(p);
double fp = p * static_cast<double>(kSinLutSize);
int i0 = static_cast<int>(fp) & (kSinLutSize - 1);
float frac = static_cast<float>(fp - static_cast<double>(i0));
return kLut[static_cast<size_t>(i0)] +
(kLut[static_cast<size_t>(i0) + 1u] - kLut[static_cast<size_t>(i0)]) * frac;
}
inline float polyblep(double t, double dt) {
if (dt <= 0.0 || dt >= 0.5) return 0.0f;
if (t < dt) {
@@ -49,12 +70,12 @@ inline float soft_limit_safety(float x, float thresh) {
return (x >= 0.0f) ? limited : -limited;
}
inline float apply_svf_2x(float x, float fc_hz, float q_damp, int sample_rate,
float& lp, float& bp) {
const float sr_f = static_cast<float>(sample_rate);
const float fc = std::clamp(fc_hz, 25.0f, 0.40f * sr_f);
const float damp = std::clamp(q_damp, 0.22f, 1.45f);
const float f = 2.0f * std::sin(static_cast<float>(kPi) * fc / (2.0f * sr_f));
inline float compute_svf_f(float fc_hz, float sr_f) {
const float fc = std::clamp(std::isfinite(fc_hz) ? fc_hz : 20000.0f, 25.0f, 0.40f * sr_f);
return 2.0f * std::sin(static_cast<float>(kPi) * fc / (2.0f * sr_f));
}
inline float apply_svf_2x_coeff(float x, float f, float damp, float& lp, float& bp) {
for (int sub = 0; sub < 2; ++sub) {
lp += f * bp;
float hp = x - lp - damp * bp;
@@ -65,6 +86,8 @@ inline float apply_svf_2x(float x, float fc_hz, float q_damp, int sample_rate,
bp = 0.0f;
return 0.0f;
}
if (std::abs(lp) < 1e-20f) lp = 0.0f;
if (std::abs(bp) < 1e-20f) bp = 0.0f;
return std::clamp(lp, -4.0f, 4.0f);
}
@@ -72,14 +95,14 @@ inline float apply_svf_2x(float x, float fc_hz, float q_damp, int sample_rate,
SfSynth::SfSynth(const assets::SoundFontBank* sf,
const assets::OplTimbreBank* opl_fallback, int sample_rate)
: sf_(sf), sample_rate_(std::max(sample_rate, 8000)) {
: sf_(sf), sample_rate_(std::clamp(sample_rate, 8000, 192000)) {
(void)opl_fallback;
set_sample_rate(sample_rate_);
reset();
}
void SfSynth::set_sample_rate(int sample_rate) {
sample_rate_ = std::max(sample_rate, 8000);
sample_rate_ = std::clamp(sample_rate, 8000, 192000);
// Primes scaled to sample_rate for stereo comb reverb (~29, 37 ms L / ~31, 41 ms R)
const size_t l0 = static_cast<size_t>(std::max(64, (sample_rate_ * 29) / 1000));
const size_t l1 = static_cast<size_t>(std::max(64, (sample_rate_ * 37) / 1000));
@@ -93,6 +116,27 @@ void SfSynth::set_sample_rate(int sample_rate) {
rev_idx_r_[0] = rev_idx_r_[1] = 0;
rev_lp_l_[0] = rev_lp_l_[1] = 0.0f;
rev_lp_r_[0] = rev_lp_r_[1] = 0.0f;
for (auto& v : voices_) {
if (v.active) finalize_voice_cache(v);
}
}
void SfSynth::finalize_voice_cache(WtVoice& v) {
constexpr float kDbToLn = 0.11512925465f;
const float sr_f = static_cast<float>(sample_rate_);
const float dt = 1.0f / sr_f;
const float p = std::clamp(v.pan, -1.0f, 1.0f);
v.pan_l = std::sqrt(0.5f * (1.0f - p));
v.pan_r = std::sqrt(0.5f * (1.0f + p));
const float atk_rate = 3.0445f / std::max(v.attack_sec, 0.001f);
v.attack_alpha = 1.0f - std::exp(-atk_rate * dt);
v.decay_mul = (v.decay_rate_db > 0.0005f) ? std::exp(-v.decay_rate_db * dt * kDbToLn) : 1.0f;
v.sustain_lin = (v.sustain_db >= 90.0f) ? 0.0f : std::exp(-v.sustain_db * kDbToLn);
v.release_mul = std::exp(-v.release_rate_db * dt * kDbToLn);
v.svf_damp = std::clamp(v.filter_q_damp, 0.22f, 1.45f);
v.svf_f_static = compute_svf_f(v.filter_fc_hz, sr_f);
v.svf_f_cached = v.svf_f_static;
v.filter_mod_counter = 0;
}
void SfSynth::reset() {
@@ -196,7 +240,8 @@ void SfSynth::spawn_sf_zone(uint8_t ch, uint8_t key, uint8_t vel, const assets::
v.l_start = static_cast<uint32_t>(ls);
v.l_end = static_cast<uint32_t>(le);
v.pos = static_cast<double>(v.s_start);
v.step = (static_cast<double>(smp.sample_rate) / static_cast<double>(sample_rate_)) * pitch_ratio;
double raw_step = (static_cast<double>(smp.sample_rate) / static_cast<double>(sample_rate_)) * pitch_ratio;
v.step = std::isfinite(raw_step) ? std::clamp(raw_step, 1e-5, 16.0) : 1.0;
} else {
v.rom_kind = classify_rom_sample(smp.name);
double eff_key = (z.scale_tuning == 0) ? static_cast<double>(root) : static_cast<double>(key);
@@ -247,6 +292,7 @@ void SfSynth::spawn_sf_zone(uint8_t ch, uint8_t key, uint8_t vel, const assets::
v.filter_q_damp = std::max(1.0f / q_lin, 0.22f);
v.mod_env_to_filter_cents = z.mod_env_to_filter_cents;
}
finalize_voice_cache(v);
}
void SfSynth::spawn_gm_voice(uint8_t ch, uint8_t key, uint8_t vel) {
@@ -367,6 +413,7 @@ void SfSynth::spawn_gm_voice(uint8_t ch, uint8_t key, uint8_t vel) {
}
v.step = v.drum_pitch_hz / static_cast<double>(sample_rate_);
v.env_stage = EnvStage::Attack;
finalize_voice_cache(v);
return;
}
@@ -498,6 +545,7 @@ void SfSynth::spawn_gm_voice(uint8_t ch, uint8_t key, uint8_t vel) {
v.sustain_db = 18.0f;
v.release_rate_db = 96.0f / 0.20f;
}
finalize_voice_cache(v);
}
void SfSynth::note_on(uint8_t ch, uint8_t key, uint8_t vel) {
@@ -605,6 +653,7 @@ void SfSynth::control_change(uint8_t ch, uint8_t cc, uint8_t val) {
cs.expr_target = 1.0f;
cs.expr_smooth = 1.0f;
cs.pitch_bend_semitones = 0.0f;
cs.bend_mul = 1.0f;
cs.sustain_pedal = false;
cs.chorus_cc = 0.0f;
cs.reverb_cc = 0.15f;
@@ -632,6 +681,7 @@ void SfSynth::control_change(uint8_t ch, uint8_t cc, uint8_t val) {
void SfSynth::pitch_bend(uint8_t ch, int16_t bend14) {
if (ch < 16) {
channels_[ch].pitch_bend_semitones = (static_cast<float>(bend14) / 8192.0f) * 2.0f;
channels_[ch].bend_mul = std::pow(2.0f, channels_[ch].pitch_bend_semitones / 12.0f);
}
}
@@ -640,28 +690,23 @@ void SfSynth::all_notes_off() {
}
void SfSynth::step_env(WtVoice& v, float dt) {
constexpr float kDbToLn = 0.11512925465f;
switch (v.env_stage) {
case EnvStage::Off:
v.env = 0.0f;
v.env_db = 96.0f;
v.active = false;
break;
case EnvStage::Delay:
v.stage_timer += dt;
v.env = 0.0f;
v.env_db = 96.0f;
if (v.stage_timer >= v.delay_sec) {
v.stage_timer = 0.0f;
v.env_stage = EnvStage::Attack;
}
break;
case EnvStage::Attack: {
float atk_rate = 3.0445f / std::max(v.attack_sec, 0.001f);
v.env += (1.05f - v.env) * (1.0f - std::exp(-atk_rate * dt));
v.env += (1.05f - v.env) * v.attack_alpha;
if (v.env >= 1.0f) {
v.env = 1.0f;
v.env_db = 0.0f;
v.stage_timer = 0.0f;
v.env_stage = (v.hold_sec > 0.0005f) ? EnvStage::Hold : EnvStage::Decay;
}
@@ -669,7 +714,6 @@ void SfSynth::step_env(WtVoice& v, float dt) {
}
case EnvStage::Hold:
v.env = 1.0f;
v.env_db = 0.0f;
v.stage_timer += dt;
if (v.stage_timer >= v.hold_sec) {
v.env_stage = EnvStage::Decay;
@@ -677,48 +721,51 @@ void SfSynth::step_env(WtVoice& v, float dt) {
break;
case EnvStage::Decay:
if (v.decay_rate_db <= 0.0f || v.sustain_db <= 0.05f) {
v.env_db = v.sustain_db;
v.env = v.sustain_lin;
v.env_stage = (v.sustain_db >= 90.0f) ? EnvStage::Off : EnvStage::Sustain;
} else {
v.env_db += v.decay_rate_db * dt;
if (v.env_db >= v.sustain_db) {
v.env_db = v.sustain_db;
v.env *= v.decay_mul;
if (v.env <= v.sustain_lin || v.env <= 3.16228e-5f) {
v.env = v.sustain_lin;
v.env_stage = (v.sustain_db >= 90.0f) ? EnvStage::Off : EnvStage::Sustain;
}
}
v.env = (v.env_db >= 90.0f) ? 0.0f : std::exp(-v.env_db * kDbToLn);
if (v.env_stage == EnvStage::Off) v.active = false;
break;
case EnvStage::Sustain:
v.env_db = v.sustain_db;
v.env = (v.sustain_db >= 90.0f) ? 0.0f : std::exp(-v.env_db * kDbToLn);
v.env = v.sustain_lin;
break;
case EnvStage::Release:
v.env_db += v.release_rate_db * dt;
if (v.env_db >= 84.0f) {
v.env *= v.release_mul;
if (v.env <= 6.309573e-5f) {
v.env = 0.0f;
v.env_db = 96.0f;
v.env_stage = EnvStage::Off;
v.active = false;
} else {
v.env = std::exp(-v.env_db * kDbToLn);
}
break;
}
}
float SfSynth::sample_osc(WtVoice& v, float dt) {
float bend_mul = std::pow(2.0f, channels_[v.channel].pitch_bend_semitones / 12.0f);
const float bend_mul = channels_[v.channel].bend_mul;
if (v.rom_kind == RomWaveKind::None) {
if (!sf_ || v.sample_idx < 0 || static_cast<size_t>(v.sample_idx) >= sf_->samples.size()) {
if (!sf_ || v.sample_idx < 0 || static_cast<size_t>(v.sample_idx) >= sf_->samples.size() ||
sf_->sample_pool.empty() || !std::isfinite(v.pos) || v.pos < 0.0 ||
!std::isfinite(v.step) || v.step <= 0.0) {
v.active = false;
return 0.0f;
}
const uint32_t safe_end = std::min<uint32_t>(v.s_end, static_cast<uint32_t>(sf_->sample_pool.size()));
uint32_t i0 = static_cast<uint32_t>(v.pos);
if (i0 + 1 >= v.s_end) {
if (v.loop && v.l_end > v.l_start + 1 && v.l_end <= v.s_end) {
v.pos = static_cast<double>(v.l_start);
i0 = v.l_start;
if (i0 + 1 >= safe_end) {
if (v.loop && v.l_end > v.l_start + 1 && v.l_end <= safe_end) {
const double span = static_cast<double>(v.l_end - v.l_start);
v.pos = static_cast<double>(v.l_start) + std::fmod(v.pos - static_cast<double>(v.l_start), span);
i0 = static_cast<uint32_t>(v.pos);
if (i0 + 1 >= safe_end) {
v.pos = static_cast<double>(v.l_start);
i0 = v.l_start;
}
} else {
v.active = false;
return 0.0f;
@@ -730,8 +777,10 @@ float SfSynth::sample_osc(WtVoice& v, float dt) {
float out = s0 + (s1 - s0) * frac;
v.pos += v.step * bend_mul;
if (v.loop && v.l_end > v.l_start + 1 && v.pos >= static_cast<double>(v.l_end)) {
v.pos -= static_cast<double>(v.l_end - v.l_start);
if (v.loop && v.l_end > v.l_start + 1 && v.l_end <= safe_end &&
v.pos >= static_cast<double>(v.l_end)) {
const double span = static_cast<double>(v.l_end - v.l_start);
v.pos = static_cast<double>(v.l_start) + std::fmod(v.pos - static_cast<double>(v.l_start), span);
}
return out;
}
@@ -754,7 +803,7 @@ float SfSynth::sample_osc(WtVoice& v, float dt) {
if (v.chorus_send > 0.05f) {
v.chorus_phase += 1.8 * static_cast<double>(dt);
if (v.chorus_phase >= 1.0) v.chorus_phase -= 1.0;
double detune = 1.0 + 0.0055 * (1.0 + 0.4 * std::sin(v.chorus_phase * kTwoPi));
double detune = 1.0 + 0.0055 * (1.0 + 0.4 * fast_sin_phase(v.chorus_phase));
v.pos2 += inc * detune;
v.pos2 -= std::floor(v.pos2);
float sub_s = blep_saw(v.pos2, inc * detune);
@@ -766,21 +815,22 @@ float SfSynth::sample_osc(WtVoice& v, float dt) {
}
case RomWaveKind::Bell: {
float decay_harm = std::max(0.0f, v.env * v.env);
float body = static_cast<float>(std::sin(ph * kTwoPi));
float overtone = static_cast<float>(std::sin(ph * 3.01 * kTwoPi + 0.45 * std::sin(ph * 2.0 * kTwoPi)));
float body = fast_sin_phase(ph);
float mod = 0.45f * fast_sin_phase(ph * 2.0) / static_cast<float>(kTwoPi);
float overtone = fast_sin_phase(ph * 3.01 + static_cast<double>(mod));
out = 0.78f * body + 0.28f * decay_harm * overtone;
break;
}
case RomWaveKind::Perc: {
float click = next_noise(v.noise_state) * std::max(0.0f, v.env * v.env * v.env);
float tone = static_cast<float>(std::sin(ph * kTwoPi));
float tone = fast_sin_phase(ph);
out = 0.82f * tone + 0.18f * click;
break;
}
case RomWaveKind::Sine: {
// Woody *SineWave with brisk attack overtone for AgogoLoTone
float wood = static_cast<float>(std::sin(ph * 4.18 * kTwoPi)) * (v.env * v.env);
out = 0.88f * static_cast<float>(std::sin(ph * kTwoPi)) + 0.16f * wood;
float wood = fast_sin_phase(ph * 4.18) * (v.env * v.env);
out = 0.88f * fast_sin_phase(ph) + 0.16f * wood;
break;
}
case RomWaveKind::GmKey: {
@@ -796,10 +846,10 @@ float SfSynth::sample_osc(WtVoice& v, float dt) {
break;
}
case RomWaveKind::GmOrgan: {
float f1 = static_cast<float>(std::sin(ph * kTwoPi));
float f2 = static_cast<float>(std::sin(ph * 2.0 * kTwoPi));
float f3 = static_cast<float>(std::sin(ph * 3.0 * kTwoPi));
float f4 = static_cast<float>(std::sin(ph * 4.0 * kTwoPi));
float f1 = fast_sin_phase(ph);
float f2 = fast_sin_phase(ph * 2.0);
float f3 = fast_sin_phase(ph * 3.0);
float f4 = fast_sin_phase(ph * 4.0);
out = 0.48f * f1 + 0.28f * f2 + 0.16f * f3 * v.gm_bright + 0.10f * f4 * v.gm_bright;
break;
}
@@ -815,7 +865,7 @@ float SfSynth::sample_osc(WtVoice& v, float dt) {
case RomWaveKind::GmBass: {
float saw_w = blep_saw(ph, inc);
float tri_w = 1.0f - 4.0f * static_cast<float>(std::abs(ph - 0.5));
float sub_w = static_cast<float>(std::sin(ph * 0.5 * kTwoPi));
float sub_w = fast_sin_phase(ph * 0.5);
out = 0.55f * tri_w + 0.35f * v.gm_bright * saw_w + 0.25f * sub_w;
break;
}
@@ -833,11 +883,11 @@ float SfSynth::sample_osc(WtVoice& v, float dt) {
v.drum_pitch_hz += (v.drum_end_hz - v.drum_pitch_hz) *
std::min(1.0f, v.drum_sweep_rate * dt);
v.step = v.drum_pitch_hz / static_cast<double>(sample_rate_);
float tone = static_cast<float>(std::sin(ph * kTwoPi));
float tone = fast_sin_phase(ph);
if (v.drum_pitch_hz > 500.0f) {
// Metallic cymbal / hi-hat partials
float m1 = (std::sin(ph * 1.47 * kTwoPi) > 0.0) ? 0.5f : -0.5f;
float m2 = (std::sin(ph * 2.13 * kTwoPi) > 0.0) ? 0.5f : -0.5f;
float m1 = (fast_sin_phase(ph * 1.47) > 0.0f) ? 0.5f : -0.5f;
float m2 = (fast_sin_phase(ph * 2.13) > 0.0f) ? 0.5f : -0.5f;
tone = 0.5f * (m1 + m2);
}
float n = next_noise(v.noise_state);
@@ -845,14 +895,16 @@ float SfSynth::sample_osc(WtVoice& v, float dt) {
break;
}
default:
out = static_cast<float>(std::sin(ph * kTwoPi));
out = fast_sin_phase(ph);
break;
}
return out;
}
void SfSynth::render(float* stereo_out, int frames) {
const float dt = 1.0f / static_cast<float>(sample_rate_);
if (!stereo_out || frames <= 0) return;
const float sr_f = static_cast<float>(sample_rate_);
const float dt = 1.0f / sr_f;
const float cc_alpha = 1.0f - std::exp(-dt / 0.005f);
for (int f = 0; f < frames; ++f) {
@@ -865,7 +917,7 @@ void SfSynth::render(float* stereo_out, int frames) {
float rev_in_l = 0.0f, rev_in_r = 0.0f;
for (auto& v : voices_) {
if (!v.active) continue;
if (!v.active || v.channel >= 16) continue;
step_env(v, dt);
if (!v.active) continue;
@@ -873,11 +925,16 @@ void SfSynth::render(float* stereo_out, int frames) {
if (!v.active) continue;
if (v.has_filter) {
float fc = v.filter_fc_hz;
if (v.mod_env_to_filter_cents != 0.0f) {
fc *= std::pow(2.0f, (v.env * v.mod_env_to_filter_cents) / 1200.0f);
if (v.filter_mod_counter == 0) {
float fc = v.filter_fc_hz * std::pow(2.0f, (v.env * v.mod_env_to_filter_cents) / 1200.0f);
v.svf_f_cached = compute_svf_f(fc, sr_f);
}
v.filter_mod_counter = (v.filter_mod_counter + 1u) & 7u;
sig = apply_svf_2x_coeff(sig, v.svf_f_cached, v.svf_damp, v.svf_lp, v.svf_bp);
} else {
sig = apply_svf_2x_coeff(sig, v.svf_f_static, v.svf_damp, v.svf_lp, v.svf_bp);
}
sig = apply_svf_2x(sig, fc, v.filter_q_damp, sample_rate_, v.svf_lp, v.svf_bp);
}
sig *= v.env;
@@ -885,10 +942,8 @@ void SfSynth::render(float* stereo_out, int frames) {
const ChState& cs = channels_[v.channel];
float cc_dyn = (cs.vol_smooth * cs.vol_smooth) * (cs.expr_smooth * cs.expr_smooth);
float g = v.base_gain * cc_dyn;
float gl = std::sqrt(0.5f * (1.0f - v.pan));
float gr = std::sqrt(0.5f * (1.0f + v.pan));
float vl = sig * g * gl;
float vr = sig * g * gr;
float vl = sig * g * v.pan_l;
float vr = sig * g * v.pan_r;
l += vl;
r += vr;
rev_in_l += vl * v.reverb_send;
@@ -904,6 +959,8 @@ void SfSynth::render(float* stereo_out, int frames) {
float dr = rev_buf_r_[i][rev_idx_r_[i]];
rev_lp_l_[i] += 0.35f * (dl - rev_lp_l_[i]);
rev_lp_r_[i] += 0.35f * (dr - rev_lp_r_[i]);
if (std::abs(rev_lp_l_[i]) < 1e-20f) rev_lp_l_[i] = 0.0f;
if (std::abs(rev_lp_r_[i]) < 1e-20f) rev_lp_r_[i] = 0.0f;
rev_buf_l_[i][rev_idx_l_[i]] = rev_in_l * 0.5f + rev_lp_r_[i] * 0.52f;
rev_buf_r_[i][rev_idx_r_[i]] = rev_in_r * 0.5f + rev_lp_l_[i] * 0.52f;
if (++rev_idx_l_[i] >= rev_buf_l_[i].size()) rev_idx_l_[i] = 0;
+12
View File
@@ -74,6 +74,8 @@ private:
float base_gain = 0.0f;
float pan = 0.0f;
float pan_l = 0.70710678f;
float pan_r = 0.70710678f;
float chorus_send = 0.0f;
float reverb_send = 0.0f;
double chorus_phase = 0.0;
@@ -89,12 +91,20 @@ private:
float decay_rate_db = 0.0f;
float sustain_db = 0.0f;
float release_rate_db = 600.0f;
float attack_alpha = 0.0f;
float decay_mul = 1.0f;
float sustain_lin = 0.0f;
float release_mul = 1.0f;
// 2x-oversampled SVF resonant low-pass filter
bool has_filter = false;
float filter_fc_hz = 20000.0f;
float filter_q_damp = 1.414f;
float mod_env_to_filter_cents = 0.0f;
float svf_f_static = 0.5f;
float svf_damp = 1.414f;
float svf_f_cached = 0.5f;
uint8_t filter_mod_counter = 0;
float svf_lp = 0.0f;
float svf_bp = 0.0f;
@@ -117,6 +127,7 @@ private:
float expr_smooth = 1.0f;
float pan = 0.0f;
float pitch_bend_semitones = 0.0f;
float bend_mul = 1.0f;
float reverb_cc = 0.15f;
float chorus_cc = 0.0f;
bool sustain_pedal = false;
@@ -124,6 +135,7 @@ private:
static RomWaveKind classify_rom_sample(const std::string& name);
int alloc_voice();
void finalize_voice_cache(WtVoice& v);
void spawn_sf_zone(uint8_t ch, uint8_t key, uint8_t vel, const assets::SoundFontZone& z);
void spawn_gm_voice(uint8_t ch, uint8_t key, uint8_t vel);
void step_env(WtVoice& v, float dt);
+20 -8
View File
@@ -36,7 +36,8 @@ void XmidiPlayer::process_tick(IMidiSynth& synth) {
const auto& evs = seq_->events;
// Fast-forward controller/program/pitch-bend setup before requested start_tick
if (pending_start_tick_ > 0) {
while (event_cursor_ < evs.size() && evs[event_cursor_].tick < pending_start_tick_) {
while (event_cursor_ < evs.size() &&
static_cast<uint64_t>(evs[event_cursor_].tick) < pending_start_tick_) {
const auto& ev = evs[event_cursor_++];
if (ev.status == 0xFFu) continue;
uint8_t hi = ev.status & 0xF0u;
@@ -73,7 +74,8 @@ void XmidiPlayer::process_tick(IMidiSynth& synth) {
};
// Fire events at or before current_tick_
while (event_cursor_ < evs.size() && evs[event_cursor_].tick <= current_tick_) {
while (event_cursor_ < evs.size() &&
static_cast<uint64_t>(evs[event_cursor_].tick) <= current_tick_) {
const auto& ev = evs[event_cursor_++];
if (ev.status == 0xFFu) {
continue;
@@ -100,15 +102,25 @@ void XmidiPlayer::process_tick(IMidiSynth& synth) {
}
synth.note_on(ch, ev.data1, ev.data2);
if (ev.duration_ticks > 0) {
PendingNoteOff* slot = nullptr;
PendingNoteOff* oldest = &note_offs_[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;
slot = &n;
break;
}
if (n.off_tick < oldest->off_tick) {
oldest = &n;
}
}
if (!slot) {
synth.note_off(oldest->channel, oldest->key);
slot = oldest;
}
slot->active = true;
slot->off_tick = current_tick_ + static_cast<uint64_t>(ev.duration_ticks);
slot->channel = ch;
slot->key = ev.data1;
}
}
break;
@@ -163,7 +175,7 @@ void XmidiPlayer::process_tick(IMidiSynth& synth) {
}
++current_tick_;
if (event_cursor_ >= evs.size() && current_tick_ > seq_->total_ticks) {
if (event_cursor_ >= evs.size() && current_tick_ > static_cast<uint64_t>(seq_->total_ticks)) {
if (loop_) {
synth.all_notes_off();
event_cursor_ = 0;
@@ -177,7 +189,7 @@ void XmidiPlayer::process_tick(IMidiSynth& synth) {
}
void XmidiPlayer::render(float* stereo_out, int frames, IMidiSynth& synth) {
if (!playing_ || !seq_) return;
if (!stereo_out || frames <= 0 || !playing_ || !seq_) return;
int offset = 0;
while (offset < frames && playing_) {
+4 -4
View File
@@ -24,14 +24,14 @@ public:
private:
struct PendingNoteOff {
bool active = false;
uint32_t off_tick = 0;
uint64_t off_tick = 0;
uint8_t channel = 0;
uint8_t key = 0;
};
struct XmiLoopFrame {
size_t event_idx = 0;
uint32_t tick = 0;
uint64_t tick = 0;
uint8_t remaining = 0;
bool infinite = true;
};
@@ -44,8 +44,8 @@ private:
int sample_rate_ = 48000;
size_t event_cursor_ = 0;
uint32_t current_tick_ = 0;
uint32_t pending_start_tick_ = 0;
uint64_t current_tick_ = 0;
uint64_t pending_start_tick_ = 0;
double samples_per_tick_ = 400.0; // 48000 / 120 Hz default
double sample_accum_ = 0.0;