commit 48f965ae8a00b74431d6498baae4cd900010900f
parent eeec4ad9d1a4658251efc5e120630748c9db756e
Author: Henry Wilson <henry@henryandlizzy.uk>
Date: Wed, 30 Dec 2020 20:47:04 +0000
polyphonic
Diffstat:
M | main.cpp | | | 42 | ++++++++++++++++++++++++++++-------------- |
1 file changed, 28 insertions(+), 14 deletions(-)
diff --git a/main.cpp b/main.cpp
@@ -164,11 +164,14 @@ int cb_sample_rate(jack_nframes_t nframes, void* arg)
return 0;
}
+static struct voice
+{
+ float envelope, freq, sample;
+} voices[128];
+
int cb_process(jack_nframes_t nframes, void* arg)
{
void* buf = jack_port_get_buffer(*p1, nframes);
- static float envelope, freq;
- static unsigned char note = 0xFF;
jack_midi_event_t event;
for (uint32_t i = 0; not jack_midi_event_get(&event, buf, i); ++i)
@@ -179,14 +182,10 @@ int cb_process(jack_nframes_t nframes, void* arg)
switch (event.buffer[0] >> 4 & 0x7)
{
case 0: // Note off
- if (event.buffer[1] == note)
- envelope = 0;
+ voices[event.buffer[1]].envelope = 0;
break;
case 1: // Note on
- note = event.buffer[1];
- freq = 440 * pow(pow(2.f, 1.f/12), note - 69);
- envelope = event.buffer[2];
- envelope /= 128;
+ voices[event.buffer[1]].envelope = event.buffer[2] / 128.f;
break;
default:
;
@@ -196,15 +195,21 @@ int cb_process(jack_nframes_t nframes, void* arg)
auto audio_buf = static_cast<float*>(jack_port_get_buffer(*p2, nframes));
int srate = sample_rate;
- static float sample;
for (unsigned i = 0; i < buffer_size; ++i)
{
- audio_buf[i] = std::sin(static_cast<float>(sample) * 6.28318530718f / srate) * envelope;
- sample += freq;
- if (sample >= srate)
- sample -= srate;
- //sample %= srate;
+ float accum = 0;
+ for (auto& v : voices)
+ {
+ if (v.envelope < .02f)
+ continue;
+
+ accum += std::sin(v.sample * 6.28318530718f / srate) * v.envelope;
+ v.sample += v.freq;
+ if (v.sample >= srate)
+ v.sample -= srate;
+ }
+ audio_buf[i] = 2 / (1 + std::exp(accum)) - 1;
}
return 0;
}
@@ -251,6 +256,15 @@ void print_sample_rate(void)
int main()
{
+ int note = 0;
+ for (auto& v : voices)
+ {
+ v.envelope = 0;
+ v.freq = 440 * std::pow(std::pow(2.f, 1.f/12), note++ - 69);
+
+ std::cout << v.freq << "Hz\n";
+ }
+
client.set_process_callback(cb_process, nullptr);
client.set_buffer_size_callback(cb_buffer_size, nullptr);
client.set_sample_rate_callback(cb_sample_rate, nullptr);