1 /* ScummVM - Graphic Adventure Engine
2  *
3  * ScummVM is the legal property of its developers, whose names
4  * are too numerous to list here. Please refer to the COPYRIGHT
5  * file distributed with this source distribution.
6  *
7  * This program is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU General Public License
9  * as published by the Free Software Foundation; either version 2
10  * of the License, or (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with this program; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
20  *
21  */
22 
23 // Disable symbol overrides so that we can use system headers.
24 #define FORBIDDEN_SYMBOL_ALLOW_ALL
25 
26 #include "common/scummsys.h"
27 
28 #if defined(USE_ALSA)
29 
30 #include "common/config-manager.h"
31 #include "common/error.h"
32 #include "common/textconsole.h"
33 #include "common/util.h"
34 #include "audio/musicplugin.h"
35 #include "audio/mpu401.h"
36 
37 #include <alsa/asoundlib.h>
38 
39 /*
40  *     ALSA sequencer driver
41  * Mostly cut'n'pasted from Virtual Tiny Keyboard (vkeybd) by Takashi Iwai
42  *                                      (you really rox, you know?)
43  */
44 
45 #if SND_LIB_MAJOR >= 1 || SND_LIB_MINOR >= 6
46 #define snd_seq_flush_output(x) snd_seq_drain_output(x)
47 #define snd_seq_set_client_group(x,name)    /*nop */
48 #define my_snd_seq_open(seqp) snd_seq_open(seqp, "hw", SND_SEQ_OPEN_DUPLEX, 0)
49 #else
50 /* SND_SEQ_OPEN_OUT causes oops on early version of ALSA */
51 #define my_snd_seq_open(seqp) snd_seq_open(seqp, SND_SEQ_OPEN)
52 #endif
53 
54 #define perm_ok(pinfo,bits) ((snd_seq_port_info_get_capability(pinfo) & (bits)) == (bits))
55 
check_permission(snd_seq_port_info_t * pinfo)56 static int check_permission(snd_seq_port_info_t *pinfo) {
57 	if (perm_ok(pinfo, SND_SEQ_PORT_CAP_WRITE | SND_SEQ_PORT_CAP_SUBS_WRITE)) {
58 		if (!(snd_seq_port_info_get_capability(pinfo) & SND_SEQ_PORT_CAP_NO_EXPORT))
59 			return 1;
60 	}
61 	return 0;
62 }
63 
64 /*
65  * parse address string
66  */
67 
68 #define ADDR_DELIM      ".:"
69 
70 class MidiDriver_ALSA : public MidiDriver_MPU401 {
71 public:
72 	MidiDriver_ALSA(int client, int port);
73 	int open();
isOpen() const74 	bool isOpen() const { return _isOpen; }
75 	void close();
76 	void send(uint32 b);
77 	void sysEx(const byte *msg, uint16 length);
78 
79 private:
80 	void send_event(int do_flush);
81 	bool _isOpen;
82 	snd_seq_event_t ev;
83 	snd_seq_t *seq_handle;
84 	int seq_client, seq_port;
85 	int my_client, my_port;
86 	// The volume controller value of the first MIDI channel
87 	int8 _channel0Volume;
88 };
89 
MidiDriver_ALSA(int client,int port)90 MidiDriver_ALSA::MidiDriver_ALSA(int client, int port)
91 	: _isOpen(false), seq_handle(0), seq_client(client), seq_port(port), my_client(0), my_port(0), _channel0Volume(127) {
92 	memset(&ev, 0, sizeof(ev));
93 }
94 
open()95 int MidiDriver_ALSA::open() {
96 	if (_isOpen)
97 		return MERR_ALREADY_OPEN;
98 	_isOpen = true;
99 
100 	if (my_snd_seq_open(&seq_handle) < 0) {
101 		error("Can't open sequencer");
102 		return -1;
103 	}
104 
105 	my_client = snd_seq_client_id(seq_handle);
106 	if (snd_seq_set_client_name(seq_handle, "RESIDUALVM") < 0) {
107 		error("Can't set sequencer client name");
108 	}
109 	snd_seq_set_client_group(seq_handle, "input");
110 
111 	// According to http://www.alsa-project.org/~tiwai/alsa-subs.html
112 	// you can set read or write capabilities to allow other clients to
113 	// read or write the port. I don't think we need that, unless maybe
114 	// to be able to record the sound, but I can't get that to work even
115 	// with those capabilities.
116 
117 	my_port = snd_seq_create_simple_port(seq_handle, "RESIDUALVM port 0", 0,
118 	                                     SND_SEQ_PORT_TYPE_MIDI_GENERIC | SND_SEQ_PORT_TYPE_APPLICATION);
119 
120 	if (my_port < 0) {
121 		snd_seq_close(seq_handle);
122 		error("Can't create port");
123 		return -1;
124 	}
125 
126 	if (seq_client != SND_SEQ_ADDRESS_SUBSCRIBERS) {
127 		// Subscribe to MIDI port. Prefer one that doesn't already have
128 		// any connections, unless we've forced a port number already.
129 		if (seq_port == -1) {
130 			snd_seq_client_info_t *cinfo;
131 			snd_seq_port_info_t *pinfo;
132 
133 			snd_seq_client_info_alloca(&cinfo);
134 			snd_seq_port_info_alloca(&pinfo);
135 
136 			snd_seq_get_any_client_info(seq_handle, seq_client, cinfo);
137 
138 			int first_port = -1;
139 			int found_port = -1;
140 
141 			snd_seq_port_info_set_client(pinfo, seq_client);
142 			snd_seq_port_info_set_port(pinfo, -1);
143 			while (found_port == -1 && snd_seq_query_next_port(seq_handle, pinfo) >= 0) {
144 				if (check_permission(pinfo)) {
145 					if (first_port == -1)
146 						first_port = snd_seq_port_info_get_port(pinfo);
147 					if (found_port == -1 && snd_seq_port_info_get_write_use(pinfo) == 0)
148 						found_port = snd_seq_port_info_get_port(pinfo);
149 				}
150 			}
151 
152 			if (found_port == -1) {
153 				// Should we abort here? For now, use the first
154 				// available port.
155 				seq_port = first_port;
156 				warning("MidiDriver_ALSA: All ports on client %d (%s) are already in use", seq_client, snd_seq_client_info_get_name(cinfo));
157 			} else {
158 				seq_port = found_port;
159 			}
160 		}
161 
162 		if (snd_seq_connect_to(seq_handle, my_port, seq_client, seq_port) < 0) {
163 			error("Can't subscribe to MIDI port (%d:%d) see README for help", seq_client, seq_port);
164 		}
165 	}
166 
167 	printf("Connected to Alsa sequencer client [%d:%d]\n", seq_client, seq_port);
168 	printf("ALSA client initialized [%d:0]\n", my_client);
169 
170 	return 0;
171 }
172 
close()173 void MidiDriver_ALSA::close() {
174 	if (_isOpen) {
175 		_isOpen = false;
176 		MidiDriver_MPU401::close();
177 		if (seq_handle)
178 			snd_seq_close(seq_handle);
179 	} else
180 		warning("MidiDriver_ALSA: Closing the driver before opening it");
181 }
182 
send(uint32 b)183 void MidiDriver_ALSA::send(uint32 b) {
184 	if (!_isOpen) {
185 		warning("MidiDriver_ALSA: Got event while not open");
186 		return;
187 	}
188 
189 	unsigned int midiCmd[4];
190 	ev.type = SND_SEQ_EVENT_OSS;
191 
192 	midiCmd[3] = (b & 0xFF000000) >> 24;
193 	midiCmd[2] = (b & 0x00FF0000) >> 16;
194 	midiCmd[1] = (b & 0x0000FF00) >> 8;
195 	midiCmd[0] = (b & 0x000000FF);
196 	ev.data.raw32.d[0] = midiCmd[0];
197 	ev.data.raw32.d[1] = midiCmd[1];
198 	ev.data.raw32.d[2] = midiCmd[2];
199 
200 	unsigned char chanID = midiCmd[0] & 0x0F;
201 	switch (midiCmd[0] & 0xF0) {
202 	case 0x80:
203 		snd_seq_ev_set_noteoff(&ev, chanID, midiCmd[1], midiCmd[2]);
204 		send_event(1);
205 		break;
206 	case 0x90:
207 		snd_seq_ev_set_noteon(&ev, chanID, midiCmd[1], midiCmd[2]);
208 		send_event(1);
209 		break;
210 	case 0xA0:
211 		snd_seq_ev_set_keypress(&ev, chanID, midiCmd[1], midiCmd[2]);
212 		send_event(1);
213 		break;
214 	case 0xB0:
215 		/* is it this simple ? Wow... */
216 		snd_seq_ev_set_controller(&ev, chanID, midiCmd[1], midiCmd[2]);
217 
218 		// We save the volume of the first MIDI channel here to utilize it in
219 		// our workaround for broken USB-MIDI cables.
220 		if (chanID == 0 && midiCmd[1] == 0x07)
221 			_channel0Volume = midiCmd[2];
222 
223 		send_event(1);
224 		break;
225 	case 0xC0:
226 		snd_seq_ev_set_pgmchange(&ev, chanID, midiCmd[1]);
227 		send_event(0);
228 
229 		// Send a volume change command to work around a firmware bug in common
230 		// USB-MIDI cables. If the first MIDI command in a USB packet is a
231 		// Cx or Dx command, the second command in the packet is dropped
232 		// somewhere.
233 		send(0x07B0 | (_channel0Volume << 16));
234 		break;
235 	case 0xD0:
236 		snd_seq_ev_set_chanpress(&ev, chanID, midiCmd[1]);
237 		send_event(1);
238 
239 		// Send a volume change command to work around a firmware bug in common
240 		// USB-MIDI cables. If the first MIDI command in a USB packet is a
241 		// Cx or Dx command, the second command in the packet is dropped
242 		// somewhere.
243 		send(0x07B0 | (_channel0Volume << 16));
244 		break;
245 	case 0xE0: {
246 		// long theBend = ((((long)midiCmd[1] + (long)(midiCmd[2] << 7))) - 0x2000) / 4;
247 		// snd_seq_ev_set_pitchbend(&ev, chanID, theBend);
248 		long theBend = ((long)midiCmd[1] + (long)(midiCmd[2] << 7)) - 0x2000;
249 		snd_seq_ev_set_pitchbend(&ev, chanID, theBend);
250 		send_event(1);
251 		} break;
252 
253 	default:
254 		warning("Unknown MIDI Command: %08x", (int)b);
255 		/* I don't know if this works but, well... */
256 		send_event(1);
257 		break;
258 	}
259 }
260 
sysEx(const byte * msg,uint16 length)261 void MidiDriver_ALSA::sysEx(const byte *msg, uint16 length) {
262 	if (!_isOpen) {
263 		warning("MidiDriver_ALSA: Got SysEx while not open");
264 		return;
265 	}
266 
267 	unsigned char buf[266];
268 
269 	assert(length + 2 <= ARRAYSIZE(buf));
270 
271 	// Add SysEx frame
272 	buf[0] = 0xF0;
273 	memcpy(buf + 1, msg, length);
274 	buf[length + 1] = 0xF7;
275 
276 	// Send it
277 	snd_seq_ev_set_sysex(&ev, length + 2, &buf);
278 	send_event(1);
279 }
280 
send_event(int do_flush)281 void MidiDriver_ALSA::send_event(int do_flush) {
282 	snd_seq_ev_set_direct(&ev);
283 	snd_seq_ev_set_source(&ev, my_port);
284 	snd_seq_ev_set_dest(&ev, seq_client, seq_port);
285 
286 	snd_seq_event_output(seq_handle, &ev);
287 	if (do_flush)
288 		snd_seq_flush_output(seq_handle);
289 }
290 
291 
292 // Plugin interface
293 
294 class AlsaDevice {
295 public:
296 	AlsaDevice(Common::String name, MusicType mt, int client);
297 	Common::String getName();
298 	MusicType getType();
299 	int getClient();
300 
301 private:
302 	Common::String _name;
303 	MusicType _type;
304 	int _client;
305 };
306 
307 typedef Common::List<AlsaDevice> AlsaDevices;
308 
AlsaDevice(Common::String name,MusicType mt,int client)309 AlsaDevice::AlsaDevice(Common::String name, MusicType mt, int client)
310 	: _name(name), _type(mt), _client(client) {
311 	// Make sure we do not get any trailing spaces to avoid problems when
312 	// storing the name in the configuration file.
313 	_name.trim();
314 }
315 
getName()316 Common::String AlsaDevice::getName() {
317 	return _name;
318 }
319 
getType()320 MusicType AlsaDevice::getType() {
321 	return _type;
322 }
323 
getClient()324 int AlsaDevice::getClient() {
325 	return _client;
326 }
327 
328 class AlsaMusicPlugin : public MusicPluginObject {
329 public:
getName() const330 	const char *getName() const {
331 		return "ALSA";
332 	}
333 
getId() const334 	const char *getId() const {
335 		return "alsa";
336 	}
337 
338 	AlsaDevices getAlsaDevices() const;
339 	MusicDevices getDevices() const;
340 	Common::Error createInstance(MidiDriver **mididriver, MidiDriver::DeviceHandle = 0) const;
341 
342 private:
343 	static int parse_addr(const char *arg, int *client, int *port);
344 };
345 
getAlsaDevices() const346 AlsaDevices AlsaMusicPlugin::getAlsaDevices() const {
347 	AlsaDevices devices;
348 	snd_seq_t *seq_handle;
349 	if (my_snd_seq_open(&seq_handle) < 0)
350 		return devices; // can't open sequencer
351 
352 	snd_seq_client_info_t *cinfo;
353 	snd_seq_client_info_alloca(&cinfo);
354 	snd_seq_port_info_t *pinfo;
355 	snd_seq_port_info_alloca(&pinfo);
356 	snd_seq_client_info_set_client(cinfo, -1);
357 	while (snd_seq_query_next_client(seq_handle, cinfo) >= 0) {
358 		bool found_valid_port = false;
359 
360 		/* reset query info */
361 		snd_seq_port_info_set_client(pinfo, snd_seq_client_info_get_client(cinfo));
362 		snd_seq_port_info_set_port(pinfo, -1);
363 		while (!found_valid_port && snd_seq_query_next_port(seq_handle, pinfo) >= 0) {
364 			if (check_permission(pinfo)) {
365 				found_valid_port = true;
366 
367 				const char *name = snd_seq_client_info_get_name(cinfo);
368 				// TODO: Can we figure out the appropriate music type?
369 				MusicType type = MT_GM;
370 				int client = snd_seq_client_info_get_client(cinfo);
371 				devices.push_back(AlsaDevice(name, type, client));
372 			}
373 		}
374 	}
375 	snd_seq_close(seq_handle);
376 
377 	return devices;
378 }
379 
getDevices() const380 MusicDevices AlsaMusicPlugin::getDevices() const {
381 	MusicDevices devices;
382 	AlsaDevices::iterator d;
383 
384 	AlsaDevices alsaDevices = getAlsaDevices();
385 
386 	// Since the default behavior is to use the first device in the list,
387 	// try to put something sensible there. We used to have 17:0 and 65:0
388 	// as defaults.
389 
390 	for (d = alsaDevices.begin(); d != alsaDevices.end();) {
391 		const int client = d->getClient();
392 
393 		if (client == 17 || client == 65) {
394 			devices.push_back(MusicDevice(this, d->getName(), d->getType()));
395 			d = alsaDevices.erase(d);
396 		} else {
397 			++d;
398 		}
399 	}
400 
401 	// 128:0 is probably TiMidity, or something like that, so that's
402 	// probably a good second choice.
403 
404 	for (d = alsaDevices.begin(); d != alsaDevices.end();) {
405 		if (d->getClient() == 128) {
406 			devices.push_back(MusicDevice(this, d->getName(), d->getType()));
407 			d = alsaDevices.erase(d);
408 		} else {
409 			++d;
410 		}
411 	}
412 
413 	// Add the remaining devices in the order they were found.
414 
415 	for (d = alsaDevices.begin(); d != alsaDevices.end(); ++d)
416 		devices.push_back(MusicDevice(this, d->getName(), d->getType()));
417 
418 	return devices;
419 }
420 
createInstance(MidiDriver ** mididriver,MidiDriver::DeviceHandle dev) const421 Common::Error AlsaMusicPlugin::createInstance(MidiDriver **mididriver, MidiDriver::DeviceHandle dev) const {
422 	bool found = false;
423 	int seq_client, seq_port;
424 
425 	const char *var = NULL;
426 
427 	// TODO: Upgrade from old alsa_port setting. This probably isn't the
428 	// right place to do that, though.
429 
430 	if (ConfMan.hasKey("alsa_port")) {
431 		warning("AlsaMusicPlugin: Found old 'alsa_port' setting, which will be ignored");
432 	}
433 
434 	// The SCUMMVM_PORT environment variable can still be used to override
435 	// any config setting.
436 
437 	var = getenv("RESIDUALVM_PORT");
438 	if (var) {
439 		warning("AlsaMusicPlugin: RESIDUALVM_PORT environment variable overrides config settings");
440 		if (parse_addr(var, &seq_client, &seq_port) >= 0) {
441 			found = true;
442 		} else {
443 			warning("AlsaMusicPlugin: Invalid port %s, using config settings instead", var);
444 		}
445 	}
446 
447 	// Try to match the setting to an available ALSA device.
448 
449 	if (!found && dev) {
450 		AlsaDevices alsaDevices = getAlsaDevices();
451 
452 		for (AlsaDevices::iterator d = alsaDevices.begin(); d != alsaDevices.end(); ++d) {
453 			MusicDevice device(this, d->getName(), d->getType());
454 
455 			if (device.getCompleteId().equals(MidiDriver::getDeviceString(dev, MidiDriver::kDeviceId))) {
456 				found = true;
457 				seq_client = d->getClient();
458 				seq_port = -1;
459 				break;
460 			}
461 		}
462 	}
463 
464 	// Still nothing? Try a sensible default.
465 
466 	if (!found) {
467 		// TODO: What's a sensible default anyway? And exactly when do
468 		// we get to this case?
469 
470 		warning("AlsaMusicPlugin: Using 17:0 as default ALSA port");
471 		seq_client = 17;
472 		seq_port = 0;
473 	}
474 
475 	*mididriver = new MidiDriver_ALSA(seq_client, seq_port);
476 
477 	return Common::kNoError;
478 }
479 
parse_addr(const char * arg,int * client,int * port)480 int AlsaMusicPlugin::parse_addr(const char *arg, int *client, int *port) {
481 	const char *p;
482 
483 	if (isdigit(*arg)) {
484 		if ((p = strpbrk(arg, ADDR_DELIM)) == NULL)
485 			return -1;
486 		*client = atoi(arg);
487 		*port = atoi(p + 1);
488 	} else {
489 		if (*arg == 's' || *arg == 'S') {
490 			*client = SND_SEQ_ADDRESS_SUBSCRIBERS;
491 			*port = 0;
492 		} else
493 			return -1;
494 	}
495 	return 0;
496 }
497 
498 //#if PLUGIN_ENABLED_DYNAMIC(ALSA)
499 	//REGISTER_PLUGIN_DYNAMIC(ALSA, PLUGIN_TYPE_MUSIC, AlsaMusicPlugin);
500 //#else
501 	REGISTER_PLUGIN_STATIC(ALSA, PLUGIN_TYPE_MUSIC, AlsaMusicPlugin);
502 //#endif
503 
504 #endif
505