summaryrefslogtreecommitdiffstats
path: root/src/midi.c
diff options
context:
space:
mode:
Diffstat (limited to 'src/midi.c')
-rw-r--r--src/midi.c108
1 files changed, 108 insertions, 0 deletions
diff --git a/src/midi.c b/src/midi.c
new file mode 100644
index 0000000..e82c921
--- /dev/null
+++ b/src/midi.c
@@ -0,0 +1,108 @@
+#include "midi.h"
+
+#include <stdint.h>
+#include <stddef.h>
+#include <stdio.h>
+#include <stdlib.h>
+
+
+#ifdef MIDI_DYNAMIC_MEMORY_ALLOC
+midi_message_t *midi_alloc_message(size_t data_size)
+{
+ return (midi_message_t *) malloc(sizeof(midi_message_t) + data_size);
+}
+
+void midi_free_message(midi_message_t *pkt)
+{
+#ifndef MIDI_UNSAFE
+ if (pkt == NULL) {
+ return;
+ }
+#endif
+
+ free(pkt);
+ pkt = NULL;
+}
+
+size_t midi_message_size(midi_message_t *pkt)
+{
+ if (pkt == NULL) {
+ return 0;
+ }
+
+ switch (pkt->status) {
+ case NOTE_ON: return sizeof(midi_message_t) + 2;
+ case NOTE_OFF: return sizeof(midi_message_t) + 1;
+ default: return sizeof(midi_message_t);
+ }
+}
+#endif
+
+
+int midi_set_status(midi_message_t *pkt, midi_status_t status)
+{
+ if (pkt == NULL) {
+ return -1;
+ }
+
+ pkt->status = status & 0x0F;
+
+ return 0;
+}
+
+int midi_set_channel(midi_message_t *pkt, unsigned channel)
+{
+ if (pkt == NULL) {
+ return -1;
+ }
+
+ pkt->channel = channel & 0x0F;
+
+ return 0;
+}
+
+int midi_note_on(midi_message_t *pkt, unsigned channel, midi_note_t note, uint8_t velocity)
+{
+ if (pkt == NULL) {
+ return -1;
+ }
+
+ if (pkt->data == NULL) {
+ return -2;
+ }
+
+ midi_set_status(pkt, NOTE_ON);
+ midi_set_channel(pkt, channel);
+
+ pkt->data[0] = note;
+ pkt->data[1] = velocity;
+
+#ifndef MIDI_DYNAMIC_MEMORY_ALLOC
+ pkt->data_size = 2;
+#endif
+
+ return 0;
+}
+
+int midi_note_off(midi_message_t *pkt, unsigned channel, midi_note_t note, uint8_t velocity)
+{
+ if (pkt == NULL) {
+ return -1;
+ }
+
+ if (pkt->data == NULL) {
+ return -2;
+ }
+
+ midi_set_status(pkt, NOTE_OFF);
+ midi_set_channel(pkt, channel);
+
+ pkt->data[0] = note;
+ pkt->data[1] = velocity;
+
+#ifndef MIDI_DYNAMIC_MEMORY_ALLOC
+ pkt->data_size = 2;
+#endif
+
+ return 0;
+}