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 #ifndef AUDIO_MT32GM_H 24 #define AUDIO_MT32GM_H 25 26 #include "audio/mididrv.h" 27 #include "audio/mididrv_ms.h" 28 #include "common/mutex.h" 29 #include "common/queue.h" 30 31 /** 32 * @defgroup audio_mt32_gm MIDI driver for MT-32 and GM 33 * @ingroup audio 34 * 35 * @brief MIDI driver for MT-32 and GM compatible emulators and devices. 36 * @{ 37 */ 38 39 /** 40 * MIDI driver for MT-32 and GM compatible emulators and devices. 41 * 42 * This class contains some commonly needed functionality for these devices and 43 * the MIDI data that targets them. It wraps the MidiDriver instance that does 44 * the actual communication with the MT-32 or GM device. 45 * 46 * This driver has the following features: 47 * 48 * - MIDI device initialization 49 * Construct the driver with the type of MIDI data that will be sent to it. 50 * When the driver is opened, it will create an output MIDI driver appropriate 51 * for the user configuration settings and the type of MIDI data. You can also 52 * create the output MIDI driver yourself and pass it to the open function. 53 * The driver will take care of initializing the MIDI device and setting up 54 * for playback of MT-32 data on a GM/GS device or the other way around. 55 * 56 * - MT-32 <> GM conversion 57 * If the incoming MIDI data has been set to MT-32 and the output device is 58 * GM, the driver will map MT-32 instruments to GM equivalents. GM playback 59 * on an MT-32 device is also supported. Set the _mt32ToGMInstrumentMap and 60 * _gmToMT32InstrumentMap variables to override the standard instrument maps, 61 * or override the mapMT32InstrumentToGM and mapGMInstrumentToMT32 functions 62 * for more advanced mapping algorithms. 63 * 64 * - Reverse stereo 65 * If the game has MIDI data with reversed stereo compared to the targeted 66 * output device, set the MIDI_DATA_REVERSE_PANNING property to reverse 67 * stereo. The driver wil automatically reverse stereo when MT-32 data is 68 * sent to a GM/GS device or the other way around. 69 * 70 * - Correct Roland GS bank and drumkit selects 71 * Some games' MIDI data relies on a feature of the Roland SC-55 MIDI module 72 * which automatically corrects invalid bank selects and drumkit program 73 * changes. The driver replicates this feature to ensure correct instrument 74 * banks and drumkits on other hardware or softsynths. 75 * 76 * - SysEx queue 77 * The sysExQueue function will queue a SysEx message and return immediately. 78 * You can send more messages to the queue while the driver sends the 79 * messages asynchronously with the necessary delays to the MIDI device. Use 80 * the isReady function to check if the device has received all messages and 81 * is ready to start playback. Use this instead of the sysEx function to 82 * prevent the main game loop from being blocked while the driver waits the 83 * necessary amount of time for the MIDI device to process the message. 84 * Use clearSysExQueue to remove all messages from the queue, in case device 85 * initialization has to be aborted. 86 * 87 * - Multiple MIDI sources 88 * If the game plays multiple streams of MIDI data at the same time, each 89 * stream can be marked with a source number. This enables the following 90 * feature: 91 * - Channel mapping 92 * If multiple sources use the same MIDI channels, the driver can map the 93 * data channels to different output channels to avoid conflicts. Use 94 * allocateSourceChannels to allocate output channels to a source. The 95 * data channels are automatically mapped to the allocated output channels 96 * during playback. The allocated channels are freed when the source is 97 * deinitialized. 98 * If you only have one source of MIDI data or the sources do not use 99 * conflicting channels, you do not need to allocate channels - the channels 100 * in the MIDI data will be used directly. If you do use this feature, you 101 * have to use it for all MIDI sources to avoid channel conflicts. 102 * The standard channel allocation scheme will allocate the available output 103 * channels with the lowest numbers and will fail if not enough channels are 104 * available. You can override the allocateSourceChannels and 105 * mapSourceChannel functions to customize the allocation and mapping 106 * algorithms. 107 * Note that you can also use the "standard" way of allocating channels 108 * using the allocateChannel function and MidiChannel objects. These two 109 * methods are not coordinated in any way, so don't use both at the same 110 * time. 111 */ 112 class MidiDriver_MT32GM : public MidiDriver_Multisource { 113 public: 114 static const byte MT32_DEFAULT_INSTRUMENTS[8]; 115 static const byte MT32_DEFAULT_PANNING[8]; 116 static const uint8 MT32_DEFAULT_CHANNEL_VOLUME = 98; 117 static const uint8 GM_DEFAULT_CHANNEL_VOLUME = 100; 118 // Map for correcting Roland GS drumkit numbers. 119 static const uint8 GS_DRUMKIT_FALLBACK_MAP[128]; 120 121 static const uint8 MT32_DISPLAY_NUM_CHARS = 20; 122 static const uint32 MT32_DISPLAY_MEMORY_ADDRESS = 0x20 << 14; 123 124 protected: 125 static const uint8 MAXIMUM_MT32_ACTIVE_NOTES = 48; 126 static const uint8 MAXIMUM_GM_ACTIVE_NOTES = 96; 127 128 protected: 129 /** 130 * This stores the values of the MIDI controllers for 131 * a MIDI channel. It is used to keep track of controller 132 * values while a channel is locked, so they can be 133 * restored when the channel is unlocked. 134 */ 135 struct MidiChannelControlData { 136 // The source that last sent an event to this channel 137 int8 source; 138 // True if the source volume has been applied to this channel 139 bool sourceVolumeApplied; 140 141 uint16 pitchWheel; 142 byte program; 143 // The Roland GS instrument bank 144 byte instrumentBank; 145 146 byte modulation; 147 // The volume specified by the MIDI data 148 byte volume; 149 // The volume set on the MIDI device. This is scaled using the source 150 // volume and optionally the user-specified volume setting. 151 byte scaledVolume; 152 byte panPosition; 153 byte expression; 154 bool sustain; 155 MidiChannelControlDataMidiChannelControlData156 MidiChannelControlData() : source(-1), 157 sourceVolumeApplied(false), 158 pitchWheel(MIDI_PITCH_BEND_DEFAULT), 159 program(0), 160 instrumentBank(0), 161 modulation(0), 162 volume(0), 163 scaledVolume(0), 164 panPosition(0x40), 165 expression(0x7F), 166 sustain(false) { } 167 }; 168 169 /** 170 * This stores data about a specific source of MIDI data. 171 */ 172 struct MidiSource { 173 // Whether this source sends music or SFX MIDI data. 174 SourceType type; 175 // The source volume (relative volume for this source as defined by the game). 176 // Default is the default neutral value (255). 177 uint16 volume; 178 // The source volume level at which no scaling is performed (volume as defined 179 // in MIDI data is used directly). Volume values below this decrease volume, 180 // values above increase volume (up to the maximum MIDI channel volume). 181 // Set this to match the volume values used by the game engine to avoid having 182 // to convert them. Default value is 255; minimum value is 1. 183 uint16 neutralVolume; 184 // The volume level at which the fade started. 185 uint16 fadeStartVolume; 186 // The target volume level for the fade. 187 uint16 fadeEndVolume; 188 // How much us has passed since the start of the fade. 189 int32 fadePassedTime; 190 // The total duration of the fade (us). 191 int32 fadeDuration; 192 // The mapping of MIDI data channels to output channels for this source. 193 int8 channelMap[MIDI_CHANNEL_COUNT]; 194 // Bitmask specifying which MIDI channels are available for use by this source. 195 uint16 availableChannels; 196 MidiSourceMidiSource197 MidiSource() : type(SOURCE_TYPE_UNDEFINED), volume(DEFAULT_SOURCE_NEUTRAL_VOLUME), 198 neutralVolume(DEFAULT_SOURCE_NEUTRAL_VOLUME), fadeStartVolume(0), 199 fadeEndVolume(0), fadePassedTime(0), fadeDuration(0), availableChannels(0xFFFF) { 200 memset(channelMap, 0, sizeof(channelMap)); 201 } 202 }; 203 204 /** 205 * This stores information about a note currently playing on the MIDI 206 * device. 207 */ 208 struct ActiveNote { 209 int8 source; 210 uint8 channel; 211 uint8 note; 212 // True if the note is sustained. The note will turn off when the 213 // sustain controller for the MIDI channel is turned off. 214 bool sustain; 215 ActiveNoteActiveNote216 ActiveNote() { clear(); } 217 clearActiveNote218 void clear() { 219 source = 0x7F; 220 channel = 0xFF; 221 note = 0xFF; 222 sustain = false; 223 } 224 225 }; 226 227 /** 228 * Stores data which is to be transmitted as a SysEx message to a MIDI 229 * device. Neither data nor length should include the SysEx start and stop 230 * bytes. 231 */ 232 struct SysExData { 233 byte data[270]; 234 uint16 length; SysExDataSysExData235 SysExData() : length(0) { 236 memset(data, 0, sizeof(data)); 237 } 238 }; 239 240 public: 241 // Callback hooked up to the driver wrapped by the MIDI driver 242 // object. Executes onTimer and the external callback set by 243 // the setTimerCallback function. 244 static void timerCallback(void *data); 245 246 MidiDriver_MT32GM(MusicType midiType); 247 ~MidiDriver_MT32GM(); 248 249 // MidiDriver interface 250 int open() override; 251 // Open the driver wrapping the specified MidiDriver instance. 252 virtual int open(MidiDriver *driver, bool nativeMT32); 253 void close() override; isOpen()254 bool isOpen() const override { return _isOpen; } isReady()255 bool isReady() override { 256 Common::StackLock lock(_sysExQueueMutex); 257 return _sysExQueue.empty(); 258 } 259 uint32 property(int prop, uint32 param) override; 260 261 using MidiDriver_BASE::send; 262 void send(uint32 b) override; 263 void send(int8 source, uint32 b) override; 264 void sysEx(const byte *msg, uint16 length) override; 265 uint16 sysExNoDelay(const byte *msg, uint16 length) override; 266 /** 267 * Puts a SysEx message on the SysEx queue. The message will be sent when 268 * the device is ready to receive it, without blocking the thread. 269 * Use the isReady function to determine if the SysEx has been sent. Other 270 * MIDI messages (not using the queue) should not be sent until the queue 271 * is empty. 272 */ 273 void sysExQueue(const byte *msg, uint16 length); 274 /** 275 * Write data to an MT-32 memory location using a SysEx message. 276 * This function will add the necessary header and checksum bytes. 277 * 278 * @param msg Pointer to the data to write to a memory location 279 * @param length The data length 280 * @param targetAddress The start memory address in 8 bit format. 281 * Note that MT-32 memory addresses are sometimes specified in 7 bit format; 282 * these must be converted (f.e. System Area: 10 00 00 -> 04 00 00). 283 * @param queue Specify this parameter to use the SysEx queue to send the 284 * message (see sysExQueue for more information). 285 * @param delay Set this to false to disable the delay to ensure that the 286 * MT-32 has enough time to process the message. This parameter has no 287 * effect if queue is true. 288 * @return The delay in ms that must pass before the next SysEx message is 289 * sent to the MT-32. If delay or queue is true this will be 0; otherwise 290 * it is the caller's responsibility to make sure that the next SysEx is 291 * not sent before this time has passed. 292 */ 293 uint16 sysExMT32(const byte *msg, uint16 length, const uint32 targetAddress, bool queue = false, bool delay = true); 294 void metaEvent(int8 source, byte type, byte *data, uint16 length) override; 295 296 void stopAllNotes(bool stopSustainedNotes = false) override; 297 /** 298 * Removes all SysEx messages in the SysEx queue. 299 */ 300 void clearSysExQueue(); 301 MidiChannel *allocateChannel() override; 302 MidiChannel *getPercussionChannel() override; 303 uint32 getBaseTempo() override; 304 305 /** 306 * Allocates a number of MIDI channels for use by the specified source. 307 * By default this implements a simple algorithm which allocates the 308 * unallocated channel(s) with the lowest numbers. The channel numbers in 309 * the MIDI data sent by this source will be mapped to the allocated MIDI 310 * output channels. The function can be overridden to implement more 311 * complex channel allocation algorithms. 312 * Channels are freed when the source is deinitialized. 313 * Note that sources are not required to allocate channels, so if sources 314 * use conflicting MIDI channels, make sure to use this function 315 * consistently. 316 * 317 * @param source The source for which to allocate channels 318 * @param numChannels The number of channels to allocate 319 * @return True if allocation was successful, false otherwise (usually 320 * because insufficent channels were available) 321 */ 322 virtual bool allocateSourceChannels(uint8 source, uint8 numChannels); 323 /** 324 * Deinitializes a source. This will abort active fades, free any output 325 * channels allocated to the source and stop active notes. 326 */ 327 void deinitSource(uint8 source) override; 328 329 protected: 330 /** 331 * This will initialize the _controlData array with the default values for 332 * MT-32 or GM (depending on the _nativeMT32 value). 333 */ 334 virtual void initControlData(); 335 /** 336 * Initializes the MIDI device. Will call initMT32 or initGM. 337 */ 338 virtual void initMidiDevice(); 339 /** 340 * Initializes the MT-32 MIDI device. The device will be reset and, 341 * if the parameter is specified, set up for General MIDI data. 342 * 343 * @param initForGM True if the MT-32 should be initialized for GM mapping 344 */ 345 virtual void initMT32(bool initForGM); 346 /** 347 * Initializes the General MIDI device. The device will be reset. 348 * If the initForMT32 parameter is specified, the device will be set up for 349 * MT-32 MIDI data. If the device supports Roland GS, the enableGS 350 * parameter can be specified for enhanced GS MT-32 compatiblity. 351 * 352 * @param initForMT32 True if the device should be initialized for MT-32 mapping 353 * @param enableGS True if the device should be initialized for GS MT-32 mapping 354 */ 355 virtual void initGM(bool initForMT32, bool enableGS); 356 /** 357 * Processes a MIDI event. The type of event is determined and the 358 * corresponding function is called to handle the event. 359 * This function is called after mapping the MIDI data channel to an output 360 * channel, so the specified output channel is used and not the channel in 361 * the event bytes. 362 * 363 * @param source The source of the event 364 * @param b The event MIDI bytes 365 * @param outputChannel The output channel for the event 366 * @param controlData The control data set to use when processing the event 367 * @param channelLockedByOtherSource True if the output channel is locked 368 * by another source. This will prevent the event from actually being sent 369 * to the MIDI device, but controlData will be updated. Default is false. 370 */ 371 virtual void processEvent(int8 source, uint32 b, uint8 outputChannel, 372 MidiChannelControlData &controlData, bool channelLockedByOtherSource = false); 373 /** 374 * Processes a note on or off MIDI event. 375 * This will apply source volume if necessary, update the active note 376 * registration and send the event to the MIDI device. 377 * 378 * @param outputChannel The MIDI output channel for the event 379 * @param command The MIDI command byte 380 * @param controlData The control data set that will be used for applying 381 * source volume 382 */ 383 virtual void noteOnOff(byte outputChannel, byte command, byte note, byte velocity, 384 int8 source, MidiChannelControlData &controlData); 385 /** 386 * Process a control change MIDI event. 387 * This will update the specified control data set and apply other 388 * processing if necessary, and then send the event to the MIDI device. 389 * 390 * @param outputChannel The MIDI output channel for the event 391 * @param controlData The control data set that the new controller value 392 * should be stored on 393 * @param channelLockedByOtherSource True if the output channel is locked 394 * by another source. Default is false. 395 */ 396 virtual void controlChange(byte outputChannel, byte controllerNumber, byte controllerValue, 397 int8 source, MidiChannelControlData &controlData, bool channelLockedByOtherSource = false); 398 /** 399 * Process a program change MIDI event. 400 * This will update the specified control data set, apply MT-32 <> GM 401 * instrument mapping and other processing, and send the event to the MIDI 402 * device. 403 * 404 * @param outputChannel The MIDI output channel for the event 405 * @param controlData The control data set that the new program value 406 * should be stored on 407 * @param channelLockedByOtherSource True if the output channel is locked 408 * by another source. Default is false. 409 */ 410 virtual void programChange(byte outputChannel, byte patchId, int8 source, 411 MidiChannelControlData &controlData, bool channelLockedByOtherSource = false); 412 /** 413 * Adds a note to the active note registration. 414 */ 415 virtual bool addActiveNote(uint8 outputChannel, uint8 note, int8 source); 416 /** 417 * Removes a note from the active note registration. 418 */ 419 virtual bool removeActiveNote(uint8 outputChannel, uint8 note, int8 source); 420 /** 421 * Removes all sustained or all non-sustained notes on the specified MIDI 422 * channel from the active note registration. 423 */ 424 virtual void removeActiveNotes(uint8 outputChannel, bool sustainedNotes); 425 /** 426 * Returns true if the MIDI device uses the specified MIDI channel. 427 */ 428 bool isOutputChannelUsed(int8 outputChannel); 429 /** 430 * Maps the specified MT-32 instrument to an equivalent GM instrument. 431 * This implementation looks up the instrument in the _mt32ToGMInstrumentMap 432 * array. Override this function to implement more complex mapping schemes. 433 */ 434 virtual byte mapMT32InstrumentToGM(byte mt32Instrument); 435 /** 436 * Maps the specified GM instrument to an equivalent MT-32 instrument. 437 * This implementation looks up the instrument in the _gmToMT32InstrumentMap 438 * array. Override this function to implement more complex mapping schemes. 439 */ 440 virtual byte mapGMInstrumentToMT32(byte gmInstrument); 441 /** 442 * Checks if the currently selected GS bank / instrument variation 443 * on the specified channel is valid for the specified patch. 444 * If this is not the case, the correct bank will be returned which 445 * can be set by sending a bank select message. If no correction is 446 * needed, 0xFF will be returned. 447 * This emulates the fallback functionality of the Roland SC-55 v1.2x, 448 * on which some games rely to correct wrong bank selects. 449 */ 450 byte correctInstrumentBank(byte outputChannel, byte patchId); 451 452 /** 453 * Returns the MIDI output channel mapped to the specified data channel. 454 * If the data channel has not been mapped yet, a new mapping to one of the 455 * output channels available to the source will be created. 456 * 457 * @param source The source using the data channel 458 * @param dataChannel The data channel to map 459 * @return The mapped output channel, or -1 if no mapping is possible 460 */ 461 virtual int8 mapSourceChannel(uint8 source, uint8 dataChannel); 462 463 void applySourceVolume(uint8 source) override; 464 void stopAllNotes(uint8 source, uint8 channel) override; 465 /** 466 * Runs the MIDI driver's timer related functionality. Will update volume 467 * fades and sends messages from the SysEx queue if necessary. 468 */ 469 void onTimer() override; 470 471 Common::Mutex _allocationMutex; // For operations on MIDI channel allocation 472 Common::Mutex _activeNotesMutex; // For operations on active notes registration 473 474 // The wrapped MIDI driver. 475 MidiDriver *_driver; 476 // The type of MIDI data supplied to the driver: MT-32 or General MIDI. 477 MusicType _midiType; 478 // True if the MIDI output is an MT-32 (hardware or 100% emulated), 479 // false if the MIDI output is a General MIDI device. 480 bool _nativeMT32; 481 // True if the General MIDI output supports Roland GS for improved MT-32 mapping. 482 bool _enableGS; 483 // Indicates if the stereo panning in the MIDI data is reversed 484 // compared to the stereo panning of the intended MIDI device. 485 bool _midiDataReversePanning; 486 // Indicates if the stereo panning of the output MIDI device is 487 // reversed compared to the stereo panning of the type of MIDI 488 // device targeted by the MIDI data (i.e. MT-32 data playing on 489 // a GM device or the other way around). 490 bool _midiDeviceReversePanning; 491 // True if GS percussion channel volume should be scaled to match MT-32 volume. 492 bool _scaleGSPercussionVolumeToMT32; 493 494 // True if this MIDI driver has been opened. 495 bool _isOpen; 496 // Bitmask of the MIDI channels in use by the output device. 497 uint16 _outputChannelMask; 498 int _baseFreq; 499 500 // stores the controller values for each MIDI channel 501 MidiChannelControlData *_controlData[MIDI_CHANNEL_COUNT]; 502 // The mapping of MIDI data channels to output channels for each source. 503 int8 _channelMap[MAXIMUM_SOURCES][MIDI_CHANNEL_COUNT]; 504 // Bitmask specifying which MIDI channels are available for use by each source. 505 uint16 _availableChannels[MAXIMUM_SOURCES]; 506 507 // Maps used for MT-32 <> GM instrument mapping. Set these to an alternate 508 // 128 byte array to customize the mapping. 509 const byte *_mt32ToGMInstrumentMap; 510 const byte *_gmToMT32InstrumentMap; 511 // The maximum active notes for the current MIDI device. 512 uint8 _maximumActiveNotes; 513 // Active note registration 514 ActiveNote *_activeNotes; 515 516 // The current number of microseconds that have to elapse before the next 517 // SysEx message can be sent. 518 uint32 _sysExDelay; 519 // Queue of SysEx messages to be sent to the MIDI device. 520 Common::Queue<SysExData> _sysExQueue; 521 // Mutex for write access to the SysEx queue. 522 Common::Mutex _sysExQueueMutex; 523 }; 524 /** @} */ 525 #endif 526