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) override;
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, "SCUMMVM") < 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, "SCUMMVM 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 	midiDriverCommonSend(b);
190 
191 	unsigned int midiCmd[4];
192 	ev.type = SND_SEQ_EVENT_OSS;
193 
194 	midiCmd[3] = (b & 0xFF000000) >> 24;
195 	midiCmd[2] = (b & 0x00FF0000) >> 16;
196 	midiCmd[1] = (b & 0x0000FF00) >> 8;
197 	midiCmd[0] = (b & 0x000000FF);
198 	ev.data.raw32.d[0] = midiCmd[0];
199 	ev.data.raw32.d[1] = midiCmd[1];
200 	ev.data.raw32.d[2] = midiCmd[2];
201 
202 	unsigned char chanID = midiCmd[0] & 0x0F;
203 	switch (midiCmd[0] & 0xF0) {
204 	case 0x80:
205 		snd_seq_ev_set_noteoff(&ev, chanID, midiCmd[1], midiCmd[2]);
206 		send_event(1);
207 		break;
208 	case 0x90:
209 		snd_seq_ev_set_noteon(&ev, chanID, midiCmd[1], midiCmd[2]);
210 		send_event(1);
211 		break;
212 	case 0xA0:
213 		snd_seq_ev_set_keypress(&ev, chanID, midiCmd[1], midiCmd[2]);
214 		send_event(1);
215 		break;
216 	case 0xB0:
217 		/* is it this simple ? Wow... */
218 		snd_seq_ev_set_controller(&ev, chanID, midiCmd[1], midiCmd[2]);
219 
220 		// We save the volume of the first MIDI channel here to utilize it in
221 		// our workaround for broken USB-MIDI cables.
222 		if (chanID == 0 && midiCmd[1] == 0x07)
223 			_channel0Volume = midiCmd[2];
224 
225 		send_event(1);
226 		break;
227 	case 0xC0:
228 		snd_seq_ev_set_pgmchange(&ev, chanID, midiCmd[1]);
229 		send_event(0);
230 
231 		// Send a volume change command to work around a firmware bug in common
232 		// USB-MIDI cables. If the first MIDI command in a USB packet is a
233 		// Cx or Dx command, the second command in the packet is dropped
234 		// somewhere.
235 		send(0x07B0 | (_channel0Volume << 16));
236 		break;
237 	case 0xD0:
238 		snd_seq_ev_set_chanpress(&ev, chanID, midiCmd[1]);
239 		send_event(1);
240 
241 		// Send a volume change command to work around a firmware bug in common
242 		// USB-MIDI cables. If the first MIDI command in a USB packet is a
243 		// Cx or Dx command, the second command in the packet is dropped
244 		// somewhere.
245 		send(0x07B0 | (_channel0Volume << 16));
246 		break;
247 	case 0xE0: {
248 		// long theBend = ((((long)midiCmd[1] + (long)(midiCmd[2] << 7))) - 0x2000) / 4;
249 		// snd_seq_ev_set_pitchbend(&ev, chanID, theBend);
250 		long theBend = ((long)midiCmd[1] + (long)(midiCmd[2] << 7)) - 0x2000;
251 		snd_seq_ev_set_pitchbend(&ev, chanID, theBend);
252 		send_event(1);
253 		} break;
254 
255 	default:
256 		warning("Unknown MIDI Command: %08x", (int)b);
257 		/* I don't know if this works but, well... */
258 		send_event(1);
259 		break;
260 	}
261 }
262 
sysEx(const byte * msg,uint16 length)263 void MidiDriver_ALSA::sysEx(const byte *msg, uint16 length) {
264 	if (!_isOpen) {
265 		warning("MidiDriver_ALSA: Got SysEx while not open");
266 		return;
267 	}
268 
269 	unsigned char buf[266];
270 
271 	assert(length + 2 <= ARRAYSIZE(buf));
272 
273 	midiDriverCommonSysEx(msg, length);
274 
275 	// Add SysEx frame
276 	buf[0] = 0xF0;
277 	memcpy(buf + 1, msg, length);
278 	buf[length + 1] = 0xF7;
279 
280 	// Send it
281 	snd_seq_ev_set_sysex(&ev, length + 2, &buf);
282 	send_event(1);
283 }
284 
send_event(int do_flush)285 void MidiDriver_ALSA::send_event(int do_flush) {
286 	snd_seq_ev_set_direct(&ev);
287 	snd_seq_ev_set_source(&ev, my_port);
288 	snd_seq_ev_set_dest(&ev, seq_client, seq_port);
289 
290 	snd_seq_event_output(seq_handle, &ev);
291 	if (do_flush)
292 		snd_seq_flush_output(seq_handle);
293 }
294 
295 
296 // Plugin interface
297 
298 class AlsaDevice {
299 public:
300 	AlsaDevice(Common::String name, MusicType mt, int client);
301 	Common::String getName();
302 	MusicType getType();
303 	int getClient();
304 
305 private:
306 	Common::String _name;
307 	MusicType _type;
308 	int _client;
309 };
310 
311 typedef Common::List<AlsaDevice> AlsaDevices;
312 
AlsaDevice(Common::String name,MusicType mt,int client)313 AlsaDevice::AlsaDevice(Common::String name, MusicType mt, int client)
314 	: _name(name), _type(mt), _client(client) {
315 	// Make sure we do not get any trailing spaces to avoid problems when
316 	// storing the name in the configuration file.
317 	_name.trim();
318 }
319 
getName()320 Common::String AlsaDevice::getName() {
321 	return _name;
322 }
323 
getType()324 MusicType AlsaDevice::getType() {
325 	return _type;
326 }
327 
getClient()328 int AlsaDevice::getClient() {
329 	return _client;
330 }
331 
332 class AlsaMusicPlugin : public MusicPluginObject {
333 public:
getName() const334 	const char *getName() const {
335 		return "ALSA";
336 	}
337 
getId() const338 	const char *getId() const {
339 		return "alsa";
340 	}
341 
342 	AlsaDevices getAlsaDevices() const;
343 	MusicDevices getDevices() const;
344 	Common::Error createInstance(MidiDriver **mididriver, MidiDriver::DeviceHandle = 0) const;
345 
346 private:
347 	static int parse_addr(const char *arg, int *client, int *port);
348 };
349 
getAlsaDevices() const350 AlsaDevices AlsaMusicPlugin::getAlsaDevices() const {
351 	AlsaDevices devices;
352 	snd_seq_t *seq_handle;
353 	if (my_snd_seq_open(&seq_handle) < 0)
354 		return devices; // can't open sequencer
355 
356 	snd_seq_client_info_t *cinfo;
357 	snd_seq_client_info_alloca(&cinfo);
358 	snd_seq_port_info_t *pinfo;
359 	snd_seq_port_info_alloca(&pinfo);
360 	snd_seq_client_info_set_client(cinfo, -1);
361 	while (snd_seq_query_next_client(seq_handle, cinfo) >= 0) {
362 		bool found_valid_port = false;
363 
364 		/* reset query info */
365 		snd_seq_port_info_set_client(pinfo, snd_seq_client_info_get_client(cinfo));
366 		snd_seq_port_info_set_port(pinfo, -1);
367 		while (!found_valid_port && snd_seq_query_next_port(seq_handle, pinfo) >= 0) {
368 			if (check_permission(pinfo)) {
369 				found_valid_port = true;
370 
371 				const char *name = snd_seq_client_info_get_name(cinfo);
372 				// TODO: Can we figure out the appropriate music type?
373 				MusicType type = MT_GM;
374 				int client = snd_seq_client_info_get_client(cinfo);
375 				devices.push_back(AlsaDevice(name, type, client));
376 			}
377 		}
378 	}
379 	snd_seq_close(seq_handle);
380 
381 	return devices;
382 }
383 
getDevices() const384 MusicDevices AlsaMusicPlugin::getDevices() const {
385 	MusicDevices devices;
386 	AlsaDevices::iterator d;
387 
388 	AlsaDevices alsaDevices = getAlsaDevices();
389 
390 	// Since the default behavior is to use the first device in the list,
391 	// try to put something sensible there. We used to have 17:0 and 65:0
392 	// as defaults.
393 
394 	for (d = alsaDevices.begin(); d != alsaDevices.end();) {
395 		const int client = d->getClient();
396 
397 		if (client == 17 || client == 65) {
398 			devices.push_back(MusicDevice(this, d->getName(), d->getType()));
399 			d = alsaDevices.erase(d);
400 		} else {
401 			++d;
402 		}
403 	}
404 
405 	// 128:0 is probably TiMidity, or something like that, so that's
406 	// probably a good second choice.
407 
408 	for (d = alsaDevices.begin(); d != alsaDevices.end();) {
409 		if (d->getClient() == 128) {
410 			devices.push_back(MusicDevice(this, d->getName(), d->getType()));
411 			d = alsaDevices.erase(d);
412 		} else {
413 			++d;
414 		}
415 	}
416 
417 	// Add the remaining devices in the order they were found.
418 
419 	for (d = alsaDevices.begin(); d != alsaDevices.end(); ++d)
420 		devices.push_back(MusicDevice(this, d->getName(), d->getType()));
421 
422 	return devices;
423 }
424 
createInstance(MidiDriver ** mididriver,MidiDriver::DeviceHandle dev) const425 Common::Error AlsaMusicPlugin::createInstance(MidiDriver **mididriver, MidiDriver::DeviceHandle dev) const {
426 	bool found = false;
427 	int seq_client, seq_port;
428 
429 	const char *var = NULL;
430 
431 	// TODO: Upgrade from old alsa_port setting. This probably isn't the
432 	// right place to do that, though.
433 
434 	if (ConfMan.hasKey("alsa_port")) {
435 		warning("AlsaMusicPlugin: Found old 'alsa_port' setting, which will be ignored");
436 	}
437 
438 	// The SCUMMVM_PORT environment variable can still be used to override
439 	// any config setting.
440 
441 	var = getenv("SCUMMVM_PORT");
442 	if (var) {
443 		warning("AlsaMusicPlugin: SCUMMVM_PORT environment variable overrides config settings");
444 		if (parse_addr(var, &seq_client, &seq_port) >= 0) {
445 			found = true;
446 		} else {
447 			warning("AlsaMusicPlugin: Invalid port %s, using config settings instead", var);
448 		}
449 	}
450 
451 	// Try to match the setting to an available ALSA device.
452 
453 	if (!found && dev) {
454 		AlsaDevices alsaDevices = getAlsaDevices();
455 
456 		for (AlsaDevices::iterator d = alsaDevices.begin(); d != alsaDevices.end(); ++d) {
457 			MusicDevice device(this, d->getName(), d->getType());
458 
459 			if (device.getCompleteId().equals(MidiDriver::getDeviceString(dev, MidiDriver::kDeviceId))) {
460 				found = true;
461 				seq_client = d->getClient();
462 				seq_port = -1;
463 				break;
464 			}
465 		}
466 	}
467 
468 	// Still nothing? Try a sensible default.
469 
470 	if (!found) {
471 		// TODO: What's a sensible default anyway? And exactly when do
472 		// we get to this case?
473 
474 		warning("AlsaMusicPlugin: Using 17:0 as default ALSA port");
475 		seq_client = 17;
476 		seq_port = 0;
477 	}
478 
479 	*mididriver = new MidiDriver_ALSA(seq_client, seq_port);
480 
481 	return Common::kNoError;
482 }
483 
parse_addr(const char * arg,int * client,int * port)484 int AlsaMusicPlugin::parse_addr(const char *arg, int *client, int *port) {
485 	const char *p;
486 
487 	if (isdigit(*arg)) {
488 		if ((p = strpbrk(arg, ADDR_DELIM)) == NULL)
489 			return -1;
490 		*client = atoi(arg);
491 		*port = atoi(p + 1);
492 	} else {
493 		if (*arg == 's' || *arg == 'S') {
494 			*client = SND_SEQ_ADDRESS_SUBSCRIBERS;
495 			*port = 0;
496 		} else
497 			return -1;
498 	}
499 	return 0;
500 }
501 
502 //#if PLUGIN_ENABLED_DYNAMIC(ALSA)
503 	//REGISTER_PLUGIN_DYNAMIC(ALSA, PLUGIN_TYPE_MUSIC, AlsaMusicPlugin);
504 //#else
505 	REGISTER_PLUGIN_STATIC(ALSA, PLUGIN_TYPE_MUSIC, AlsaMusicPlugin);
506 //#endif
507 
508 #endif
509