implement voice stealing
This commit is contained in:
1 parent
5e5f08c4f9
commit
2b1a2b59d4
3 files changed
+45
-24
No files matched your search
@@ -96,29 +96,54 @@ static int parse_port(int *src_client, int *src_port, const char *str) {
|
||||
|
||||
static Note notes[MAX_NOTES] = {0};
|
||||
|
||||
void note_on(uint8_t note, uint8_t velocity) {
|
||||
static void start_note(Note *n, uint8_t id, float freq, uint8_t velocity) {
|
||||
n->id = id;
|
||||
n->gain = 0.0f;
|
||||
n->attack_ms = 100.0f;
|
||||
n->release_ms = 50.0f;
|
||||
n->form = WAVE_SAW;
|
||||
n->freq = freq;
|
||||
n->is_playing = velocity != 0;
|
||||
}
|
||||
|
||||
static void note_on(uint8_t note, uint8_t velocity) {
|
||||
// TODO map velocity to note gain
|
||||
|
||||
// find first free slot in notes array
|
||||
for (size_t i = 0; i < MAX_NOTES; i++) {
|
||||
if (!notes[i].is_playing && notes[i].gain == 0) {
|
||||
notes[i].attack_ms = 100.0f;
|
||||
notes[i].release_ms = 50.0f;
|
||||
notes[i].form = WAVE_SAW;
|
||||
notes[i].freq = midi_note_to_freq(note);
|
||||
notes[i].is_playing = velocity != 0;
|
||||
if (!notes[i].is_playing && notes[i].gain <= 0) {
|
||||
start_note(¬es[i], note, midi_note_to_freq(note), velocity);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: handle no free slots
|
||||
assert(false && "No free slots in notes array");
|
||||
// No free slots. Note stealing
|
||||
// first pass: steal voice with quietest note and not playing
|
||||
float min_gain = INFINITY;
|
||||
Note* note_ptr = NULL;
|
||||
for (size_t i = 0; i < MAX_NOTES; i++) {
|
||||
if (!notes[i].is_playing && notes[i].gain < min_gain) {
|
||||
min_gain = notes[i].gain;
|
||||
note_ptr = ¬es[i];
|
||||
}
|
||||
}
|
||||
// second pass: steal voice with quietest note and playing
|
||||
min_gain = INFINITY;
|
||||
if (note_ptr == NULL) {
|
||||
for (size_t i = 0; i < MAX_NOTES; i++) {
|
||||
if (notes[i].gain < min_gain) {
|
||||
min_gain = notes[i].gain;
|
||||
note_ptr = ¬es[i];
|
||||
}
|
||||
}
|
||||
}
|
||||
assert(note_ptr != NULL && "No free slots");
|
||||
start_note(note_ptr, note, midi_note_to_freq(note), velocity);
|
||||
}
|
||||
|
||||
void note_off(uint8_t note) {
|
||||
float freq = midi_note_to_freq(note);
|
||||
static void note_off(uint8_t note) {
|
||||
for (size_t i = 0; i < MAX_NOTES; i++) {
|
||||
if (notes[i].is_playing && notes[i].freq == freq) {
|
||||
if (notes[i].is_playing && notes[i].id == note) {
|
||||
notes[i].is_playing = false;
|
||||
return;
|
||||
}
|
||||
@@ -216,7 +241,7 @@ int main(int argc, const char** argv) {
|
||||
|
||||
memset(mixing_buffer, 0, sizeof(mixing_buffer));
|
||||
for (size_t i = 0; i < MAX_NOTES; i++) {
|
||||
play_note(¬es[i], mixing_buffer, PLAYBACK_BUFFER_SIZE);
|
||||
play_note(¬es[i], mixing_buffer, PLAYBACK_BUFFER_SIZE, SAMPLE_RATE);
|
||||
}
|
||||
|
||||
// mix voices into playing buffer
|
||||
|
||||
Reference in new issue
Block a user