summaryrefslogtreecommitdiffstats
path: root/src/midi.c
blob: 7ae8df450b62bd83cbf29328284cccc873a225f6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
#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)
{
    if (pkt == NULL) {
        return;
    }
    
    free(pkt);
    pkt = NULL;
}

size_t midi_message_size(const 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, unsigned note, uint8_t velocity)
{
    if (pkt == NULL) {
        return -1;
    }

#ifdef MIDI_DYNAMIC_MEMORY_ALLOC
    if (pkt->data == NULL) {
        return -2;
    }
#endif
    
    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, unsigned note, uint8_t velocity)
{
    if (pkt == NULL) {
        return -1;
    }

#ifdef MIDI_DYNAMIC_MEMORY_ALLOC
    if (pkt->data == NULL) {
        return -2;
    }
#endif
    
    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;
}