адаптация s13bby/osc под vst и gui. (вайбкод)

вайбкод потому что мне в моменте стало понятно. что проще было сразу писать на фреймворке JUCE, чем адаптировать консольное приложение на MiniAudio.
обновляться данный репозиторий не будет. СmakeLists адаптирован онли под linux.
This commit is contained in:
2026-11-20 14:52:33 +06:00
parent 8384123f87
commit b0a75e98db
10387 changed files with 4025195 additions and 0 deletions
+50
View File
@@ -0,0 +1,50 @@
#include "../include/audio_engine.hpp"
int AudioEngine::start(){
if (device_is_started) throw std::runtime_error("ошибка: повторный запуск");
if (device_is_init){
result_start = ma_device_start(&device);
if (result_start == MA_SUCCESS){
device_is_started = true;
}
else {
throw std::runtime_error("ошибка: запуск не удался");
}
}
else{
throw std::runtime_error("ошибка: запуск не удался. девайс не был проинициализирован");
}
return 0;
}
int AudioEngine::stop(){
if (!device_is_started) throw std::runtime_error("ошибка: повторная остановка");
result_stop = ma_device_stop(&device);
if (result_stop == MA_SUCCESS){
device_is_started = false;
}
return 0;
}
void AudioEngine::data_callback(ma_device* pDevice, void* pOutput, const void* pInput, ma_uint32 frameCount){
AudioEngine* data = static_cast<AudioEngine*>(pDevice->pUserData);
float* output = static_cast<float*>(pOutput);
for (ma_uint32 i = 0; i < frameCount; ++i){
float left_acc = 0.0f;
float right_acc = 0.0f;
for (auto& synth : data->synths){
StereoSample buf = synth->generate();
left_acc += buf.left;
right_acc += buf.right;
}
output[i * 2] = left_acc;
output[i * 2 + 1] = right_acc;
}
}
+138
View File
@@ -0,0 +1,138 @@
#include "../include/envelope.hpp"
void Envelope::set_sample_rate(double sample_rate_){
if (sample_rate_ <= 0.0) return;
sample_rate = sample_rate_;
switch (condition){
case Condition::Attack:{
if (attack_time <= 0.0) attack_time = 0.0001;
rate = (1.0 - currnet_amplitude) / (attack_time * sample_rate);
break;
}
case Condition::Decay:{
if (decay_time <= 0.0) decay_time = 0.0001;
rate = (sustain_level - 1.0) / (decay_time * sample_rate);
break;
}
case Condition::Release:{
if (release_time <= 0.0) release_time = 0.0001;
rate = (0.0 - currnet_amplitude) / (release_time * sample_rate);
break;
}
default:
break;
}
}
void Envelope::set_attack(double value){
if (value < 0.0) value = 0.0;
attack_time = value;
if (condition == Condition::Attack){
if (attack_time <= 0.0) attack_time = 0.0001;
rate = (1.0 - currnet_amplitude) / (attack_time * sample_rate);
}
}
void Envelope::set_decay(double value){
if (value < 0.0) value = 0.0;
decay_time = value;
if (condition == Condition::Decay){
if (decay_time <= 0.0) decay_time = 0.0001;
rate = (sustain_level - 1.0) / (decay_time * sample_rate);
}
}
void Envelope::set_sustain(double value){
if (value < 0.0) value = 0.0;
if (value > 1.0) value = 1.0;
sustain_level = value;
if (condition == Condition::Decay){
if (decay_time <= 0.0) decay_time = 0.0001;
rate = (sustain_level - 1.0) / (decay_time * sample_rate);
}
}
void Envelope::set_release(double value){
if (value < 0.0) value = 0.0;
release_time = value;
if (condition == Condition::Release){
if (release_time <= 0.0) release_time = 0.0001;
rate = (0.0 - currnet_amplitude) / (release_time * sample_rate);
}
}
void Envelope::note_on(){
condition = Condition::Attack;
if (attack_time <= 0.0){
attack_time = 0.0001;
}
rate = (1.0 - currnet_amplitude)/(attack_time*sample_rate);
}
void Envelope::note_off(){
if (condition != Condition::Idle){
condition = Condition::Release;
if (release_time <= 0.0){
release_time = 0.0001;
}
rate = (0.0 - currnet_amplitude)/(release_time*sample_rate);
}
}
double Envelope::process(){
switch(condition){
case Condition::Attack:{
currnet_amplitude += rate;
if (currnet_amplitude >= 1.0){
currnet_amplitude = 1.0;
if (decay_time <= 0.0){
condition = Condition::Sustain;
}
else{
condition = Condition::Decay;
rate = (sustain_level - 1.0)/(decay_time*sample_rate);
}
}
return currnet_amplitude;
}
case Condition::Decay:{
currnet_amplitude += rate;
if (currnet_amplitude <= sustain_level){
currnet_amplitude = sustain_level;
condition = Condition::Sustain;
}
return currnet_amplitude;
}
case Condition::Sustain:{
return currnet_amplitude;
}
case Condition::Release:{
currnet_amplitude += rate;
if (currnet_amplitude <= 0.0){
currnet_amplitude = 0.0;
condition = Condition::Idle;
}
return currnet_amplitude;
}
case Condition::Idle:{
return 0.0;
}
default: return 0.0;
}
}
bool Envelope::is_idle() const{
return condition == Condition::Idle;
}
bool Envelope::is_release() const{
return condition == Condition::Release;
}
+85
View File
@@ -0,0 +1,85 @@
#include "../include/filter.hpp"
#include <algorithm>
double Filter::max_stable_cutoff() const{
// Chamberlin SVF stability for this topology: keep f = 2*sin(pi*fc/sr) below ~1
return sample_rate / 6.2;
}
void Filter::set_sample_rate(double sample_rate_){
if (sample_rate_ > 0.0){
sample_rate = sample_rate_;
double max_c = max_stable_cutoff();
if (cutoff > max_c){
cutoff = max_c;
}
update_coefficients();
}
}
void Filter::set_cutoff(double value){
double max_c = max_stable_cutoff();
value = std::clamp(value, 20.0, max_c);
cutoff = value;
update_coefficients();
}
void Filter::set_resonance(double value){
value = std::clamp(value, 0.0, 0.99);
resonance = value;
update_coefficients();
}
void Filter::set_filter_off(){
mode = CommandType::SetFilterOff;
}
void Filter::set_low_pass_filter(){
mode = CommandType::SetLowPassFilter;
}
void Filter::set_band_pass_filter(){
mode = CommandType::SetBandPassFilter;
}
void Filter::set_high_pass_filter(){
mode = CommandType::SetHighPassFilter;
}
void Filter::update_coefficients(){
damping = 2.0 * (1.0 - resonance);
if (damping < 0.05) damping = 0.05;
frequency_coefficient = 2.0 * std::sin(std::numbers::pi * (cutoff / sample_rate));
if (frequency_coefficient > 0.99) frequency_coefficient = 0.99;
if (frequency_coefficient < 0.0) frequency_coefficient = 0.0;
}
double Filter::process(double input){
high = (input - low - damping * band);
band = (band + frequency_coefficient * high);
low = (low + frequency_coefficient * band);
if (!std::isfinite(low) || !std::isfinite(band) || !std::isfinite(high)){
low = band = high = 0.0;
}
switch(mode){
default:{
return input;
}
case CommandType::SetFilterOff:{
return input;
}
case CommandType::SetLowPassFilter:{
return low;
}
case CommandType::SetBandPassFilter:{
return band;
}
case CommandType::SetHighPassFilter:{
return high;
}
}
}
+16
View File
@@ -0,0 +1,16 @@
#include "../include/lfo.hpp"
void Lfo::set_sample_rate(double sample_rate_){
if (sample_rate_ > 0.0) sample_rate = sample_rate_;
}
double Lfo::generate(){
sample = std::sin(phase);
phase += (2*std::numbers::pi*frequency)/sample_rate;
phase = std::fmod(phase, (2*std::numbers::pi));
return sample;
}
void Lfo::set_frequency(double value){
if (value > 0.0 && value < 25.0) frequency = value;
}
+150
View File
@@ -0,0 +1,150 @@
#include <iostream>
#include <stdexcept>
#include <thread>
#include <sstream>
#include <atomic>
#include "../include/synth.hpp"
#include "../include/audio_engine.hpp"
#include "../include/spsc_queue.hpp"
#include "../include/command.hpp"
#include "../include/midi_input.hpp"
#include "../include/voice.hpp"
#include "../include/filter.hpp"
/*
реализовать позже
1.добавить управление частотой LFO через MIDI CC, чтобы можно было регулировать скорость вибрато прямо с контроллера.
*/
void console_loop(Synth& synth){
std::string line;
while (std::getline(std::cin, line)){
if (line.empty()) continue;
std::istringstream iss(line);
std::string cmd;
iss >> cmd;
if (cmd == "voices") {
int value;
if (iss >> value) {
synth.set_unison_voices(value);
std::cout << "unison voices = " << value << "\n";
} else {
std::cerr << "ошибка: неверное значение\n";
}
}
else if (cmd == "sin"){
synth.set_wavetable_sin();
std::cout << "waveform sin\n";
}
else if (cmd == "saw"){
synth.set_wavetable_saw();
std::cout << "waveform saw\n";
}
else if (cmd == "square"){
synth.set_wavetable_square();
std::cout << "waveform square\n";
}
else if (cmd == "triangle"){
synth.set_wavetable_triangle();
std::cout << "waveform triangle\n";
}
else if (cmd == "spread") {
float value;
if (iss >> value) {
synth.set_stereo_spread(value);
std::cout << "stereo spread = " << value << "\n";
} else {
std::cerr << "ошибка: неверное значение\n";
}
}
else if (cmd == "detune") {
float value;
if (iss >> value) {
synth.set_detune_amount(value);
std::cout << "detune amount = " << value << "\n";
} else {
std::cerr << "ошибка: неверное значение\n";
}
}
else if (cmd == "gain") {
float value;
if (iss >> value) {
synth.set_unison_gain(value);
std::cout << "unison gain = " << value << "\n";
} else {
std::cerr << "ошибка: неверное значение\n";
}
}
else if (cmd == "exit" || cmd == "quit") {
std::cout << "выход\n";
break;
}
else {
std::cerr << "ошибка: неизвестная команда " << cmd << "\n";
}
}
}
int main(){
// Filter filter;
// Mode mode;
// double input = 100.0;
// filter.set_cutoff(1000.0);
// filter.set_resonance(0.0);
// filter.set_high_pass_filter();
// double sum_squares = 0.0;
// const int N = 48000;
// for (int i = 0; i < N; ++i){
// input = std::sin(2 * std::numbers::pi * i * (10000.0 / 48000.0));
// // std::cout << filter.process(input) << "\n";
// double output = filter.process(input);
// sum_squares += output * output;
// }
// double rms = std::sqrt(sum_squares / N);
// std::cout << "RMS = " << rms << "\n";
Synth synth;
Synth synth2;
SpscQueue queue;
MidiInput midi(synth, synth2);
synth.set_wavetable_saw();
synth.set_unison_voices(7);
synth.set_unison_gain(0.5);
synth.set_stereo_spread(1.0);
synth.set_detune_amount(30.0);
synth.set_bpf();
synth.set_filter_resonance(0.0);
synth.set_filter_cutoff(1000.0);
synth2.set_wavetable_square();
synth2.set_unison_voices(7);
synth2.set_unison_gain(0.5);
synth2.set_stereo_spread(1.0);
synth2.set_detune_amount(30.0);
synth2.set_bpf();
synth2.set_filter_resonance(0.0);
synth2.set_filter_cutoff(1000.0);
midi.list_ports();
midi.open_port(2);
std::thread console_thread(console_loop, std::ref(synth));
console_thread.detach();
try{
AudioEngine audio_engine(synth,synth2);
audio_engine.start();
while (true) midi.read_message();
}
catch (const std::exception& error){
std::cerr << error.what() << "\n";
return 1;
}
return 0;
}
+58
View File
@@ -0,0 +1,58 @@
#include "../include/midi_input.hpp"
void MidiInput::list_ports(){
unsigned int nPort = midiIn.getPortCount();
for (unsigned int i = 0; i < nPort; ++i){
std::string namePort = midiIn.getPortName(i);
std::cout<< i << " : " << namePort <<"\n";
}
}
void MidiInput::open_port(unsigned int port){
unsigned int nPort = midiIn.getPortCount();
try{
if (nPort > port){
midiIn.openPort(port);
std::cout << port << ": порт открыт\n";
}
}
catch(RtMidiError& error){
error.printMessage();
throw std::runtime_error("ошибка");
}
}
void MidiInput::read_message(){
std::vector<unsigned char> message;
midiIn.getMessage(&message);
if (!message.empty()){
unsigned char status;
unsigned char note;
unsigned char velocity;
unsigned char channel;
status = message[0];
note = message[1];
velocity = message[2];
channel = (status & 0x0F) + 1;
if (channel == 1){
for (auto& synth : synths){
if ((status & 0xF0) == 0x90 ) {
if (velocity > 0) synth->note_on(note, velocity);
else synth->note_off(note);
}
else if ( (status & 0xF0) == 0x80 ) synth->note_off(note);
else if ( (status & 0xF0) == 0xE0 ){
pitch = ((velocity & 0x7F)<<7) | (note & 0x7F);
synth->pitch_bend(pitch);
}
else if ( (status & 0xF0) == 0xB0 && note == 1){
mod_wheel = static_cast<uint8_t>(velocity);
synth->set_mod_wheel(mod_wheel);
}
}
}
}
}
+2
View File
@@ -0,0 +1,2 @@
#define MINIAUDIO_IMPLEMENTATION
#include "../external/miniaudio.h"
+27
View File
@@ -0,0 +1,27 @@
#include "../include/spsc_queue.hpp"
bool SpscQueue::push(const Command& command){
std::size_t current_head = head.load(std::memory_order_relaxed);
std::size_t current_tail = tail.load(std::memory_order_acquire);
if ((current_head - current_tail) >= buffer.size()){
return false;
}
else{
buffer[current_head % buffer.size()] = command;
head.store(++current_head, std::memory_order_release);
return true;
}
}
bool SpscQueue::pop(Command& command){
std::size_t current_head = head.load(std::memory_order_acquire);
std::size_t current_tail = tail.load(std::memory_order_relaxed);
if (current_head == current_tail){
return false;
}
else{
command = buffer[current_tail % buffer.size()];
tail.store(++current_tail, std::memory_order_release);
return true;
}
}
+563
View File
@@ -0,0 +1,563 @@
#include "../include/synth.hpp"
void Synth::prepare(double sample_rate_){
if (sample_rate_ <= 0.0) return;
sample_rate = sample_rate_;
lfo.set_sample_rate(sample_rate);
for (auto& voice : voices){
voice.set_sample_rate(sample_rate);
}
}
void Synth::render_block(float* left, float* right, int num_samples){
for (int i = 0; i < num_samples; ++i){
StereoSample sample = generate();
left[i] = static_cast<float>(sample.left);
right[i] = static_cast<float>(sample.right);
}
}
StereoSample Synth::generate(){
int processed = 0;
int active_voices = 0;
double mod_lfo = 0.0;
double delta_c = 0.0;
double delta_s = 0.0;
StereoSample generated = {0.0, 0.0};
StereoSample result = {0.0, 0.0};
Command command;
while (processed < 16 && midi_queue.pop(command)){
switch (command.type){
default:{
++processed;
break;
}
case CommandType::None:{
++processed;
break;
}
case CommandType::NoteOn:{
for (auto& v : voices){
if (v.is_playing(command.note)){
v.note_off();
}
}
Voice* voice = find_free_voice();
if (voice == nullptr){
voice = find_quietest_voice();
if (voice != nullptr){
++stolen_voices;
}
}
if (voice != nullptr){
voice->note_on(command.note, command.velocity);
}
++processed;
break;
}
case CommandType::NoteOff:{
for (auto& voice : voices){
if (voice.is_playing(command.note)){
voice.note_off();
}
}
++processed;
break;
}
case CommandType::PitchBend:{
pitch_semitones = pitch_to_semitones(command.pitch_bend);
pitch_multiplier = semitones_to_multiplier(pitch_semitones);
for (auto& voice : voices){
voice.set_pitch_bend(pitch_multiplier);
}
++processed;
break;
}
case CommandType::ModWheel:{
mod_wheel = command.mod_wheel;
vibrato_depth_ = mod_wheel_to_depth(mod_wheel);
++processed;
break;
}
}
}
while (processed < 16 && gui_queue.pop(command)){
switch(command.type){
default:{
++processed;
break;
}
case CommandType::SetUnisonVoices:{
for (auto& voice : voices){
voice.set_unison_voices(static_cast<uint8_t>(command.value));
}
++processed;
break;
}
case CommandType::SetUnisonGain:{
for (auto& voice : voices){
voice.set_unison_gain(command.value);
}
++processed;
break;
}
case CommandType::SetStereoSpread:{
for (auto& voice : voices){
voice.set_stereo_spread(command.value);
}
++processed;
break;
}
case CommandType::SetDetuneAmount:{
for (auto& voice : voices){
voice.set_detune_amount(command.value);
}
++processed;
break;
}
case CommandType::SetWavetableSin:{
set_wavetable(&sin_wavetable);
++processed;
break;
}
case CommandType::SetWavetableSaw:{
set_wavetable(&saw_wavetable);
++processed;
break;
}
case CommandType::SetWavetableSquare:{
set_wavetable(&square_wavetable);
++processed;
break;
}
case CommandType::SetWavetableTriangle:{
set_wavetable(&triangle_wavetable);
++processed;
break;
}
case CommandType::SetFilterCutOff:{
for (auto& voice : voices){
voice.set_filter_cutoff(command.value);
}
++processed;
break;
}
case CommandType::SetFilterResonance:{
for (auto& voice : voices){
voice.set_filter_resonance(command.value);
}
++processed;
break;
}
case CommandType::SetFilterOff:{
for (auto& voice : voices){
voice.set_filter_off();
}
++processed;
break;
}
case CommandType::SetLowPassFilter:{
for (auto& voice : voices){
voice.set_lpf();
}
++processed;
break;
}
case CommandType::SetBandPassFilter:{
for (auto& voice : voices){
voice.set_bpf();
}
++processed;
break;
}
case CommandType::SetHighPassFilter:{
for (auto& voice : voices){
voice.set_hpf();
}
++processed;
break;
}
}
}
mod_lfo = lfo.generate();
delta_c = vibrato_depth_ * mod_lfo;
delta_s = semitones_to_multiplier(delta_c/100.0);
for (auto& voice : voices){
voice.set_vibrato(delta_s);
generated = voice.generate();
result.left += generated.left;
result.right += generated.right;
if (voice.is_active()){
++active_voices;
}
}
if (active_voices > 0) return {(result.left / active_voices),(result.right / active_voices)};
return result;
}
void Synth::set_mod_wheel(uint8_t value){
Command command;
command.type = CommandType::ModWheel;
command.mod_wheel = value;
midi_queue.push(command);
}
void Synth::set_unison_voices(uint8_t value){
Command command;
command.type = CommandType::SetUnisonVoices;
if (value > 0 && value <=7){
command.value = value;
gui_queue.push(command);
}
}
void Synth::set_unison_gain(double value){
Command command;
command.type = CommandType::SetUnisonGain;
if (value >= 0.0 && value <= 1.0){
command.value = value;
gui_queue.push(command);
}
}
void Synth::set_stereo_spread(double value){
Command command;
command.type = CommandType::SetStereoSpread;
if (value >= 0.0 && value <= 1.0){
command.value = value;
gui_queue.push(command);
}
}
void Synth::set_detune_amount(double value){
Command command;
command.type = CommandType::SetDetuneAmount;
if (value >= 0.0 && value <= 100.0){
command.value = value;
gui_queue.push(command);
}
}
void Synth::set_wavetable(Wavetable* wavetable){
for (auto& voice : voices){
voice.set_wavetable(wavetable);
}
}
void Synth::set_wavetable2(Wavetable* wavetable){
for (auto& voice : voices){
voice.set_wavetable2(wavetable);
}
}
void Synth::set_wavetable_sin(){
Command command;
command.type = CommandType::SetWavetableSin;
gui_queue.push(command);
}
void Synth::set_wavetable_saw(){
Command command;
command.type = CommandType::SetWavetableSaw;
gui_queue.push(command);
}
void Synth::set_wavetable_square(){
Command command;
command.type = CommandType::SetWavetableSquare;
gui_queue.push(command);
}
void Synth::set_wavetable_triangle(){
Command command;
command.type = CommandType::SetWavetableTriangle;
gui_queue.push(command);
}
void Synth::set_filter_cutoff(double value){
Command command;
command.type = CommandType::SetFilterCutOff;
double max_c = sample_rate / 6.2;
if (value < 20.0) value = 20.0;
if (value > max_c) value = max_c;
command.value = value;
gui_queue.push(command);
}
void Synth::set_filter_resonance(double value){
Command command;
command.type = CommandType::SetFilterResonance;
if (value >= 0.0 && value <= 1.0){
command.value = value;
gui_queue.push(command);
}
}
void Synth::set_filter_off(){
Command command;
command.type = CommandType::SetFilterOff;
gui_queue.push(command);
}
void Synth::set_hpf(){
Command command;
command.type = CommandType::SetHighPassFilter;
gui_queue.push(command);
}
void Synth::set_bpf(){
Command command;
command.type = CommandType::SetBandPassFilter;
gui_queue.push(command);
}
void Synth::set_lpf(){
Command command;
command.type = CommandType::SetLowPassFilter;
gui_queue.push(command);
}
void Synth::set_attack(double value){
for (auto& voice : voices) voice.set_attack(value);
}
void Synth::set_decay(double value){
for (auto& voice : voices) voice.set_decay(value);
}
void Synth::set_sustain(double value){
for (auto& voice : voices) voice.set_sustain(value);
}
void Synth::set_release(double value){
for (auto& voice : voices) voice.set_release(value);
}
void Synth::set_lfo_frequency(double value){
lfo.set_frequency(value);
}
void Synth::set_pitch_bend_range(double value){
if (value > 0.0) pitch_bend_range = value;
}
void Synth::apply_unison_voices(int value){
if (value < 1) value = 1;
if (value > 7) value = 7;
for (auto& voice : voices) voice.set_unison_voices(static_cast<uint8_t>(value));
}
void Synth::apply_unison_gain(double value){
for (auto& voice : voices) voice.set_unison_gain(value);
}
void Synth::apply_stereo_spread(double value){
for (auto& voice : voices) voice.set_stereo_spread(value);
}
void Synth::apply_detune_amount(double value){
for (auto& voice : voices) voice.set_detune_amount(value);
}
void Synth::apply_waveform(int index){
switch (index){
case 0: set_wavetable(&sin_wavetable); break;
case 1: set_wavetable(&saw_wavetable); break;
case 2: set_wavetable(&square_wavetable); break;
case 3: set_wavetable(&triangle_wavetable); break;
default: break;
}
}
void Synth::apply_waveform2(int index){
switch (index){
case 0: set_wavetable2(&sin_wavetable); break;
case 1: set_wavetable2(&saw_wavetable); break;
case 2: set_wavetable2(&square_wavetable); break;
case 3: set_wavetable2(&triangle_wavetable); break;
default: break;
}
}
void Synth::apply_osc1_enabled(bool enabled){ for (auto& v : voices) v.set_osc1_enabled(enabled); }
void Synth::apply_osc2_enabled(bool enabled){ for (auto& v : voices) v.set_osc2_enabled(enabled); }
void Synth::apply_osc1_level(double value){ for (auto& v : voices) v.set_osc1_level(value); }
void Synth::apply_osc2_level(double value){ for (auto& v : voices) v.set_osc2_level(value); }
Wavetable* Synth::get_wavetable(int index){
switch (index){ case 0: return &sin_wavetable; case 1: return &saw_wavetable; case 2: return &square_wavetable; case 3: return &triangle_wavetable; default: return &saw_wavetable; }
}
Wavetable* Synth::get_wavetable2(int index){
return get_wavetable(index);
}
void Synth::apply_filter_type(int index){
for (auto& voice : voices){
switch (index){
case 0: voice.set_filter_off(); break;
case 1: voice.set_lpf(); break;
case 2: voice.set_bpf(); break;
case 3: voice.set_hpf(); break;
default: break;
}
}
}
void Synth::apply_filter_cutoff(double value){
double max_c = sample_rate / 6.2;
if (value < 20.0) value = 20.0;
if (value > max_c) value = max_c;
for (auto& voice : voices) voice.set_filter_cutoff(value);
}
void Synth::apply_filter_resonance(double value){
for (auto& voice : voices) voice.set_filter_resonance(value);
}
void Synth::apply_mod_wheel(uint8_t value){
mod_wheel = value;
vibrato_depth_ = mod_wheel_to_depth(mod_wheel);
}
void Synth::apply_pitch_bend(uint16_t value){
pitch_semitones = pitch_to_semitones(value);
pitch_multiplier = semitones_to_multiplier(pitch_semitones);
for (auto& voice : voices){
voice.set_pitch_bend(pitch_multiplier);
}
}
void Synth::note_on_direct(uint8_t note, uint8_t velocity){
for (auto& voice : voices){
if (voice.is_playing(note)){
voice.note_off();
}
}
Voice* voice = find_free_voice();
if (voice == nullptr){
voice = find_quietest_voice();
if (voice != nullptr){
++stolen_voices;
}
}
if (voice != nullptr){
voice->note_on(note, velocity);
}
}
void Synth::note_off_direct(uint8_t note){
for (auto& voice : voices){
if (voice.is_playing(note)){
voice.note_off();
break;
}
}
}
void Synth::all_notes_off(){
for (auto& voice : voices){
if (voice.is_active()){
voice.note_off();
}
}
}
void Synth::pitch_bend(uint16_t value){
Command command;
command.type = CommandType::PitchBend;
command.pitch_bend = value;
midi_queue.push(command);
}
double Synth::pitch_to_semitones(uint16_t value){
double n = 0.0;
double casted_value = static_cast<double>(value);
if (value < 8192) n = (casted_value - 8192)/8192.0;
else n = (casted_value - 8192)/8191.0;
return n * pitch_bend_range;
}
double Synth::semitones_to_multiplier(double semitones){
return std::pow(2.0, (semitones/12));
}
double Synth::mod_wheel_to_depth(uint8_t value){
return (static_cast<double>(value)/127.0)*100;
}
bool Synth::note_on(uint8_t note, uint8_t velocity){
return midi_queue.push({CommandType::NoteOn, note, velocity});
}
bool Synth::note_off(uint8_t note){
return midi_queue.push({CommandType::NoteOff, note, 0});
}
Voice* Synth::find_free_voice(){
for (auto& voice : voices){
if (!voice.is_active()){
return &voice;
}
}
return nullptr;
}
Voice* Synth::find_quietest_voice(){
Voice* quietest = nullptr;
for (auto& voice : voices){
if (!voice.is_active()){
continue;
}
if (quietest == nullptr){
quietest = &voice;
continue;
}
if (!quietest->is_released() && voice.is_released()){
quietest = &voice;
}
else if (quietest->is_released() && voice.is_released()){
if (quietest->get_volume() > voice.get_volume()){
quietest = &voice;
}
}
else if (!quietest->is_released() && !voice.is_released()){
if (quietest->get_volume() > voice.get_volume()){
quietest = &voice;
}
}
}
return quietest;
}
+188
View File
@@ -0,0 +1,188 @@
#include "../include/voice.hpp"
void Voice::set_sample_rate(double sample_rate_){
envelope.set_sample_rate(sample_rate_);
filter_left.set_sample_rate(sample_rate_);
filter_right.set_sample_rate(sample_rate_);
for (auto& osc : oscillators){
osc.osc1.set_sample_rate(sample_rate_);
osc.osc2.set_sample_rate(sample_rate_);
}
}
void Voice::set_attack(double value){ envelope.set_attack(value); }
void Voice::set_decay(double value){ envelope.set_decay(value); }
void Voice::set_sustain(double value){ envelope.set_sustain(value); }
void Voice::set_release(double value){ envelope.set_release(value); }
void Voice::note_on(uint8_t note_, uint8_t velocity){
note = note_;
base_frequency = 440.0*std::pow(2.0,( (static_cast<int>(note)-69)/12.0 ));
for (auto& oscillator : oscillators){
oscillator.osc1.phase = 0.0;
oscillator.osc2.phase = 0.0;
oscillator.osc1.amplitude = velocity/127.0;
oscillator.osc2.amplitude = velocity/127.0;
}
update_frequency();
envelope.note_on();
active = true;
}
void Voice::note_off(){
envelope.note_off();
if (envelope.is_idle()){
active = false;
}
}
void Voice::set_pitch_bend(double multiplier){
pitch_bend = multiplier;
update_frequency();
}
void Voice::set_vibrato(double multiplier){
vibrato = multiplier;
update_frequency();
}
void Voice::set_unison_voices(uint8_t value){
if (value > 0 && value <=7) unison_voices = value;
}
void Voice::set_stereo_spread(double value){
if (value >= 0.0 && value <= 1.0){
stereo_spread = value;
for (auto& oscillator : oscillators){
oscillator.pan = oscillator.base_pan * value;
}
}
}
void Voice::set_detune_amount(double value){
if (value >= 0.0 && value <= 100.0){
detune_amount = value;
for (std::size_t i = 1; i < oscillators.size(); ++i){
oscillators[i].detune = oscillators[i].base_detune * (value/30.0);
}
update_frequency();
}
}
void Voice::set_unison_gain(double value){
if (value >= 0.0 && value <= 1.0){
unison_gain = value;
for (std::size_t i = 1; i < oscillators.size(); ++i){
oscillators[i].amplitude = value;
}
}
}
void Voice::set_wavetable(Wavetable* Wavetable){
for (auto& oscillator : oscillators){
oscillator.osc1.set_wavetable(Wavetable);
}
}
void Voice::set_wavetable2(Wavetable* Wavetable){
for (auto& oscillator : oscillators){
oscillator.osc2.set_wavetable(Wavetable);
}
}
void Voice::set_osc1_enabled(bool enabled){ osc1_enabled = enabled; }
void Voice::set_osc2_enabled(bool enabled){ osc2_enabled = enabled; }
void Voice::set_osc1_level(double value){ osc1_level = std::clamp(value, 0.0, 1.0); }
void Voice::set_osc2_level(double value){ osc2_level = std::clamp(value, 0.0, 1.0); }
void Voice::set_filter_cutoff(double value){
filter_left.set_cutoff(value);
filter_right.set_cutoff(value);
}
void Voice::set_filter_resonance(double value){
filter_left.set_resonance(value);
filter_right.set_resonance(value);
}
void Voice::set_filter_off(){
filter_left.set_filter_off();
filter_right.set_filter_off();
}
void Voice::set_hpf(){
filter_left.set_high_pass_filter();
filter_right.set_high_pass_filter();
}
void Voice::set_bpf(){
filter_left.set_band_pass_filter();
filter_right.set_band_pass_filter();
}
void Voice::set_lpf(){
filter_left.set_low_pass_filter();
filter_right.set_low_pass_filter();
}
void Voice::update_frequency(){
for (auto& oscillator : oscillators){
double freq = base_frequency * pitch_bend * vibrato * std::pow(2.0,(oscillator.detune/1200.0));
oscillator.osc1.frequency = freq;
oscillator.osc2.frequency = freq;
}
}
StereoSample Voice::generate(){
envelope_value = envelope.process();
double left = 0.0;
double right = 0.0;
double total_gain = 0.0;
if (envelope.is_idle()){
active = false;
}
for (std::size_t i = 0; i < unison_voices; ++i){
double sample_mix = 0.0;
if (osc1_enabled){
oscillators[i].osc1.phase = std::fmod(oscillators[i].osc1.phase, (2*std::numbers::pi));
sample_mix += osc1_level * oscillators[i].osc1.generate();
oscillators[i].osc1.phase += (2*std::numbers::pi*oscillators[i].osc1.frequency)/(oscillators[i].osc1.sample_rate);
}
if (osc2_enabled){
oscillators[i].osc2.phase = std::fmod(oscillators[i].osc2.phase, (2*std::numbers::pi));
sample_mix += osc2_level * oscillators[i].osc2.generate();
oscillators[i].osc2.phase += (2*std::numbers::pi*oscillators[i].osc2.frequency)/(oscillators[i].osc2.sample_rate);
}
double unison_amp = oscillators[i].amplitude;
total_gain += unison_amp;
double center = unison_amp * oscillators[i].osc1.amplitude * sample_mix;
double angle = ((oscillators[i].pan + 1.0)/2.0)*(std::numbers::pi/2.0);
left += center*std::cos(angle);
right += center*std::sin(angle);
}
if ( total_gain <= 0.0) return {0.0, 0.0};
left *= (envelope_value/total_gain);
right *= (envelope_value/total_gain);
return {filter_left.process(left), filter_right.process(right)};
}
double Voice::get_volume() const{
return envelope_value;
}
bool Voice::is_active() const{
return active;
}
bool Voice::is_playing(uint8_t note_) const {
return is_active() && note == note_;
}
bool Voice::is_released() const{
return envelope.is_release();
}
+69
View File
@@ -0,0 +1,69 @@
#include "../include/wavetable.hpp"
void Wavetable::generate_sin(uint16_t harmonics_){
harmonics = harmonics_;
for (std::size_t i = 0; i < wavetable.size(); ++i){
double phase = 2.0 * std::numbers::pi * static_cast<double>(i) / wavetable.size();
wavetable[i] = std::sin(phase);
}
}
void Wavetable::generate_saw(uint16_t harmonics_){
harmonics = harmonics_;
for (std::size_t i = 0; i < wavetable.size(); ++i){
double value = 0.0;
for (std::size_t j = 1; j <= harmonics; ++j){
value += -(2.0/std::numbers::pi)*(std::sin((2*std::numbers::pi*(static_cast<double>(i)/wavetable.size())*j))/j);
}
wavetable[i] = value;
}
}
void Wavetable::generate_square(uint16_t harmonics_){
harmonics = harmonics_;
for (std::size_t i = 0; i < wavetable.size(); ++i){
double value = 0.0;
double phase = 2.0 * std::numbers::pi * static_cast<double>(i) / wavetable.size();
for (std::size_t j = 1; j <= harmonics; j += 2){
value += (4.0 / std::numbers::pi) * (std::sin(phase * j) / j);
}
wavetable[i] = value;
}
}
void Wavetable::generate_triangle(uint16_t harmonics_){
harmonics = harmonics_;
double const_factor = 8.0 / (std::numbers::pi * std::numbers::pi);
for (std::size_t i = 0; i < wavetable.size(); ++i){
double value = 0.0;
double phase = 2.0 * std::numbers::pi * static_cast<double>(i) / wavetable.size();
double sign = 1.0;
for (std::size_t j = 1; j <= harmonics; j += 2){
value += const_factor * sign * (std::sin(phase * j) / (j * j));
sign = -sign;
}
wavetable[i] = value;
}
}
void Tables::generate_saw_tables(){
for (std::size_t i = 0; i < tables.size(); ++i){
tables[i].generate_saw(std::size_t{1} << i);
}
}
Wavetable* Tables::select_saw_tables(double frequency){
if (frequency <= 0.0) {
return &tables[0];
}
std::size_t harmonics = static_cast<std::size_t>(24000.0/frequency);
std::size_t best_index = 0;
for (std::size_t i = 0; i < tables.size(); ++i){
std::size_t max = std::size_t{1} << i;
if (harmonics >= max){
best_index = i;
}
else break;
}
return &tables[best_index];
}