diff --git a/CMakeLists.txt b/CMakeLists.txt index bf5f91f..a1be942 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -20,6 +20,8 @@ set(SOURCES src/midi_input.cpp src/voice.cpp src/lfo.cpp + src/wavetable.cpp + src/filter.cpp ) add_executable(${PROJECT_NAME} ${SOURCES}) diff --git a/include/audio_engine.hpp b/include/audio_engine.hpp index 8f42075..61cc9ea 100644 --- a/include/audio_engine.hpp +++ b/include/audio_engine.hpp @@ -2,7 +2,9 @@ #define AUDIO_ENGINE #include +#include #include + #include "../external/miniaudio.h" #include "../include/synth.hpp" #include "../include/stereo_sample.hpp" @@ -10,12 +12,13 @@ class AudioEngine{ public: - AudioEngine(Synth& synth) : synth_(synth){ + AudioEngine(Synth& synth, Synth& synth2) : synths{&synth, &synth2}{ config = ma_device_config_init(ma_device_type_playback); config.playback.format = ma_format_f32; config.playback.channels = 2; config.sampleRate = 48000; config.pUserData = this; + config.periodSizeInFrames = 512; config.dataCallback = data_callback; result_init = ma_device_init(NULL, &config, &device); @@ -34,7 +37,7 @@ class AudioEngine{ int stop(); private: - Synth& synth_; + std::array synths; bool device_is_init = false; bool device_is_started = false; diff --git a/include/command.hpp b/include/command.hpp index f1b92cb..6334c7f 100644 --- a/include/command.hpp +++ b/include/command.hpp @@ -8,7 +8,21 @@ enum class CommandType{ NoteOn, NoteOff, PitchBend, - ModWheel + ModWheel, + SetUnisonVoices, + SetStereoSpread, + SetDetuneAmount, + SetUnisonGain, + SetWavetableSin, + SetWavetableSaw, + SetWavetableSquare, + SetWavetableTriangle, + SetFilterCutOff, + SetFilterResonance, + SetFilterOff, + SetLowPassFilter, + SetBandPassFilter, + SetHighPassFilter }; struct Command{ @@ -17,6 +31,7 @@ struct Command{ uint8_t velocity = 0; uint16_t pitch_bend = 8192; uint8_t mod_wheel = 0; + double value = 0.0; }; #endif diff --git a/include/filter.hpp b/include/filter.hpp new file mode 100644 index 0000000..ca318f3 --- /dev/null +++ b/include/filter.hpp @@ -0,0 +1,50 @@ +#ifndef FILTER +#define FILTER + +#include +#include +#include + +#include "../include/command.hpp" + +class Filter{ + public: + Filter(){ + mode = CommandType::SetFilterOff; + + cutoff = 1000.0; + resonance = 0.707; + frequency_coefficient = 0.0; + low = 0.0; + band = 0.0; + high = 0.0; + damping = 0.0; + + sample_rate = 48000; + } + + void set_cutoff(double value); + void set_resonance(double value); + void set_filter_off(); + void set_low_pass_filter(); + void set_band_pass_filter(); + void set_high_pass_filter(); + void update_coefficients(); + + double process(double input); + + private: + CommandType mode; + + double cutoff; + double resonance; + double frequency_coefficient; + double low; + double band; + double high; + double damping; + + uint32_t sample_rate; +}; + +#endif diff --git a/include/midi_input.hpp b/include/midi_input.hpp index 4b0d2b7..c86c187 100644 --- a/include/midi_input.hpp +++ b/include/midi_input.hpp @@ -5,6 +5,7 @@ #include #include #include +#include #include "../include/synth.hpp" @@ -12,7 +13,7 @@ class MidiInput{ public: - MidiInput(Synth& synth) : synth_(synth){ + MidiInput(Synth& synth, Synth& synth2) : synths{&synth, &synth2} { pitch = 8192; mod_wheel = 0; } @@ -23,7 +24,7 @@ class MidiInput{ private: RtMidiIn midiIn; - Synth& synth_; + std::array synths; uint16_t pitch; uint8_t mod_wheel; diff --git a/include/oscillator.hpp b/include/oscillator.hpp index 6506143..4e49a47 100644 --- a/include/oscillator.hpp +++ b/include/oscillator.hpp @@ -2,8 +2,40 @@ #define OSCILLATOR #include +#include +#include +#include +#include + +#include "../include/wavetable.hpp" struct Oscillator{ + + double generate(){ + if (wavetable != nullptr){ + const std::size_t table_size = wavetable->wavetable.size(); + double position = (phase / (2.0 * std::numbers::pi)) * table_size; + std::size_t index = static_cast(position); + std::size_t next_index = (index + 1) % table_size; + double fraction = position - index; + double y0 = wavetable->wavetable[index]; + double y1 = wavetable->wavetable[next_index]; + double value = y0 + (y1 - y0) * fraction; + + + phase += (2 * std::numbers::pi * frequency)/(sample_rate); + phase = std::fmod(phase, (2 * std::numbers::pi)); + return value; + } + else return 0.0; + } + + void set_wavetable(Wavetable* wavetable_){ + wavetable = wavetable_; + } + + Wavetable* wavetable = nullptr; + double frequency = 440.0; double amplitude = 0.5; double phase = 0.0; @@ -11,4 +43,13 @@ struct Oscillator{ uint32_t sample_rate = 48000; }; +struct UnisonOscillator{ + Oscillator oscillator; + double pan = 0.0; + double base_pan = 0.0; + double base_detune = 0.0; + double amplitude = 1.0; + double detune = 0.0; +}; + #endif diff --git a/include/spsc_queue.hpp b/include/spsc_queue.hpp index 585b139..402b67e 100644 --- a/include/spsc_queue.hpp +++ b/include/spsc_queue.hpp @@ -13,7 +13,7 @@ class SpscQueue{ SpscQueue(){ head.store(0, std::memory_order_relaxed); tail.store(0, std::memory_order_relaxed); - buffer.fill({CommandType::None, 0, 0}); + buffer.fill(Command{}); } bool push(const Command&); diff --git a/include/synth.hpp b/include/synth.hpp index 8ed11fe..54551a9 100644 --- a/include/synth.hpp +++ b/include/synth.hpp @@ -15,6 +15,12 @@ class Synth { public: Synth(){ + + sin_wavetable.generate_sin(32); + saw_wavetable.generate_saw(32); + square_wavetable.generate_square(28); + triangle_wavetable.generate_triangle(40); + pitch_bend_range = 2.0; pitch_semitones = 0.0; pitch_multiplier = 1.0; @@ -28,6 +34,21 @@ class Synth { void generate_buffer(double* array, int size); void set_mod_wheel(uint8_t value); + void set_unison_voices(uint8_t value); + void set_unison_gain(double value); + void set_stereo_spread(double value); + void set_detune_amount(double value); + void set_wavetable(Wavetable* wavetable); + void set_wavetable_sin(); + void set_wavetable_saw(); + void set_wavetable_square(); + void set_wavetable_triangle(); + void set_filter_cutoff(double value); + void set_filter_resonance(double value); + void set_filter_off(); + void set_hpf(); + void set_bpf(); + void set_lpf(); void pitch_bend(uint16_t value); double pitch_to_semitones(uint16_t value); @@ -41,9 +62,18 @@ class Synth { Voice* find_free_voice(); Voice* find_quietest_voice(); - SpscQueue queue; + SpscQueue midi_queue; + SpscQueue gui_queue; + Lfo lfo; + Tables tables; + + Wavetable sin_wavetable; + Wavetable saw_wavetable; + Wavetable square_wavetable; + Wavetable triangle_wavetable; + double pitch_bend_range; double pitch_semitones; double pitch_multiplier; diff --git a/include/voice.hpp b/include/voice.hpp index 4def4ff..4b8bc12 100644 --- a/include/voice.hpp +++ b/include/voice.hpp @@ -2,35 +2,68 @@ #define VOICE #include +#include #include #include #include -#include +#include #include "../include/envelope.hpp" #include "../include/oscillator.hpp" #include "../include/stereo_sample.hpp" - +#include "../include/filter.hpp" class Voice{ public: Voice(){ + + oscillators[1].base_detune = -10.0; + oscillators[1].base_pan = -1.0; + + oscillators[2].base_detune = 10.0; + oscillators[2].base_pan = 1.0; + + oscillators[3].base_detune = -20.0; + oscillators[3].base_pan = -0.6; + + oscillators[4].base_detune = 20.0; + oscillators[4].base_pan = 0.6; + + oscillators[5].base_detune = -30.0; + oscillators[5].base_pan = -0.3; + + oscillators[6].base_detune = 30.0; + oscillators[6].base_pan = 0.3; + note = 0; + unison_voices = 7; envelope_value = 0.0; - pan = 0.0; base_frequency = 440.0; pitch_bend = 1.0; vibrato = 1.0; + stereo_spread = 1.0; + detune_amount = 1.0; + unison_gain = 1.0; active = false; } void note_on(uint8_t note, uint8_t velocity); void note_off(); - void set_pan(double value); void set_pitch_bend(double multiplier); void set_vibrato(double multiplier); + void set_unison_voices(uint8_t value); + void set_stereo_spread(double value); + void set_detune_amount(double value); + void set_unison_gain(double value); + void set_wavetable(Wavetable* Wavetable); + void set_filter_cutoff(double value); + void set_filter_resonance(double value); + void set_filter_off(); + void set_hpf(); + void set_bpf(); + void set_lpf(); void update_frequency(); StereoSample generate(); @@ -43,15 +76,20 @@ class Voice{ private: Envelope envelope; - Oscillator oscillator; + Filter filter_left; + Filter filter_right; + std::array oscillators{}; uint8_t note; + uint8_t unison_voices; double envelope_value; - double pan; double base_frequency; double pitch_bend; double vibrato; + double stereo_spread; + double detune_amount; + double unison_gain; bool active; }; diff --git a/include/wavetable.hpp b/include/wavetable.hpp new file mode 100644 index 0000000..043ce91 --- /dev/null +++ b/include/wavetable.hpp @@ -0,0 +1,26 @@ +#ifndef WAVETABLE +#define WAVETABLE + +#include +#include +#include +#include + +struct Wavetable{ + void generate_sin(uint16_t harmonics_); + void generate_saw(uint16_t harmonics_); + void generate_square(uint16_t harmonics_); + void generate_triangle(uint16_t harmonics_); + + std::array wavetable{}; + uint16_t harmonics = 0; +}; + +struct Tables{ + Wavetable* select_saw_tables(double frequency); + void generate_saw_tables(); + + std::array tables; +}; + +#endif diff --git a/src/audio_engine.cpp b/src/audio_engine.cpp index ee7affb..40e21f2 100644 --- a/src/audio_engine.cpp +++ b/src/audio_engine.cpp @@ -33,12 +33,18 @@ int AudioEngine::stop(){ } void AudioEngine::data_callback(ma_device* pDevice, void* pOutput, const void* pInput, ma_uint32 frameCount){ - AudioEngine* data = static_cast(pDevice->pUserData); - float* output = static_cast (pOutput); + float* output = static_cast(pOutput); for (ma_uint32 i = 0; i < frameCount; ++i){ - StereoSample buf = data->synth_.generate(); - output[i*2] = buf.left; - output[i*2+1] = buf.right; + 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; } } diff --git a/src/filter.cpp b/src/filter.cpp new file mode 100644 index 0000000..cd74a7b --- /dev/null +++ b/src/filter.cpp @@ -0,0 +1,61 @@ +#include "../include/filter.hpp" + +void Filter::set_cutoff(double value){ + if (value >= 20.0 && value <= 0.25 * sample_rate){ + cutoff = value; + update_coefficients(); + } +} + +void Filter::set_resonance(double value){ + if (value >= 0.0 && value <= 1.0){ + 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 * (1 - resonance); + frequency_coefficient = 2 * std::sin(std::numbers::pi*( (cutoff)/sample_rate )); +} + +double Filter::process(double input){ + high = (input - low - damping * band); + band = (band + frequency_coefficient * high); + low = (low + frequency_coefficient * band); + 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; + } + } +} diff --git a/src/main.cpp b/src/main.cpp index e11b1c2..4e20b69 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -1,6 +1,7 @@ #include #include #include +#include #include #include "../include/synth.hpp" @@ -9,130 +10,135 @@ #include "../include/command.hpp" #include "../include/midi_input.hpp" #include "../include/voice.hpp" +#include "../include/filter.hpp" -// void producer(SpscQueue& queue, std::atomic& producer_done){ -// for (int i = 0; i < 32; ++i){ -// while(!queue.push(Command::NoteOn)){ -// std::this_thread::yield(); -// } -// while(!queue.push(Command::NoteOff)){ -// std::this_thread::yield(); -// } -// } -// producer_done.store(true, std::memory_order_release); -// } -// -// void consumer(SpscQueue& queue, std::atomic& producer_done){ -// Command command; -// Command expected = Command::NoteOn; -// int counter = 0; -// -// while (true){ -// if (!queue.pop(command)){ -// if (producer_done.load(std::memory_order_acquire)) break; -// else{ -// std::this_thread::yield(); -// continue; -// } -// } -// else{ -// ++counter; -// if (command != expected){ -// std::cerr << "команда из очереди не совпадает с ожидаемой"; -// break; -// } -// switch(command){ -// case Command::NoteOn: { -// expected = Command::NoteOff; -// break; -// } -// case Command::NoteOff: { -// expected = Command::NoteOn; -// break; -// } -// case Command::None: { -// break; -// } -// } -// -// } -// } -// std::cout << counter; -// } +/* + реализовать позже + 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(){ - std::string a = ""; + // 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; - // Command command; + Synth synth2; SpscQueue queue; - MidiInput midi(synth); + 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); - // while (true) midi.read_message(); + std::thread console_thread(console_loop, std::ref(synth)); + console_thread.detach(); - - // for (int i = 0; i < 33; ++i){ - // std::cout << queue.push({CommandType::NoteOn, 60, 100}) << "\n"; - // std::cout << queue.push({CommandType::NoteOn, 20, 80}) << "\n"; - // } - // std::cout << "выгрузка\n"; - // for (int i = 0; i < 65; ++i){ - // std::cout << queue.pop(command) << "\n"; - // - // } - // std::cout << static_cast(command.type) << "\n"; - // std::cout << static_cast(command.note)<< "\n"; - // std::cout << static_cast(command.velocity) << "\n"; - - - // std::atomic producer_done{false}; - // - // std::thread thread1 ( - // producer, std::ref(queue), std::ref(producer_done) - // ); - // - // std::thread thread2 (consumer, std::ref(queue), std::ref(producer_done)); - // - // thread1.join(); - // thread2.join(); - - // synth.set_frequency(440); - - // synth.set_amplitude(0.5); - // try{ - AudioEngine audio_engine(synth); + AudioEngine audio_engine(synth,synth2); audio_engine.start(); - while (true){ - // std::cin >> a; - // if (a == "on"){ - // synth.note_on(69, 127); - // synth.note_on(60, 127); - // synth.note_on(48, 127); - // } - // if (a == "1"){ - // synth.note_on(69, 127); - // // if (!synth.note_on()){ - // // throw std::runtime_error("ошибка: не удалось воспроизвести ноту"); - // // } - // } - // else if (a == "2") synth.note_on(60, 127); - // else if (a == "3") synth.note_on(48, 127); - // else if (a == "off"){ - // synth.note_off(60); - // // if (!synth.note_off()){ - // // throw std::runtime_error("ошибка: не удалось воспроизвести ноту"); - // // } - // } - // else if (a == "exit"){ - // audio_engine.stop(); - // return 0; - // } - while (true) midi.read_message(); - } + while (true) midi.read_message(); } catch (const std::exception& error){ std::cerr << error.what() << "\n"; diff --git a/src/midi_input.cpp b/src/midi_input.cpp index 0d44395..c023409 100644 --- a/src/midi_input.cpp +++ b/src/midi_input.cpp @@ -27,7 +27,6 @@ void MidiInput::read_message(){ std::vector message; midiIn.getMessage(&message); if (!message.empty()){ - // if (message.size() < 3) throw std::runtime_error("ошибка: сообщение меньше 3"); unsigned char status; unsigned char note; unsigned char velocity; @@ -38,20 +37,21 @@ void MidiInput::read_message(){ velocity = message[2]; channel = (status & 0x0F) + 1; - std::cout << static_cast(status) << " | " << static_cast(note) << " | " << static_cast(velocity) << " | " << static_cast(channel)<< "\n"; if (channel == 1){ - 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(velocity); - synth_.set_mod_wheel(mod_wheel); + 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(velocity); + synth->set_mod_wheel(mod_wheel); + } } } } diff --git a/src/synth.cpp b/src/synth.cpp index f81063d..493f2bc 100644 --- a/src/synth.cpp +++ b/src/synth.cpp @@ -11,11 +11,13 @@ StereoSample Synth::generate(){ StereoSample result = {0.0, 0.0}; Command command; - while (processed < 16 && queue.pop(command)){ - + while (processed < 16 && midi_queue.pop(command)){ switch (command.type){ - default: + default:{ + ++processed; break; + } + case CommandType::None:{ ++processed; break; @@ -53,16 +55,132 @@ StereoSample Synth::generate(){ 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(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); @@ -83,14 +201,128 @@ void Synth::set_mod_wheel(uint8_t value){ Command command; command.type = CommandType::ModWheel; command.mod_wheel = value; - queue.push(command); + 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_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; + + if (value >= 20.0 && value <= 0.25 * 48000){ + 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::pitch_bend(uint16_t value){ Command command; command.type = CommandType::PitchBend; command.pitch_bend = value; - queue.push(command); + midi_queue.push(command); } double Synth::pitch_to_semitones(uint16_t value){ @@ -111,11 +343,11 @@ double Synth::mod_wheel_to_depth(uint8_t value){ } bool Synth::note_on(uint8_t note, uint8_t velocity){ - return queue.push({CommandType::NoteOn, note, velocity}); + return midi_queue.push({CommandType::NoteOn, note, velocity}); } bool Synth::note_off(uint8_t note){ - return queue.push({CommandType::NoteOff, note, 0}); + return midi_queue.push({CommandType::NoteOff, note, 0}); } Voice* Synth::find_free_voice(){ diff --git a/src/voice.cpp b/src/voice.cpp index 5fa10ea..5b461fd 100644 --- a/src/voice.cpp +++ b/src/voice.cpp @@ -1,15 +1,14 @@ #include "../include/voice.hpp" -std::random_device rd; -std::mt19937 gen(rd()); void Voice::note_on(uint8_t note_, uint8_t velocity){ note = note_; - std::uniform_real_distribution pan_distribution(-1.0, 1.0); base_frequency = 440.0*std::pow(2.0,( (static_cast(note)-69)/12.0 )); + for (auto& oscillator : oscillators){ + oscillator.oscillator.phase = 0.0; + oscillator.oscillator.amplitude = velocity/127.0; + } update_frequency(); - oscillator.amplitude = (static_cast(velocity) / 127.0); - set_pan(pan_distribution(gen)); envelope.note_on(); active = true; } @@ -21,10 +20,6 @@ void Voice::note_off(){ } } -void Voice::set_pan(double value){ - pan = std::clamp(value, -1.0, 1.0); -} - void Voice::set_pitch_bend(double multiplier){ pitch_bend = multiplier; update_frequency(); @@ -35,23 +30,105 @@ void Voice::set_vibrato(double 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.oscillator.set_wavetable(Wavetable); + } +} + +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(){ - oscillator.frequency = base_frequency * pitch_bend * vibrato; + for (auto& oscillator : oscillators){ + oscillator.oscillator.frequency = base_frequency * pitch_bend * vibrato * std::pow(2.0,(oscillator.detune/1200.0)); + } } StereoSample Voice::generate(){ envelope_value = envelope.process(); + double center = 0.0; + double angle = 0.0; + double left = 0.0; + double right = 0.0; + double total_gain = 0.0; if (envelope.is_idle()){ active = false; } - oscillator.phase = std::fmod(oscillator.phase, (2*std::numbers::pi)); - double center = oscillator.amplitude*std::sin(oscillator.phase); - double angle = ((pan+1.0)/2.0)*(std::numbers::pi/2.0); - double left = center*std::cos(angle); - double right = center*std::sin(angle); - oscillator.phase += (2*std::numbers::pi*oscillator.frequency)/(oscillator.sample_rate); + for (std::size_t i = 0; i < unison_voices; ++i){ + oscillators[i].oscillator.phase = std::fmod(oscillators[i].oscillator.phase, (2*std::numbers::pi)); + center = oscillators[i].amplitude*oscillators[i].oscillator.amplitude*oscillators[i].oscillator.generate(); + total_gain += oscillators[i].amplitude; + angle = ((oscillators[i].pan + 1.0)/2.0)*(std::numbers::pi/2.0); + left += center*std::cos(angle); + right += center*std::sin(angle); + oscillators[i].oscillator.phase += (2*std::numbers::pi*oscillators[i].oscillator.frequency)/(oscillators[i].oscillator.sample_rate); + } - return {left*envelope_value, right*envelope_value}; + 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{ diff --git a/src/wavetable.cpp b/src/wavetable.cpp new file mode 100644 index 0000000..3603e4f --- /dev/null +++ b/src/wavetable.cpp @@ -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(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(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(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(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(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]; +}