~foura/midifs

ref: d084b72774385e5930b74cdfabca164768a39877 midifs/midi.c -rw-r--r-- 1.9 KiB
d084b727james palmer implement reads of the ctl file 3 months ago
                                                                                
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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
#include <u.h>
#include <libc.h>

#include "midi.h"

static int
usbsend(Midi *m, Pkt *p)
{
	u8int buf[4];

	buf[0] = m->cable << 4;
	buf[0] |= p->type;
	buf[1] = p->type << 4;
	buf[1] |= m->chan;
	buf[2] = p->arg1;
	buf[3] = p->arg2;

	if(write(m->fd, buf, 4) < 4)
		return -1;

	return 0;
}

static int
usbrecv(Midi *m, Pkt *p)
{
	u8int buf[4];

again:
	if(read(m->fd, buf, 4) < 4)
		return -1;

	/* accept messages for our channel and cable */
	if(buf[0] >> 4 != m->cable)
		goto again;
	if(buf[1] & 0x0f != m->chan)
		goto again;

	p->type = buf[0] & 0x0f;
	p->arg1 = buf[2];
	p->arg2 = buf[3];

	return 0;
}

static int
midisend(Midi *m, Pkt *p)
{
	u8int buf[3];

	buf[0] = 0x80;
	buf[0] |= (p->type & 0x7f) << 4;
	buf[0] |= (m->chan & 0xf);
	buf[1] = p->arg1 & 0x7f;
	buf[2] = p->arg2 & 0x7f;

	if(write(m->fd, buf, 3) < 3)
		return -1;

	return 0;
}

static int
midirecv(Midi *m, Pkt *p)
{
	u8int buf[3];

again:
	if(read(m->fd, buf, 3) < 3)
		return -1;

	/* accept messages for our channel */
	if(buf[0] & 0x0f != m->chan)
		goto again;

	p->type = ((buf[0] >> 4) & 0x7f);
	p->arg1 = buf[1] & 0x7f;
	p->arg2 = buf[2] & 0x7f;

	return 0;
}

static int
pipeexec(char *prog)
{
	int fd[2];

	pipe(fd);
	switch(rfork(RFFDG|RFREND|RFPROC)) {
	case -1:
		werrstr("out of procs");
		return -1;
	case 0:
		dup(fd[1], 0);
		dup(fd[1], 1);
		close(fd[0]);
		
		execl("/bin/rc", "rc", "-c", prog, nil);
		abort();
	}

	close(fd[1]);
	return fd[0];
}

Midi *
mkusbdev(char *dev)
{
	Midi *m;

	m = malloc(sizeof(Midi));
	if(!m)
		return nil;

	m->fd = open(dev, ORDWR);
	if(m->fd < 0) {
		free(m);
		return nil;
	}

	m->chan = 0;
	m->cable = 0;
	m->send = usbsend;
	m->recv = usbrecv;

	return m;
}

Midi *
mkpipedev(char *prog)
{
	Midi *m;

	m = malloc(sizeof(Midi));
	if(!m)
		return nil;

	m->fd = pipeexec(prog);
	if(m->fd < 0) {
		free(m);
		return nil;
	}

	m->chan = 0;
	m->cable = 0;
	m->send = midisend;
	m->recv = midirecv;

	return m;
}

void
freedev(Midi *m)
{
	close(m->fd);
	free(m);
}