Initial commit

This commit is contained in:
2026-02-02 04:50:13 +01:00
commit 5b11698731
22592 changed files with 7677434 additions and 0 deletions

516
backends/midi/alsa.cpp Normal file
View File

@@ -0,0 +1,516 @@
/* ScummVM - Graphic Adventure Engine
*
* ScummVM is the legal property of its developers, whose names
* are too numerous to list here. Please refer to the COPYRIGHT
* file distributed with this source distribution.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program 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 <http://www.gnu.org/licenses/>.
*
*/
// Disable symbol overrides so that we can use system headers.
#define FORBIDDEN_SYMBOL_ALLOW_ALL
#include "common/scummsys.h"
#if defined(USE_ALSA)
#include "common/config-manager.h"
#include "common/error.h"
#include "common/textconsole.h"
#include "common/util.h"
#include "audio/musicplugin.h"
#include "audio/mpu401.h"
#include <alsa/asoundlib.h>
#define MIDI_USB_HACK
/*
* ALSA sequencer driver
* Mostly cut'n'pasted from Virtual Tiny Keyboard (vkeybd) by Takashi Iwai
* (you really rox, you know?)
*/
#if SND_LIB_MAJOR >= 1 || SND_LIB_MINOR >= 6
#define snd_seq_flush_output(x) snd_seq_drain_output(x)
#define snd_seq_set_client_group(x,name) /*nop */
#define my_snd_seq_open(seqp) snd_seq_open(seqp, "hw", SND_SEQ_OPEN_DUPLEX, 0)
#else
/* SND_SEQ_OPEN_OUT causes oops on early version of ALSA */
#define my_snd_seq_open(seqp) snd_seq_open(seqp, SND_SEQ_OPEN)
#endif
#define perm_ok(pinfo,bits) ((snd_seq_port_info_get_capability(pinfo) & (bits)) == (bits))
static int check_permission(snd_seq_port_info_t *pinfo) {
if (perm_ok(pinfo, SND_SEQ_PORT_CAP_WRITE | SND_SEQ_PORT_CAP_SUBS_WRITE)) {
if (!(snd_seq_port_info_get_capability(pinfo) & SND_SEQ_PORT_CAP_NO_EXPORT))
return 1;
}
return 0;
}
/*
* parse address string
*/
#define ADDR_DELIM ".:"
class MidiDriver_ALSA : public MidiDriver_MPU401 {
public:
MidiDriver_ALSA(int client, int port);
int open() override;
bool isOpen() const override { return _isOpen; }
void close() override;
void send(uint32 b) override;
void sysEx(const byte *msg, uint16 length) override;
private:
void send_event(int do_flush);
bool _isOpen;
snd_seq_event_t ev;
snd_seq_t *seq_handle;
int seq_client, seq_port;
int my_client, my_port;
// The volume controller value of the first MIDI channel
int8 _channel0Volume;
};
MidiDriver_ALSA::MidiDriver_ALSA(int client, int port)
: _isOpen(false), seq_handle(0), seq_client(client), seq_port(port), my_client(0), my_port(0), _channel0Volume(127) {
memset(&ev, 0, sizeof(ev));
}
int MidiDriver_ALSA::open() {
if (_isOpen)
return MERR_ALREADY_OPEN;
_isOpen = true;
if (my_snd_seq_open(&seq_handle) < 0) {
error("Can't open sequencer");
return -1;
}
my_client = snd_seq_client_id(seq_handle);
if (snd_seq_set_client_name(seq_handle, "SCUMMVM") < 0) {
error("Can't set sequencer client name");
}
snd_seq_set_client_group(seq_handle, "input");
// According to
// https://web.archive.org/web/20120505164948/http://www.alsa-project.org/~tiwai/alsa-subs.html
// you can set read or write capabilities to allow other clients to
// read or write the port. I don't think we need that, unless maybe
// to be able to record the sound, but I can't get that to work even
// with those capabilities.
my_port = snd_seq_create_simple_port(seq_handle, "SCUMMVM port 0", 0,
SND_SEQ_PORT_TYPE_MIDI_GENERIC | SND_SEQ_PORT_TYPE_APPLICATION);
if (my_port < 0) {
snd_seq_close(seq_handle);
error("Can't create port");
return -1;
}
if (seq_client != SND_SEQ_ADDRESS_SUBSCRIBERS) {
// Subscribe to MIDI port. Prefer one that doesn't already have
// any connections, unless we've forced a port number already.
if (seq_port == -1) {
snd_seq_client_info_t *cinfo;
snd_seq_port_info_t *pinfo;
snd_seq_client_info_alloca(&cinfo);
snd_seq_port_info_alloca(&pinfo);
snd_seq_get_any_client_info(seq_handle, seq_client, cinfo);
int first_port = -1;
int found_port = -1;
snd_seq_port_info_set_client(pinfo, seq_client);
snd_seq_port_info_set_port(pinfo, -1);
while (found_port == -1 && snd_seq_query_next_port(seq_handle, pinfo) >= 0) {
if (check_permission(pinfo)) {
if (first_port == -1)
first_port = snd_seq_port_info_get_port(pinfo);
if (found_port == -1 && snd_seq_port_info_get_write_use(pinfo) == 0)
found_port = snd_seq_port_info_get_port(pinfo);
}
}
if (found_port == -1) {
// Should we abort here? For now, use the first
// available port.
seq_port = first_port;
warning("MidiDriver_ALSA: All ports on client %d (%s) are already in use", seq_client, snd_seq_client_info_get_name(cinfo));
} else {
seq_port = found_port;
}
}
if (snd_seq_connect_to(seq_handle, my_port, seq_client, seq_port) < 0) {
error("Can't subscribe to MIDI port (%d:%d) see README for help", seq_client, seq_port);
}
}
printf("Connected to Alsa sequencer client [%d:%d]\n", seq_client, seq_port);
printf("ALSA client initialized [%d:0]\n", my_client);
return 0;
}
void MidiDriver_ALSA::close() {
if (_isOpen) {
_isOpen = false;
MidiDriver_MPU401::close();
if (seq_handle)
snd_seq_close(seq_handle);
} else
warning("MidiDriver_ALSA: Closing the driver before opening it");
}
void MidiDriver_ALSA::send(uint32 b) {
if (!_isOpen) {
warning("MidiDriver_ALSA: Got event while not open");
return;
}
midiDriverCommonSend(b);
unsigned int midiCmd[4];
ev.type = SND_SEQ_EVENT_OSS;
midiCmd[3] = (b & 0xFF000000) >> 24;
midiCmd[2] = (b & 0x00FF0000) >> 16;
midiCmd[1] = (b & 0x0000FF00) >> 8;
midiCmd[0] = (b & 0x000000FF);
ev.data.raw32.d[0] = midiCmd[0];
ev.data.raw32.d[1] = midiCmd[1];
ev.data.raw32.d[2] = midiCmd[2];
unsigned char chanID = midiCmd[0] & 0x0F;
switch (midiCmd[0] & 0xF0) {
case 0x80:
snd_seq_ev_set_noteoff(&ev, chanID, midiCmd[1], midiCmd[2]);
send_event(1);
break;
case 0x90:
snd_seq_ev_set_noteon(&ev, chanID, midiCmd[1], midiCmd[2]);
send_event(1);
break;
case 0xA0:
snd_seq_ev_set_keypress(&ev, chanID, midiCmd[1], midiCmd[2]);
send_event(1);
break;
case 0xB0:
/* is it this simple ? Wow... */
snd_seq_ev_set_controller(&ev, chanID, midiCmd[1], midiCmd[2]);
#ifdef MIDI_USB_HACK
// We save the volume of the first MIDI channel here to utilize it in
// our workaround for broken USB-MIDI cables.
if (chanID == 0 && midiCmd[1] == 0x07)
_channel0Volume = midiCmd[2];
#endif
send_event(1);
break;
case 0xC0:
snd_seq_ev_set_pgmchange(&ev, chanID, midiCmd[1]);
send_event(0);
#ifdef MIDI_USB_HACK
// Send a volume change command to work around a firmware bug in common
// USB-MIDI cables. If the first MIDI command in a USB packet is a
// Cx or Dx command, the second command in the packet is dropped
// somewhere.
send(0x07B0 | (_channel0Volume << 16));
#endif
break;
case 0xD0:
snd_seq_ev_set_chanpress(&ev, chanID, midiCmd[1]);
send_event(1);
#ifdef MIDI_USB_HACK
// Send a volume change command to work around a firmware bug in common
// USB-MIDI cables. If the first MIDI command in a USB packet is a
// Cx or Dx command, the second command in the packet is dropped
// somewhere.
send(0x07B0 | (_channel0Volume << 16));
#endif
break;
case 0xE0: {
// long theBend = ((((long)midiCmd[1] + (long)(midiCmd[2] << 7))) - 0x2000) / 4;
// snd_seq_ev_set_pitchbend(&ev, chanID, theBend);
long theBend = ((long)midiCmd[1] + (long)(midiCmd[2] << 7)) - 0x2000;
snd_seq_ev_set_pitchbend(&ev, chanID, theBend);
send_event(1);
} break;
default:
warning("Unknown MIDI Command: %08x", (int)b);
/* I don't know if this works but, well... */
send_event(1);
break;
}
}
void MidiDriver_ALSA::sysEx(const byte *msg, uint16 length) {
if (!_isOpen) {
warning("MidiDriver_ALSA: Got SysEx while not open");
return;
}
unsigned char buf[270];
assert(length + 2 <= ARRAYSIZE(buf));
midiDriverCommonSysEx(msg, length);
// Add SysEx frame
buf[0] = 0xF0;
memcpy(buf + 1, msg, length);
buf[length + 1] = 0xF7;
// Send it
snd_seq_ev_set_sysex(&ev, length + 2, &buf);
send_event(1);
}
void MidiDriver_ALSA::send_event(int do_flush) {
snd_seq_ev_set_direct(&ev);
snd_seq_ev_set_source(&ev, my_port);
snd_seq_ev_set_dest(&ev, seq_client, seq_port);
snd_seq_event_output(seq_handle, &ev);
if (do_flush)
snd_seq_flush_output(seq_handle);
}
// Plugin interface
class AlsaDevice {
public:
AlsaDevice(Common::String name, MusicType mt, int client);
Common::String getName();
MusicType getType();
int getClient();
private:
Common::String _name;
MusicType _type;
int _client;
};
typedef Common::List<AlsaDevice> AlsaDevices;
AlsaDevice::AlsaDevice(Common::String name, MusicType mt, int client)
: _name(name), _type(mt), _client(client) {
// Make sure we do not get any trailing spaces to avoid problems when
// storing the name in the configuration file.
_name.trim();
}
Common::String AlsaDevice::getName() {
return _name;
}
MusicType AlsaDevice::getType() {
return _type;
}
int AlsaDevice::getClient() {
return _client;
}
class AlsaMusicPlugin : public MusicPluginObject {
public:
const char *getName() const {
return "ALSA";
}
const char *getId() const {
return "alsa";
}
AlsaDevices getAlsaDevices() const;
MusicDevices getDevices() const;
Common::Error createInstance(MidiDriver **mididriver, MidiDriver::DeviceHandle = 0) const;
private:
static int parse_addr(const char *arg, int *client, int *port);
};
AlsaDevices AlsaMusicPlugin::getAlsaDevices() const {
AlsaDevices devices;
snd_seq_t *seq_handle;
if (my_snd_seq_open(&seq_handle) < 0)
return devices; // can't open sequencer
snd_seq_client_info_t *cinfo;
snd_seq_client_info_alloca(&cinfo);
snd_seq_port_info_t *pinfo;
snd_seq_port_info_alloca(&pinfo);
snd_seq_client_info_set_client(cinfo, -1);
while (snd_seq_query_next_client(seq_handle, cinfo) >= 0) {
bool found_valid_port = false;
/* reset query info */
snd_seq_port_info_set_client(pinfo, snd_seq_client_info_get_client(cinfo));
snd_seq_port_info_set_port(pinfo, -1);
while (!found_valid_port && snd_seq_query_next_port(seq_handle, pinfo) >= 0) {
if (check_permission(pinfo)) {
found_valid_port = true;
const char *name = snd_seq_client_info_get_name(cinfo);
// TODO: Can we figure out the appropriate music type?
MusicType type = MT_GM;
int client = snd_seq_client_info_get_client(cinfo);
devices.push_back(AlsaDevice(name, type, client));
}
}
}
snd_seq_close(seq_handle);
return devices;
}
MusicDevices AlsaMusicPlugin::getDevices() const {
MusicDevices devices;
AlsaDevices::iterator d;
AlsaDevices alsaDevices = getAlsaDevices();
// Since the default behavior is to use the first device in the list,
// try to put something sensible there. We used to have 17:0 and 65:0
// as defaults.
for (d = alsaDevices.begin(); d != alsaDevices.end();) {
const int client = d->getClient();
if (client == 17 || client == 65) {
devices.push_back(MusicDevice(this, d->getName(), d->getType()));
d = alsaDevices.erase(d);
} else {
++d;
}
}
// 128:0 is probably TiMidity, or something like that, so that's
// probably a good second choice.
for (d = alsaDevices.begin(); d != alsaDevices.end();) {
if (d->getClient() == 128) {
devices.push_back(MusicDevice(this, d->getName(), d->getType()));
d = alsaDevices.erase(d);
} else {
++d;
}
}
// Add the remaining devices in the order they were found.
for (auto &device : alsaDevices)
devices.push_back(MusicDevice(this, device.getName(), device.getType()));
return devices;
}
Common::Error AlsaMusicPlugin::createInstance(MidiDriver **mididriver, MidiDriver::DeviceHandle dev) const {
bool found = false;
int seq_client, seq_port;
const char *var = NULL;
// TODO: Upgrade from old alsa_port setting. This probably isn't the
// right place to do that, though.
if (ConfMan.hasKey("alsa_port")) {
warning("AlsaMusicPlugin: Found old 'alsa_port' setting, which will be ignored");
}
// The SCUMMVM_PORT environment variable can still be used to override
// any config setting.
var = getenv("SCUMMVM_PORT");
if (var) {
warning("AlsaMusicPlugin: SCUMMVM_PORT environment variable overrides config settings");
if (parse_addr(var, &seq_client, &seq_port) >= 0) {
found = true;
} else {
warning("AlsaMusicPlugin: Invalid port %s, using config settings instead", var);
}
}
// Try to match the setting to an available ALSA device.
if (!found && dev) {
AlsaDevices alsaDevices = getAlsaDevices();
for (auto &d : alsaDevices) {
MusicDevice device(this, d.getName(), d.getType());
if (device.getCompleteId().equals(MidiDriver::getDeviceString(dev, MidiDriver::kDeviceId))) {
found = true;
seq_client = d.getClient();
seq_port = -1;
break;
}
}
}
// Still nothing? Try a sensible default.
if (!found) {
// TODO: What's a sensible default anyway? And exactly when do
// we get to this case?
warning("AlsaMusicPlugin: Using 17:0 as default ALSA port");
seq_client = 17;
seq_port = 0;
}
*mididriver = new MidiDriver_ALSA(seq_client, seq_port);
return Common::kNoError;
}
int AlsaMusicPlugin::parse_addr(const char *arg, int *client, int *port) {
const char *p;
if (isdigit(*arg)) {
if ((p = strpbrk(arg, ADDR_DELIM)) == NULL)
return -1;
*client = atoi(arg);
*port = atoi(p + 1);
} else {
if (*arg == 's' || *arg == 'S') {
*client = SND_SEQ_ADDRESS_SUBSCRIBERS;
*port = 0;
} else
return -1;
}
return 0;
}
//#if PLUGIN_ENABLED_DYNAMIC(ALSA)
//REGISTER_PLUGIN_DYNAMIC(ALSA, PLUGIN_TYPE_MUSIC, AlsaMusicPlugin);
//#else
REGISTER_PLUGIN_STATIC(ALSA, PLUGIN_TYPE_MUSIC, AlsaMusicPlugin);
//#endif
#endif

288
backends/midi/camd.cpp Normal file
View File

@@ -0,0 +1,288 @@
/* ScummVM - Graphic Adventure Engine
*
* ScummVM is the legal property of its developers, whose names
* are too numerous to list here. Please refer to the COPYRIGHT
* file distributed with this source distribution.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program 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 <http://www.gnu.org/licenses/>.
*
*/
// Disable symbol overrides so that we can use system headers.
#define FORBIDDEN_SYMBOL_ALLOW_ALL
#include "common/scummsys.h"
#if defined(__amigaos4__) || defined(__MORPHOS__)
#include "common/textconsole.h"
#include "common/error.h"
#include "common/endian.h"
#include "common/util.h"
#include "common/str.h"
#include "audio/musicplugin.h"
#include "audio/mpu401.h"
#include <proto/camd.h>
#include <proto/exec.h>
#include <proto/dos.h>
/*
* CAMD sequencer driver
* Mostly cut'n'pasted from FreeSCI by Christoph Reichenbach
*/
class MidiDriver_CAMD : public MidiDriver_MPU401 {
public:
MidiDriver_CAMD();
int open();
bool isOpen() const { return _isOpen; }
void close();
void send(uint32 b) override;
void sysEx(const byte *msg, uint16 length);
private:
bool _isOpen;
struct Library *_CamdBase;
#if defined(__amigaos4__)
struct CamdIFace *_ICamd;
#endif
struct MidiNode *_midi_node;
struct MidiLink *_midi_link;
char _outport[128];
char *getDevice();
void closeAll();
};
MidiDriver_CAMD::MidiDriver_CAMD()
#if defined(__amigaos4__)
: _isOpen(false), _CamdBase(NULL), _ICamd(NULL), _midi_link(NULL) {
#else
: _isOpen(false), _CamdBase(NULL), _midi_link(NULL) {
#endif
}
int MidiDriver_CAMD::open() {
if (_isOpen)
return MERR_ALREADY_OPEN;
#if defined(__amigaos4__)
_CamdBase = IExec->OpenLibrary("camd.library", 36L);
#else
_CamdBase = OpenLibrary("camd.library", 36L);
#endif
if (!_CamdBase) {
error("Could not open 'camd.library'");
return -1;
}
#if defined(__amigaos4__)
_ICamd = (struct CamdIFace *) IExec->GetInterface(_CamdBase, "main", 1, NULL);
if (!_ICamd) {
closeAll();
error("Error while retrieving CAMD interface");
return -1;
}
#endif
#if defined(__amigaos4__)
_midi_node = _ICamd->CreateMidi(MIDI_MsgQueue, 0L, MIDI_SysExSize, 4096L, MIDI_Name, "scummvm", TAG_END);
#else
TagItem tags[] = { MIDI_MsgQueue, 0L, MIDI_SysExSize, 4096L, MIDI_Name, (ULONG)"scummvm", TAG_END, 0};
_midi_node = CreateMidiA(tags);
#endif
if (!_midi_node) {
closeAll();
error("Could not create CAMD MIDI node");
return -1;
}
char *devicename = getDevice();
if (!devicename) {
closeAll();
error("Could not find an output device");
return MERR_DEVICE_NOT_AVAILABLE;
}
#if defined(__amigaos4__)
_midi_link = _ICamd->AddMidiLink(_midi_node, MLTYPE_Sender, MLINK_Location, devicename, TAG_END);
#else
TagItem tagsLink[] = { MLINK_Location, (ULONG)devicename, TAG_END, 0};
_midi_link = AddMidiLinkA(_midi_node, MLTYPE_Sender, tagsLink);
#endif
if (!_midi_link) {
closeAll();
error("Could not create CAMD MIDI link to '%s'", devicename);
return MERR_CANNOT_CONNECT;
}
_isOpen = true;
return 0;
}
void MidiDriver_CAMD::close() {
MidiDriver_MPU401::close();
closeAll();
}
void MidiDriver_CAMD::send(uint32 b) {
if (!_isOpen) {
warning("MidiDriver_CAMD: Got event while not open");
return;
}
midiDriverCommonSend(b);
ULONG data = READ_LE_UINT32(&b);
#if defined(__amigaos4__)
_ICamd->PutMidi(_midi_link, data);
#else
PutMidi(_midi_link, data);
#endif
}
void MidiDriver_CAMD::sysEx(const byte *msg, uint16 length) {
if (!_isOpen) {
warning("MidiDriver_CAMD: Got SysEx while not open");
return;
}
unsigned char buf[266];
assert(length + 2 <= ARRAYSIZE(buf));
// Add SysEx frame
buf[0] = 0xF0;
memcpy(buf + 1, msg, length);
buf[length + 1] = 0xF7;
// Send it
#if defined(__amigaos4__)
_ICamd->PutSysEx(_midi_link, buf);
#else
PutSysEx(_midi_link, buf);
#endif
}
char *MidiDriver_CAMD::getDevice() {
char *retname = NULL;
#if defined(__amigaos4__)
APTR key = _ICamd->LockCAMD(CD_Linkages);
#else
APTR key = LockCAMD(CD_Linkages);
#endif
if (key != NULL) {
#if defined(__amigaos4__)
struct MidiCluster *cluster = _ICamd->NextCluster(NULL);
#else
struct MidiCluster *cluster = NextCluster(NULL);
#endif
while (cluster && !retname) {
// Get the current cluster name
char *dev = cluster->mcl_Node.ln_Name;
if (strstr(dev, "out") != NULL) {
// This is an output device, return this
Common::strlcpy(_outport, dev, sizeof(_outport));
retname = _outport;
} else {
// Search the next one
#if defined(__amigaos4__)
cluster = _ICamd->NextCluster(cluster);
#else
cluster = NextCluster(cluster);
#endif
}
}
// If the user has a preference outport set, use this instead
#if defined(__amigaos4__)
if(IDOS->GetVar("DefMidiOut", _outport, 128, 0))
#else
if (GetVar("DefMidiOut", _outport, 128, 0))
#endif
retname = _outport;
#if defined(__amigaos4__)
_ICamd->UnlockCAMD(key);
#else
UnlockCAMD(key);
#endif
}
return retname;
}
void MidiDriver_CAMD::closeAll() {
if (_CamdBase) {
#if defined(__amigaos4__)
if (_ICamd)
IExec->DropInterface((struct Interface *)_ICamd);
IExec->CloseLibrary(_CamdBase);
_CamdBase = NULL;
#else
FlushMidi(_midi_node);
if (_midi_link) {
RemoveMidiLink(_midi_link);
_midi_link = NULL;
}
if (_midi_node) {
DeleteMidi(_midi_node);
_midi_node = NULL;
}
CloseLibrary(_CamdBase);
_CamdBase = NULL;
#endif
}
_isOpen = false;
}
// Plugin interface
class CamdMusicPlugin : public MusicPluginObject {
public:
const char *getName() const {
return "CAMD";
}
const char *getId() const {
return "camd";
}
MusicDevices getDevices() const;
Common::Error createInstance(MidiDriver **mididriver, MidiDriver::DeviceHandle = 0) const;
};
MusicDevices CamdMusicPlugin::getDevices() const {
MusicDevices devices;
// TODO: Return a different music type depending on the configuration
// TODO: List the available devices
devices.push_back(MusicDevice(this, "", MT_GM));
return devices;
}
Common::Error CamdMusicPlugin::createInstance(MidiDriver **mididriver, MidiDriver::DeviceHandle) const {
*mididriver = new MidiDriver_CAMD();
return Common::kNoError;
}
REGISTER_PLUGIN_STATIC(CAMD, PLUGIN_TYPE_MUSIC, CamdMusicPlugin);
#endif

292
backends/midi/coreaudio.cpp Normal file
View File

@@ -0,0 +1,292 @@
/* ScummVM - Graphic Adventure Engine
*
* ScummVM is the legal property of its developers, whose names
* are too numerous to list here. Please refer to the COPYRIGHT
* file distributed with this source distribution.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program 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 <http://www.gnu.org/licenses/>.
*
*/
// Disable symbol overrides so that we can use system headers.
#define FORBIDDEN_SYMBOL_ALLOW_ALL
#include "common/scummsys.h"
#ifdef MACOSX
#include "backends/platform/sdl/macosx/macosx-compat.h"
// With the release of Mac OS X 10.5 in October 2007, Apple deprecated the
// AUGraphNewNode & AUGraphGetNodeInfo APIs in favor of the new AUGraphAddNode &
// AUGraphNodeInfo APIs. The newer APIs are used by default, but we do need to
// use the old ones when building for 10.4.
#if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
#define USE_DEPRECATED_COREAUDIO_API 1
#else
#define USE_DEPRECATED_COREAUDIO_API 0
#endif
#include "common/config-manager.h"
#include "common/error.h"
#include "common/textconsole.h"
#include "common/util.h"
#include "audio/musicplugin.h"
#include "audio/mpu401.h"
#include <CoreServices/CoreServices.h>
#include <AudioToolbox/AUGraph.h>
// Activating the following switch disables reverb support in the CoreAudio
// midi backend. Reverb will suck away a *lot* of CPU time, so on slower
// systems, you may want to turn it off completely.
// TODO: Maybe make this a config option?
//#define COREAUDIO_DISABLE_REVERB
// A macro to simplify error handling a bit.
#define RequireNoErr(error) \
do { \
err = error; \
if (err != noErr) \
goto bail; \
} while (false)
/* CoreAudio MIDI driver
* By Max Horn / Fingolfin
* Based on code by Benjamin W. Zale
*/
class MidiDriver_CORE : public MidiDriver_MPU401 {
public:
MidiDriver_CORE();
~MidiDriver_CORE();
int open() override;
bool isOpen() const override { return _auGraph != 0; }
void close() override;
void send(uint32 b) override;
void sysEx(const byte *msg, uint16 length) override;
private:
void loadSoundFont(const char *soundfont);
AUGraph _auGraph;
AudioUnit _synth;
};
MidiDriver_CORE::MidiDriver_CORE()
: _auGraph(0) {
}
MidiDriver_CORE::~MidiDriver_CORE() {
if (_auGraph) {
AUGraphStop(_auGraph);
DisposeAUGraph(_auGraph);
_auGraph = 0;
}
}
int MidiDriver_CORE::open() {
OSStatus err = 0;
if (isOpen())
return MERR_ALREADY_OPEN;
// Open the Music Device.
RequireNoErr(NewAUGraph(&_auGraph));
AUNode outputNode, synthNode;
#if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_6
ComponentDescription desc;
#else
AudioComponentDescription desc;
#endif
// The default output device
desc.componentType = kAudioUnitType_Output;
desc.componentSubType = kAudioUnitSubType_DefaultOutput;
desc.componentManufacturer = kAudioUnitManufacturer_Apple;
desc.componentFlags = 0;
desc.componentFlagsMask = 0;
#if USE_DEPRECATED_COREAUDIO_API
RequireNoErr(AUGraphNewNode(_auGraph, &desc, 0, NULL, &outputNode));
#else
RequireNoErr(AUGraphAddNode(_auGraph, &desc, &outputNode));
#endif
// The built-in default (softsynth) music device
desc.componentType = kAudioUnitType_MusicDevice;
desc.componentSubType = kAudioUnitSubType_DLSSynth;
desc.componentManufacturer = kAudioUnitManufacturer_Apple;
#if USE_DEPRECATED_COREAUDIO_API
RequireNoErr(AUGraphNewNode(_auGraph, &desc, 0, NULL, &synthNode));
#else
RequireNoErr(AUGraphAddNode(_auGraph, &desc, &synthNode));
#endif
// Connect the softsynth to the default output
RequireNoErr(AUGraphConnectNodeInput(_auGraph, synthNode, 0, outputNode, 0));
// Open and initialize the whole graph
RequireNoErr(AUGraphOpen(_auGraph));
RequireNoErr(AUGraphInitialize(_auGraph));
// Get the music device from the graph.
#if USE_DEPRECATED_COREAUDIO_API
RequireNoErr(AUGraphGetNodeInfo(_auGraph, synthNode, NULL, NULL, NULL, &_synth));
#else
RequireNoErr(AUGraphNodeInfo(_auGraph, synthNode, NULL, &_synth));
#endif
// Load custom soundfont, if specified
if (ConfMan.hasKey("soundfont"))
loadSoundFont(ConfMan.getPath("soundfont").toString(Common::Path::kNativeSeparator).c_str());
#ifdef COREAUDIO_DISABLE_REVERB
// Disable reverb mode, as that sucks up a lot of CPU power, which can
// be painful on low end machines.
// TODO: Make this customizable via a config key?
UInt32 usesReverb = 0;
AudioUnitSetProperty (_synth, kMusicDeviceProperty_UsesInternalReverb,
kAudioUnitScope_Global, 0, &usesReverb, sizeof (usesReverb));
#endif
// Finally: Start the graph!
RequireNoErr(AUGraphStart(_auGraph));
return 0;
bail:
if (_auGraph) {
AUGraphStop(_auGraph);
DisposeAUGraph(_auGraph);
_auGraph = 0;
}
return MERR_CANNOT_CONNECT;
}
void MidiDriver_CORE::loadSoundFont(const char *soundfont) {
// TODO: We should really check whether the file contains an
// actual soundfont...
OSStatus err = 0;
#if USE_DEPRECATED_COREAUDIO_API
FSRef fsref;
err = FSPathMakeRef((const UInt8 *)soundfont, &fsref, NULL);
if (err == noErr) {
err = AudioUnitSetProperty(
_synth,
kMusicDeviceProperty_SoundBankFSRef, kAudioUnitScope_Global,
0,
&fsref, sizeof(fsref)
);
}
#else
// kMusicDeviceProperty_SoundBankURL was added in 10.5 as a replacement
// In addition, the File Manager API became deprecated starting in 10.8
CFURLRef url = CFURLCreateFromFileSystemRepresentation(kCFAllocatorDefault, (const UInt8 *)soundfont, strlen(soundfont), false);
if (url) {
err = AudioUnitSetProperty(
_synth,
kMusicDeviceProperty_SoundBankURL, kAudioUnitScope_Global,
0,
&url, sizeof(url)
);
CFRelease(url);
} else {
warning("Failed to allocate CFURLRef from '%s'", soundfont);
}
#endif // USE_DEPRECATED_COREAUDIO_API
if (err != noErr)
error("Failed loading custom SoundFont '%s' (error %ld)", soundfont, (long)err);
}
void MidiDriver_CORE::close() {
MidiDriver_MPU401::close();
if (_auGraph) {
AUGraphStop(_auGraph);
DisposeAUGraph(_auGraph);
_auGraph = 0;
}
}
void MidiDriver_CORE::send(uint32 b) {
assert(isOpen());
midiDriverCommonSend(b);
byte status_byte = (b & 0x000000FF);
byte first_byte = (b & 0x0000FF00) >> 8;
byte second_byte = (b & 0x00FF0000) >> 16;
MusicDeviceMIDIEvent(_synth, status_byte, first_byte, second_byte, 0);
}
void MidiDriver_CORE::sysEx(const byte *msg, uint16 length) {
unsigned char buf[266];
assert(length + 2 <= ARRAYSIZE(buf));
assert(isOpen());
// Add SysEx frame
buf[0] = 0xF0;
memcpy(buf + 1, msg, length);
buf[length + 1] = 0xF7;
// Send it
MusicDeviceSysEx(_synth, buf, length+2);
}
// Plugin interface
class CoreAudioMusicPlugin : public MusicPluginObject {
public:
const char *getName() const {
return "Apple DLS Software Synthesizer";
}
const char *getId() const {
return "core";
}
MusicDevices getDevices() const;
Common::Error createInstance(MidiDriver **mididriver, MidiDriver::DeviceHandle = 0) const;
};
MusicDevices CoreAudioMusicPlugin::getDevices() const {
MusicDevices devices;
devices.push_back(MusicDevice(this, "", MT_GM));
return devices;
}
Common::Error CoreAudioMusicPlugin::createInstance(MidiDriver **mididriver, MidiDriver::DeviceHandle) const {
*mididriver = new MidiDriver_CORE();
return Common::kNoError;
}
//#if PLUGIN_ENABLED_DYNAMIC(COREAUDIO)
//REGISTER_PLUGIN_DYNAMIC(COREAUDIO, PLUGIN_TYPE_MUSIC, CoreAudioMusicPlugin);
//#else
REGISTER_PLUGIN_STATIC(COREAUDIO, PLUGIN_TYPE_MUSIC, CoreAudioMusicPlugin);
//#endif
#endif // MACOSX

260
backends/midi/coremidi.cpp Normal file
View File

@@ -0,0 +1,260 @@
/* ScummVM - Graphic Adventure Engine
*
* ScummVM is the legal property of its developers, whose names
* are too numerous to list here. Please refer to the COPYRIGHT
* file distributed with this source distribution.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program 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 <http://www.gnu.org/licenses/>.
*
*/
// Disable symbol overrides so that we can use system headers.
#define FORBIDDEN_SYMBOL_ALLOW_ALL
#include "common/scummsys.h"
#ifdef MACOSX
#include "common/config-manager.h"
#include "common/error.h"
#include "common/textconsole.h"
#include "common/util.h"
#include "audio/musicplugin.h"
#include "audio/mpu401.h"
#include <CoreMIDI/CoreMIDI.h>
/*
For information on how to unify the CoreMidi and MusicDevice code:
https://lists.apple.com/archives/coreaudio-api/2005/Jun/msg00194.html
https://lists.apple.com/archives/coreaudio-api/2003/Mar/msg00248.html
https://lists.apple.com/archives/coreaudio-api/2003/Jul/msg00137.html
*/
/* CoreMIDI MIDI driver
* By Max Horn
*/
class MidiDriver_CoreMIDI : public MidiDriver_MPU401 {
public:
MidiDriver_CoreMIDI(ItemCount device);
~MidiDriver_CoreMIDI();
int open() override;
bool isOpen() const override { return mOutPort != 0 && mDest != 0; }
void close() override;
void send(uint32 b) override;
void sysEx(const byte *msg, uint16 length) override;
private:
ItemCount mDevice;
MIDIClientRef mClient;
MIDIPortRef mOutPort;
MIDIEndpointRef mDest;
};
MidiDriver_CoreMIDI::MidiDriver_CoreMIDI(ItemCount device)
: mDevice(device), mClient(0), mOutPort(0), mDest(0) {
/*OSStatus err = */MIDIClientCreate(CFSTR("ScummVM MIDI Driver for macOS"), NULL, NULL, &mClient);
}
MidiDriver_CoreMIDI::~MidiDriver_CoreMIDI() {
if (mClient)
MIDIClientDispose(mClient);
mClient = 0;
}
int MidiDriver_CoreMIDI::open() {
if (isOpen())
return MERR_ALREADY_OPEN;
OSStatus err = noErr;
mOutPort = 0;
ItemCount dests = MIDIGetNumberOfDestinations();
if (mDevice < dests && mClient) {
mDest = MIDIGetDestination(mDevice);
err = MIDIOutputPortCreate( mClient,
CFSTR("scummvm_output_port"),
&mOutPort);
} else {
return MERR_DEVICE_NOT_AVAILABLE;
}
if (err != noErr)
return MERR_CANNOT_CONNECT;
return 0;
}
void MidiDriver_CoreMIDI::close() {
MidiDriver_MPU401::close();
if (isOpen()) {
MIDIPortDispose(mOutPort);
mOutPort = 0;
mDest = 0;
}
}
void MidiDriver_CoreMIDI::send(uint32 b) {
assert(isOpen());
midiDriverCommonSend(b);
// Extract the MIDI data
byte status_byte = (b & 0x000000FF);
byte first_byte = (b & 0x0000FF00) >> 8;
byte second_byte = (b & 0x00FF0000) >> 16;
// Generate a single MIDI packet with that data
MIDIPacketList packetList;
MIDIPacket *packet = &packetList.packet[0];
packetList.numPackets = 1;
packet->timeStamp = 0;
packet->data[0] = status_byte;
packet->data[1] = first_byte;
packet->data[2] = second_byte;
// Compute the correct length of the MIDI command. This is important,
// else things may screw up badly...
switch (status_byte & 0xF0) {
case 0x80: // Note Off
case 0x90: // Note On
case 0xA0: // Polyphonic Aftertouch
case 0xB0: // Controller Change
case 0xE0: // Pitch Bending
packet->length = 3;
break;
case 0xC0: // Programm Change
case 0xD0: // Monophonic Aftertouch
packet->length = 2;
break;
default:
warning("CoreMIDI driver encountered unsupported status byte: 0x%02x", status_byte);
packet->length = 3;
break;
}
// Finally send it out to the synthesizer.
MIDISend(mOutPort, mDest, &packetList);
}
void MidiDriver_CoreMIDI::sysEx(const byte *msg, uint16 length) {
assert(isOpen());
byte buf[384];
MIDIPacketList *packetList = (MIDIPacketList *)buf;
MIDIPacket *packet = packetList->packet;
assert(sizeof(buf) >= sizeof(UInt32) + sizeof(MIDITimeStamp) + sizeof(UInt16) + length + 2);
packetList->numPackets = 1;
packet->timeStamp = 0;
// Add SysEx frame
packet->length = length + 2;
packet->data[0] = 0xF0;
memcpy(packet->data + 1, msg, length);
packet->data[length + 1] = 0xF7;
// Send it
MIDISend(mOutPort, mDest, packetList);
}
// Plugin interface
class CoreMIDIMusicPlugin : public MusicPluginObject {
public:
const char *getName() const {
return "CoreMIDI";
}
const char *getId() const {
return "coremidi";
}
MusicDevices getDevices() const;
Common::Error createInstance(MidiDriver **mididriver, MidiDriver::DeviceHandle = 0) const;
private:
bool getDeviceName(ItemCount deviceIndex, Common::String &outName) const;
};
MusicDevices CoreMIDIMusicPlugin::getDevices() const {
// TODO: Is it possible to get the music type for each device?
// Maybe look at the kMIDIPropertyModel property?
MusicDevices devices;
ItemCount deviceCount = MIDIGetNumberOfDestinations();
for (ItemCount i = 0 ; i < deviceCount ; ++i) {
Common::String name;
if (getDeviceName(i, name))
devices.push_back(MusicDevice(this, name, MT_GM));
}
return devices;
}
Common::Error CoreMIDIMusicPlugin::createInstance(MidiDriver **mididriver, MidiDriver::DeviceHandle device) const {
ItemCount deviceCount = MIDIGetNumberOfDestinations();
for (ItemCount i = 0 ; i < deviceCount ; ++i) {
Common::String name;
if (getDeviceName(i, name)) {
MusicDevice md(this, name, MT_GM);
if (md.getHandle() == device) {
*mididriver = new MidiDriver_CoreMIDI(i);
return Common::kNoError;
}
}
}
return Common::kUnknownError;
}
bool CoreMIDIMusicPlugin::getDeviceName(ItemCount deviceIndex, Common::String &outName) const {
MIDIEndpointRef dest = MIDIGetDestination(deviceIndex);
if (!dest)
return false;
CFStringRef name = nil;
if (MIDIObjectGetStringProperty(dest, kMIDIPropertyDisplayName, &name) == noErr) {
char buffer[128];
if (CFStringGetCString(name, buffer, sizeof(buffer), kCFStringEncodingASCII)) {
outName = buffer;
CFRelease(name);
return true;
}
CFRelease(name);
}
// Rather than fail use a default name
warning("Failed to get name for CoreMIDi device %lu", deviceIndex);
outName = Common::String::format("Unknown Device %lu", deviceIndex);
return true;
}
//#if PLUGIN_ENABLED_DYNAMIC(COREMIDI)
//REGISTER_PLUGIN_DYNAMIC(COREMIDI, PLUGIN_TYPE_MUSIC, CoreMIDIMusicPlugin);
//#else
REGISTER_PLUGIN_STATIC(COREMIDI, PLUGIN_TYPE_MUSIC, CoreMIDIMusicPlugin);
//#endif
#endif // MACOSX

249
backends/midi/dmedia.cpp Normal file
View File

@@ -0,0 +1,249 @@
/* ScummVM - Graphic Adventure Engine
*
* ScummVM is the legal property of its developers, whose names
* are too numerous to list here. Please refer to the COPYRIGHT
* file distributed with this source distribution.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program 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 <http://www.gnu.org/licenses/>.
*
*/
/*
* IRIX dmedia support by Rainer Canavan <scumm@canavan.de>
* some code liberated from seq.cpp and coremidi.cpp
*/
// Disable symbol overrides so that we can use system headers.
#define FORBIDDEN_SYMBOL_ALLOW_ALL
#include "common/scummsys.h"
#if defined(IRIX)
#include "common/config-manager.h"
#include "common/error.h"
#include "common/textconsole.h"
#include "common/util.h"
#include "audio/musicplugin.h"
#include "audio/mpu401.h"
#include <dmedia/midi.h>
#include <sys/types.h>
#include <bstring.h>
#include <unistd.h>
////////////////////////////////////////
//
// IRIX dmedia midi driver
//
////////////////////////////////////////
#define SEQ_MIDIPUTC 5
class MidiDriver_DMEDIA : public MidiDriver_MPU401 {
public:
MidiDriver_DMEDIA();
int open();
bool isOpen() const { return _isOpen; }
void close();
void send(uint32 b) override;
void sysEx(const byte *msg, uint16 length);
private:
bool _isOpen;
int _deviceNum;
char *_midiportName;
MDport _midiPort;
int _fd;
};
MidiDriver_DMEDIA::MidiDriver_DMEDIA() {
_isOpen = false;
_deviceNum = 0;
_midiportName = NULL;
}
int MidiDriver_DMEDIA::open() {
int numinterfaces;
int i;
const char *var;
char *portName;
if (_isOpen)
return MERR_ALREADY_OPEN;
_isOpen = true;
numinterfaces = mdInit();
if (numinterfaces <= 0) {
fprintf(stderr, "No MIDI interfaces configured.\n");
perror("Cannot initialize libmd for sound output");
return -1;
}
if (getenv("SCUMMVM_MIDIPORT")) {
_deviceNum = atoi(getenv("SCUMMVM_MIDIPORT"));
_midiportName = mdGetName(_deviceNum);
} else {
var = ConfMan.get("dmedia_port").c_str();
if (strlen(var) > 0) {
for (i = 0; i < numinterfaces; i++) {
portName = mdGetName(i);
if (strcmp(var, portName) == 0) {
_deviceNum = i;
_midiportName = portName;
}
}
}
}
_midiPort = mdOpenOutPort(_midiportName);
if (!_midiPort) {
warning("Failed to open MIDI interface %s", _midiportName);
return -1;
}
_fd = mdGetFd(_midiPort);
if (!_fd) {
warning("Failed to acquire filehandle for MIDI port %s", _midiportName);
mdClosePort(_midiPort);
return -1;
}
mdSetStampMode(_midiPort, MD_NOSTAMP); /* don't use Timestamps */
return 0;
}
void MidiDriver_DMEDIA::close() {
mdClosePort(_midiPort);
_isOpen = false;
_deviceNum = 0;
_midiportName = NULL;
}
void MidiDriver_DMEDIA::send(uint32 b) {
midiDriverCommonSend(b);
MDevent event;
byte status_byte = (b & 0x000000FF);
byte first_byte = (b & 0x0000FF00) >> 8;
byte second_byte = (b & 0x00FF0000) >> 16;
event.sysexmsg = NULL;
event.msg[0] = status_byte;
event.msg[1] = first_byte;
event.msg[2] = second_byte;
switch (status_byte & 0xF0) {
case 0x80: // Note Off
case 0x90: // Note On
case 0xA0: // Polyphonic Aftertouch
case 0xB0: // Controller Change
case 0xE0: // Pitch Bending
event.msglen = 3;
break;
case 0xC0: // Programm Change
case 0xD0: // Monophonic Aftertouch
event.msglen = 2;
break;
default:
warning("DMediaMIDI driver encountered unsupported status byte: 0x%02x", status_byte);
event.msglen = 3;
break;
}
if (mdSend(_midiPort, &event, 1) != 1) {
warning("failed sending MIDI event (dump follows...)");
warning("MIDI Event (len=%u):", event.msglen);
for (int i = 0; i < event.msglen; i++)
warning("%02x ", (int)event.msg[i]);
}
}
void MidiDriver_DMEDIA::sysEx (const byte *msg, uint16 length) {
MDevent event;
char buf [1024];
assert(length + 2 <= 256);
midiDriverCommonSysEx(msg, length);
memcpy(buf, msg, length);
buf[length] = MD_EOX;
event.sysexmsg = buf;
event.msglen = length;
event.msg[0] = MD_SYSEX;
event.msg[1] = 0;
event.msg[2] = 0;
if (mdSend(_midiPort, &event, 1) != 1) {
fprintf(stderr, "failed sending MIDI SYSEX event (dump follows...)\n");
for (int i = 0; i < event.msglen; i++)
warning("%02x ", (int)event.msg[i]);
}
}
// Plugin interface
class DMediaMusicPlugin : public MusicPluginObject {
public:
const char *getName() const {
return "DMedia";
}
const char *getId() const {
return "dmedia";
}
MusicDevices getDevices() const;
Common::Error createInstance(MidiDriver **mididriver, MidiDriver::DeviceHandle = 0) const;
};
MusicDevices DMediaMusicPlugin::getDevices() const {
int numinterfaces;
int i;
char *portName;
MusicDevices devices;
// TODO: Return a different music type depending on the configuration
numinterfaces = mdInit();
if (numinterfaces <= 0) {
fprintf(stderr, "No MIDI interfaces configured.\n");
}
for (i=0; i<numinterfaces; i++) {
portName = mdGetName(0);
fprintf(stderr, "device %i %s\n", i, portName);
devices.push_back(MusicDevice(this, portName, MT_GM));
}
return devices;
}
Common::Error DMediaMusicPlugin::createInstance(MidiDriver **mididriver, MidiDriver::DeviceHandle) const {
*mididriver = new MidiDriver_DMEDIA();
return Common::kNoError;
}
//#if PLUGIN_ENABLED_DYNAMIC(DMEDIA)
//REGISTER_PLUGIN_DYNAMIC(DMEDIA, PLUGIN_TYPE_MUSIC, DMediaMusicPlugin);
//#else
REGISTER_PLUGIN_STATIC(DMEDIA, PLUGIN_TYPE_MUSIC, DMediaMusicPlugin);
//#endif
#endif

174
backends/midi/riscos.cpp Normal file
View File

@@ -0,0 +1,174 @@
/* ScummVM - Graphic Adventure Engine
*
* ScummVM is the legal property of its developers, whose names
* are too numerous to list here. Please refer to the COPYRIGHT
* file distributed with this source distribution.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program 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 <http://www.gnu.org/licenses/>.
*
*/
// Disable symbol overrides so that we can use system headers.
#define FORBIDDEN_SYMBOL_ALLOW_ALL
#include "common/scummsys.h"
#ifdef RISCOS
#include "common/error.h"
#include "common/textconsole.h"
#include "audio/musicplugin.h"
#include "audio/mpu401.h"
#include <kernel.h>
#include <swis.h>
#ifndef MIDI_TxByte
#define MIDI_TxByte 0x404C9
#endif
#ifndef MIDI_TxCommand
#define MIDI_TxCommand 0x404CA
#endif
class MidiDriver_RISCOS final : public MidiDriver_MPU401 {
public:
MidiDriver_RISCOS(int port = 0) : _isOpen(false), _port(port) {}
~MidiDriver_RISCOS() {}
int open() override;
bool isOpen() const override { return _isOpen; }
void close() override;
void send(uint32 b) override;
void sysEx(const byte *msg, uint16 length) override;
private:
_kernel_oserror *txByte(int r0);
_kernel_oserror *txCommand(int r0, int r1);
bool _isOpen;
int _port;
};
int MidiDriver_RISCOS::open() {
if (isOpen())
return MERR_ALREADY_OPEN;
_isOpen = true;
return 0;
}
void MidiDriver_RISCOS::close() {
MidiDriver_MPU401::close();
_isOpen = false;
}
void MidiDriver_RISCOS::send(uint32 b) {
assert(isOpen());
midiDriverCommonSend(b);
// Extract the MIDI data
byte status_byte = (b & 0x000000FF);
// byte first_byte = (b & 0x0000FF00) >> 8;
// byte second_byte = (b & 0x00FF0000) >> 16;
// Compute the correct length of the MIDI command. This is important,
// else things may screw up badly...
byte length;
switch (status_byte & 0xF0) {
case 0x80: // Note Off
case 0x90: // Note On
case 0xA0: // Polyphonic Aftertouch
case 0xB0: // Controller Change
case 0xE0: // Pitch Bending
length = 3;
break;
case 0xC0: // Programm Change
case 0xD0: // Monophonic Aftertouch
length = 2;
break;
default:
warning("RISC OS driver encountered unsupported status byte: 0x%02x", status_byte);
length = 3;
break;
}
// Finally send it out to the synthesizer.
txCommand(b | (length << 24) | (_port << 28), 0);
}
void MidiDriver_RISCOS::sysEx(const byte *msg, uint16 length) {
assert(isOpen());
int port = (_port << 28);
txByte(0xF0 | port);
for (; length; --length, ++msg) {
txByte(*msg | port);
}
txByte(0xF7 | port);
}
_kernel_oserror *MidiDriver_RISCOS::txByte(int r0) {
_kernel_swi_regs regs;
regs.r[0] = r0;
return _kernel_swi(MIDI_TxByte, &regs, &regs);
}
_kernel_oserror *MidiDriver_RISCOS::txCommand(int r0, int r1) {
_kernel_swi_regs regs;
regs.r[0] = r0;
regs.r[1] = r1;
return _kernel_swi(MIDI_TxCommand, &regs, &regs);
}
// Plugin interface
class RISCOSMusicPlugin : public MusicPluginObject {
public:
const char *getName() const {
return "RISC OS MIDI";
}
const char *getId() const {
return "riscos";
}
MusicDevices getDevices() const;
Common::Error createInstance(MidiDriver **mididriver, MidiDriver::DeviceHandle = 0) const;
};
MusicDevices RISCOSMusicPlugin::getDevices() const {
MusicDevices devices;
// TODO: Return a different music type depending on the configuration
// TODO: List the available devices
devices.push_back(MusicDevice(this, "", MT_GM));
return devices;
}
Common::Error RISCOSMusicPlugin::createInstance(MidiDriver **mididriver, MidiDriver::DeviceHandle device) const {
*mididriver = new MidiDriver_RISCOS();
return Common::kNoError;
}
//#if PLUGIN_ENABLED_DYNAMIC(RISCOS)
//REGISTER_PLUGIN_DYNAMIC(RISCOS, PLUGIN_TYPE_MUSIC, RISCOSMusicPlugin);
//#else
REGISTER_PLUGIN_STATIC(RISCOS, PLUGIN_TYPE_MUSIC, RISCOSMusicPlugin);
//#endif
#endif // RISCOS

395
backends/midi/seq.cpp Normal file
View File

@@ -0,0 +1,395 @@
/* ScummVM - Graphic Adventure Engine
*
* ScummVM is the legal property of its developers, whose names
* are too numerous to list here. Please refer to the COPYRIGHT
* file distributed with this source distribution.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program 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 <http://www.gnu.org/licenses/>.
*
*/
/*
* Raw output support by Michael Pearce
* Alsa support by Nicolas Noble <nicolas@nobis-crew.org> copied from
* both the QuickTime support and (vkeybd https://web.archive.org/web/20070629122111/http://www.alsa-project.org/~iwai/alsa.html)
*/
// Disable symbol overrides so that we can use system headers.
#define FORBIDDEN_SYMBOL_ALLOW_ALL
#include "common/scummsys.h"
#if defined(USE_SEQ_MIDI)
#include "common/error.h"
#include "common/textconsole.h"
#include "common/util.h"
#include "audio/musicplugin.h"
#include "audio/mpu401.h"
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <sys/ioctl.h>
#include <sys/soundcard.h>
////////////////////////////////////////
//
// Unix dev/sequencer driver
//
////////////////////////////////////////
#define SEQ_MIDIPUTC 5
class MidiDriver_SEQ : public MidiDriver_MPU401 {
public:
MidiDriver_SEQ(int port, bool isSynth);
int open() override;
bool isOpen() const override { return _isOpen; }
void close() override;
void send(uint32 b) override;
void sysEx(const byte *msg, uint16 length) override;
static const char *getDeviceName();
private:
bool _isSynth;
bool _isOpen;
int _device;
int _port;
};
MidiDriver_SEQ::MidiDriver_SEQ(int port, bool isSynth) {
_isOpen = false;
_isSynth = isSynth;
_device = -1;
_port = port;
}
int MidiDriver_SEQ::open() {
if (_isOpen)
return MERR_ALREADY_OPEN;
const char *deviceName = getDeviceName();
_isOpen = true;
_device = ::open(deviceName, O_RDWR, 0);
if (_device < 0) {
warning("Cannot open rawmidi device %s - using /dev/null (no music will be heard)", deviceName);
_device = (::open(("/dev/null"), O_RDWR, 0));
if (_device < 0)
error("Cannot open /dev/null to dump midi output");
}
return 0;
}
void MidiDriver_SEQ::close() {
MidiDriver_MPU401::close();
if (_isOpen)
::close(_device);
_isOpen = false;
}
void MidiDriver_SEQ::send(uint32 b) {
midiDriverCommonSend(b);
unsigned char buf[256];
int position = 0;
if (_isSynth) {
switch (b & 0xf0) {
case 0x80:
case 0x90:
case 0xa0:
buf[position++] = EV_CHN_VOICE;
buf[position++] = _port;
buf[position++] = (unsigned char)(b & 0xf0);
buf[position++] = (unsigned char)(b & 0x0f);
buf[position++] = (unsigned char)((b >> 8) & 0xff);
buf[position++] = (unsigned char)((b >> 16) & 0xff);
buf[position++] = 0;
buf[position++] = 0;
break;
case 0xc0: // Program change
case 0xd0: // Channel pressure
buf[position++] = EV_CHN_COMMON;
buf[position++] = _port;
buf[position++] = (unsigned char)(b & 0xf0);
buf[position++] = (unsigned char)(b & 0x0f);
buf[position++] = (unsigned char)((b >> 8) & 0xff);
buf[position++] = 0;
buf[position++] = 0;
buf[position++] = 0;
break;
case 0xb0: // Control change
buf[position++] = EV_CHN_COMMON;
buf[position++] = _port;
buf[position++] = (unsigned char)(b & 0xf0);
buf[position++] = (unsigned char)(b & 0x0f);
buf[position++] = (unsigned char)((b >> 8) & 0xff);
buf[position++] = 0;
// TODO/FIXME?: Main volume control in the soundcard.h macros is value*16383/100, expression is value*128, and pan is (value+128)/2
// Not sure how those translate to the scales we're using here.
*reinterpret_cast<uint16 *>(buf + position) = static_cast<uint16>((b >> 16) & 0xffff);
position += 2;
break;
case 0xe0: // Pitch bend
buf[position++] = EV_CHN_COMMON;
buf[position++] = _port;
buf[position++] = (unsigned char)(b & 0xf0);
buf[position++] = (unsigned char)(b & 0x0f);
buf[position++] = 0;
buf[position++] = 0;
*reinterpret_cast<uint16 *>(buf + position) = static_cast<uint16>((b >> 8) & 0xffff);
position += 2;
break;
default:
warning("MidiDriver_SEQ::send: unknown: %08x", (int)b);
break;
}
} else {
switch (b & 0xF0) {
case 0x80:
case 0x90:
case 0xA0:
case 0xB0:
case 0xE0:
buf[position++] = SEQ_MIDIPUTC;
buf[position++] = (unsigned char)b;
buf[position++] = _port;
buf[position++] = 0;
buf[position++] = SEQ_MIDIPUTC;
buf[position++] = (unsigned char)((b >> 8) & 0x7F);
buf[position++] = _port;
buf[position++] = 0;
buf[position++] = SEQ_MIDIPUTC;
buf[position++] = (unsigned char)((b >> 16) & 0x7F);
buf[position++] = _port;
buf[position++] = 0;
break;
case 0xC0:
case 0xD0:
buf[position++] = SEQ_MIDIPUTC;
buf[position++] = (unsigned char)b;
buf[position++] = _port;
buf[position++] = 0;
buf[position++] = SEQ_MIDIPUTC;
buf[position++] = (unsigned char)((b >> 8) & 0x7F);
buf[position++] = _port;
buf[position++] = 0;
break;
default:
warning("MidiDriver_SEQ::send: unknown: %08x", (int)b);
break;
}
}
if (write(_device, buf, position) == -1)
warning("MidiDriver_SEQ::send: write failed (%s)", strerror(errno));
}
void MidiDriver_SEQ::sysEx(const byte *msg, uint16 length) {
unsigned char buf [266*4];
int position = 0;
const byte *chr = msg;
assert(length + 2 <= 266);
midiDriverCommonSysEx(msg, length);
if (_isSynth) {
int chunksRequired = (length + 7) / 6;
assert(chunksRequired * 8 <= static_cast<int>(sizeof(buf)));
for (int i = 0; i < chunksRequired; i++) {
int chunkStart = i * 6;
buf[position++] = EV_SYSEX;
buf[position++] = _port;
for (int j = 0; j < 6; j++) {
int pos = chunkStart + j - 1;
if (pos < 0)
buf[position++] = 0xf0;
else if (pos < length)
buf[position++] = msg[pos];
else if (pos == length)
buf[position++] = 0x7f;
else
buf[position++] = 0xff;
}
}
} else {
buf[position++] = SEQ_MIDIPUTC;
buf[position++] = 0xF0;
buf[position++] = _port;
buf[position++] = 0;
for (; length; --length, ++chr) {
buf[position++] = SEQ_MIDIPUTC;
buf[position++] = (unsigned char)*chr & 0x7F;
buf[position++] = _port;
buf[position++] = 0;
}
buf[position++] = SEQ_MIDIPUTC;
buf[position++] = 0xF7;
buf[position++] = _port;
buf[position++] = 0;
}
if (write(_device, buf, position) == -1)
warning("MidiDriver_SEQ::send: write failed (%s)", strerror(errno));
}
const char *MidiDriver_SEQ::getDeviceName() {
const char *devName = getenv("SCUMMVM_MIDI");
if (devName)
return devName;
else
return "/dev/sequencer";
}
// Plugin interface
class SeqMusicPlugin : public MusicPluginObject {
public:
const char *getName() const {
return "SEQ";
}
const char *getId() const {
return "seq";
}
MusicDevices getDevices() const;
Common::Error createInstance(MidiDriver **mididriver, MidiDriver::DeviceHandle = 0) const;
bool checkDevice(MidiDriver::DeviceHandle hdl, int checkFlags, bool quiet) const;
private:
void addMidiDevices(int deviceFD, MusicDevices &devices, Common::Array<int> *portIDs) const;
void addSynthDevices(int deviceFD, MusicDevices &devices, Common::Array<int> *portIDs) const;
};
MusicDevices SeqMusicPlugin::getDevices() const {
MusicDevices devices;
int deviceFD = ::open(MidiDriver_SEQ::getDeviceName(), O_RDWR, 0);
if (deviceFD >= 0) {
addMidiDevices(deviceFD, devices, nullptr);
addSynthDevices(deviceFD, devices, nullptr);
::close(deviceFD);
}
return devices;
}
void SeqMusicPlugin::addMidiDevices(int deviceFD, MusicDevices &devices, Common::Array<int> *portIDs) const {
int midiDeviceCount = 0;
if (ioctl(deviceFD, SNDCTL_SEQ_NRMIDIS, &midiDeviceCount) == 0) {
for (int i = 0; i < midiDeviceCount; i++) {
midi_info midiInfo;
midiInfo.device = i;
if (ioctl(deviceFD, SNDCTL_MIDI_INFO, &midiInfo) == 0) {
devices.push_back(MusicDevice(this, midiInfo.name, MT_GM)); // dev_type is unimplemented so we just assume GM
if (portIDs)
portIDs->push_back(i);
}
}
}
}
void SeqMusicPlugin::addSynthDevices(int deviceFD, MusicDevices &devices, Common::Array<int> *portIDs) const {
int synthDeviceCount = 0;
if (ioctl(deviceFD, SNDCTL_SEQ_NRSYNTHS, &synthDeviceCount) == 0) {
for (int i = 0; i < synthDeviceCount; i++) {
synth_info synthInfo;
synthInfo.device = i;
if (ioctl(deviceFD, SNDCTL_SYNTH_ID, &synthInfo) == 0) {
MusicType musicType = MT_GM;
if (synthInfo.synth_type == SYNTH_TYPE_FM)
musicType = MT_ADLIB;
devices.push_back(MusicDevice(this, synthInfo.name, musicType)); // dev_type is unimplemented so we just assume GM
if (portIDs)
portIDs->push_back(i);
}
}
}
}
Common::Error SeqMusicPlugin::createInstance(MidiDriver **mididriver, MidiDriver::DeviceHandle dev) const {
int port = 0;
bool isSynth = false;
bool found = false;
if (dev) {
Common::String deviceIDString = MidiDriver::getDeviceString(dev, MidiDriver::kDeviceId);
MusicDevices devices;
Common::Array<int> ports;
int firstSynthIndex = 0;
int deviceFD = ::open(MidiDriver_SEQ::getDeviceName(), O_RDONLY, 0);
if (deviceFD >= 0) {
addMidiDevices(deviceFD, devices, &ports);
firstSynthIndex = static_cast<int>(ports.size());
addSynthDevices(deviceFD, devices, &ports);
::close(deviceFD);
} else {
warning("Device enumeration failed when creating device");
}
int devIndex = 0;
for (auto &d : devices) {
if (d.getCompleteId().equals(deviceIDString)) {
found = true;
isSynth = (devIndex >= firstSynthIndex);
port = ports[devIndex];
break;
}
devIndex++;
}
}
if (found) {
*mididriver = new MidiDriver_SEQ(port, isSynth);
return Common::kNoError;
}
return Common::kAudioDeviceInitFailed;
}
bool SeqMusicPlugin::checkDevice(MidiDriver::DeviceHandle hdl, int checkFlags, bool quiet) const {
return true;
}
//#if PLUGIN_ENABLED_DYNAMIC(SEQ)
//REGISTER_PLUGIN_DYNAMIC(SEQ, PLUGIN_TYPE_MUSIC, SeqMusicPlugin);
//#else
REGISTER_PLUGIN_STATIC(SEQ, PLUGIN_TYPE_MUSIC, SeqMusicPlugin);
//#endif
#endif

156
backends/midi/sndio.cpp Normal file
View File

@@ -0,0 +1,156 @@
/* ScummVM - Graphic Adventure Engine
*
* ScummVM is the legal property of its developers, whose names
* are too numerous to list here. Please refer to the COPYRIGHT
* file distributed with this source distribution.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program 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 <http://www.gnu.org/licenses/>.
*
*/
// Disable symbol overrides so that we can use system headers.
#define FORBIDDEN_SYMBOL_ALLOW_ALL
#include "common/scummsys.h"
#if defined(USE_SNDIO)
#include "common/error.h"
#include "common/textconsole.h"
#include "common/util.h"
#include "audio/musicplugin.h"
#include "audio/mpu401.h"
#include <sndio.h>
////////////////////////////////////////
//
// sndio MIDI driver
//
////////////////////////////////////////
class MidiDriver_Sndio : public MidiDriver_MPU401 {
public:
MidiDriver_Sndio();
int open() override;
bool isOpen() const override { return hdl != NULL; }
void close() override;
void send(uint32 b) override;
void sysEx(const byte *msg, uint16 length) override;
private:
struct mio_hdl *hdl;
};
MidiDriver_Sndio::MidiDriver_Sndio() {
hdl = NULL;
}
int MidiDriver_Sndio::open() {
if (hdl != NULL)
return MERR_ALREADY_OPEN;
hdl = ::mio_open(NULL, MIO_OUT, 0);
if (hdl == NULL)
warning("Could open MIDI port (no music)");
return 0;
}
void MidiDriver_Sndio::close() {
MidiDriver_MPU401::close();
if (!hdl)
return;
mio_close(hdl);
hdl = NULL;
}
void MidiDriver_Sndio::send(uint32 b) {
unsigned char buf[4];
unsigned int len;
midiDriverCommonSend(b);
if (!hdl)
return;
buf[0] = b & 0xff;
buf[1] = (b >> 8) & 0xff;
buf[2] = (b >> 16) & 0xff;
buf[3] = (b >> 24) & 0xff;
switch (buf[0] & 0xf0) {
case 0xf0:
return;
case 0xc0:
case 0xd0:
len = 2;
break;
default:
len = 3;
}
mio_write(hdl, buf, len);
}
void MidiDriver_Sndio::sysEx(const byte *msg, uint16 length) {
if (!hdl)
return;
unsigned char buf[266];
assert(length + 2 <= ARRAYSIZE(buf));
midiDriverCommonSysEx(msg, length);
// Add SysEx frame
buf[0] = 0xF0;
memcpy(buf + 1, msg, length);
buf[length + 1] = 0xF7;
mio_write(hdl, buf, length + 2);
}
// Plugin interface
class SndioMusicPlugin : public MusicPluginObject {
public:
const char *getName() const {
return "Sndio";
}
const char *getId() const {
return "sndio";
}
MusicDevices getDevices() const;
Common::Error createInstance(MidiDriver **mididriver, MidiDriver::DeviceHandle = 0) const;
};
MusicDevices SndioMusicPlugin::getDevices() const {
MusicDevices devices;
devices.push_back(MusicDevice(this, "", MT_GM));
return devices;
}
Common::Error SndioMusicPlugin::createInstance(MidiDriver **mididriver, MidiDriver::DeviceHandle) const {
*mididriver = new MidiDriver_Sndio();
return Common::kNoError;
}
//#if PLUGIN_ENABLED_DYNAMIC(Sndio)
//REGISTER_PLUGIN_DYNAMIC(SNDIO, PLUGIN_TYPE_MUSIC, SndioMusicPlugin);
//#else
REGISTER_PLUGIN_STATIC(SNDIO, PLUGIN_TYPE_MUSIC, SndioMusicPlugin);
//#endif
#endif

149
backends/midi/stmidi.cpp Normal file
View File

@@ -0,0 +1,149 @@
/* ScummVM - Graphic Adventure Engine
*
* ScummVM is the legal property of its developers, whose names
* are too numerous to list here. Please refer to the COPYRIGHT
* file distributed with this source distribution.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program 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 <http://www.gnu.org/licenses/>.
*
*/
/*
* Raw MIDI output for the Atari ST line of computers.
* Based on the ScummVM SEQ & CoreMIDI drivers.
* Atari code by Keith Scroggins
* We, unfortunately, could not use the SEQ driver because the /dev/midi under
* FreeMiNT (and hence in libc) is considered to be a serial port for machine
* access. So, we just use OS calls then to send the data to the MIDI ports
* directly. The current implementation is sending 1 byte at a time because
* in most cases we are only sending up to 3 bytes, I believe this saves a few
* cycles. I might change so sysex messages are sent the other way later.
*/
// Disable symbol overrides so that we can use system headers.
#define FORBIDDEN_SYMBOL_ALLOW_ALL
#include "common/scummsys.h"
#if defined(__MINT__)
#include <osbind.h>
#include "audio/mpu401.h"
#include "common/error.h"
#include "common/util.h"
#include "audio/musicplugin.h"
class MidiDriver_STMIDI : public MidiDriver_MPU401 {
public:
MidiDriver_STMIDI() : _isOpen (false) { }
int open();
bool isOpen() const { return _isOpen; }
void close();
void send(uint32 b) override;
void sysEx(const byte *msg, uint16 length);
private:
bool _isOpen;
};
int MidiDriver_STMIDI::open() {
if (_isOpen && (!Bcostat(4)))
return MERR_ALREADY_OPEN;
warning("ST Midi Port Open");
_isOpen = true;
return 0;
}
void MidiDriver_STMIDI::close() {
MidiDriver_MPU401::close();
_isOpen = false;
}
void MidiDriver_STMIDI::send(uint32 b) {
midiDriverCommonSend(b);
byte status_byte = (b & 0x000000FF);
byte first_byte = (b & 0x0000FF00) >> 8;
byte second_byte = (b & 0x00FF0000) >> 16;
// warning("ST MIDI Packet sent");
switch (b & 0xF0) {
case 0x80: // Note Off
case 0x90: // Note On
case 0xA0: // Polyphonic Key Pressure
case 0xB0: // Controller
case 0xE0: // Pitch Bend
Bconout(DEV_MIDI, status_byte);
Bconout(DEV_MIDI, first_byte);
Bconout(DEV_MIDI, second_byte);
break;
case 0xC0: // Program Change
case 0xD0: // Aftertouch
Bconout(DEV_MIDI, status_byte);
Bconout(DEV_MIDI, first_byte);
break;
default:
fprintf(stderr, "Unknown : %08x\n", (int)b);
break;
}
}
void MidiDriver_STMIDI::sysEx (const byte *msg, uint16 length) {
midiDriverCommonSysEx(msg, length);
warning("Sending SysEx Message (%d bytes)", length);
Bconout(DEV_MIDI, 0xF0);
Midiws(length-1, msg);
Bconout(DEV_MIDI, 0xF7);
}
// Plugin interface
class StMidiMusicPlugin : public MusicPluginObject {
public:
const char *getName() const {
return "STMIDI";
}
const char *getId() const {
return "stmidi";
}
MusicDevices getDevices() const;
Common::Error createInstance(MidiDriver **mididriver, MidiDriver::DeviceHandle = 0) const;
};
MusicDevices StMidiMusicPlugin::getDevices() const {
MusicDevices devices;
// TODO: Return a different music type depending on the configuration
// TODO: List the available devices
devices.push_back(MusicDevice(this, "", MT_GM));
return devices;
}
Common::Error StMidiMusicPlugin::createInstance(MidiDriver **mididriver, MidiDriver::DeviceHandle) const {
*mididriver = new MidiDriver_STMIDI();
return Common::kNoError;
}
//#if PLUGIN_ENABLED_DYNAMIC(STMIDI)
//REGISTER_PLUGIN_DYNAMIC(STMIDI, PLUGIN_TYPE_MUSIC, StMidiMusicPlugin);
//#else
REGISTER_PLUGIN_STATIC(STMIDI, PLUGIN_TYPE_MUSIC, StMidiMusicPlugin);
//#endif
#endif

549
backends/midi/timidity.cpp Normal file
View File

@@ -0,0 +1,549 @@
/* ScummVM - Graphic Adventure Engine
*
* ScummVM is the legal property of its developers, whose names
* are too numerous to list here. Please refer to the COPYRIGHT
* file distributed with this source distribution.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program 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 <http://www.gnu.org/licenses/>.
*
*/
/*
* Output to TiMidity++ MIDI server support
* by Dmitry Marakasov <amdmi3@amdmi3.ru>
* based on:
* - Raw output support (seq.cpp) by Michael Pearce
* - Pseudo /dev/sequencer of TiMidity (timidity-io.c)
* by Masanao Izumo <mo@goice.co.jp>
* - sys/soundcard.h by Hannu Savolainen (got from my FreeBSD
* distribution, for which it was modified by Luigi Rizzo)
*
*/
// Disable symbol overrides so that we can use system headers.
#define FORBIDDEN_SYMBOL_ALLOW_ALL
#include "common/scummsys.h"
#if defined(USE_TIMIDITY)
#include "common/endian.h"
#include "common/error.h"
#include "common/str.h"
#include "common/textconsole.h"
#include "audio/musicplugin.h"
#include "audio/mpu401.h"
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/param.h>
#include <netdb.h> /* for getaddrinfo */
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdarg.h>
#include <stdlib.h>
#include <errno.h>
// BeOS BONE uses snooze (x/1000) in place of usleep(x)
#ifdef __BEOS__
#define usleep(v) snooze(v/1000)
#endif
#define SEQ_MIDIPUTC 5
#define TIMIDITY_LOW_DELAY
#ifdef TIMIDITY_LOW_DELAY
#define BUF_LOW_SYNC 0.1
#define BUF_HIGH_SYNC 0.15
#else
#define BUF_LOW_SYNC 0.4
#define BUF_HIGH_SYNC 0.8
#endif
/* default host & port */
#define DEFAULT_TIMIDITY_HOST "127.0.0.1"
#define DEFAULT_TIMIDITY_PORT "7777"
class MidiDriver_TIMIDITY : public MidiDriver_MPU401 {
public:
MidiDriver_TIMIDITY();
int open() override;
bool isOpen() const override { return _isOpen; }
void close() override;
void send(uint32 b) override;
void sysEx(const byte *msg, uint16 length) override;
private:
/* creates a tcp connection to TiMidity server, returns filedesc (like open()) */
int connect_to_server(const char* hostname, const char* tcp_port);
/* send command to the server; printf-like; returns reply string */
char *timidity_ctl_command(MSVC_PRINTF const char *fmt, ...) GCC_PRINTF(2, 3);
/* timidity data socket-related stuff */
void timidity_meta_seq(int p1, int p2, int p3);
int timidity_sync(int centsec);
int timidity_eot();
/* write() analogue for any midi data */
void timidity_write_data(const void *buf, size_t nbytes);
/* get single line of server reply on control connection */
int fdgets(char *buff, size_t buff_size);
/* teardown connection to server */
void teardown();
/* close (if needed) and nullify both control and data filedescs */
void close_all();
private:
bool _isOpen;
int _device_num;
int _control_fd;
int _data_fd;
/* buffer for partial data read from _control_fd - from timidity-io.c, see fdgets() */
char _controlbuffer[BUFSIZ];
int _controlbuffer_count; /* beginning of read pointer */
int _controlbuffer_size; /* end of read pointer */
};
MidiDriver_TIMIDITY::MidiDriver_TIMIDITY() {
_isOpen = false;
_device_num = 0;
/* init fd's */
_control_fd = _data_fd = -1;
/* init buffer for control connection */
_controlbuffer_count = _controlbuffer_size = 0;
}
int MidiDriver_TIMIDITY::open() {
char *res;
char timidity_host[NI_MAXHOST];
char timidity_port[6], data_port[6];
/* count ourselves open */
if (_isOpen)
return MERR_ALREADY_OPEN;
_isOpen = true;
/* get server hostname; if not specified in env, use default */
if ((res = getenv("TIMIDITY_HOST")) == NULL)
Common::strlcpy(timidity_host, DEFAULT_TIMIDITY_HOST, sizeof(timidity_host));
else
Common::strlcpy(timidity_host, res, sizeof(timidity_host));
/* extract control port */
if ((res = strrchr(timidity_host, ':')) != NULL) {
*res++ = '\0';
Common::strlcpy(timidity_port, res, sizeof(timidity_port));
} else {
Common::strlcpy(timidity_port, DEFAULT_TIMIDITY_PORT, sizeof(timidity_port));
}
/*
* create control connection to the server
*/
if ((_control_fd = connect_to_server(timidity_host, timidity_port)) < 0) {
warning("TiMidity: can't open control connection (host=%s, port=%s)", timidity_host, timidity_port);
return -1;
}
/* should read greeting issued by server upon connect:
* "220 TiMidity++ v2.13.2 ready)" */
res = timidity_ctl_command(NULL);
if (atoi(res) != 220) {
warning("TiMidity: bad response from server (host=%s, port=%s): %s", timidity_host, timidity_port, res);
close_all();
return -1;
}
/*
* setup buf and prepare data connection
*/
/* should read: "200 OK" */
res = timidity_ctl_command("SETBUF %f %f", BUF_LOW_SYNC, BUF_HIGH_SYNC);
if (atoi(res) != 200)
warning("TiMidity: bad reply for SETBUF command: %s", res);
/* should read something like "200 63017 is ready acceptable",
* where 63017 is port for data connection */
#ifdef SCUMM_LITTLE_ENDIAN
res = timidity_ctl_command("OPEN lsb");
#else
res = timidity_ctl_command("OPEN msb");
#endif
if (atoi(res) != 200) {
warning("TiMidity: bad reply for OPEN command: %s", res);
close_all();
return -1;
}
/*
* open data connection
*/
uint num = atoi(res + 4);
if (num > 65535) {
warning("TiMidity: Invalid port %d given.\n", num);
close_all();
return -1;
}
snprintf(data_port, sizeof(data_port), "%.5d", (uint16)num);
if ((_data_fd = connect_to_server(timidity_host, data_port)) < 0) {
warning("TiMidity: can't open data connection (host=%s, port=%s)", timidity_host, data_port);
close_all();
return -1;
}
/* should read message issued after connecting to data port:
* "200 Ready data connection" */
res = timidity_ctl_command(NULL);
if (atoi(res) != 200) {
warning("Can't connect timidity: %s\t(host=%s, port=%s)", res, timidity_host, data_port);
close_all();
return -1;
}
/*
* From seq.cpp
*/
if (getenv("SCUMMVM_MIDIPORT"))
_device_num = atoi(getenv("SCUMMVM_MIDIPORT"));
return 0;
}
void MidiDriver_TIMIDITY::close() {
teardown();
MidiDriver_MPU401::close();
_isOpen = false;
}
void MidiDriver_TIMIDITY::close_all() {
if (_control_fd >= 0)
::close(_control_fd);
if (_data_fd >= 0)
::close(_data_fd);
_control_fd = _data_fd = -1;
}
void MidiDriver_TIMIDITY::teardown() {
char *res;
/* teardown connection to server (see timidity-io.c) if it
* is initialized */
if (_data_fd >= 0 && _control_fd >= 0) {
timidity_eot();
timidity_sync(0);
/* scroll through all "302 Data connection is (already) closed"
* messages till we reach something like "200 Bye" */
do {
res = timidity_ctl_command("QUIT");
} while (*res && atoi(res) && atoi(res) != 302);
}
/* now close and nullify both filedescs */
close_all();
}
int MidiDriver_TIMIDITY::connect_to_server(const char* hostname, const char* tcp_port) {
struct addrinfo hints;
struct addrinfo *result, *rp;
int fd = -1;
/* get all address(es) matching host and port */
memset(&hints, 0, sizeof(struct addrinfo));
hints.ai_socktype = SOCK_STREAM;
hints.ai_family = AF_UNSPEC; /* Allow IPv4 or IPv6 */
if (getaddrinfo(hostname, tcp_port, &hints, &result) != 0) {
warning("TiMidity: getaddrinfo: %s\n", strerror(errno));
return -1;
}
/* Try all address structures we have got previously */
for (rp = result; rp != NULL; rp = rp->ai_next) {
if ((fd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol)) == -1)
continue;
if (connect(fd, rp->ai_addr, rp->ai_addrlen) != -1)
break;
::close(fd);
}
freeaddrinfo(result);
if (rp == NULL) {
warning("TiMidity: Could not connect\n");
return -1;
}
return fd;
}
char *MidiDriver_TIMIDITY::timidity_ctl_command(const char *fmt, ...) {
/* XXX: I don't like this static buffer!!! */
static char buff[BUFSIZ];
va_list ap;
if (fmt != NULL) {
/* if argumends are present, write them to control connection */
va_start(ap, fmt);
int len = vsnprintf(buff, BUFSIZ-1, fmt, ap); /* leave one byte for \n */
va_end(ap);
/* add newline if needed */
if (len > 0 && buff[len - 1] != '\n')
buff[len++] = '\n';
/* write command to control socket */
if (write(_control_fd, buff, len) == -1) {
warning("TiMidity: CONTROL WRITE FAILED (%s)", strerror(errno));
// TODO: Disable output?
//close_all();
}
}
while (1) {
/* read reply */
if (fdgets(buff, sizeof(buff)) <= 0) {
Common::strcpy_s(buff, "Read error\n");
break;
}
/* report errors from server */
int status = atoi(buff);
if (400 <= status && status <= 499) { /* Error of data stream */
warning("TiMidity: error from server: %s", buff);
continue;
}
break;
}
return buff;
}
void MidiDriver_TIMIDITY::timidity_meta_seq(int p1, int p2, int p3) {
/* see _CHN_COMMON from soundcard.h; this is simplified
* to just send seq to the server without any buffers,
* delays and extra functions/macros */
unsigned char seqbuf[8];
seqbuf[0] = 0x92;
seqbuf[1] = 0;
seqbuf[2] = 0xff;
seqbuf[3] = 0x7f;
seqbuf[4] = p1;
seqbuf[5] = p2;
WRITE_UINT16(&seqbuf[6], p3);
timidity_write_data(seqbuf, sizeof(seqbuf));
}
int MidiDriver_TIMIDITY::timidity_sync(int centsec) {
char *res;
int status;
unsigned long sleep_usec;
timidity_meta_seq(0x02, 0x00, centsec); /* Wait playout */
/* Wait "301 Sync OK" */
do {
res = timidity_ctl_command(NULL);
status = atoi(res);
if (status != 301)
warning("TiMidity: error: SYNC: %s", res);
} while (status && status != 301);
if (status != 301)
return -1; /* error */
sleep_usec = (unsigned long)(atof(res + 4) * 1000000);
if (sleep_usec > 0)
usleep(sleep_usec);
return 0;
}
int MidiDriver_TIMIDITY::timidity_eot(void) {
timidity_meta_seq(0x00, 0x00, 0); /* End of playing */
return timidity_sync(0);
}
void MidiDriver_TIMIDITY::timidity_write_data(const void *buf, size_t nbytes) {
/* nowhere to write... */
if (_data_fd < 0)
return;
/* write, and disable everything if write failed */
/* TODO: add reconnect? */
if (write(_data_fd, buf, nbytes) == -1) {
warning("TiMidity: DATA WRITE FAILED (%s), DISABLING MUSIC OUTPUT", strerror(errno));
close_all();
}
}
int MidiDriver_TIMIDITY::fdgets(char *buff, size_t buff_size) {
int n, count, size;
char *buff_endp = buff + buff_size - 1, *pbuff, *beg;
count = _controlbuffer_count;
size = _controlbuffer_size;
pbuff = _controlbuffer;
beg = buff;
do {
if (count == size) {
if ((n = read(_control_fd, pbuff, BUFSIZ)) <= 0) {
*buff = '\0';
if (n == 0) {
_controlbuffer_count = _controlbuffer_size = 0;
return buff - beg;
}
return -1; /* < 0 error */
}
count = _controlbuffer_count = 0;
size = _controlbuffer_size = n;
}
*buff++ = pbuff[count++];
} while (*(buff - 1) != '\n' && buff != buff_endp);
*buff = '\0';
_controlbuffer_count = count;
return buff - beg;
}
void MidiDriver_TIMIDITY::send(uint32 b) {
unsigned char buf[256];
int position = 0;
midiDriverCommonSend(b);
switch (b & 0xF0) {
case 0x80:
case 0x90:
case 0xA0:
case 0xB0:
case 0xE0:
buf[position++] = SEQ_MIDIPUTC;
buf[position++] = (unsigned char)b;
buf[position++] = _device_num;
buf[position++] = 0;
buf[position++] = SEQ_MIDIPUTC;
buf[position++] = (unsigned char)((b >> 8) & 0x7F);
buf[position++] = _device_num;
buf[position++] = 0;
buf[position++] = SEQ_MIDIPUTC;
buf[position++] = (unsigned char)((b >> 16) & 0x7F);
buf[position++] = _device_num;
buf[position++] = 0;
break;
case 0xC0:
case 0xD0:
buf[position++] = SEQ_MIDIPUTC;
buf[position++] = (unsigned char)b;
buf[position++] = _device_num;
buf[position++] = 0;
buf[position++] = SEQ_MIDIPUTC;
buf[position++] = (unsigned char)((b >> 8) & 0x7F);
buf[position++] = _device_num;
buf[position++] = 0;
break;
default:
warning("MidiDriver_TIMIDITY::send: unknown : %08x", (int)b);
break;
}
timidity_write_data(buf, position);
}
void MidiDriver_TIMIDITY::sysEx(const byte *msg, uint16 length) {
fprintf(stderr, "Timidity::sysEx\n");
unsigned char buf[266*4];
int position = 0;
const byte *chr = msg;
assert(length + 2 <= 266);
midiDriverCommonSysEx(msg, length);
buf[position++] = SEQ_MIDIPUTC;
buf[position++] = 0xF0;
buf[position++] = _device_num;
buf[position++] = 0;
for (; length; --length, ++chr) {
buf[position++] = SEQ_MIDIPUTC;
buf[position++] = (unsigned char) *chr & 0x7F;
buf[position++] = _device_num;
buf[position++] = 0;
}
buf[position++] = SEQ_MIDIPUTC;
buf[position++] = 0xF7;
buf[position++] = _device_num;
buf[position++] = 0;
timidity_write_data(buf, position);
}
// Plugin interface
class TimidityMusicPlugin : public MusicPluginObject {
public:
const char *getName() const {
return "TiMidity";
}
const char *getId() const {
return "timidity";
}
MusicDevices getDevices() const;
Common::Error createInstance(MidiDriver **mididriver, MidiDriver::DeviceHandle = 0) const;
};
MusicDevices TimidityMusicPlugin::getDevices() const {
MusicDevices devices;
devices.push_back(MusicDevice(this, "", MT_GM));
return devices;
}
Common::Error TimidityMusicPlugin::createInstance(MidiDriver **mididriver, MidiDriver::DeviceHandle) const {
*mididriver = new MidiDriver_TIMIDITY();
return Common::kNoError;
}
//#if PLUGIN_ENABLED_DYNAMIC(TIMIDITY)
//REGISTER_PLUGIN_DYNAMIC(TIMIDITY, PLUGIN_TYPE_MUSIC, TimidityMusicPlugin);
//#else
REGISTER_PLUGIN_STATIC(TIMIDITY, PLUGIN_TYPE_MUSIC, TimidityMusicPlugin);
//#endif
#endif // defined(USE_TIMIDITY)

210
backends/midi/webmidi.cpp Normal file
View File

@@ -0,0 +1,210 @@
/* ScummVM - Graphic Adventure Engine
*
* ScummVM is the legal property of its developers, whose names
* are too numerous to list here. Please refer to the COPYRIGHT
* file distributed with this source distribution.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program 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 <http://www.gnu.org/licenses/>.
*
*/
// Disable symbol overrides so that we can use system headers.
#define FORBIDDEN_SYMBOL_EXCEPTION_FILE
#define FORBIDDEN_SYMBOL_EXCEPTION_getenv
#ifdef EMSCRIPTEN
#include <emscripten.h>
#include "audio/mpu401.h"
#include "audio/musicplugin.h"
#include "common/config-manager.h"
#include "common/debug.h"
#include "common/error.h"
#include "common/scummsys.h"
#include "common/textconsole.h"
#include "common/util.h"
/* WebMidi MIDI driver
*/
class MidiDriver_WebMIDI : public MidiDriver_MPU401 {
public:
MidiDriver_WebMIDI(Common::String name, const char *id);
~MidiDriver_WebMIDI();
int open() override;
bool isOpen() const override;
void close() override;
void send(uint32 b) override;
void sysEx(const byte *msg, uint16 length) override;
private:
Common::String _name;
const char *_id;
};
MidiDriver_WebMIDI::MidiDriver_WebMIDI(Common::String name, const char *id)
: _name(name), _id(id), MidiDriver_MPU401() {
debug(5, "WebMIDI: Creating device %s %s", _name.c_str(), _id);
}
MidiDriver_WebMIDI::~MidiDriver_WebMIDI() {
}
EM_ASYNC_JS(int, _midiOpen, (const char *id_c), {
var id = UTF8ToString(id_c);
result = await midiOutputMap.get(id).open().catch((error) => {
console.error(error);
return 1;
});
return 0;
});
int MidiDriver_WebMIDI::open() {
debug(5, "WebMIDI: Opening device %s", _name.c_str());
if (isOpen())
return MERR_ALREADY_OPEN;
return _midiOpen(_id);
}
EM_JS(bool, _midiIsOpen, (const char *id_c), {
var id = UTF8ToString(id_c);
return midiOutputMap.get(id) && midiOutputMap.get(id).connection == "open";
});
bool MidiDriver_WebMIDI::isOpen() const {
return _midiIsOpen(_id);
}
EM_ASYNC_JS(void, _midiClose, (const char *id_c), {
var id = UTF8ToString(id_c);
await midiOutputMap.get(id).close(); // TODO: Wait for promise to resolve (should be possible with Asyncify)
});
void MidiDriver_WebMIDI::close() {
debug(5, "WebMIDI: Closing device %s", _name.c_str());
MidiDriver_MPU401::close();
if(_midiIsOpen(_id))
_midiClose(_id);
else
warning("WebMIDI: Device %s is not open", _name.c_str());
}
EM_JS(void, _midiSendMessage, (const char *id_c, int status_byte, int first_byte, int second_byte), {
var id = UTF8ToString(id_c);
if (status_byte < 0xc0 || status_byte > 0xdf) {
midiOutputMap.get(id).send([status_byte, first_byte, second_byte]);
} else {
midiOutputMap.get(id).send([status_byte, first_byte]);
}
});
void MidiDriver_WebMIDI::send(uint32 b) {
if(!isOpen()) {
warning("WebMIDI: Send called on closed device %s", _name.c_str());
return;
}
debug(5, "WebMIDI: Sending message for device %s %x", _name.c_str(), b);
midiDriverCommonSend(b);
const byte status_byte = b & 0xff;
const byte first_byte = (b >> 8) & 0xff;
const byte second_byte = (b >> 16) & 0xff;
_midiSendMessage(_id, status_byte, first_byte, second_byte);
}
void MidiDriver_WebMIDI::sysEx(const byte *msg, uint16 length) {
if(!isOpen()) {
warning("WebMIDI: SysEx called on closed device %s", _name.c_str());
return;
}
midiDriverCommonSysEx(msg, length);
warning("WebMIDI: SysEx not implemented yet, skipping %d bytes", length);
}
// Plugin interface
class WebMIDIMusicPlugin : public MusicPluginObject {
public:
const char *getName() const {
return "Web Midi";
}
const char *getId() const {
return "WebMidi";
}
MusicDevices getDevices() const;
Common::Error createInstance(MidiDriver **mididriver, MidiDriver::DeviceHandle = 0) const;
};
EM_JS(char **, _midiGetOutputNames, (), {
deviceNames = Array.from(midiOutputMap || []).map((elem) => elem[1].name);
deviceNames.push(""); // we need this to find the end of the array on the native side.
// convert the strings to C strings
var c_strings = deviceNames.map((s) => {
var size = lengthBytesUTF8(s) + 1;
var ret = Module._malloc(size);
stringToUTF8Array(s, HEAP8, ret, size);
return ret;
});
// populate return array
var ret_arr = Module._malloc(c_strings.length * 4); // 4-bytes per pointer
c_strings.forEach((ptr, i) => { Module.setValue(ret_arr + i * 4, ptr, "i32"); });
return ret_arr;
});
MusicDevices WebMIDIMusicPlugin::getDevices() const {
MusicDevices devices;
char **outputNames = _midiGetOutputNames();
char **iter = outputNames;
while (strcmp(*iter, "") != 0) {
char *c_name = *iter++;
Common::String name = Common::String(c_name);
devices.push_back(MusicDevice(this, name, MT_GM));
free(c_name);
}
free(outputNames);
return devices;
}
EM_JS(const char *, _midiGetOutputId, (const char *name_c), {
var name = UTF8ToString(name_c);
for (const [key, midiOutput] of midiOutputMap.entries()) {
if (midiOutput.name == name) {
return stringToNewUTF8(key)
}
}
return;
});
Common::Error WebMIDIMusicPlugin::createInstance(MidiDriver **mididriver, MidiDriver::DeviceHandle device) const {
MusicDevices deviceList = getDevices();
for (MusicDevices::iterator j = deviceList.begin(), jend = deviceList.end(); j != jend; ++j) {
if (j->getHandle() == device) {
*mididriver = new MidiDriver_WebMIDI(j->getName(), _midiGetOutputId(j->getName().c_str()));
return Common::kNoError;
}
}
return Common::kUnknownError;
}
//#if PLUGIN_ENABLED_DYNAMIC(WebMidi)
//REGISTER_PLUGIN_DYNAMIC(WebMidi, PLUGIN_TYPE_MUSIC, WebMIDIMusicPlugin);
//#else
REGISTER_PLUGIN_STATIC(WEBMIDI, PLUGIN_TYPE_MUSIC, WebMIDIMusicPlugin);
//#endif
#endif // EMSCRIPTEN

266
backends/midi/windows.cpp Normal file
View File

@@ -0,0 +1,266 @@
/* ScummVM - Graphic Adventure Engine
*
* ScummVM is the legal property of its developers, whose names
* are too numerous to list here. Please refer to the COPYRIGHT
* file distributed with this source distribution.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program 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 <http://www.gnu.org/licenses/>.
*
*/
// Disable symbol overrides so that we can use system headers.
#define FORBIDDEN_SYMBOL_ALLOW_ALL
#include "common/scummsys.h"
#if defined(WIN32)
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include "audio/musicplugin.h"
#include "audio/mpu401.h"
#include "backends/platform/sdl/win32/win32_wrapper.h"
#include "common/config-manager.h"
#include "common/translation.h"
#include "common/textconsole.h"
#include "common/error.h"
#include <mmsystem.h>
////////////////////////////////////////
//
// Windows MIDI driver
//
////////////////////////////////////////
class MidiDriver_WIN final : public MidiDriver_MPU401 {
private:
MIDIHDR _streamHeader;
byte _streamBuffer[266]; // SysEx blocks should be no larger than 266 bytes
HANDLE _streamEvent;
HMIDIOUT _mo;
bool _isOpen;
int _device;
void check_error(MMRESULT result);
public:
MidiDriver_WIN(int deviceIndex) : _isOpen(false), _device(deviceIndex) { }
int open() override;
bool isOpen() const override { return _isOpen; }
void close() override;
void send(uint32 b) override;
void sysEx(const byte *msg, uint16 length) override;
};
int MidiDriver_WIN::open() {
if (_isOpen)
return MERR_ALREADY_OPEN;
_streamEvent = CreateEvent(nullptr, true, true, nullptr);
MMRESULT res = midiOutOpen((HMIDIOUT *)&_mo, _device, (DWORD_PTR)_streamEvent, 0, CALLBACK_EVENT);
if (res != MMSYSERR_NOERROR) {
check_error(res);
CloseHandle(_streamEvent);
return MERR_DEVICE_NOT_AVAILABLE;
}
_isOpen = true;
return 0;
}
void MidiDriver_WIN::close() {
if (!_isOpen)
return;
_isOpen = false;
MidiDriver_MPU401::close();
midiOutUnprepareHeader(_mo, &_streamHeader, sizeof(_streamHeader));
check_error(midiOutClose(_mo));
CloseHandle(_streamEvent);
}
void MidiDriver_WIN::send(uint32 b) {
assert(_isOpen);
midiDriverCommonSend(b);
union {
DWORD dwData;
BYTE bData[4];
} u;
u.bData[3] = (byte)((b & 0xFF000000) >> 24);
u.bData[2] = (byte)((b & 0x00FF0000) >> 16);
u.bData[1] = (byte)((b & 0x0000FF00) >> 8);
u.bData[0] = (byte)(b & 0x000000FF);
check_error(midiOutShortMsg(_mo, u.dwData));
}
void MidiDriver_WIN::sysEx(const byte *msg, uint16 length) {
if (!_isOpen)
return;
if (WaitForSingleObject (_streamEvent, 2000) == WAIT_TIMEOUT) {
warning ("Could not send SysEx - MMSYSTEM is still trying to send data");
return;
}
assert(length+2 <= 266);
midiDriverCommonSysEx(msg, length);
midiOutUnprepareHeader(_mo, &_streamHeader, sizeof(_streamHeader));
// Add SysEx frame
_streamBuffer[0] = 0xF0;
memcpy(&_streamBuffer[1], msg, length);
_streamBuffer[length+1] = 0xF7;
_streamHeader.lpData = (char *)_streamBuffer;
_streamHeader.dwBufferLength = length + 2;
_streamHeader.dwBytesRecorded = length + 2;
_streamHeader.dwUser = 0;
_streamHeader.dwFlags = 0;
MMRESULT result = midiOutPrepareHeader(_mo, &_streamHeader, sizeof(_streamHeader));
if (result != MMSYSERR_NOERROR) {
check_error (result);
return;
}
ResetEvent(_streamEvent);
result = midiOutLongMsg(_mo, &_streamHeader, sizeof(_streamHeader));
if (result != MMSYSERR_NOERROR) {
check_error(result);
SetEvent(_streamEvent);
return;
}
}
void MidiDriver_WIN::check_error(MMRESULT result) {
TCHAR buf[MAXERRORLENGTH];
if (result != MMSYSERR_NOERROR) {
midiOutGetErrorText(result, buf, MAXERRORLENGTH);
Common::String errorMessage = Win32::tcharToString(buf);
warning("MM System Error '%s'", errorMessage.c_str());
}
}
// Plugin interface
class WindowsMusicPlugin : public MusicPluginObject {
public:
const char *getName() const override {
return _s("Windows MIDI");
}
const char *getId() const override {
return "windows";
}
MusicDevices getDevices() const override;
Common::Error createInstance(MidiDriver **mididriver, MidiDriver::DeviceHandle = 0) const override;
bool checkDevice(MidiDriver::DeviceHandle hdl, int checkFlags, bool quiet) const override;
};
MusicDevices WindowsMusicPlugin::getDevices() const {
MusicDevices devices;
int numDevs = midiOutGetNumDevs();
MIDIOUTCAPS tmp;
Common::StringArray deviceNames;
for (int i = 0; i < numDevs; i++) {
if (midiOutGetDevCaps(i, &tmp, sizeof(MIDIOUTCAPS)) != MMSYSERR_NOERROR)
break;
Common::String deviceName = Win32::tcharToString(tmp.szPname);
deviceNames.push_back(deviceName);
}
// Limit us to the number of actually retrieved devices.
numDevs = deviceNames.size();
// Check for non-unique device names. This may happen if someone has devices with identical
// names (e. g. more than one USB device of the exact same hardware type). It seems that this
// does happen in reality sometimes. We generate index numbers for these devices.
// This is not an ideal solution, since this index could change whenever another USB
// device gets plugged in or removed, switched off or just plugged into a different port.
// Unfortunately midiOutGetDevCaps() does not generate any other unique information
// that could be used. Our index numbers which match the device order should at least be
// a little more stable than just using the midiOutGetDevCaps() device ID, since a missing
// device (e.g. switched off) should actually not be harmful to our indices (as it would be
// when using the device IDs). The cases where users have devices with identical names should
// be rare enough anyway.
Common::Array<int> nonUniqueIndex;
for (int i = 0; i < numDevs; i++) {
int match = -1;
for (int ii = 0; ii < i; ii++) {
if (deviceNames[i] == deviceNames[ii]) {
if (nonUniqueIndex[ii] == -1)
nonUniqueIndex[ii] = 0;
if (++match == 0)
++match;
}
}
nonUniqueIndex.push_back(match);
}
// We now add the index number to the non-unique device names to make them unique.
for (int i = 0; i < numDevs; i++) {
if (nonUniqueIndex[i] != -1)
deviceNames[i] = Common::String::format("%s - #%.02d", deviceNames[i].c_str(), nonUniqueIndex[i]);
}
for (Common::StringArray::iterator i = deviceNames.begin(); i != deviceNames.end(); ++i)
// There is no way to detect the "MusicType" so I just set it to MT_GM
// The user will have to manually select his MT32 type device and his GM type device.
devices.push_back(MusicDevice(this, *i, MT_GM));
return devices;
}
Common::Error WindowsMusicPlugin::createInstance(MidiDriver **mididriver, MidiDriver::DeviceHandle dev) const {
int devIndex = 0;
bool found = false;
if (dev) {
Common::String deviceIDString = MidiDriver::getDeviceString(dev, MidiDriver::kDeviceId);
MusicDevices i = getDevices();
for (auto &d : i) {
if (d.getCompleteId().equals(deviceIDString)) {
found = true;
break;
}
devIndex++;
}
}
*mididriver = new MidiDriver_WIN(found ? devIndex : 0);
return Common::kNoError;
}
bool WindowsMusicPlugin::checkDevice(MidiDriver::DeviceHandle hdl, int checkFlags, bool quiet) const {
return true;
}
//#if PLUGIN_ENABLED_DYNAMIC(WINDOWS)
//REGISTER_PLUGIN_DYNAMIC(WINDOWS, PLUGIN_TYPE_MUSIC, WindowsMusicPlugin);
//#else
REGISTER_PLUGIN_STATIC(WINDOWS, PLUGIN_TYPE_MUSIC, WindowsMusicPlugin);
//#endif
#endif