forked from xwax/xwax
-
Notifications
You must be signed in to change notification settings - Fork 0
/
midi.c
111 lines (91 loc) · 2.37 KB
/
midi.c
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
111
/*
* Copyright (C) 2021 Mark Hills <mark@xwax.org>
*
* This file is part of "xwax".
*
* "xwax" is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License, version 3 as
* published by the Free Software Foundation.
*
* "xwax" is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, see <https://www.gnu.org/licenses/>.
*
*/
#include <stdio.h>
#include "midi.h"
/*
* Print error code from ALSA
*/
static void alsa_error(const char *msg, int r)
{
fprintf(stderr, "ALSA %s: %s\n", msg, snd_strerror(r));
}
int midi_open(struct midi *m, const char *name)
{
int r;
r = snd_rawmidi_open(&m->in, &m->out, name, SND_RAWMIDI_NONBLOCK);
if (r < 0) {
alsa_error("rawmidi_open", r);
return -1;
}
return 0;
}
void midi_close(struct midi *m)
{
if (snd_rawmidi_close(m->in) < 0)
abort();
if (snd_rawmidi_close(m->out) < 0)
abort();
}
/*
* Get the poll descriptors for reading on this MIDI device
*
* Pre: len is maximum size of array pe
* Return: -1 if len is not large enough, otherwise n on success
* Post: on success, pe is filled with n entries
*/
ssize_t midi_pollfds(struct midi *m, struct pollfd *pe, size_t len)
{
int r;
if (snd_rawmidi_poll_descriptors_count(m->in) > len)
return -1;
r = snd_rawmidi_poll_descriptors(m->in, pe, len);
assert(r >= 0);
return r;
}
/*
* Read raw bytes of input
*
* Pre: len is maximum size of buffer
* Return: -1 on error, otherwise n on success
* Post: on success, buf is filled with n bytes of data
*/
ssize_t midi_read(struct midi *m, void *buf, size_t len)
{
int r;
r = snd_rawmidi_read(m->in, buf, len);
if (r < 0) {
if (r == -EAGAIN)
return 0;
alsa_error("rawmidi_read", r);
return -1;
}
return r;
}
ssize_t midi_write(struct midi *m, const void *buf, size_t len)
{
int r;
r = snd_rawmidi_write(m->out, buf, len);
if (r < 0) {
if (r == -EAGAIN)
return 0;
alsa_error("rawmidi_write", r);
return -1;
}
return r;
}