File: midi_device.cpp

package info (click to toggle)
nageru 2.3.2-1
  • links: PTS
  • area: main
  • in suites: forky, sid
  • size: 3,120 kB
  • sloc: cpp: 39,131; perl: 94; sh: 18; makefile: 4
file content (296 lines) | stat: -rw-r--r-- 9,417 bytes parent folder | download | duplicates (4)
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
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
#include "midi_device.h"

#include <alsa/asoundlib.h>
#include <sys/eventfd.h>
#include <unistd.h>
#include <thread>
#include <utility>

using namespace std;

MIDIDevice::MIDIDevice(MIDIReceiver *receiver)
	: receiver(receiver)
{
	should_quit_fd = eventfd(/*initval=*/0, /*flags=*/0);
	assert(should_quit_fd != -1);
}

MIDIDevice::~MIDIDevice()
{
	should_quit = true;
	const uint64_t one = 1;
	if (write(should_quit_fd, &one, sizeof(one)) != sizeof(one)) {
		perror("write(should_quit_fd)");
		abort();
	}
	midi_thread.join();
	close(should_quit_fd);
}

void MIDIDevice::start_thread()
{
	midi_thread = thread(&MIDIDevice::thread_func, this);
}

#define RETURN_ON_ERROR(msg, expr) do {                            \
	int err = (expr);                                          \
	if (err < 0) {                                             \
		fprintf(stderr, msg ": %s\n", snd_strerror(err));  \
		return;                                            \
	}                                                          \
} while (false)

#define WARN_ON_ERROR(msg, expr) do {                              \
	int err = (expr);                                          \
	if (err < 0) {                                             \
		fprintf(stderr, msg ": %s\n", snd_strerror(err));  \
	}                                                          \
} while (false)


void MIDIDevice::thread_func()
{
	pthread_setname_np(pthread_self(), "MIDIDevice");

	snd_seq_t *seq;
	int err;

	RETURN_ON_ERROR("snd_seq_open", snd_seq_open(&seq, "default", SND_SEQ_OPEN_DUPLEX, 0));
	RETURN_ON_ERROR("snd_seq_nonblock", snd_seq_nonblock(seq, 1));
	RETURN_ON_ERROR("snd_seq_client_name", snd_seq_set_client_name(seq, "nageru"));
	RETURN_ON_ERROR("snd_seq_create_simple_port",
		snd_seq_create_simple_port(seq, "nageru",
			SND_SEQ_PORT_CAP_READ |
				SND_SEQ_PORT_CAP_SUBS_READ |
				SND_SEQ_PORT_CAP_WRITE |
				SND_SEQ_PORT_CAP_SUBS_WRITE,
			SND_SEQ_PORT_TYPE_MIDI_GENERIC |
				SND_SEQ_PORT_TYPE_APPLICATION));

	int queue_id = snd_seq_alloc_queue(seq);
	RETURN_ON_ERROR("snd_seq_create_queue", queue_id);
	RETURN_ON_ERROR("snd_seq_start_queue", snd_seq_start_queue(seq, queue_id, nullptr));

	// The sequencer object is now ready to be used from other threads.
	{
		lock_guard<recursive_mutex> lock(mu);
		alsa_seq = seq;
		alsa_queue_id = queue_id;
	}

	// Listen to the announce port (0:1), which will tell us about new ports.
	RETURN_ON_ERROR("snd_seq_connect_from", snd_seq_connect_from(seq, 0, /*client=*/0, /*port=*/1));

	// Now go through all ports and subscribe to them.
	snd_seq_client_info_t *cinfo;
	snd_seq_client_info_alloca(&cinfo);

	snd_seq_client_info_set_client(cinfo, -1);
	while (snd_seq_query_next_client(seq, cinfo) >= 0) {
		int client = snd_seq_client_info_get_client(cinfo);

		snd_seq_port_info_t *pinfo;
		snd_seq_port_info_alloca(&pinfo);

		snd_seq_port_info_set_client(pinfo, client);
		snd_seq_port_info_set_port(pinfo, -1);
		while (snd_seq_query_next_port(seq, pinfo) >= 0) {
			constexpr int mask = SND_SEQ_PORT_CAP_READ | SND_SEQ_PORT_CAP_SUBS_READ;
			if ((snd_seq_port_info_get_capability(pinfo) & mask) == mask) {
				lock_guard<recursive_mutex> lock(mu);
				subscribe_to_port_lock_held(seq, *snd_seq_port_info_get_addr(pinfo));
			}
		}
	}

	int num_alsa_fds = snd_seq_poll_descriptors_count(seq, POLLIN);
	unique_ptr<pollfd[]> fds(new pollfd[num_alsa_fds + 1]);

	while (!should_quit) {
		snd_seq_poll_descriptors(seq, fds.get(), num_alsa_fds, POLLIN);
		fds[num_alsa_fds].fd = should_quit_fd;
		fds[num_alsa_fds].events = POLLIN;
		fds[num_alsa_fds].revents = 0;

		err = poll(fds.get(), num_alsa_fds + 1, -1);
		if (err == 0 || (err == -1 && errno == EINTR)) {
			continue;
		}
		if (err == -1) {
			perror("poll");
			break;
		}
		if (fds[num_alsa_fds].revents) {
			// Activity on should_quit_fd.
			break;
		}

		// Seemingly we can get multiple events in a single poll,
		// and if we don't handle them all, poll will _not_ alert us!
		while (!should_quit) {
			snd_seq_event_t *event;
			err = snd_seq_event_input(seq, &event);
			if (err < 0) {
				if (err == -EINTR) continue;
				if (err == -EAGAIN) break;
				if (err == -ENOSPC) {
					fprintf(stderr, "snd_seq_event_input: Some events were lost.\n");
					continue;
				}
				fprintf(stderr, "snd_seq_event_input: %s\n", snd_strerror(err));
				return;
			}
			if (event) {
				handle_event(seq, event);
			}
		}
	}
}

void MIDIDevice::handle_event(snd_seq_t *seq, snd_seq_event_t *event)
{
	if (event->source.client == snd_seq_client_id(seq)) {
		// Ignore events we sent out ourselves.
		return;
	}

	switch (event->type) {
	case SND_SEQ_EVENT_CONTROLLER: {
		receiver->controller_received(event->data.control.param, event->data.control.value);
		break;
	}
	case SND_SEQ_EVENT_PITCHBEND: {
		// Note, -8192 to 8191 instead of 0 to 127.
		receiver->controller_received(MIDIReceiver::PITCH_BEND_CONTROLLER, event->data.control.value);
		break;
	}
	case SND_SEQ_EVENT_NOTEON: {
		receiver->note_on_received(event->data.note.note);
		break;
	}
	case SND_SEQ_EVENT_PORT_START: {
		lock_guard<recursive_mutex> lock(mu);
		subscribe_to_port_lock_held(seq, event->data.addr);
		break;
	}
	case SND_SEQ_EVENT_PORT_EXIT:
		printf("MIDI port %d:%d went away.\n", event->data.addr.client, event->data.addr.port);
		break;
	case SND_SEQ_EVENT_PORT_SUBSCRIBED:
		if (event->data.connect.sender.client != 0 &&  // Ignore system senders.
		    event->data.connect.sender.client != snd_seq_client_id(seq) &&
		    event->data.connect.dest.client == snd_seq_client_id(seq)) {
			receiver->update_num_subscribers(++num_subscribed_ports);
		}
		break;
	case SND_SEQ_EVENT_PORT_UNSUBSCRIBED:
		if (event->data.connect.sender.client != 0 &&  // Ignore system senders.
		    event->data.connect.sender.client != snd_seq_client_id(seq) &&
		    event->data.connect.dest.client == snd_seq_client_id(seq)) {
			receiver->update_num_subscribers(--num_subscribed_ports);
		}
		break;
	case SND_SEQ_EVENT_NOTEOFF:
	case SND_SEQ_EVENT_CLIENT_START:
	case SND_SEQ_EVENT_CLIENT_EXIT:
	case SND_SEQ_EVENT_CLIENT_CHANGE:
	case SND_SEQ_EVENT_PORT_CHANGE:
		break;
	default:
		printf("Ignoring MIDI event of unknown type %d.\n", event->type);
	}
}

void MIDIDevice::subscribe_to_port_lock_held(snd_seq_t *seq, const snd_seq_addr_t &addr)
{
	// Client 0 (SNDRV_SEQ_CLIENT_SYSTEM) is basically the system; ignore it.
	// MIDI through (SNDRV_SEQ_CLIENT_DUMMY) echoes back what we give it, so ignore that, too.
	if (addr.client == 0 || addr.client == 14) {
		return;
	}

	// Don't listen to ourselves.
	if (addr.client == snd_seq_client_id(seq)) {
		return;
	}

	int err = snd_seq_connect_from(seq, 0, addr.client, addr.port);
	if (err < 0) {
		// Just print out a warning (i.e., don't die); it could
		// very well just be e.g. another application.
		printf("Couldn't subscribe to MIDI port %d:%d (%s).\n",
			addr.client, addr.port, snd_strerror(err));
	} else {
		printf("Subscribed to MIDI port %d:%d.\n", addr.client, addr.port);
	}

	// For sending data back.
	err = snd_seq_connect_to(seq, 0, addr.client, addr.port);
	if (err < 0) {
		printf("Couldn't subscribe MIDI port %d:%d (%s) to us.\n",
			addr.client, addr.port, snd_strerror(err));
	} else {
		printf("Subscribed MIDI port %d:%d to us.\n", addr.client, addr.port);
	}

	// The current status of the device is unknown, so refresh it.
	map<LightKey, uint8_t> active_lights = move(current_light_status);
	current_light_status.clear();
	update_lights_lock_held(active_lights);
}

void MIDIDevice::update_lights_lock_held(const map<LightKey, uint8_t> &active_lights)
{
	if (alsa_seq == nullptr) {
		return;
	}

	unsigned num_events = 0;
	for (auto type : { LightKey::NOTE, LightKey::CONTROLLER }) {
		for (unsigned num = 1; num <= 127; ++num) {  // Note: Pitch bend is ignored.
			LightKey key{type, num};
			const auto it = active_lights.find(key);
			uint8_t value;  // Velocity for notes, controller value for controllers.

			// Notes have a natural “off”, while controllers don't really.
			// For some reason, not all devices respond to note off.
			// Use note-on with value of 0 (which is equivalent) instead.
			if (it == active_lights.end()) {
				// Notes have a natural “off”, while controllers don't really,
				// so just skip them if we have no set value.
				if (type == LightKey::CONTROLLER) continue;

				// For some reason, not all devices respond to note off.
				// Use note-on with value of 0 (which is equivalent) instead.
				value = 0;
			} else {
				value = it->second;
			}
			if (current_light_status.count(key) &&
			    current_light_status[key] == value) {
				// Already known to be in the desired state.
				continue;
			}

			snd_seq_event_t ev;
			snd_seq_ev_clear(&ev);

			// Some devices drop events if we throw them onto them
			// too quickly. Add a 1 ms delay for each.
			snd_seq_real_time_t tm{0, num_events++ * 1000000};
			snd_seq_ev_schedule_real(&ev, alsa_queue_id, true, &tm);
			snd_seq_ev_set_source(&ev, 0);
			snd_seq_ev_set_subs(&ev);

			if (type == LightKey::NOTE) {
				snd_seq_ev_set_noteon(&ev, /*channel=*/0, num, value);
				current_light_status[key] = value;
			} else {
				snd_seq_ev_set_controller(&ev, /*channel=*/0, num, value);
				current_light_status[key] = value;
			}
			WARN_ON_ERROR("snd_seq_event_output", snd_seq_event_output(alsa_seq, &ev));
		}
	}
	WARN_ON_ERROR("snd_seq_drain_output", snd_seq_drain_output(alsa_seq));
}