You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2953 lines
93KB

  1. /**********************************************************************/
  2. /*! \class RtMidi
  3. \brief An abstract base class for realtime MIDI input/output.
  4. This class implements some common functionality for the realtime
  5. MIDI input/output subclasses RtMidiIn and RtMidiOut.
  6. RtMidi WWW site: http://music.mcgill.ca/~gary/rtmidi/
  7. RtMidi: realtime MIDI i/o C++ classes
  8. Copyright (c) 2003-2017 Gary P. Scavone
  9. Permission is hereby granted, free of charge, to any person
  10. obtaining a copy of this software and associated documentation files
  11. (the "Software"), to deal in the Software without restriction,
  12. including without limitation the rights to use, copy, modify, merge,
  13. publish, distribute, sublicense, and/or sell copies of the Software,
  14. and to permit persons to whom the Software is furnished to do so,
  15. subject to the following conditions:
  16. The above copyright notice and this permission notice shall be
  17. included in all copies or substantial portions of the Software.
  18. Any person wishing to distribute modifications to the Software is
  19. asked to send the modifications to the original developer so that
  20. they can be incorporated into the canonical version. This is,
  21. however, not a binding provision of this license.
  22. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  23. EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  24. MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
  25. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
  26. ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
  27. CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  28. WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  29. */
  30. /**********************************************************************/
  31. #include "RtMidi.h"
  32. #include <sstream>
  33. #if defined(__MACOSX_CORE__)
  34. #if TARGET_OS_IPHONE
  35. #define AudioGetCurrentHostTime CAHostTimeBase::GetCurrentTime
  36. #define AudioConvertHostTimeToNanos CAHostTimeBase::ConvertToNanos
  37. #endif
  38. #endif
  39. // Default for Windows is to add an identifier to the port names; this
  40. // flag can be undefined to disable this behaviour.
  41. #define RTMIDI_ENSURE_UNIQUE_PORTNAMES
  42. //*********************************************************************//
  43. // RtMidi Definitions
  44. //*********************************************************************//
  45. RtMidi :: RtMidi()
  46. : rtapi_(0)
  47. {
  48. }
  49. RtMidi :: ~RtMidi()
  50. {
  51. delete rtapi_;
  52. rtapi_ = 0;
  53. }
  54. std::string RtMidi :: getVersion( void ) throw()
  55. {
  56. return std::string( RTMIDI_VERSION );
  57. }
  58. void RtMidi :: getCompiledApi( std::vector<RtMidi::Api> &apis ) throw()
  59. {
  60. apis.clear();
  61. // The order here will control the order of RtMidi's API search in
  62. // the constructor.
  63. #if defined(__MACOSX_CORE__)
  64. apis.push_back( MACOSX_CORE );
  65. #endif
  66. #if defined(__LINUX_ALSA__)
  67. apis.push_back( LINUX_ALSA );
  68. #endif
  69. #if defined(__UNIX_JACK__)
  70. apis.push_back( UNIX_JACK );
  71. #endif
  72. #if defined(__WINDOWS_MM__)
  73. apis.push_back( WINDOWS_MM );
  74. #endif
  75. #if defined(__RTMIDI_DUMMY__)
  76. apis.push_back( RTMIDI_DUMMY );
  77. #endif
  78. }
  79. //*********************************************************************//
  80. // RtMidiIn Definitions
  81. //*********************************************************************//
  82. void RtMidiIn :: openMidiApi( RtMidi::Api api, const std::string &clientName, unsigned int queueSizeLimit )
  83. {
  84. delete rtapi_;
  85. rtapi_ = 0;
  86. #if defined(__UNIX_JACK__)
  87. if ( api == UNIX_JACK )
  88. rtapi_ = new MidiInJack( clientName, queueSizeLimit );
  89. #endif
  90. #if defined(__LINUX_ALSA__)
  91. if ( api == LINUX_ALSA )
  92. rtapi_ = new MidiInAlsa( clientName, queueSizeLimit );
  93. #endif
  94. #if defined(__WINDOWS_MM__)
  95. if ( api == WINDOWS_MM )
  96. rtapi_ = new MidiInWinMM( clientName, queueSizeLimit );
  97. #endif
  98. #if defined(__MACOSX_CORE__)
  99. if ( api == MACOSX_CORE )
  100. rtapi_ = new MidiInCore( clientName, queueSizeLimit );
  101. #endif
  102. #if defined(__RTMIDI_DUMMY__)
  103. if ( api == RTMIDI_DUMMY )
  104. rtapi_ = new MidiInDummy( clientName, queueSizeLimit );
  105. #endif
  106. }
  107. RtMidiIn :: RtMidiIn( RtMidi::Api api, const std::string &clientName, unsigned int queueSizeLimit )
  108. : RtMidi()
  109. {
  110. if ( api != UNSPECIFIED ) {
  111. // Attempt to open the specified API.
  112. openMidiApi( api, clientName, queueSizeLimit );
  113. if ( rtapi_ ) return;
  114. // No compiled support for specified API value. Issue a warning
  115. // and continue as if no API was specified.
  116. std::cerr << "\nRtMidiIn: no compiled support for specified API argument!\n\n" << std::endl;
  117. }
  118. // Iterate through the compiled APIs and return as soon as we find
  119. // one with at least one port or we reach the end of the list.
  120. std::vector< RtMidi::Api > apis;
  121. getCompiledApi( apis );
  122. for ( unsigned int i=0; i<apis.size(); i++ ) {
  123. openMidiApi( apis[i], clientName, queueSizeLimit );
  124. if ( rtapi_ && rtapi_->getPortCount() ) break;
  125. }
  126. if ( rtapi_ ) return;
  127. // It should not be possible to get here because the preprocessor
  128. // definition __RTMIDI_DUMMY__ is automatically defined if no
  129. // API-specific definitions are passed to the compiler. But just in
  130. // case something weird happens, we'll throw an error.
  131. std::string errorText = "RtMidiIn: no compiled API support found ... critical error!!";
  132. throw( RtMidiError( errorText, RtMidiError::UNSPECIFIED ) );
  133. }
  134. RtMidiIn :: ~RtMidiIn() throw()
  135. {
  136. }
  137. //*********************************************************************//
  138. // RtMidiOut Definitions
  139. //*********************************************************************//
  140. void RtMidiOut :: openMidiApi( RtMidi::Api api, const std::string &clientName )
  141. {
  142. delete rtapi_;
  143. rtapi_ = 0;
  144. #if defined(__UNIX_JACK__)
  145. if ( api == UNIX_JACK )
  146. rtapi_ = new MidiOutJack( clientName );
  147. #endif
  148. #if defined(__LINUX_ALSA__)
  149. if ( api == LINUX_ALSA )
  150. rtapi_ = new MidiOutAlsa( clientName );
  151. #endif
  152. #if defined(__WINDOWS_MM__)
  153. if ( api == WINDOWS_MM )
  154. rtapi_ = new MidiOutWinMM( clientName );
  155. #endif
  156. #if defined(__MACOSX_CORE__)
  157. if ( api == MACOSX_CORE )
  158. rtapi_ = new MidiOutCore( clientName );
  159. #endif
  160. #if defined(__RTMIDI_DUMMY__)
  161. if ( api == RTMIDI_DUMMY )
  162. rtapi_ = new MidiOutDummy( clientName );
  163. #endif
  164. }
  165. RtMidiOut :: RtMidiOut( RtMidi::Api api, const std::string &clientName)
  166. {
  167. if ( api != UNSPECIFIED ) {
  168. // Attempt to open the specified API.
  169. openMidiApi( api, clientName );
  170. if ( rtapi_ ) return;
  171. // No compiled support for specified API value. Issue a warning
  172. // and continue as if no API was specified.
  173. std::cerr << "\nRtMidiOut: no compiled support for specified API argument!\n\n" << std::endl;
  174. }
  175. // Iterate through the compiled APIs and return as soon as we find
  176. // one with at least one port or we reach the end of the list.
  177. std::vector< RtMidi::Api > apis;
  178. getCompiledApi( apis );
  179. for ( unsigned int i=0; i<apis.size(); i++ ) {
  180. openMidiApi( apis[i], clientName );
  181. if ( rtapi_ && rtapi_->getPortCount() ) break;
  182. }
  183. if ( rtapi_ ) return;
  184. // It should not be possible to get here because the preprocessor
  185. // definition __RTMIDI_DUMMY__ is automatically defined if no
  186. // API-specific definitions are passed to the compiler. But just in
  187. // case something weird happens, we'll thrown an error.
  188. std::string errorText = "RtMidiOut: no compiled API support found ... critical error!!";
  189. throw( RtMidiError( errorText, RtMidiError::UNSPECIFIED ) );
  190. }
  191. RtMidiOut :: ~RtMidiOut() throw()
  192. {
  193. }
  194. //*********************************************************************//
  195. // Common MidiApi Definitions
  196. //*********************************************************************//
  197. MidiApi :: MidiApi( void )
  198. : apiData_( 0 ), connected_( false ), errorCallback_(0), firstErrorOccurred_(false), errorCallbackUserData_(0)
  199. {
  200. }
  201. MidiApi :: ~MidiApi( void )
  202. {
  203. }
  204. void MidiApi :: setErrorCallback( RtMidiErrorCallback errorCallback, void *userData = 0 )
  205. {
  206. errorCallback_ = errorCallback;
  207. errorCallbackUserData_ = userData;
  208. }
  209. void MidiApi :: error( RtMidiError::Type type, std::string errorString )
  210. {
  211. if ( errorCallback_ ) {
  212. if ( firstErrorOccurred_ )
  213. return;
  214. firstErrorOccurred_ = true;
  215. const std::string errorMessage = errorString;
  216. errorCallback_( type, errorMessage, errorCallbackUserData_);
  217. firstErrorOccurred_ = false;
  218. return;
  219. }
  220. if ( type == RtMidiError::WARNING ) {
  221. std::cerr << '\n' << errorString << "\n\n";
  222. }
  223. else if ( type == RtMidiError::DEBUG_WARNING ) {
  224. #if defined(__RTMIDI_DEBUG__)
  225. std::cerr << '\n' << errorString << "\n\n";
  226. #endif
  227. }
  228. else {
  229. std::cerr << '\n' << errorString << "\n\n";
  230. throw RtMidiError( errorString, type );
  231. }
  232. }
  233. //*********************************************************************//
  234. // Common MidiInApi Definitions
  235. //*********************************************************************//
  236. MidiInApi :: MidiInApi( unsigned int queueSizeLimit )
  237. : MidiApi()
  238. {
  239. // Allocate the MIDI queue.
  240. inputData_.queue.ringSize = queueSizeLimit;
  241. if ( inputData_.queue.ringSize > 0 )
  242. inputData_.queue.ring = new MidiMessage[ inputData_.queue.ringSize ];
  243. }
  244. MidiInApi :: ~MidiInApi( void )
  245. {
  246. // Delete the MIDI queue.
  247. if ( inputData_.queue.ringSize > 0 ) delete [] inputData_.queue.ring;
  248. }
  249. void MidiInApi :: setCallback( RtMidiIn::RtMidiCallback callback, void *userData )
  250. {
  251. if ( inputData_.usingCallback ) {
  252. errorString_ = "MidiInApi::setCallback: a callback function is already set!";
  253. error( RtMidiError::WARNING, errorString_ );
  254. return;
  255. }
  256. if ( !callback ) {
  257. errorString_ = "RtMidiIn::setCallback: callback function value is invalid!";
  258. error( RtMidiError::WARNING, errorString_ );
  259. return;
  260. }
  261. inputData_.userCallback = callback;
  262. inputData_.userData = userData;
  263. inputData_.usingCallback = true;
  264. }
  265. void MidiInApi :: cancelCallback()
  266. {
  267. if ( !inputData_.usingCallback ) {
  268. errorString_ = "RtMidiIn::cancelCallback: no callback function was set!";
  269. error( RtMidiError::WARNING, errorString_ );
  270. return;
  271. }
  272. inputData_.userCallback = 0;
  273. inputData_.userData = 0;
  274. inputData_.usingCallback = false;
  275. }
  276. void MidiInApi :: ignoreTypes( bool midiSysex, bool midiTime, bool midiSense )
  277. {
  278. inputData_.ignoreFlags = 0;
  279. if ( midiSysex ) inputData_.ignoreFlags = 0x01;
  280. if ( midiTime ) inputData_.ignoreFlags |= 0x02;
  281. if ( midiSense ) inputData_.ignoreFlags |= 0x04;
  282. }
  283. double MidiInApi :: getMessage( std::vector<unsigned char> *message )
  284. {
  285. message->clear();
  286. if ( inputData_.usingCallback ) {
  287. errorString_ = "RtMidiIn::getNextMessage: a user callback is currently set for this port.";
  288. error( RtMidiError::WARNING, errorString_ );
  289. return 0.0;
  290. }
  291. double timeStamp;
  292. if (!inputData_.queue.pop(message, &timeStamp))
  293. return 0.0;
  294. return timeStamp;
  295. }
  296. unsigned int MidiInApi::MidiQueue::size(unsigned int *__back,
  297. unsigned int *__front)
  298. {
  299. // Access back/front members exactly once and make stack copies for
  300. // size calculation
  301. unsigned int _back = back, _front = front, _size;
  302. if (_back >= _front)
  303. _size = _back - _front;
  304. else
  305. _size = ringSize - _front + _back;
  306. // Return copies of back/front so no new and unsynchronized accesses
  307. // to member variables are needed.
  308. if (__back) *__back = _back;
  309. if (__front) *__front = _front;
  310. return _size;
  311. }
  312. // As long as we haven't reached our queue size limit, push the message.
  313. bool MidiInApi::MidiQueue::push(const MidiInApi::MidiMessage& msg)
  314. {
  315. // Local stack copies of front/back
  316. unsigned int _back, _front, _size;
  317. // Get back/front indexes exactly once and calculate current size
  318. _size = size(&_back, &_front);
  319. if ( _size < ringSize-1 )
  320. {
  321. ring[_back] = msg;
  322. back = (back+1)%ringSize;
  323. return true;
  324. }
  325. return false;
  326. }
  327. bool MidiInApi::MidiQueue::pop(std::vector<unsigned char> *msg, double* timeStamp)
  328. {
  329. // Local stack copies of front/back
  330. unsigned int _back, _front, _size;
  331. // Get back/front indexes exactly once and calculate current size
  332. _size = size(&_back, &_front);
  333. if (_size == 0)
  334. return false;
  335. // Copy queued message to the vector pointer argument and then "pop" it.
  336. msg->assign( ring[_front].bytes.begin(), ring[_front].bytes.end() );
  337. *timeStamp = ring[_front].timeStamp;
  338. // Update front
  339. front = (front+1)%ringSize;
  340. return true;
  341. }
  342. //*********************************************************************//
  343. // Common MidiOutApi Definitions
  344. //*********************************************************************//
  345. MidiOutApi :: MidiOutApi( void )
  346. : MidiApi()
  347. {
  348. }
  349. MidiOutApi :: ~MidiOutApi( void )
  350. {
  351. }
  352. // *************************************************** //
  353. //
  354. // OS/API-specific methods.
  355. //
  356. // *************************************************** //
  357. #if defined(__MACOSX_CORE__)
  358. // The CoreMIDI API is based on the use of a callback function for
  359. // MIDI input. We convert the system specific time stamps to delta
  360. // time values.
  361. // OS-X CoreMIDI header files.
  362. #include <CoreMIDI/CoreMIDI.h>
  363. #include <CoreAudio/HostTime.h>
  364. #include <CoreServices/CoreServices.h>
  365. // A structure to hold variables related to the CoreMIDI API
  366. // implementation.
  367. struct CoreMidiData {
  368. MIDIClientRef client;
  369. MIDIPortRef port;
  370. MIDIEndpointRef endpoint;
  371. MIDIEndpointRef destinationId;
  372. unsigned long long lastTime;
  373. MIDISysexSendRequest sysexreq;
  374. };
  375. //*********************************************************************//
  376. // API: OS-X
  377. // Class Definitions: MidiInCore
  378. //*********************************************************************//
  379. static void midiInputCallback( const MIDIPacketList *list, void *procRef, void */*srcRef*/ )
  380. {
  381. MidiInApi::RtMidiInData *data = static_cast<MidiInApi::RtMidiInData *> (procRef);
  382. CoreMidiData *apiData = static_cast<CoreMidiData *> (data->apiData);
  383. unsigned char status;
  384. unsigned short nBytes, iByte, size;
  385. unsigned long long time;
  386. bool& continueSysex = data->continueSysex;
  387. MidiInApi::MidiMessage& message = data->message;
  388. const MIDIPacket *packet = &list->packet[0];
  389. for ( unsigned int i=0; i<list->numPackets; ++i ) {
  390. // My interpretation of the CoreMIDI documentation: all message
  391. // types, except sysex, are complete within a packet and there may
  392. // be several of them in a single packet. Sysex messages can be
  393. // broken across multiple packets and PacketLists but are bundled
  394. // alone within each packet (these packets do not contain other
  395. // message types). If sysex messages are split across multiple
  396. // MIDIPacketLists, they must be handled by multiple calls to this
  397. // function.
  398. nBytes = packet->length;
  399. if ( nBytes == 0 ) continue;
  400. // Calculate time stamp.
  401. if ( data->firstMessage ) {
  402. message.timeStamp = 0.0;
  403. data->firstMessage = false;
  404. }
  405. else {
  406. time = packet->timeStamp;
  407. if ( time == 0 ) { // this happens when receiving asynchronous sysex messages
  408. time = AudioGetCurrentHostTime();
  409. }
  410. time -= apiData->lastTime;
  411. time = AudioConvertHostTimeToNanos( time );
  412. if ( !continueSysex )
  413. message.timeStamp = time * 0.000000001;
  414. }
  415. apiData->lastTime = packet->timeStamp;
  416. if ( apiData->lastTime == 0 ) { // this happens when receiving asynchronous sysex messages
  417. apiData->lastTime = AudioGetCurrentHostTime();
  418. }
  419. //std::cout << "TimeStamp = " << packet->timeStamp << std::endl;
  420. iByte = 0;
  421. if ( continueSysex ) {
  422. // We have a continuing, segmented sysex message.
  423. if ( !( data->ignoreFlags & 0x01 ) ) {
  424. // If we're not ignoring sysex messages, copy the entire packet.
  425. for ( unsigned int j=0; j<nBytes; ++j )
  426. message.bytes.push_back( packet->data[j] );
  427. }
  428. continueSysex = packet->data[nBytes-1] != 0xF7;
  429. if ( !( data->ignoreFlags & 0x01 ) && !continueSysex ) {
  430. // If not a continuing sysex message, invoke the user callback function or queue the message.
  431. if ( data->usingCallback ) {
  432. RtMidiIn::RtMidiCallback callback = (RtMidiIn::RtMidiCallback) data->userCallback;
  433. callback( message.timeStamp, &message.bytes, data->userData );
  434. }
  435. else {
  436. // As long as we haven't reached our queue size limit, push the message.
  437. if (!data->queue.push(message))
  438. std::cerr << "\nMidiInCore: message queue limit reached!!\n\n";
  439. }
  440. message.bytes.clear();
  441. }
  442. }
  443. else {
  444. while ( iByte < nBytes ) {
  445. size = 0;
  446. // We are expecting that the next byte in the packet is a status byte.
  447. status = packet->data[iByte];
  448. if ( !(status & 0x80) ) break;
  449. // Determine the number of bytes in the MIDI message.
  450. if ( status < 0xC0 ) size = 3;
  451. else if ( status < 0xE0 ) size = 2;
  452. else if ( status < 0xF0 ) size = 3;
  453. else if ( status == 0xF0 ) {
  454. // A MIDI sysex
  455. if ( data->ignoreFlags & 0x01 ) {
  456. size = 0;
  457. iByte = nBytes;
  458. }
  459. else size = nBytes - iByte;
  460. continueSysex = packet->data[nBytes-1] != 0xF7;
  461. }
  462. else if ( status == 0xF1 ) {
  463. // A MIDI time code message
  464. if ( data->ignoreFlags & 0x02 ) {
  465. size = 0;
  466. iByte += 2;
  467. }
  468. else size = 2;
  469. }
  470. else if ( status == 0xF2 ) size = 3;
  471. else if ( status == 0xF3 ) size = 2;
  472. else if ( status == 0xF8 && ( data->ignoreFlags & 0x02 ) ) {
  473. // A MIDI timing tick message and we're ignoring it.
  474. size = 0;
  475. iByte += 1;
  476. }
  477. else if ( status == 0xFE && ( data->ignoreFlags & 0x04 ) ) {
  478. // A MIDI active sensing message and we're ignoring it.
  479. size = 0;
  480. iByte += 1;
  481. }
  482. else size = 1;
  483. // Copy the MIDI data to our vector.
  484. if ( size ) {
  485. message.bytes.assign( &packet->data[iByte], &packet->data[iByte+size] );
  486. if ( !continueSysex ) {
  487. // If not a continuing sysex message, invoke the user callback function or queue the message.
  488. if ( data->usingCallback ) {
  489. RtMidiIn::RtMidiCallback callback = (RtMidiIn::RtMidiCallback) data->userCallback;
  490. callback( message.timeStamp, &message.bytes, data->userData );
  491. }
  492. else {
  493. // As long as we haven't reached our queue size limit, push the message.
  494. if (!data->queue.push(message))
  495. std::cerr << "\nMidiInCore: message queue limit reached!!\n\n";
  496. }
  497. message.bytes.clear();
  498. }
  499. iByte += size;
  500. }
  501. }
  502. }
  503. packet = MIDIPacketNext(packet);
  504. }
  505. }
  506. MidiInCore :: MidiInCore( const std::string &clientName, unsigned int queueSizeLimit ) : MidiInApi( queueSizeLimit )
  507. {
  508. initialize( clientName );
  509. }
  510. MidiInCore :: ~MidiInCore( void )
  511. {
  512. // Close a connection if it exists.
  513. closePort();
  514. // Cleanup.
  515. CoreMidiData *data = static_cast<CoreMidiData *> (apiData_);
  516. MIDIClientDispose( data->client );
  517. if ( data->endpoint ) MIDIEndpointDispose( data->endpoint );
  518. delete data;
  519. }
  520. void MidiInCore :: initialize( const std::string& clientName )
  521. {
  522. // Set up our client.
  523. MIDIClientRef client;
  524. CFStringRef name = CFStringCreateWithCString( NULL, clientName.c_str(), kCFStringEncodingASCII );
  525. OSStatus result = MIDIClientCreate(name, NULL, NULL, &client );
  526. if ( result != noErr ) {
  527. std::ostringstream ost;
  528. ost << "MidiInCore::initialize: error creating OS-X MIDI client object (" << result << ").";
  529. errorString_ = ost.str();
  530. error( RtMidiError::DRIVER_ERROR, errorString_ );
  531. return;
  532. }
  533. // Save our api-specific connection information.
  534. CoreMidiData *data = (CoreMidiData *) new CoreMidiData;
  535. data->client = client;
  536. data->endpoint = 0;
  537. apiData_ = (void *) data;
  538. inputData_.apiData = (void *) data;
  539. CFRelease(name);
  540. }
  541. void MidiInCore :: openPort( unsigned int portNumber, const std::string &portName )
  542. {
  543. if ( connected_ ) {
  544. errorString_ = "MidiInCore::openPort: a valid connection already exists!";
  545. error( RtMidiError::WARNING, errorString_ );
  546. return;
  547. }
  548. CFRunLoopRunInMode( kCFRunLoopDefaultMode, 0, false );
  549. unsigned int nSrc = MIDIGetNumberOfSources();
  550. if (nSrc < 1) {
  551. errorString_ = "MidiInCore::openPort: no MIDI input sources found!";
  552. error( RtMidiError::NO_DEVICES_FOUND, errorString_ );
  553. return;
  554. }
  555. if ( portNumber >= nSrc ) {
  556. std::ostringstream ost;
  557. ost << "MidiInCore::openPort: the 'portNumber' argument (" << portNumber << ") is invalid.";
  558. errorString_ = ost.str();
  559. error( RtMidiError::INVALID_PARAMETER, errorString_ );
  560. return;
  561. }
  562. MIDIPortRef port;
  563. CoreMidiData *data = static_cast<CoreMidiData *> (apiData_);
  564. OSStatus result = MIDIInputPortCreate( data->client,
  565. CFStringCreateWithCString( NULL, portName.c_str(), kCFStringEncodingASCII ),
  566. midiInputCallback, (void *)&inputData_, &port );
  567. if ( result != noErr ) {
  568. MIDIClientDispose( data->client );
  569. errorString_ = "MidiInCore::openPort: error creating OS-X MIDI input port.";
  570. error( RtMidiError::DRIVER_ERROR, errorString_ );
  571. return;
  572. }
  573. // Get the desired input source identifier.
  574. MIDIEndpointRef endpoint = MIDIGetSource( portNumber );
  575. if ( endpoint == 0 ) {
  576. MIDIPortDispose( port );
  577. MIDIClientDispose( data->client );
  578. errorString_ = "MidiInCore::openPort: error getting MIDI input source reference.";
  579. error( RtMidiError::DRIVER_ERROR, errorString_ );
  580. return;
  581. }
  582. // Make the connection.
  583. result = MIDIPortConnectSource( port, endpoint, NULL );
  584. if ( result != noErr ) {
  585. MIDIPortDispose( port );
  586. MIDIClientDispose( data->client );
  587. errorString_ = "MidiInCore::openPort: error connecting OS-X MIDI input port.";
  588. error( RtMidiError::DRIVER_ERROR, errorString_ );
  589. return;
  590. }
  591. // Save our api-specific port information.
  592. data->port = port;
  593. connected_ = true;
  594. }
  595. void MidiInCore :: openVirtualPort( const std::string &portName )
  596. {
  597. CoreMidiData *data = static_cast<CoreMidiData *> (apiData_);
  598. // Create a virtual MIDI input destination.
  599. MIDIEndpointRef endpoint;
  600. OSStatus result = MIDIDestinationCreate( data->client,
  601. CFStringCreateWithCString( NULL, portName.c_str(), kCFStringEncodingASCII ),
  602. midiInputCallback, (void *)&inputData_, &endpoint );
  603. if ( result != noErr ) {
  604. errorString_ = "MidiInCore::openVirtualPort: error creating virtual OS-X MIDI destination.";
  605. error( RtMidiError::DRIVER_ERROR, errorString_ );
  606. return;
  607. }
  608. // Save our api-specific connection information.
  609. data->endpoint = endpoint;
  610. }
  611. void MidiInCore :: closePort( void )
  612. {
  613. CoreMidiData *data = static_cast<CoreMidiData *> (apiData_);
  614. if ( data->endpoint ) {
  615. MIDIEndpointDispose( data->endpoint );
  616. data->endpoint = 0;
  617. }
  618. if ( data->port ) {
  619. MIDIPortDispose( data->port );
  620. data->port = 0;
  621. }
  622. connected_ = false;
  623. }
  624. unsigned int MidiInCore :: getPortCount()
  625. {
  626. CFRunLoopRunInMode( kCFRunLoopDefaultMode, 0, false );
  627. return MIDIGetNumberOfSources();
  628. }
  629. // This function was submitted by Douglas Casey Tucker and apparently
  630. // derived largely from PortMidi.
  631. CFStringRef EndpointName( MIDIEndpointRef endpoint, bool isExternal )
  632. {
  633. CFMutableStringRef result = CFStringCreateMutable( NULL, 0 );
  634. CFStringRef str;
  635. // Begin with the endpoint's name.
  636. str = NULL;
  637. MIDIObjectGetStringProperty( endpoint, kMIDIPropertyName, &str );
  638. if ( str != NULL ) {
  639. CFStringAppend( result, str );
  640. CFRelease( str );
  641. }
  642. MIDIEntityRef entity = 0;
  643. MIDIEndpointGetEntity( endpoint, &entity );
  644. if ( entity == 0 )
  645. // probably virtual
  646. return result;
  647. if ( CFStringGetLength( result ) == 0 ) {
  648. // endpoint name has zero length -- try the entity
  649. str = NULL;
  650. MIDIObjectGetStringProperty( entity, kMIDIPropertyName, &str );
  651. if ( str != NULL ) {
  652. CFStringAppend( result, str );
  653. CFRelease( str );
  654. }
  655. }
  656. // now consider the device's name
  657. MIDIDeviceRef device = 0;
  658. MIDIEntityGetDevice( entity, &device );
  659. if ( device == 0 )
  660. return result;
  661. str = NULL;
  662. MIDIObjectGetStringProperty( device, kMIDIPropertyName, &str );
  663. if ( CFStringGetLength( result ) == 0 ) {
  664. CFRelease( result );
  665. return str;
  666. }
  667. if ( str != NULL ) {
  668. // if an external device has only one entity, throw away
  669. // the endpoint name and just use the device name
  670. if ( isExternal && MIDIDeviceGetNumberOfEntities( device ) < 2 ) {
  671. CFRelease( result );
  672. return str;
  673. } else {
  674. if ( CFStringGetLength( str ) == 0 ) {
  675. CFRelease( str );
  676. return result;
  677. }
  678. // does the entity name already start with the device name?
  679. // (some drivers do this though they shouldn't)
  680. // if so, do not prepend
  681. if ( CFStringCompareWithOptions( result, /* endpoint name */
  682. str /* device name */,
  683. CFRangeMake(0, CFStringGetLength( str ) ), 0 ) != kCFCompareEqualTo ) {
  684. // prepend the device name to the entity name
  685. if ( CFStringGetLength( result ) > 0 )
  686. CFStringInsert( result, 0, CFSTR(" ") );
  687. CFStringInsert( result, 0, str );
  688. }
  689. CFRelease( str );
  690. }
  691. }
  692. return result;
  693. }
  694. // This function was submitted by Douglas Casey Tucker and apparently
  695. // derived largely from PortMidi.
  696. static CFStringRef ConnectedEndpointName( MIDIEndpointRef endpoint )
  697. {
  698. CFMutableStringRef result = CFStringCreateMutable( NULL, 0 );
  699. CFStringRef str;
  700. OSStatus err;
  701. int i;
  702. // Does the endpoint have connections?
  703. CFDataRef connections = NULL;
  704. int nConnected = 0;
  705. bool anyStrings = false;
  706. err = MIDIObjectGetDataProperty( endpoint, kMIDIPropertyConnectionUniqueID, &connections );
  707. if ( connections != NULL ) {
  708. // It has connections, follow them
  709. // Concatenate the names of all connected devices
  710. nConnected = CFDataGetLength( connections ) / sizeof(MIDIUniqueID);
  711. if ( nConnected ) {
  712. const SInt32 *pid = (const SInt32 *)(CFDataGetBytePtr(connections));
  713. for ( i=0; i<nConnected; ++i, ++pid ) {
  714. MIDIUniqueID id = EndianS32_BtoN( *pid );
  715. MIDIObjectRef connObject;
  716. MIDIObjectType connObjectType;
  717. err = MIDIObjectFindByUniqueID( id, &connObject, &connObjectType );
  718. if ( err == noErr ) {
  719. if ( connObjectType == kMIDIObjectType_ExternalSource ||
  720. connObjectType == kMIDIObjectType_ExternalDestination ) {
  721. // Connected to an external device's endpoint (10.3 and later).
  722. str = EndpointName( (MIDIEndpointRef)(connObject), true );
  723. } else {
  724. // Connected to an external device (10.2) (or something else, catch-
  725. str = NULL;
  726. MIDIObjectGetStringProperty( connObject, kMIDIPropertyName, &str );
  727. }
  728. if ( str != NULL ) {
  729. if ( anyStrings )
  730. CFStringAppend( result, CFSTR(", ") );
  731. else anyStrings = true;
  732. CFStringAppend( result, str );
  733. CFRelease( str );
  734. }
  735. }
  736. }
  737. }
  738. CFRelease( connections );
  739. }
  740. if ( anyStrings )
  741. return result;
  742. CFRelease( result );
  743. // Here, either the endpoint had no connections, or we failed to obtain names
  744. return EndpointName( endpoint, false );
  745. }
  746. std::string MidiInCore :: getPortName( unsigned int portNumber )
  747. {
  748. CFStringRef nameRef;
  749. MIDIEndpointRef portRef;
  750. char name[128];
  751. std::string stringName;
  752. CFRunLoopRunInMode( kCFRunLoopDefaultMode, 0, false );
  753. if ( portNumber >= MIDIGetNumberOfSources() ) {
  754. std::ostringstream ost;
  755. ost << "MidiInCore::getPortName: the 'portNumber' argument (" << portNumber << ") is invalid.";
  756. errorString_ = ost.str();
  757. error( RtMidiError::WARNING, errorString_ );
  758. return stringName;
  759. }
  760. portRef = MIDIGetSource( portNumber );
  761. nameRef = ConnectedEndpointName(portRef);
  762. CFStringGetCString( nameRef, name, sizeof(name), kCFStringEncodingUTF8);
  763. CFRelease( nameRef );
  764. return stringName = name;
  765. }
  766. //*********************************************************************//
  767. // API: OS-X
  768. // Class Definitions: MidiOutCore
  769. //*********************************************************************//
  770. MidiOutCore :: MidiOutCore( const std::string &clientName ) : MidiOutApi()
  771. {
  772. initialize( clientName );
  773. }
  774. MidiOutCore :: ~MidiOutCore( void )
  775. {
  776. // Close a connection if it exists.
  777. closePort();
  778. // Cleanup.
  779. CoreMidiData *data = static_cast<CoreMidiData *> (apiData_);
  780. MIDIClientDispose( data->client );
  781. if ( data->endpoint ) MIDIEndpointDispose( data->endpoint );
  782. delete data;
  783. }
  784. void MidiOutCore :: initialize( const std::string& clientName )
  785. {
  786. // Set up our client.
  787. MIDIClientRef client;
  788. CFStringRef name = CFStringCreateWithCString( NULL, clientName.c_str(), kCFStringEncodingASCII );
  789. OSStatus result = MIDIClientCreate(name, NULL, NULL, &client );
  790. if ( result != noErr ) {
  791. std::ostringstream ost;
  792. ost << "MidiInCore::initialize: error creating OS-X MIDI client object (" << result << ").";
  793. errorString_ = ost.str();
  794. error( RtMidiError::DRIVER_ERROR, errorString_ );
  795. return;
  796. }
  797. // Save our api-specific connection information.
  798. CoreMidiData *data = (CoreMidiData *) new CoreMidiData;
  799. data->client = client;
  800. data->endpoint = 0;
  801. apiData_ = (void *) data;
  802. CFRelease( name );
  803. }
  804. unsigned int MidiOutCore :: getPortCount()
  805. {
  806. CFRunLoopRunInMode( kCFRunLoopDefaultMode, 0, false );
  807. return MIDIGetNumberOfDestinations();
  808. }
  809. std::string MidiOutCore :: getPortName( unsigned int portNumber )
  810. {
  811. CFStringRef nameRef;
  812. MIDIEndpointRef portRef;
  813. char name[128];
  814. std::string stringName;
  815. CFRunLoopRunInMode( kCFRunLoopDefaultMode, 0, false );
  816. if ( portNumber >= MIDIGetNumberOfDestinations() ) {
  817. std::ostringstream ost;
  818. ost << "MidiOutCore::getPortName: the 'portNumber' argument (" << portNumber << ") is invalid.";
  819. errorString_ = ost.str();
  820. error( RtMidiError::WARNING, errorString_ );
  821. return stringName;
  822. }
  823. portRef = MIDIGetDestination( portNumber );
  824. nameRef = ConnectedEndpointName(portRef);
  825. CFStringGetCString( nameRef, name, sizeof(name), kCFStringEncodingUTF8 );
  826. CFRelease( nameRef );
  827. return stringName = name;
  828. }
  829. void MidiOutCore :: openPort( unsigned int portNumber, const std::string &portName )
  830. {
  831. if ( connected_ ) {
  832. errorString_ = "MidiOutCore::openPort: a valid connection already exists!";
  833. error( RtMidiError::WARNING, errorString_ );
  834. return;
  835. }
  836. CFRunLoopRunInMode( kCFRunLoopDefaultMode, 0, false );
  837. unsigned int nDest = MIDIGetNumberOfDestinations();
  838. if (nDest < 1) {
  839. errorString_ = "MidiOutCore::openPort: no MIDI output destinations found!";
  840. error( RtMidiError::NO_DEVICES_FOUND, errorString_ );
  841. return;
  842. }
  843. if ( portNumber >= nDest ) {
  844. std::ostringstream ost;
  845. ost << "MidiOutCore::openPort: the 'portNumber' argument (" << portNumber << ") is invalid.";
  846. errorString_ = ost.str();
  847. error( RtMidiError::INVALID_PARAMETER, errorString_ );
  848. return;
  849. }
  850. MIDIPortRef port;
  851. CoreMidiData *data = static_cast<CoreMidiData *> (apiData_);
  852. CFStringRef portNameRef = CFStringCreateWithCString( NULL, portName.c_str(), kCFStringEncodingASCII );
  853. OSStatus result = MIDIOutputPortCreate( data->client,
  854. portNameRef,
  855. &port );
  856. CFRelease( portNameRef );
  857. if ( result != noErr ) {
  858. MIDIClientDispose( data->client );
  859. errorString_ = "MidiOutCore::openPort: error creating OS-X MIDI output port.";
  860. error( RtMidiError::DRIVER_ERROR, errorString_ );
  861. return;
  862. }
  863. // Get the desired output port identifier.
  864. MIDIEndpointRef destination = MIDIGetDestination( portNumber );
  865. if ( destination == 0 ) {
  866. MIDIPortDispose( port );
  867. MIDIClientDispose( data->client );
  868. errorString_ = "MidiOutCore::openPort: error getting MIDI output destination reference.";
  869. error( RtMidiError::DRIVER_ERROR, errorString_ );
  870. return;
  871. }
  872. // Save our api-specific connection information.
  873. data->port = port;
  874. data->destinationId = destination;
  875. connected_ = true;
  876. }
  877. void MidiOutCore :: closePort( void )
  878. {
  879. CoreMidiData *data = static_cast<CoreMidiData *> (apiData_);
  880. if ( data->endpoint ) {
  881. MIDIEndpointDispose( data->endpoint );
  882. data->endpoint = 0;
  883. }
  884. if ( data->port ) {
  885. MIDIPortDispose( data->port );
  886. data->port = 0;
  887. }
  888. connected_ = false;
  889. }
  890. void MidiOutCore :: openVirtualPort( const std::string &portName )
  891. {
  892. CoreMidiData *data = static_cast<CoreMidiData *> (apiData_);
  893. if ( data->endpoint ) {
  894. errorString_ = "MidiOutCore::openVirtualPort: a virtual output port already exists!";
  895. error( RtMidiError::WARNING, errorString_ );
  896. return;
  897. }
  898. // Create a virtual MIDI output source.
  899. MIDIEndpointRef endpoint;
  900. OSStatus result = MIDISourceCreate( data->client,
  901. CFStringCreateWithCString( NULL, portName.c_str(), kCFStringEncodingASCII ),
  902. &endpoint );
  903. if ( result != noErr ) {
  904. errorString_ = "MidiOutCore::initialize: error creating OS-X virtual MIDI source.";
  905. error( RtMidiError::DRIVER_ERROR, errorString_ );
  906. return;
  907. }
  908. // Save our api-specific connection information.
  909. data->endpoint = endpoint;
  910. }
  911. void MidiOutCore :: sendMessage( const unsigned char *message, size_t size )
  912. {
  913. // We use the MIDISendSysex() function to asynchronously send sysex
  914. // messages. Otherwise, we use a single CoreMidi MIDIPacket.
  915. unsigned int nBytes = static_cast<unsigned int> (size);
  916. if ( nBytes == 0 ) {
  917. errorString_ = "MidiOutCore::sendMessage: no data in message argument!";
  918. error( RtMidiError::WARNING, errorString_ );
  919. return;
  920. }
  921. MIDITimeStamp timeStamp = AudioGetCurrentHostTime();
  922. CoreMidiData *data = static_cast<CoreMidiData *> (apiData_);
  923. OSStatus result;
  924. if ( message[0] != 0xF0 && nBytes > 3 ) {
  925. errorString_ = "MidiOutCore::sendMessage: message format problem ... not sysex but > 3 bytes?";
  926. error( RtMidiError::WARNING, errorString_ );
  927. return;
  928. }
  929. Byte buffer[nBytes+(sizeof(MIDIPacketList))];
  930. ByteCount listSize = sizeof(buffer);
  931. MIDIPacketList *packetList = (MIDIPacketList*)buffer;
  932. MIDIPacket *packet = MIDIPacketListInit( packetList );
  933. ByteCount remainingBytes = nBytes;
  934. while (remainingBytes && packet) {
  935. ByteCount bytesForPacket = remainingBytes > 65535 ? 65535 : remainingBytes; // 65535 = maximum size of a MIDIPacket
  936. const Byte* dataStartPtr = (const Byte *) &message[nBytes - remainingBytes];
  937. packet = MIDIPacketListAdd( packetList, listSize, packet, timeStamp, bytesForPacket, dataStartPtr);
  938. remainingBytes -= bytesForPacket;
  939. }
  940. if ( !packet ) {
  941. errorString_ = "MidiOutCore::sendMessage: could not allocate packet list";
  942. error( RtMidiError::DRIVER_ERROR, errorString_ );
  943. return;
  944. }
  945. // Send to any destinations that may have connected to us.
  946. if ( data->endpoint ) {
  947. result = MIDIReceived( data->endpoint, packetList );
  948. if ( result != noErr ) {
  949. errorString_ = "MidiOutCore::sendMessage: error sending MIDI to virtual destinations.";
  950. error( RtMidiError::WARNING, errorString_ );
  951. }
  952. }
  953. // And send to an explicit destination port if we're connected.
  954. if ( connected_ ) {
  955. result = MIDISend( data->port, data->destinationId, packetList );
  956. if ( result != noErr ) {
  957. errorString_ = "MidiOutCore::sendMessage: error sending MIDI message to port.";
  958. error( RtMidiError::WARNING, errorString_ );
  959. }
  960. }
  961. }
  962. #endif // __MACOSX_CORE__
  963. //*********************************************************************//
  964. // API: LINUX ALSA SEQUENCER
  965. //*********************************************************************//
  966. // API information found at:
  967. // - http://www.alsa-project.org/documentation.php#Library
  968. #if defined(__LINUX_ALSA__)
  969. // The ALSA Sequencer API is based on the use of a callback function for
  970. // MIDI input.
  971. //
  972. // Thanks to Pedro Lopez-Cabanillas for help with the ALSA sequencer
  973. // time stamps and other assorted fixes!!!
  974. // If you don't need timestamping for incoming MIDI events, define the
  975. // preprocessor definition AVOID_TIMESTAMPING to save resources
  976. // associated with the ALSA sequencer queues.
  977. #include <pthread.h>
  978. #include <sys/time.h>
  979. // ALSA header file.
  980. #include <alsa/asoundlib.h>
  981. // A structure to hold variables related to the ALSA API
  982. // implementation.
  983. struct AlsaMidiData {
  984. snd_seq_t *seq;
  985. unsigned int portNum;
  986. int vport;
  987. snd_seq_port_subscribe_t *subscription;
  988. snd_midi_event_t *coder;
  989. unsigned int bufferSize;
  990. unsigned char *buffer;
  991. pthread_t thread;
  992. pthread_t dummy_thread_id;
  993. snd_seq_real_time_t lastTime;
  994. int queue_id; // an input queue is needed to get timestamped events
  995. int trigger_fds[2];
  996. };
  997. #define PORT_TYPE( pinfo, bits ) ((snd_seq_port_info_get_capability(pinfo) & (bits)) == (bits))
  998. //*********************************************************************//
  999. // API: LINUX ALSA
  1000. // Class Definitions: MidiInAlsa
  1001. //*********************************************************************//
  1002. static void *alsaMidiHandler( void *ptr )
  1003. {
  1004. MidiInApi::RtMidiInData *data = static_cast<MidiInApi::RtMidiInData *> (ptr);
  1005. AlsaMidiData *apiData = static_cast<AlsaMidiData *> (data->apiData);
  1006. long nBytes;
  1007. double time;
  1008. bool continueSysex = false;
  1009. bool doDecode = false;
  1010. MidiInApi::MidiMessage message;
  1011. int poll_fd_count;
  1012. struct pollfd *poll_fds;
  1013. snd_seq_event_t *ev;
  1014. int result;
  1015. apiData->bufferSize = 32;
  1016. result = snd_midi_event_new( 0, &apiData->coder );
  1017. if ( result < 0 ) {
  1018. data->doInput = false;
  1019. std::cerr << "\nMidiInAlsa::alsaMidiHandler: error initializing MIDI event parser!\n\n";
  1020. return 0;
  1021. }
  1022. unsigned char *buffer = (unsigned char *) malloc( apiData->bufferSize );
  1023. if ( buffer == NULL ) {
  1024. data->doInput = false;
  1025. snd_midi_event_free( apiData->coder );
  1026. apiData->coder = 0;
  1027. std::cerr << "\nMidiInAlsa::alsaMidiHandler: error initializing buffer memory!\n\n";
  1028. return 0;
  1029. }
  1030. snd_midi_event_init( apiData->coder );
  1031. snd_midi_event_no_status( apiData->coder, 1 ); // suppress running status messages
  1032. poll_fd_count = snd_seq_poll_descriptors_count( apiData->seq, POLLIN ) + 1;
  1033. poll_fds = (struct pollfd*)alloca( poll_fd_count * sizeof( struct pollfd ));
  1034. snd_seq_poll_descriptors( apiData->seq, poll_fds + 1, poll_fd_count - 1, POLLIN );
  1035. poll_fds[0].fd = apiData->trigger_fds[0];
  1036. poll_fds[0].events = POLLIN;
  1037. while ( data->doInput ) {
  1038. if ( snd_seq_event_input_pending( apiData->seq, 1 ) == 0 ) {
  1039. // No data pending
  1040. if ( poll( poll_fds, poll_fd_count, -1) >= 0 ) {
  1041. if ( poll_fds[0].revents & POLLIN ) {
  1042. bool dummy;
  1043. int res = read( poll_fds[0].fd, &dummy, sizeof(dummy) );
  1044. (void) res;
  1045. }
  1046. }
  1047. continue;
  1048. }
  1049. // If here, there should be data.
  1050. result = snd_seq_event_input( apiData->seq, &ev );
  1051. if ( result == -ENOSPC ) {
  1052. std::cerr << "\nMidiInAlsa::alsaMidiHandler: MIDI input buffer overrun!\n\n";
  1053. continue;
  1054. }
  1055. else if ( result <= 0 ) {
  1056. std::cerr << "\nMidiInAlsa::alsaMidiHandler: unknown MIDI input error!\n";
  1057. perror("System reports");
  1058. continue;
  1059. }
  1060. // This is a bit weird, but we now have to decode an ALSA MIDI
  1061. // event (back) into MIDI bytes. We'll ignore non-MIDI types.
  1062. if ( !continueSysex ) message.bytes.clear();
  1063. doDecode = false;
  1064. switch ( ev->type ) {
  1065. case SND_SEQ_EVENT_PORT_SUBSCRIBED:
  1066. #if defined(__RTMIDI_DEBUG__)
  1067. std::cout << "MidiInAlsa::alsaMidiHandler: port connection made!\n";
  1068. #endif
  1069. break;
  1070. case SND_SEQ_EVENT_PORT_UNSUBSCRIBED:
  1071. #if defined(__RTMIDI_DEBUG__)
  1072. std::cerr << "MidiInAlsa::alsaMidiHandler: port connection has closed!\n";
  1073. std::cout << "sender = " << (int) ev->data.connect.sender.client << ":"
  1074. << (int) ev->data.connect.sender.port
  1075. << ", dest = " << (int) ev->data.connect.dest.client << ":"
  1076. << (int) ev->data.connect.dest.port
  1077. << std::endl;
  1078. #endif
  1079. break;
  1080. case SND_SEQ_EVENT_QFRAME: // MIDI time code
  1081. if ( !( data->ignoreFlags & 0x02 ) ) doDecode = true;
  1082. break;
  1083. case SND_SEQ_EVENT_TICK: // 0xF9 ... MIDI timing tick
  1084. if ( !( data->ignoreFlags & 0x02 ) ) doDecode = true;
  1085. break;
  1086. case SND_SEQ_EVENT_CLOCK: // 0xF8 ... MIDI timing (clock) tick
  1087. if ( !( data->ignoreFlags & 0x02 ) ) doDecode = true;
  1088. break;
  1089. case SND_SEQ_EVENT_SENSING: // Active sensing
  1090. if ( !( data->ignoreFlags & 0x04 ) ) doDecode = true;
  1091. break;
  1092. case SND_SEQ_EVENT_SYSEX:
  1093. if ( (data->ignoreFlags & 0x01) ) break;
  1094. if ( ev->data.ext.len > apiData->bufferSize ) {
  1095. apiData->bufferSize = ev->data.ext.len;
  1096. free( buffer );
  1097. buffer = (unsigned char *) malloc( apiData->bufferSize );
  1098. if ( buffer == NULL ) {
  1099. data->doInput = false;
  1100. std::cerr << "\nMidiInAlsa::alsaMidiHandler: error resizing buffer memory!\n\n";
  1101. break;
  1102. }
  1103. }
  1104. default:
  1105. doDecode = true;
  1106. }
  1107. if ( doDecode ) {
  1108. nBytes = snd_midi_event_decode( apiData->coder, buffer, apiData->bufferSize, ev );
  1109. if ( nBytes > 0 ) {
  1110. // The ALSA sequencer has a maximum buffer size for MIDI sysex
  1111. // events of 256 bytes. If a device sends sysex messages larger
  1112. // than this, they are segmented into 256 byte chunks. So,
  1113. // we'll watch for this and concatenate sysex chunks into a
  1114. // single sysex message if necessary.
  1115. if ( !continueSysex )
  1116. message.bytes.assign( buffer, &buffer[nBytes] );
  1117. else
  1118. message.bytes.insert( message.bytes.end(), buffer, &buffer[nBytes] );
  1119. continueSysex = ( ( ev->type == SND_SEQ_EVENT_SYSEX ) && ( message.bytes.back() != 0xF7 ) );
  1120. if ( !continueSysex ) {
  1121. // Calculate the time stamp:
  1122. message.timeStamp = 0.0;
  1123. // Method 1: Use the system time.
  1124. //(void)gettimeofday(&tv, (struct timezone *)NULL);
  1125. //time = (tv.tv_sec * 1000000) + tv.tv_usec;
  1126. // Method 2: Use the ALSA sequencer event time data.
  1127. // (thanks to Pedro Lopez-Cabanillas!).
  1128. // Using method from:
  1129. // https://www.gnu.org/software/libc/manual/html_node/Elapsed-Time.html
  1130. // Perform the carry for the later subtraction by updating y.
  1131. snd_seq_real_time_t &x(ev->time.time);
  1132. snd_seq_real_time_t &y(apiData->lastTime);
  1133. if (x.tv_nsec < y.tv_nsec) {
  1134. int nsec = (y.tv_nsec - x.tv_nsec) / 1000000000 + 1;
  1135. y.tv_nsec -= 1000000000 * nsec;
  1136. y.tv_sec += nsec;
  1137. }
  1138. if (x.tv_nsec - y.tv_nsec > 1000000000) {
  1139. int nsec = (x.tv_nsec - y.tv_nsec) / 1000000000;
  1140. y.tv_nsec += 1000000000 * nsec;
  1141. y.tv_sec -= nsec;
  1142. }
  1143. // Compute the time difference.
  1144. time = x.tv_sec - y.tv_sec + (x.tv_nsec - y.tv_nsec)*1e-9;
  1145. apiData->lastTime = ev->time.time;
  1146. if ( data->firstMessage == true )
  1147. data->firstMessage = false;
  1148. else
  1149. message.timeStamp = time;
  1150. }
  1151. else {
  1152. #if defined(__RTMIDI_DEBUG__)
  1153. std::cerr << "\nMidiInAlsa::alsaMidiHandler: event parsing error or not a MIDI event!\n\n";
  1154. #endif
  1155. }
  1156. }
  1157. }
  1158. snd_seq_free_event( ev );
  1159. if ( message.bytes.size() == 0 || continueSysex ) continue;
  1160. if ( data->usingCallback ) {
  1161. RtMidiIn::RtMidiCallback callback = (RtMidiIn::RtMidiCallback) data->userCallback;
  1162. callback( message.timeStamp, &message.bytes, data->userData );
  1163. }
  1164. else {
  1165. // As long as we haven't reached our queue size limit, push the message.
  1166. if (!data->queue.push(message))
  1167. std::cerr << "\nMidiInAlsa: message queue limit reached!!\n\n";
  1168. }
  1169. }
  1170. if ( buffer ) free( buffer );
  1171. snd_midi_event_free( apiData->coder );
  1172. apiData->coder = 0;
  1173. apiData->thread = apiData->dummy_thread_id;
  1174. return 0;
  1175. }
  1176. MidiInAlsa :: MidiInAlsa( const std::string &clientName, unsigned int queueSizeLimit ) : MidiInApi( queueSizeLimit )
  1177. {
  1178. initialize( clientName );
  1179. }
  1180. MidiInAlsa :: ~MidiInAlsa()
  1181. {
  1182. // Close a connection if it exists.
  1183. closePort();
  1184. // Shutdown the input thread.
  1185. AlsaMidiData *data = static_cast<AlsaMidiData *> (apiData_);
  1186. if ( inputData_.doInput ) {
  1187. inputData_.doInput = false;
  1188. int res = write( data->trigger_fds[1], &inputData_.doInput, sizeof(inputData_.doInput) );
  1189. (void) res;
  1190. if ( !pthread_equal(data->thread, data->dummy_thread_id) )
  1191. pthread_join( data->thread, NULL );
  1192. }
  1193. // Cleanup.
  1194. close ( data->trigger_fds[0] );
  1195. close ( data->trigger_fds[1] );
  1196. if ( data->vport >= 0 ) snd_seq_delete_port( data->seq, data->vport );
  1197. #ifndef AVOID_TIMESTAMPING
  1198. snd_seq_free_queue( data->seq, data->queue_id );
  1199. #endif
  1200. snd_seq_close( data->seq );
  1201. delete data;
  1202. }
  1203. void MidiInAlsa :: initialize( const std::string& clientName )
  1204. {
  1205. // Set up the ALSA sequencer client.
  1206. snd_seq_t *seq;
  1207. int result = snd_seq_open(&seq, "default", SND_SEQ_OPEN_DUPLEX, SND_SEQ_NONBLOCK);
  1208. if ( result < 0 ) {
  1209. errorString_ = "MidiInAlsa::initialize: error creating ALSA sequencer client object.";
  1210. error( RtMidiError::DRIVER_ERROR, errorString_ );
  1211. return;
  1212. }
  1213. // Set client name.
  1214. snd_seq_set_client_name( seq, clientName.c_str() );
  1215. // Save our api-specific connection information.
  1216. AlsaMidiData *data = (AlsaMidiData *) new AlsaMidiData;
  1217. data->seq = seq;
  1218. data->portNum = -1;
  1219. data->vport = -1;
  1220. data->subscription = 0;
  1221. data->dummy_thread_id = pthread_self();
  1222. data->thread = data->dummy_thread_id;
  1223. data->trigger_fds[0] = -1;
  1224. data->trigger_fds[1] = -1;
  1225. apiData_ = (void *) data;
  1226. inputData_.apiData = (void *) data;
  1227. if ( pipe(data->trigger_fds) == -1 ) {
  1228. errorString_ = "MidiInAlsa::initialize: error creating pipe objects.";
  1229. error( RtMidiError::DRIVER_ERROR, errorString_ );
  1230. return;
  1231. }
  1232. // Create the input queue
  1233. #ifndef AVOID_TIMESTAMPING
  1234. data->queue_id = snd_seq_alloc_named_queue(seq, "RtMidi Queue");
  1235. // Set arbitrary tempo (mm=100) and resolution (240)
  1236. snd_seq_queue_tempo_t *qtempo;
  1237. snd_seq_queue_tempo_alloca(&qtempo);
  1238. snd_seq_queue_tempo_set_tempo(qtempo, 600000);
  1239. snd_seq_queue_tempo_set_ppq(qtempo, 240);
  1240. snd_seq_set_queue_tempo(data->seq, data->queue_id, qtempo);
  1241. snd_seq_drain_output(data->seq);
  1242. #endif
  1243. }
  1244. // This function is used to count or get the pinfo structure for a given port number.
  1245. unsigned int portInfo( snd_seq_t *seq, snd_seq_port_info_t *pinfo, unsigned int type, int portNumber )
  1246. {
  1247. snd_seq_client_info_t *cinfo;
  1248. int client;
  1249. int count = 0;
  1250. snd_seq_client_info_alloca( &cinfo );
  1251. snd_seq_client_info_set_client( cinfo, -1 );
  1252. while ( snd_seq_query_next_client( seq, cinfo ) >= 0 ) {
  1253. client = snd_seq_client_info_get_client( cinfo );
  1254. if ( client == 0 ) continue;
  1255. // Reset query info
  1256. snd_seq_port_info_set_client( pinfo, client );
  1257. snd_seq_port_info_set_port( pinfo, -1 );
  1258. while ( snd_seq_query_next_port( seq, pinfo ) >= 0 ) {
  1259. unsigned int atyp = snd_seq_port_info_get_type( pinfo );
  1260. if ( ( ( atyp & SND_SEQ_PORT_TYPE_MIDI_GENERIC ) == 0 ) &&
  1261. ( ( atyp & SND_SEQ_PORT_TYPE_SYNTH ) == 0 ) &&
  1262. ( ( atyp & SND_SEQ_PORT_TYPE_APPLICATION ) == 0 ) ) continue;
  1263. unsigned int caps = snd_seq_port_info_get_capability( pinfo );
  1264. if ( ( caps & type ) != type ) continue;
  1265. if ( count == portNumber ) return 1;
  1266. ++count;
  1267. }
  1268. }
  1269. // If a negative portNumber was used, return the port count.
  1270. if ( portNumber < 0 ) return count;
  1271. return 0;
  1272. }
  1273. unsigned int MidiInAlsa :: getPortCount()
  1274. {
  1275. snd_seq_port_info_t *pinfo;
  1276. snd_seq_port_info_alloca( &pinfo );
  1277. AlsaMidiData *data = static_cast<AlsaMidiData *> (apiData_);
  1278. return portInfo( data->seq, pinfo, SND_SEQ_PORT_CAP_READ|SND_SEQ_PORT_CAP_SUBS_READ, -1 );
  1279. }
  1280. std::string MidiInAlsa :: getPortName( unsigned int portNumber )
  1281. {
  1282. snd_seq_client_info_t *cinfo;
  1283. snd_seq_port_info_t *pinfo;
  1284. snd_seq_client_info_alloca( &cinfo );
  1285. snd_seq_port_info_alloca( &pinfo );
  1286. std::string stringName;
  1287. AlsaMidiData *data = static_cast<AlsaMidiData *> (apiData_);
  1288. if ( portInfo( data->seq, pinfo, SND_SEQ_PORT_CAP_READ|SND_SEQ_PORT_CAP_SUBS_READ, (int) portNumber ) ) {
  1289. int cnum = snd_seq_port_info_get_client( pinfo );
  1290. snd_seq_get_any_client_info( data->seq, cnum, cinfo );
  1291. std::ostringstream os;
  1292. os << snd_seq_client_info_get_name( cinfo );
  1293. os << ":";
  1294. os << snd_seq_port_info_get_name( pinfo );
  1295. os << " "; // These lines added to make sure devices are listed
  1296. os << snd_seq_port_info_get_client( pinfo ); // with full portnames added to ensure individual device names
  1297. os << ":";
  1298. os << snd_seq_port_info_get_port( pinfo );
  1299. stringName = os.str();
  1300. return stringName;
  1301. }
  1302. // If we get here, we didn't find a match.
  1303. errorString_ = "MidiInAlsa::getPortName: error looking for port name!";
  1304. error( RtMidiError::WARNING, errorString_ );
  1305. return stringName;
  1306. }
  1307. void MidiInAlsa :: openPort( unsigned int portNumber, const std::string &portName )
  1308. {
  1309. if ( connected_ ) {
  1310. errorString_ = "MidiInAlsa::openPort: a valid connection already exists!";
  1311. error( RtMidiError::WARNING, errorString_ );
  1312. return;
  1313. }
  1314. unsigned int nSrc = this->getPortCount();
  1315. if ( nSrc < 1 ) {
  1316. errorString_ = "MidiInAlsa::openPort: no MIDI input sources found!";
  1317. error( RtMidiError::NO_DEVICES_FOUND, errorString_ );
  1318. return;
  1319. }
  1320. snd_seq_port_info_t *src_pinfo;
  1321. snd_seq_port_info_alloca( &src_pinfo );
  1322. AlsaMidiData *data = static_cast<AlsaMidiData *> (apiData_);
  1323. if ( portInfo( data->seq, src_pinfo, SND_SEQ_PORT_CAP_READ|SND_SEQ_PORT_CAP_SUBS_READ, (int) portNumber ) == 0 ) {
  1324. std::ostringstream ost;
  1325. ost << "MidiInAlsa::openPort: the 'portNumber' argument (" << portNumber << ") is invalid.";
  1326. errorString_ = ost.str();
  1327. error( RtMidiError::INVALID_PARAMETER, errorString_ );
  1328. return;
  1329. }
  1330. snd_seq_addr_t sender, receiver;
  1331. sender.client = snd_seq_port_info_get_client( src_pinfo );
  1332. sender.port = snd_seq_port_info_get_port( src_pinfo );
  1333. receiver.client = snd_seq_client_id( data->seq );
  1334. snd_seq_port_info_t *pinfo;
  1335. snd_seq_port_info_alloca( &pinfo );
  1336. if ( data->vport < 0 ) {
  1337. snd_seq_port_info_set_client( pinfo, 0 );
  1338. snd_seq_port_info_set_port( pinfo, 0 );
  1339. snd_seq_port_info_set_capability( pinfo,
  1340. SND_SEQ_PORT_CAP_WRITE |
  1341. SND_SEQ_PORT_CAP_SUBS_WRITE );
  1342. snd_seq_port_info_set_type( pinfo,
  1343. SND_SEQ_PORT_TYPE_MIDI_GENERIC |
  1344. SND_SEQ_PORT_TYPE_APPLICATION );
  1345. snd_seq_port_info_set_midi_channels(pinfo, 16);
  1346. #ifndef AVOID_TIMESTAMPING
  1347. snd_seq_port_info_set_timestamping(pinfo, 1);
  1348. snd_seq_port_info_set_timestamp_real(pinfo, 1);
  1349. snd_seq_port_info_set_timestamp_queue(pinfo, data->queue_id);
  1350. #endif
  1351. snd_seq_port_info_set_name(pinfo, portName.c_str() );
  1352. data->vport = snd_seq_create_port(data->seq, pinfo);
  1353. if ( data->vport < 0 ) {
  1354. errorString_ = "MidiInAlsa::openPort: ALSA error creating input port.";
  1355. error( RtMidiError::DRIVER_ERROR, errorString_ );
  1356. return;
  1357. }
  1358. data->vport = snd_seq_port_info_get_port(pinfo);
  1359. }
  1360. receiver.port = data->vport;
  1361. if ( !data->subscription ) {
  1362. // Make subscription
  1363. if (snd_seq_port_subscribe_malloc( &data->subscription ) < 0) {
  1364. errorString_ = "MidiInAlsa::openPort: ALSA error allocation port subscription.";
  1365. error( RtMidiError::DRIVER_ERROR, errorString_ );
  1366. return;
  1367. }
  1368. snd_seq_port_subscribe_set_sender(data->subscription, &sender);
  1369. snd_seq_port_subscribe_set_dest(data->subscription, &receiver);
  1370. if ( snd_seq_subscribe_port(data->seq, data->subscription) ) {
  1371. snd_seq_port_subscribe_free( data->subscription );
  1372. data->subscription = 0;
  1373. errorString_ = "MidiInAlsa::openPort: ALSA error making port connection.";
  1374. error( RtMidiError::DRIVER_ERROR, errorString_ );
  1375. return;
  1376. }
  1377. }
  1378. if ( inputData_.doInput == false ) {
  1379. // Start the input queue
  1380. #ifndef AVOID_TIMESTAMPING
  1381. snd_seq_start_queue( data->seq, data->queue_id, NULL );
  1382. snd_seq_drain_output( data->seq );
  1383. #endif
  1384. // Start our MIDI input thread.
  1385. pthread_attr_t attr;
  1386. pthread_attr_init(&attr);
  1387. pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
  1388. pthread_attr_setschedpolicy(&attr, SCHED_OTHER);
  1389. inputData_.doInput = true;
  1390. int err = pthread_create(&data->thread, &attr, alsaMidiHandler, &inputData_);
  1391. pthread_attr_destroy(&attr);
  1392. if ( err ) {
  1393. snd_seq_unsubscribe_port( data->seq, data->subscription );
  1394. snd_seq_port_subscribe_free( data->subscription );
  1395. data->subscription = 0;
  1396. inputData_.doInput = false;
  1397. errorString_ = "MidiInAlsa::openPort: error starting MIDI input thread!";
  1398. error( RtMidiError::THREAD_ERROR, errorString_ );
  1399. return;
  1400. }
  1401. }
  1402. connected_ = true;
  1403. }
  1404. void MidiInAlsa :: openVirtualPort( const std::string &portName )
  1405. {
  1406. AlsaMidiData *data = static_cast<AlsaMidiData *> (apiData_);
  1407. if ( data->vport < 0 ) {
  1408. snd_seq_port_info_t *pinfo;
  1409. snd_seq_port_info_alloca( &pinfo );
  1410. snd_seq_port_info_set_capability( pinfo,
  1411. SND_SEQ_PORT_CAP_WRITE |
  1412. SND_SEQ_PORT_CAP_SUBS_WRITE );
  1413. snd_seq_port_info_set_type( pinfo,
  1414. SND_SEQ_PORT_TYPE_MIDI_GENERIC |
  1415. SND_SEQ_PORT_TYPE_APPLICATION );
  1416. snd_seq_port_info_set_midi_channels(pinfo, 16);
  1417. #ifndef AVOID_TIMESTAMPING
  1418. snd_seq_port_info_set_timestamping(pinfo, 1);
  1419. snd_seq_port_info_set_timestamp_real(pinfo, 1);
  1420. snd_seq_port_info_set_timestamp_queue(pinfo, data->queue_id);
  1421. #endif
  1422. snd_seq_port_info_set_name(pinfo, portName.c_str());
  1423. data->vport = snd_seq_create_port(data->seq, pinfo);
  1424. if ( data->vport < 0 ) {
  1425. errorString_ = "MidiInAlsa::openVirtualPort: ALSA error creating virtual port.";
  1426. error( RtMidiError::DRIVER_ERROR, errorString_ );
  1427. return;
  1428. }
  1429. data->vport = snd_seq_port_info_get_port(pinfo);
  1430. }
  1431. if ( inputData_.doInput == false ) {
  1432. // Wait for old thread to stop, if still running
  1433. if ( !pthread_equal(data->thread, data->dummy_thread_id) )
  1434. pthread_join( data->thread, NULL );
  1435. // Start the input queue
  1436. #ifndef AVOID_TIMESTAMPING
  1437. snd_seq_start_queue( data->seq, data->queue_id, NULL );
  1438. snd_seq_drain_output( data->seq );
  1439. #endif
  1440. // Start our MIDI input thread.
  1441. pthread_attr_t attr;
  1442. pthread_attr_init(&attr);
  1443. pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
  1444. pthread_attr_setschedpolicy(&attr, SCHED_OTHER);
  1445. inputData_.doInput = true;
  1446. int err = pthread_create(&data->thread, &attr, alsaMidiHandler, &inputData_);
  1447. pthread_attr_destroy(&attr);
  1448. if ( err ) {
  1449. if ( data->subscription ) {
  1450. snd_seq_unsubscribe_port( data->seq, data->subscription );
  1451. snd_seq_port_subscribe_free( data->subscription );
  1452. data->subscription = 0;
  1453. }
  1454. inputData_.doInput = false;
  1455. errorString_ = "MidiInAlsa::openPort: error starting MIDI input thread!";
  1456. error( RtMidiError::THREAD_ERROR, errorString_ );
  1457. return;
  1458. }
  1459. }
  1460. }
  1461. void MidiInAlsa :: closePort( void )
  1462. {
  1463. AlsaMidiData *data = static_cast<AlsaMidiData *> (apiData_);
  1464. if ( connected_ ) {
  1465. if ( data->subscription ) {
  1466. snd_seq_unsubscribe_port( data->seq, data->subscription );
  1467. snd_seq_port_subscribe_free( data->subscription );
  1468. data->subscription = 0;
  1469. }
  1470. // Stop the input queue
  1471. #ifndef AVOID_TIMESTAMPING
  1472. snd_seq_stop_queue( data->seq, data->queue_id, NULL );
  1473. snd_seq_drain_output( data->seq );
  1474. #endif
  1475. connected_ = false;
  1476. }
  1477. // Stop thread to avoid triggering the callback, while the port is intended to be closed
  1478. if ( inputData_.doInput ) {
  1479. inputData_.doInput = false;
  1480. int res = write( data->trigger_fds[1], &inputData_.doInput, sizeof(inputData_.doInput) );
  1481. (void) res;
  1482. if ( !pthread_equal(data->thread, data->dummy_thread_id) )
  1483. pthread_join( data->thread, NULL );
  1484. }
  1485. }
  1486. //*********************************************************************//
  1487. // API: LINUX ALSA
  1488. // Class Definitions: MidiOutAlsa
  1489. //*********************************************************************//
  1490. MidiOutAlsa :: MidiOutAlsa( const std::string &clientName ) : MidiOutApi()
  1491. {
  1492. initialize( clientName );
  1493. }
  1494. MidiOutAlsa :: ~MidiOutAlsa()
  1495. {
  1496. // Close a connection if it exists.
  1497. closePort();
  1498. // Cleanup.
  1499. AlsaMidiData *data = static_cast<AlsaMidiData *> (apiData_);
  1500. if ( data->vport >= 0 ) snd_seq_delete_port( data->seq, data->vport );
  1501. if ( data->coder ) snd_midi_event_free( data->coder );
  1502. if ( data->buffer ) free( data->buffer );
  1503. snd_seq_close( data->seq );
  1504. delete data;
  1505. }
  1506. void MidiOutAlsa :: initialize( const std::string& clientName )
  1507. {
  1508. // Set up the ALSA sequencer client.
  1509. snd_seq_t *seq;
  1510. int result1 = snd_seq_open( &seq, "default", SND_SEQ_OPEN_OUTPUT, SND_SEQ_NONBLOCK );
  1511. if ( result1 < 0 ) {
  1512. errorString_ = "MidiOutAlsa::initialize: error creating ALSA sequencer client object.";
  1513. error( RtMidiError::DRIVER_ERROR, errorString_ );
  1514. return;
  1515. }
  1516. // Set client name.
  1517. snd_seq_set_client_name( seq, clientName.c_str() );
  1518. // Save our api-specific connection information.
  1519. AlsaMidiData *data = (AlsaMidiData *) new AlsaMidiData;
  1520. data->seq = seq;
  1521. data->portNum = -1;
  1522. data->vport = -1;
  1523. data->bufferSize = 32;
  1524. data->coder = 0;
  1525. data->buffer = 0;
  1526. int result = snd_midi_event_new( data->bufferSize, &data->coder );
  1527. if ( result < 0 ) {
  1528. delete data;
  1529. errorString_ = "MidiOutAlsa::initialize: error initializing MIDI event parser!\n\n";
  1530. error( RtMidiError::DRIVER_ERROR, errorString_ );
  1531. return;
  1532. }
  1533. data->buffer = (unsigned char *) malloc( data->bufferSize );
  1534. if ( data->buffer == NULL ) {
  1535. delete data;
  1536. errorString_ = "MidiOutAlsa::initialize: error allocating buffer memory!\n\n";
  1537. error( RtMidiError::MEMORY_ERROR, errorString_ );
  1538. return;
  1539. }
  1540. snd_midi_event_init( data->coder );
  1541. apiData_ = (void *) data;
  1542. }
  1543. unsigned int MidiOutAlsa :: getPortCount()
  1544. {
  1545. snd_seq_port_info_t *pinfo;
  1546. snd_seq_port_info_alloca( &pinfo );
  1547. AlsaMidiData *data = static_cast<AlsaMidiData *> (apiData_);
  1548. return portInfo( data->seq, pinfo, SND_SEQ_PORT_CAP_WRITE|SND_SEQ_PORT_CAP_SUBS_WRITE, -1 );
  1549. }
  1550. std::string MidiOutAlsa :: getPortName( unsigned int portNumber )
  1551. {
  1552. snd_seq_client_info_t *cinfo;
  1553. snd_seq_port_info_t *pinfo;
  1554. snd_seq_client_info_alloca( &cinfo );
  1555. snd_seq_port_info_alloca( &pinfo );
  1556. std::string stringName;
  1557. AlsaMidiData *data = static_cast<AlsaMidiData *> (apiData_);
  1558. if ( portInfo( data->seq, pinfo, SND_SEQ_PORT_CAP_WRITE|SND_SEQ_PORT_CAP_SUBS_WRITE, (int) portNumber ) ) {
  1559. int cnum = snd_seq_port_info_get_client(pinfo);
  1560. snd_seq_get_any_client_info( data->seq, cnum, cinfo );
  1561. std::ostringstream os;
  1562. os << snd_seq_client_info_get_name(cinfo);
  1563. os << ":";
  1564. os << snd_seq_port_info_get_name( pinfo );
  1565. os << " "; // These lines added to make sure devices are listed
  1566. os << snd_seq_port_info_get_client( pinfo ); // with full portnames added to ensure individual device names
  1567. os << ":";
  1568. os << snd_seq_port_info_get_port(pinfo);
  1569. stringName = os.str();
  1570. return stringName;
  1571. }
  1572. // If we get here, we didn't find a match.
  1573. errorString_ = "MidiOutAlsa::getPortName: error looking for port name!";
  1574. error( RtMidiError::WARNING, errorString_ );
  1575. return stringName;
  1576. }
  1577. void MidiOutAlsa :: openPort( unsigned int portNumber, const std::string &portName )
  1578. {
  1579. if ( connected_ ) {
  1580. errorString_ = "MidiOutAlsa::openPort: a valid connection already exists!";
  1581. error( RtMidiError::WARNING, errorString_ );
  1582. return;
  1583. }
  1584. unsigned int nSrc = this->getPortCount();
  1585. if (nSrc < 1) {
  1586. errorString_ = "MidiOutAlsa::openPort: no MIDI output sources found!";
  1587. error( RtMidiError::NO_DEVICES_FOUND, errorString_ );
  1588. return;
  1589. }
  1590. snd_seq_port_info_t *pinfo;
  1591. snd_seq_port_info_alloca( &pinfo );
  1592. AlsaMidiData *data = static_cast<AlsaMidiData *> (apiData_);
  1593. if ( portInfo( data->seq, pinfo, SND_SEQ_PORT_CAP_WRITE|SND_SEQ_PORT_CAP_SUBS_WRITE, (int) portNumber ) == 0 ) {
  1594. std::ostringstream ost;
  1595. ost << "MidiOutAlsa::openPort: the 'portNumber' argument (" << portNumber << ") is invalid.";
  1596. errorString_ = ost.str();
  1597. error( RtMidiError::INVALID_PARAMETER, errorString_ );
  1598. return;
  1599. }
  1600. snd_seq_addr_t sender, receiver;
  1601. receiver.client = snd_seq_port_info_get_client( pinfo );
  1602. receiver.port = snd_seq_port_info_get_port( pinfo );
  1603. sender.client = snd_seq_client_id( data->seq );
  1604. if ( data->vport < 0 ) {
  1605. data->vport = snd_seq_create_simple_port( data->seq, portName.c_str(),
  1606. SND_SEQ_PORT_CAP_READ|SND_SEQ_PORT_CAP_SUBS_READ,
  1607. SND_SEQ_PORT_TYPE_MIDI_GENERIC|SND_SEQ_PORT_TYPE_APPLICATION );
  1608. if ( data->vport < 0 ) {
  1609. errorString_ = "MidiOutAlsa::openPort: ALSA error creating output port.";
  1610. error( RtMidiError::DRIVER_ERROR, errorString_ );
  1611. return;
  1612. }
  1613. }
  1614. sender.port = data->vport;
  1615. // Make subscription
  1616. if (snd_seq_port_subscribe_malloc( &data->subscription ) < 0) {
  1617. snd_seq_port_subscribe_free( data->subscription );
  1618. errorString_ = "MidiOutAlsa::openPort: error allocating port subscription.";
  1619. error( RtMidiError::DRIVER_ERROR, errorString_ );
  1620. return;
  1621. }
  1622. snd_seq_port_subscribe_set_sender(data->subscription, &sender);
  1623. snd_seq_port_subscribe_set_dest(data->subscription, &receiver);
  1624. snd_seq_port_subscribe_set_time_update(data->subscription, 1);
  1625. snd_seq_port_subscribe_set_time_real(data->subscription, 1);
  1626. if ( snd_seq_subscribe_port(data->seq, data->subscription) ) {
  1627. snd_seq_port_subscribe_free( data->subscription );
  1628. errorString_ = "MidiOutAlsa::openPort: ALSA error making port connection.";
  1629. error( RtMidiError::DRIVER_ERROR, errorString_ );
  1630. return;
  1631. }
  1632. connected_ = true;
  1633. }
  1634. void MidiOutAlsa :: closePort( void )
  1635. {
  1636. if ( connected_ ) {
  1637. AlsaMidiData *data = static_cast<AlsaMidiData *> (apiData_);
  1638. snd_seq_unsubscribe_port( data->seq, data->subscription );
  1639. snd_seq_port_subscribe_free( data->subscription );
  1640. data->subscription = 0;
  1641. connected_ = false;
  1642. }
  1643. }
  1644. void MidiOutAlsa :: openVirtualPort( const std::string &portName )
  1645. {
  1646. AlsaMidiData *data = static_cast<AlsaMidiData *> (apiData_);
  1647. if ( data->vport < 0 ) {
  1648. data->vport = snd_seq_create_simple_port( data->seq, portName.c_str(),
  1649. SND_SEQ_PORT_CAP_READ|SND_SEQ_PORT_CAP_SUBS_READ,
  1650. SND_SEQ_PORT_TYPE_MIDI_GENERIC|SND_SEQ_PORT_TYPE_APPLICATION );
  1651. if ( data->vport < 0 ) {
  1652. errorString_ = "MidiOutAlsa::openVirtualPort: ALSA error creating virtual port.";
  1653. error( RtMidiError::DRIVER_ERROR, errorString_ );
  1654. }
  1655. }
  1656. }
  1657. void MidiOutAlsa :: sendMessage( const unsigned char *message, size_t size )
  1658. {
  1659. int result;
  1660. AlsaMidiData *data = static_cast<AlsaMidiData *> (apiData_);
  1661. unsigned int nBytes = static_cast<unsigned int> (size);
  1662. if ( nBytes > data->bufferSize ) {
  1663. data->bufferSize = nBytes;
  1664. result = snd_midi_event_resize_buffer ( data->coder, nBytes);
  1665. if ( result != 0 ) {
  1666. errorString_ = "MidiOutAlsa::sendMessage: ALSA error resizing MIDI event buffer.";
  1667. error( RtMidiError::DRIVER_ERROR, errorString_ );
  1668. return;
  1669. }
  1670. free (data->buffer);
  1671. data->buffer = (unsigned char *) malloc( data->bufferSize );
  1672. if ( data->buffer == NULL ) {
  1673. errorString_ = "MidiOutAlsa::initialize: error allocating buffer memory!\n\n";
  1674. error( RtMidiError::MEMORY_ERROR, errorString_ );
  1675. return;
  1676. }
  1677. }
  1678. snd_seq_event_t ev;
  1679. snd_seq_ev_clear(&ev);
  1680. snd_seq_ev_set_source(&ev, data->vport);
  1681. snd_seq_ev_set_subs(&ev);
  1682. snd_seq_ev_set_direct(&ev);
  1683. for ( unsigned int i=0; i<nBytes; ++i ) data->buffer[i] = message[i];
  1684. result = snd_midi_event_encode( data->coder, data->buffer, (long)nBytes, &ev );
  1685. if ( result < (int)nBytes ) {
  1686. errorString_ = "MidiOutAlsa::sendMessage: event parsing error!";
  1687. error( RtMidiError::WARNING, errorString_ );
  1688. return;
  1689. }
  1690. // Send the event.
  1691. result = snd_seq_event_output(data->seq, &ev);
  1692. if ( result < 0 ) {
  1693. errorString_ = "MidiOutAlsa::sendMessage: error sending MIDI message to port.";
  1694. error( RtMidiError::WARNING, errorString_ );
  1695. return;
  1696. }
  1697. snd_seq_drain_output(data->seq);
  1698. }
  1699. #endif // __LINUX_ALSA__
  1700. //*********************************************************************//
  1701. // API: Windows Multimedia Library (MM)
  1702. //*********************************************************************//
  1703. // API information deciphered from:
  1704. // - http://msdn.microsoft.com/library/default.asp?url=/library/en-us/multimed/htm/_win32_midi_reference.asp
  1705. // Thanks to Jean-Baptiste Berruchon for the sysex code.
  1706. #if defined(__WINDOWS_MM__)
  1707. // The Windows MM API is based on the use of a callback function for
  1708. // MIDI input. We convert the system specific time stamps to delta
  1709. // time values.
  1710. // Windows MM MIDI header files.
  1711. #include <windows.h>
  1712. #include <mmsystem.h>
  1713. // Convert a null-terminated wide string or ANSI-encoded string to UTF-8.
  1714. static std::string ConvertToUTF8(const TCHAR *str)
  1715. {
  1716. std::string u8str;
  1717. const WCHAR *wstr = L"";
  1718. #if defined( UNICODE ) || defined( _UNICODE )
  1719. wstr = str;
  1720. #else
  1721. // Convert from ANSI encoding to wide string
  1722. int wlength = MultiByteToWideChar( CP_ACP, 0, str, -1, NULL, 0 );
  1723. std::wstring wstrtemp;
  1724. if ( wlength )
  1725. {
  1726. wstrtemp.assign( wlength - 1, 0 );
  1727. MultiByteToWideChar( CP_ACP, 0, str, -1, &wstrtemp[0], wlength );
  1728. wstr = &wstrtemp[0];
  1729. }
  1730. #endif
  1731. // Convert from wide string to UTF-8
  1732. int length = WideCharToMultiByte( CP_UTF8, 0, wstr, -1, NULL, 0, NULL, NULL );
  1733. if ( length )
  1734. {
  1735. u8str.assign( length - 1, 0 );
  1736. length = WideCharToMultiByte( CP_UTF8, 0, wstr, -1, &u8str[0], length, NULL, NULL );
  1737. }
  1738. return u8str;
  1739. }
  1740. #define RT_SYSEX_BUFFER_SIZE 1024
  1741. #define RT_SYSEX_BUFFER_COUNT 4
  1742. // A structure to hold variables related to the CoreMIDI API
  1743. // implementation.
  1744. struct WinMidiData {
  1745. HMIDIIN inHandle; // Handle to Midi Input Device
  1746. HMIDIOUT outHandle; // Handle to Midi Output Device
  1747. DWORD lastTime;
  1748. MidiInApi::MidiMessage message;
  1749. LPMIDIHDR sysexBuffer[RT_SYSEX_BUFFER_COUNT];
  1750. CRITICAL_SECTION _mutex; // [Patrice] see https://groups.google.com/forum/#!topic/mididev/6OUjHutMpEo
  1751. };
  1752. //*********************************************************************//
  1753. // API: Windows MM
  1754. // Class Definitions: MidiInWinMM
  1755. //*********************************************************************//
  1756. static void CALLBACK midiInputCallback( HMIDIIN /*hmin*/,
  1757. UINT inputStatus,
  1758. DWORD_PTR instancePtr,
  1759. DWORD_PTR midiMessage,
  1760. DWORD timestamp )
  1761. {
  1762. if ( inputStatus != MIM_DATA && inputStatus != MIM_LONGDATA && inputStatus != MIM_LONGERROR ) return;
  1763. //MidiInApi::RtMidiInData *data = static_cast<MidiInApi::RtMidiInData *> (instancePtr);
  1764. MidiInApi::RtMidiInData *data = (MidiInApi::RtMidiInData *)instancePtr;
  1765. WinMidiData *apiData = static_cast<WinMidiData *> (data->apiData);
  1766. // Calculate time stamp.
  1767. if ( data->firstMessage == true ) {
  1768. apiData->message.timeStamp = 0.0;
  1769. data->firstMessage = false;
  1770. }
  1771. else apiData->message.timeStamp = (double) ( timestamp - apiData->lastTime ) * 0.001;
  1772. apiData->lastTime = timestamp;
  1773. if ( inputStatus == MIM_DATA ) { // Channel or system message
  1774. // Make sure the first byte is a status byte.
  1775. unsigned char status = (unsigned char) (midiMessage & 0x000000FF);
  1776. if ( !(status & 0x80) ) return;
  1777. // Determine the number of bytes in the MIDI message.
  1778. unsigned short nBytes = 1;
  1779. if ( status < 0xC0 ) nBytes = 3;
  1780. else if ( status < 0xE0 ) nBytes = 2;
  1781. else if ( status < 0xF0 ) nBytes = 3;
  1782. else if ( status == 0xF1 ) {
  1783. if ( data->ignoreFlags & 0x02 ) return;
  1784. else nBytes = 2;
  1785. }
  1786. else if ( status == 0xF2 ) nBytes = 3;
  1787. else if ( status == 0xF3 ) nBytes = 2;
  1788. else if ( status == 0xF8 && (data->ignoreFlags & 0x02) ) {
  1789. // A MIDI timing tick message and we're ignoring it.
  1790. return;
  1791. }
  1792. else if ( status == 0xFE && (data->ignoreFlags & 0x04) ) {
  1793. // A MIDI active sensing message and we're ignoring it.
  1794. return;
  1795. }
  1796. // Copy bytes to our MIDI message.
  1797. unsigned char *ptr = (unsigned char *) &midiMessage;
  1798. for ( int i=0; i<nBytes; ++i ) apiData->message.bytes.push_back( *ptr++ );
  1799. }
  1800. else { // Sysex message ( MIM_LONGDATA or MIM_LONGERROR )
  1801. MIDIHDR *sysex = ( MIDIHDR *) midiMessage;
  1802. if ( !( data->ignoreFlags & 0x01 ) && inputStatus != MIM_LONGERROR ) {
  1803. // Sysex message and we're not ignoring it
  1804. for ( int i=0; i<(int)sysex->dwBytesRecorded; ++i )
  1805. apiData->message.bytes.push_back( sysex->lpData[i] );
  1806. }
  1807. // The WinMM API requires that the sysex buffer be requeued after
  1808. // input of each sysex message. Even if we are ignoring sysex
  1809. // messages, we still need to requeue the buffer in case the user
  1810. // decides to not ignore sysex messages in the future. However,
  1811. // it seems that WinMM calls this function with an empty sysex
  1812. // buffer when an application closes and in this case, we should
  1813. // avoid requeueing it, else the computer suddenly reboots after
  1814. // one or two minutes.
  1815. if ( apiData->sysexBuffer[sysex->dwUser]->dwBytesRecorded > 0 ) {
  1816. //if ( sysex->dwBytesRecorded > 0 ) {
  1817. EnterCriticalSection( &(apiData->_mutex) );
  1818. MMRESULT result = midiInAddBuffer( apiData->inHandle, apiData->sysexBuffer[sysex->dwUser], sizeof(MIDIHDR) );
  1819. LeaveCriticalSection( &(apiData->_mutex) );
  1820. if ( result != MMSYSERR_NOERROR )
  1821. std::cerr << "\nRtMidiIn::midiInputCallback: error sending sysex to Midi device!!\n\n";
  1822. if ( data->ignoreFlags & 0x01 ) return;
  1823. }
  1824. else return;
  1825. }
  1826. if ( data->usingCallback ) {
  1827. RtMidiIn::RtMidiCallback callback = (RtMidiIn::RtMidiCallback) data->userCallback;
  1828. callback( apiData->message.timeStamp, &apiData->message.bytes, data->userData );
  1829. }
  1830. else {
  1831. // As long as we haven't reached our queue size limit, push the message.
  1832. if (!data->queue.push(apiData->message))
  1833. std::cerr << "\nMidiInWinMM: message queue limit reached!!\n\n";
  1834. }
  1835. // Clear the vector for the next input message.
  1836. apiData->message.bytes.clear();
  1837. }
  1838. MidiInWinMM :: MidiInWinMM( const std::string &clientName, unsigned int queueSizeLimit ) : MidiInApi( queueSizeLimit )
  1839. {
  1840. initialize( clientName );
  1841. }
  1842. MidiInWinMM :: ~MidiInWinMM()
  1843. {
  1844. // Close a connection if it exists.
  1845. closePort();
  1846. WinMidiData *data = static_cast<WinMidiData *> (apiData_);
  1847. DeleteCriticalSection( &(data->_mutex) );
  1848. // Cleanup.
  1849. delete data;
  1850. }
  1851. void MidiInWinMM :: initialize( const std::string& /*clientName*/ )
  1852. {
  1853. // We'll issue a warning here if no devices are available but not
  1854. // throw an error since the user can plugin something later.
  1855. unsigned int nDevices = midiInGetNumDevs();
  1856. if ( nDevices == 0 ) {
  1857. errorString_ = "MidiInWinMM::initialize: no MIDI input devices currently available.";
  1858. error( RtMidiError::WARNING, errorString_ );
  1859. }
  1860. // Save our api-specific connection information.
  1861. WinMidiData *data = (WinMidiData *) new WinMidiData;
  1862. apiData_ = (void *) data;
  1863. inputData_.apiData = (void *) data;
  1864. data->message.bytes.clear(); // needs to be empty for first input message
  1865. if ( !InitializeCriticalSectionAndSpinCount(&(data->_mutex), 0x00000400) ) {
  1866. errorString_ = "MidiInWinMM::initialize: InitializeCriticalSectionAndSpinCount failed.";
  1867. error( RtMidiError::WARNING, errorString_ );
  1868. }
  1869. }
  1870. void MidiInWinMM :: openPort( unsigned int portNumber, const std::string &/*portName*/ )
  1871. {
  1872. if ( connected_ ) {
  1873. errorString_ = "MidiInWinMM::openPort: a valid connection already exists!";
  1874. error( RtMidiError::WARNING, errorString_ );
  1875. return;
  1876. }
  1877. unsigned int nDevices = midiInGetNumDevs();
  1878. if (nDevices == 0) {
  1879. errorString_ = "MidiInWinMM::openPort: no MIDI input sources found!";
  1880. error( RtMidiError::NO_DEVICES_FOUND, errorString_ );
  1881. return;
  1882. }
  1883. if ( portNumber >= nDevices ) {
  1884. std::ostringstream ost;
  1885. ost << "MidiInWinMM::openPort: the 'portNumber' argument (" << portNumber << ") is invalid.";
  1886. errorString_ = ost.str();
  1887. error( RtMidiError::INVALID_PARAMETER, errorString_ );
  1888. return;
  1889. }
  1890. WinMidiData *data = static_cast<WinMidiData *> (apiData_);
  1891. MMRESULT result = midiInOpen( &data->inHandle,
  1892. portNumber,
  1893. (DWORD_PTR)&midiInputCallback,
  1894. (DWORD_PTR)&inputData_,
  1895. CALLBACK_FUNCTION );
  1896. if ( result != MMSYSERR_NOERROR ) {
  1897. errorString_ = "MidiInWinMM::openPort: error creating Windows MM MIDI input port.";
  1898. error( RtMidiError::DRIVER_ERROR, errorString_ );
  1899. return;
  1900. }
  1901. // Allocate and init the sysex buffers.
  1902. for ( int i=0; i<RT_SYSEX_BUFFER_COUNT; ++i ) {
  1903. data->sysexBuffer[i] = (MIDIHDR*) new char[ sizeof(MIDIHDR) ];
  1904. data->sysexBuffer[i]->lpData = new char[ RT_SYSEX_BUFFER_SIZE ];
  1905. data->sysexBuffer[i]->dwBufferLength = RT_SYSEX_BUFFER_SIZE;
  1906. data->sysexBuffer[i]->dwUser = i; // We use the dwUser parameter as buffer indicator
  1907. data->sysexBuffer[i]->dwFlags = 0;
  1908. result = midiInPrepareHeader( data->inHandle, data->sysexBuffer[i], sizeof(MIDIHDR) );
  1909. if ( result != MMSYSERR_NOERROR ) {
  1910. midiInClose( data->inHandle );
  1911. data->inHandle = 0;
  1912. errorString_ = "MidiInWinMM::openPort: error starting Windows MM MIDI input port (PrepareHeader).";
  1913. error( RtMidiError::DRIVER_ERROR, errorString_ );
  1914. return;
  1915. }
  1916. // Register the buffer.
  1917. result = midiInAddBuffer( data->inHandle, data->sysexBuffer[i], sizeof(MIDIHDR) );
  1918. if ( result != MMSYSERR_NOERROR ) {
  1919. midiInClose( data->inHandle );
  1920. data->inHandle = 0;
  1921. errorString_ = "MidiInWinMM::openPort: error starting Windows MM MIDI input port (AddBuffer).";
  1922. error( RtMidiError::DRIVER_ERROR, errorString_ );
  1923. return;
  1924. }
  1925. }
  1926. result = midiInStart( data->inHandle );
  1927. if ( result != MMSYSERR_NOERROR ) {
  1928. midiInClose( data->inHandle );
  1929. data->inHandle = 0;
  1930. errorString_ = "MidiInWinMM::openPort: error starting Windows MM MIDI input port.";
  1931. error( RtMidiError::DRIVER_ERROR, errorString_ );
  1932. return;
  1933. }
  1934. connected_ = true;
  1935. }
  1936. void MidiInWinMM :: openVirtualPort( const std::string &/*portName*/ )
  1937. {
  1938. // This function cannot be implemented for the Windows MM MIDI API.
  1939. errorString_ = "MidiInWinMM::openVirtualPort: cannot be implemented in Windows MM MIDI API!";
  1940. error( RtMidiError::WARNING, errorString_ );
  1941. }
  1942. void MidiInWinMM :: closePort( void )
  1943. {
  1944. if ( connected_ ) {
  1945. WinMidiData *data = static_cast<WinMidiData *> (apiData_);
  1946. EnterCriticalSection( &(data->_mutex) );
  1947. midiInReset( data->inHandle );
  1948. midiInStop( data->inHandle );
  1949. for ( int i=0; i<RT_SYSEX_BUFFER_COUNT; ++i ) {
  1950. int result = midiInUnprepareHeader(data->inHandle, data->sysexBuffer[i], sizeof(MIDIHDR));
  1951. delete [] data->sysexBuffer[i]->lpData;
  1952. delete [] data->sysexBuffer[i];
  1953. if ( result != MMSYSERR_NOERROR ) {
  1954. midiInClose( data->inHandle );
  1955. data->inHandle = 0;
  1956. errorString_ = "MidiInWinMM::openPort: error closing Windows MM MIDI input port (midiInUnprepareHeader).";
  1957. error( RtMidiError::DRIVER_ERROR, errorString_ );
  1958. return;
  1959. }
  1960. }
  1961. midiInClose( data->inHandle );
  1962. data->inHandle = 0;
  1963. connected_ = false;
  1964. LeaveCriticalSection( &(data->_mutex) );
  1965. }
  1966. }
  1967. unsigned int MidiInWinMM :: getPortCount()
  1968. {
  1969. return midiInGetNumDevs();
  1970. }
  1971. std::string MidiInWinMM :: getPortName( unsigned int portNumber )
  1972. {
  1973. std::string stringName;
  1974. unsigned int nDevices = midiInGetNumDevs();
  1975. if ( portNumber >= nDevices ) {
  1976. std::ostringstream ost;
  1977. ost << "MidiInWinMM::getPortName: the 'portNumber' argument (" << portNumber << ") is invalid.";
  1978. errorString_ = ost.str();
  1979. error( RtMidiError::WARNING, errorString_ );
  1980. return stringName;
  1981. }
  1982. MIDIINCAPS deviceCaps;
  1983. midiInGetDevCaps( portNumber, &deviceCaps, sizeof(MIDIINCAPS));
  1984. stringName = ConvertToUTF8( deviceCaps.szPname );
  1985. // Next lines added to add the portNumber to the name so that
  1986. // the device's names are sure to be listed with individual names
  1987. // even when they have the same brand name
  1988. #ifdef RTMIDI_ENSURE_UNIQUE_PORTNAMES
  1989. std::ostringstream os;
  1990. os << " ";
  1991. os << portNumber;
  1992. stringName += os.str();
  1993. #endif
  1994. return stringName;
  1995. }
  1996. //*********************************************************************//
  1997. // API: Windows MM
  1998. // Class Definitions: MidiOutWinMM
  1999. //*********************************************************************//
  2000. MidiOutWinMM :: MidiOutWinMM( const std::string &clientName ) : MidiOutApi()
  2001. {
  2002. initialize( clientName );
  2003. }
  2004. MidiOutWinMM :: ~MidiOutWinMM()
  2005. {
  2006. // Close a connection if it exists.
  2007. closePort();
  2008. // Cleanup.
  2009. WinMidiData *data = static_cast<WinMidiData *> (apiData_);
  2010. delete data;
  2011. }
  2012. void MidiOutWinMM :: initialize( const std::string& /*clientName*/ )
  2013. {
  2014. // We'll issue a warning here if no devices are available but not
  2015. // throw an error since the user can plug something in later.
  2016. unsigned int nDevices = midiOutGetNumDevs();
  2017. if ( nDevices == 0 ) {
  2018. errorString_ = "MidiOutWinMM::initialize: no MIDI output devices currently available.";
  2019. error( RtMidiError::WARNING, errorString_ );
  2020. }
  2021. // Save our api-specific connection information.
  2022. WinMidiData *data = (WinMidiData *) new WinMidiData;
  2023. apiData_ = (void *) data;
  2024. }
  2025. unsigned int MidiOutWinMM :: getPortCount()
  2026. {
  2027. return midiOutGetNumDevs();
  2028. }
  2029. std::string MidiOutWinMM :: getPortName( unsigned int portNumber )
  2030. {
  2031. std::string stringName;
  2032. unsigned int nDevices = midiOutGetNumDevs();
  2033. if ( portNumber >= nDevices ) {
  2034. std::ostringstream ost;
  2035. ost << "MidiOutWinMM::getPortName: the 'portNumber' argument (" << portNumber << ") is invalid.";
  2036. errorString_ = ost.str();
  2037. error( RtMidiError::WARNING, errorString_ );
  2038. return stringName;
  2039. }
  2040. MIDIOUTCAPS deviceCaps;
  2041. midiOutGetDevCaps( portNumber, &deviceCaps, sizeof(MIDIOUTCAPS));
  2042. stringName = ConvertToUTF8( deviceCaps.szPname );
  2043. // Next lines added to add the portNumber to the name so that
  2044. // the device's names are sure to be listed with individual names
  2045. // even when they have the same brand name
  2046. std::ostringstream os;
  2047. #ifdef RTMIDI_ENSURE_UNIQUE_PORTNAMES
  2048. os << " ";
  2049. os << portNumber;
  2050. stringName += os.str();
  2051. #endif
  2052. return stringName;
  2053. }
  2054. void MidiOutWinMM :: openPort( unsigned int portNumber, const std::string &/*portName*/ )
  2055. {
  2056. if ( connected_ ) {
  2057. errorString_ = "MidiOutWinMM::openPort: a valid connection already exists!";
  2058. error( RtMidiError::WARNING, errorString_ );
  2059. return;
  2060. }
  2061. unsigned int nDevices = midiOutGetNumDevs();
  2062. if (nDevices < 1) {
  2063. errorString_ = "MidiOutWinMM::openPort: no MIDI output destinations found!";
  2064. error( RtMidiError::NO_DEVICES_FOUND, errorString_ );
  2065. return;
  2066. }
  2067. if ( portNumber >= nDevices ) {
  2068. std::ostringstream ost;
  2069. ost << "MidiOutWinMM::openPort: the 'portNumber' argument (" << portNumber << ") is invalid.";
  2070. errorString_ = ost.str();
  2071. error( RtMidiError::INVALID_PARAMETER, errorString_ );
  2072. return;
  2073. }
  2074. WinMidiData *data = static_cast<WinMidiData *> (apiData_);
  2075. MMRESULT result = midiOutOpen( &data->outHandle,
  2076. portNumber,
  2077. (DWORD)NULL,
  2078. (DWORD)NULL,
  2079. CALLBACK_NULL );
  2080. if ( result != MMSYSERR_NOERROR ) {
  2081. errorString_ = "MidiOutWinMM::openPort: error creating Windows MM MIDI output port.";
  2082. error( RtMidiError::DRIVER_ERROR, errorString_ );
  2083. return;
  2084. }
  2085. connected_ = true;
  2086. }
  2087. void MidiOutWinMM :: closePort( void )
  2088. {
  2089. if ( connected_ ) {
  2090. WinMidiData *data = static_cast<WinMidiData *> (apiData_);
  2091. midiOutReset( data->outHandle );
  2092. midiOutClose( data->outHandle );
  2093. data->outHandle = 0;
  2094. connected_ = false;
  2095. }
  2096. }
  2097. void MidiOutWinMM :: openVirtualPort( const std::string &/*portName*/ )
  2098. {
  2099. // This function cannot be implemented for the Windows MM MIDI API.
  2100. errorString_ = "MidiOutWinMM::openVirtualPort: cannot be implemented in Windows MM MIDI API!";
  2101. error( RtMidiError::WARNING, errorString_ );
  2102. }
  2103. void MidiOutWinMM :: sendMessage( const unsigned char *message, size_t size )
  2104. {
  2105. if ( !connected_ ) return;
  2106. unsigned int nBytes = static_cast<unsigned int>(size);
  2107. if ( nBytes == 0 ) {
  2108. errorString_ = "MidiOutWinMM::sendMessage: message argument is empty!";
  2109. error( RtMidiError::WARNING, errorString_ );
  2110. return;
  2111. }
  2112. MMRESULT result;
  2113. WinMidiData *data = static_cast<WinMidiData *> (apiData_);
  2114. if ( message[0] == 0xF0 ) { // Sysex message
  2115. // Allocate buffer for sysex data.
  2116. char *buffer = (char *) malloc( nBytes );
  2117. if ( buffer == NULL ) {
  2118. errorString_ = "MidiOutWinMM::sendMessage: error allocating sysex message memory!";
  2119. error( RtMidiError::MEMORY_ERROR, errorString_ );
  2120. return;
  2121. }
  2122. // Copy data to buffer.
  2123. for ( unsigned int i=0; i<nBytes; ++i ) buffer[i] = message[i];
  2124. // Create and prepare MIDIHDR structure.
  2125. MIDIHDR sysex;
  2126. sysex.lpData = (LPSTR) buffer;
  2127. sysex.dwBufferLength = nBytes;
  2128. sysex.dwFlags = 0;
  2129. result = midiOutPrepareHeader( data->outHandle, &sysex, sizeof(MIDIHDR) );
  2130. if ( result != MMSYSERR_NOERROR ) {
  2131. free( buffer );
  2132. errorString_ = "MidiOutWinMM::sendMessage: error preparing sysex header.";
  2133. error( RtMidiError::DRIVER_ERROR, errorString_ );
  2134. return;
  2135. }
  2136. // Send the message.
  2137. result = midiOutLongMsg( data->outHandle, &sysex, sizeof(MIDIHDR) );
  2138. if ( result != MMSYSERR_NOERROR ) {
  2139. free( buffer );
  2140. errorString_ = "MidiOutWinMM::sendMessage: error sending sysex message.";
  2141. error( RtMidiError::DRIVER_ERROR, errorString_ );
  2142. return;
  2143. }
  2144. // Unprepare the buffer and MIDIHDR.
  2145. while ( MIDIERR_STILLPLAYING == midiOutUnprepareHeader( data->outHandle, &sysex, sizeof (MIDIHDR) ) ) Sleep( 1 );
  2146. free( buffer );
  2147. }
  2148. else { // Channel or system message.
  2149. // Make sure the message size isn't too big.
  2150. if ( nBytes > 3 ) {
  2151. errorString_ = "MidiOutWinMM::sendMessage: message size is greater than 3 bytes (and not sysex)!";
  2152. error( RtMidiError::WARNING, errorString_ );
  2153. return;
  2154. }
  2155. // Pack MIDI bytes into double word.
  2156. DWORD packet;
  2157. unsigned char *ptr = (unsigned char *) &packet;
  2158. for ( unsigned int i=0; i<nBytes; ++i ) {
  2159. *ptr = message[i];
  2160. ++ptr;
  2161. }
  2162. // Send the message immediately.
  2163. result = midiOutShortMsg( data->outHandle, packet );
  2164. if ( result != MMSYSERR_NOERROR ) {
  2165. errorString_ = "MidiOutWinMM::sendMessage: error sending MIDI message.";
  2166. error( RtMidiError::DRIVER_ERROR, errorString_ );
  2167. }
  2168. }
  2169. }
  2170. #endif // __WINDOWS_MM__
  2171. //*********************************************************************//
  2172. // API: UNIX JACK
  2173. //
  2174. // Written primarily by Alexander Svetalkin, with updates for delta
  2175. // time by Gary Scavone, April 2011.
  2176. //
  2177. // *********************************************************************//
  2178. #if defined(__UNIX_JACK__)
  2179. // JACK header files
  2180. #include <jack/jack.h>
  2181. #include <jack/midiport.h>
  2182. #include <jack/ringbuffer.h>
  2183. #ifdef HAVE_SEMAPHORE
  2184. #include <semaphore.h>
  2185. #endif
  2186. #define JACK_RINGBUFFER_SIZE 16384 // Default size for ringbuffer
  2187. struct JackMidiData {
  2188. jack_client_t *client;
  2189. jack_port_t *port;
  2190. jack_ringbuffer_t *buffSize;
  2191. jack_ringbuffer_t *buffMessage;
  2192. jack_time_t lastTime;
  2193. #ifdef HAVE_SEMAPHORE
  2194. sem_t sem_cleanup;
  2195. sem_t sem_needpost;
  2196. #endif
  2197. MidiInApi :: RtMidiInData *rtMidiIn;
  2198. };
  2199. //*********************************************************************//
  2200. // API: JACK
  2201. // Class Definitions: MidiInJack
  2202. //*********************************************************************//
  2203. static int jackProcessIn( jack_nframes_t nframes, void *arg )
  2204. {
  2205. JackMidiData *jData = (JackMidiData *) arg;
  2206. MidiInApi :: RtMidiInData *rtData = jData->rtMidiIn;
  2207. jack_midi_event_t event;
  2208. jack_time_t time;
  2209. // Is port created?
  2210. if ( jData->port == NULL ) return 0;
  2211. void *buff = jack_port_get_buffer( jData->port, nframes );
  2212. // We have midi events in buffer
  2213. int evCount = jack_midi_get_event_count( buff );
  2214. for (int j = 0; j < evCount; j++) {
  2215. MidiInApi::MidiMessage message;
  2216. message.bytes.clear();
  2217. jack_midi_event_get( &event, buff, j );
  2218. for ( unsigned int i = 0; i < event.size; i++ )
  2219. message.bytes.push_back( event.buffer[i] );
  2220. // Compute the delta time.
  2221. time = jack_get_time();
  2222. if ( rtData->firstMessage == true )
  2223. rtData->firstMessage = false;
  2224. else
  2225. message.timeStamp = ( time - jData->lastTime ) * 0.000001;
  2226. jData->lastTime = time;
  2227. if ( !rtData->continueSysex ) {
  2228. if ( rtData->usingCallback ) {
  2229. RtMidiIn::RtMidiCallback callback = (RtMidiIn::RtMidiCallback) rtData->userCallback;
  2230. callback( message.timeStamp, &message.bytes, rtData->userData );
  2231. }
  2232. else {
  2233. // As long as we haven't reached our queue size limit, push the message.
  2234. if (!rtData->queue.push(message))
  2235. std::cerr << "\nMidiInJack: message queue limit reached!!\n\n";
  2236. }
  2237. }
  2238. }
  2239. return 0;
  2240. }
  2241. MidiInJack :: MidiInJack( const std::string &clientName, unsigned int queueSizeLimit ) : MidiInApi( queueSizeLimit )
  2242. {
  2243. initialize( clientName );
  2244. }
  2245. void MidiInJack :: initialize( const std::string& clientName )
  2246. {
  2247. JackMidiData *data = new JackMidiData;
  2248. apiData_ = (void *) data;
  2249. data->rtMidiIn = &inputData_;
  2250. data->port = NULL;
  2251. data->client = NULL;
  2252. this->clientName = clientName;
  2253. connect();
  2254. }
  2255. void MidiInJack :: connect()
  2256. {
  2257. JackMidiData *data = static_cast<JackMidiData *> (apiData_);
  2258. if ( data->client )
  2259. return;
  2260. // Initialize JACK client
  2261. if (( data->client = jack_client_open( clientName.c_str(), JackNoStartServer, NULL )) == 0) {
  2262. errorString_ = "MidiInJack::initialize: JACK server not running?";
  2263. error( RtMidiError::WARNING, errorString_ );
  2264. return;
  2265. }
  2266. jack_set_process_callback( data->client, jackProcessIn, data );
  2267. jack_activate( data->client );
  2268. }
  2269. MidiInJack :: ~MidiInJack()
  2270. {
  2271. JackMidiData *data = static_cast<JackMidiData *> (apiData_);
  2272. closePort();
  2273. if ( data->client )
  2274. jack_client_close( data->client );
  2275. delete data;
  2276. }
  2277. void MidiInJack :: openPort( unsigned int portNumber, const std::string &portName )
  2278. {
  2279. JackMidiData *data = static_cast<JackMidiData *> (apiData_);
  2280. connect();
  2281. // Creating new port
  2282. if ( data->port == NULL)
  2283. data->port = jack_port_register( data->client, portName.c_str(),
  2284. JACK_DEFAULT_MIDI_TYPE, JackPortIsInput, 0 );
  2285. if ( data->port == NULL) {
  2286. errorString_ = "MidiInJack::openPort: JACK error creating port";
  2287. error( RtMidiError::DRIVER_ERROR, errorString_ );
  2288. return;
  2289. }
  2290. // Connecting to the output
  2291. std::string name = getPortName( portNumber );
  2292. jack_connect( data->client, name.c_str(), jack_port_name( data->port ) );
  2293. }
  2294. void MidiInJack :: openVirtualPort( const std::string &portName )
  2295. {
  2296. JackMidiData *data = static_cast<JackMidiData *> (apiData_);
  2297. connect();
  2298. if ( data->port == NULL )
  2299. data->port = jack_port_register( data->client, portName.c_str(),
  2300. JACK_DEFAULT_MIDI_TYPE, JackPortIsInput, 0 );
  2301. if ( data->port == NULL ) {
  2302. errorString_ = "MidiInJack::openVirtualPort: JACK error creating virtual port";
  2303. error( RtMidiError::DRIVER_ERROR, errorString_ );
  2304. }
  2305. }
  2306. unsigned int MidiInJack :: getPortCount()
  2307. {
  2308. int count = 0;
  2309. JackMidiData *data = static_cast<JackMidiData *> (apiData_);
  2310. connect();
  2311. if ( !data->client )
  2312. return 0;
  2313. // List of available ports
  2314. const char **ports = jack_get_ports( data->client, NULL, JACK_DEFAULT_MIDI_TYPE, JackPortIsOutput );
  2315. if ( ports == NULL ) return 0;
  2316. while ( ports[count] != NULL )
  2317. count++;
  2318. free( ports );
  2319. return count;
  2320. }
  2321. std::string MidiInJack :: getPortName( unsigned int portNumber )
  2322. {
  2323. JackMidiData *data = static_cast<JackMidiData *> (apiData_);
  2324. std::string retStr("");
  2325. connect();
  2326. // List of available ports
  2327. const char **ports = jack_get_ports( data->client, NULL,
  2328. JACK_DEFAULT_MIDI_TYPE, JackPortIsOutput );
  2329. // Check port validity
  2330. if ( ports == NULL ) {
  2331. errorString_ = "MidiInJack::getPortName: no ports available!";
  2332. error( RtMidiError::WARNING, errorString_ );
  2333. return retStr;
  2334. }
  2335. if ( ports[portNumber] == NULL ) {
  2336. std::ostringstream ost;
  2337. ost << "MidiInJack::getPortName: the 'portNumber' argument (" << portNumber << ") is invalid.";
  2338. errorString_ = ost.str();
  2339. error( RtMidiError::WARNING, errorString_ );
  2340. }
  2341. else retStr.assign( ports[portNumber] );
  2342. free( ports );
  2343. return retStr;
  2344. }
  2345. void MidiInJack :: closePort()
  2346. {
  2347. JackMidiData *data = static_cast<JackMidiData *> (apiData_);
  2348. if ( data->port == NULL ) return;
  2349. jack_port_unregister( data->client, data->port );
  2350. data->port = NULL;
  2351. }
  2352. //*********************************************************************//
  2353. // API: JACK
  2354. // Class Definitions: MidiOutJack
  2355. //*********************************************************************//
  2356. // Jack process callback
  2357. static int jackProcessOut( jack_nframes_t nframes, void *arg )
  2358. {
  2359. JackMidiData *data = (JackMidiData *) arg;
  2360. jack_midi_data_t *midiData;
  2361. int space;
  2362. // Is port created?
  2363. if ( data->port == NULL ) return 0;
  2364. void *buff = jack_port_get_buffer( data->port, nframes );
  2365. jack_midi_clear_buffer( buff );
  2366. while ( jack_ringbuffer_read_space( data->buffSize ) > 0 ) {
  2367. jack_ringbuffer_read( data->buffSize, (char *) &space, (size_t) sizeof(space) );
  2368. midiData = jack_midi_event_reserve( buff, 0, space );
  2369. jack_ringbuffer_read( data->buffMessage, (char *) midiData, (size_t) space );
  2370. }
  2371. #ifdef HAVE_SEMAPHORE
  2372. if (!sem_trywait(&data->sem_needpost))
  2373. sem_post(&data->sem_cleanup);
  2374. #endif
  2375. return 0;
  2376. }
  2377. MidiOutJack :: MidiOutJack( const std::string &clientName ) : MidiOutApi()
  2378. {
  2379. initialize( clientName );
  2380. }
  2381. void MidiOutJack :: initialize( const std::string& clientName )
  2382. {
  2383. JackMidiData *data = new JackMidiData;
  2384. apiData_ = (void *) data;
  2385. data->port = NULL;
  2386. data->client = NULL;
  2387. #ifdef HAVE_SEMAPHORE
  2388. sem_init(&data->sem_cleanup, 0, 0);
  2389. sem_init(&data->sem_needpost, 0, 0);
  2390. #endif
  2391. this->clientName = clientName;
  2392. connect();
  2393. }
  2394. void MidiOutJack :: connect()
  2395. {
  2396. JackMidiData *data = static_cast<JackMidiData *> (apiData_);
  2397. if ( data->client )
  2398. return;
  2399. // Initialize output ringbuffers
  2400. data->buffSize = jack_ringbuffer_create( JACK_RINGBUFFER_SIZE );
  2401. data->buffMessage = jack_ringbuffer_create( JACK_RINGBUFFER_SIZE );
  2402. // Initialize JACK client
  2403. if (( data->client = jack_client_open( clientName.c_str(), JackNoStartServer, NULL )) == 0) {
  2404. errorString_ = "MidiOutJack::initialize: JACK server not running?";
  2405. error( RtMidiError::WARNING, errorString_ );
  2406. return;
  2407. }
  2408. jack_set_process_callback( data->client, jackProcessOut, data );
  2409. jack_activate( data->client );
  2410. }
  2411. MidiOutJack :: ~MidiOutJack()
  2412. {
  2413. JackMidiData *data = static_cast<JackMidiData *> (apiData_);
  2414. closePort();
  2415. // Cleanup
  2416. jack_ringbuffer_free( data->buffSize );
  2417. jack_ringbuffer_free( data->buffMessage );
  2418. if ( data->client ) {
  2419. jack_client_close( data->client );
  2420. }
  2421. #ifdef HAVE_SEMAPHORE
  2422. sem_destroy(&data->sem_cleanup);
  2423. sem_destroy(&data->sem_needpost);
  2424. #endif
  2425. delete data;
  2426. }
  2427. void MidiOutJack :: openPort( unsigned int portNumber, const std::string &portName )
  2428. {
  2429. JackMidiData *data = static_cast<JackMidiData *> (apiData_);
  2430. connect();
  2431. // Creating new port
  2432. if ( data->port == NULL )
  2433. data->port = jack_port_register( data->client, portName.c_str(),
  2434. JACK_DEFAULT_MIDI_TYPE, JackPortIsOutput, 0 );
  2435. if ( data->port == NULL ) {
  2436. errorString_ = "MidiOutJack::openPort: JACK error creating port";
  2437. error( RtMidiError::DRIVER_ERROR, errorString_ );
  2438. return;
  2439. }
  2440. // Connecting to the output
  2441. std::string name = getPortName( portNumber );
  2442. jack_connect( data->client, jack_port_name( data->port ), name.c_str() );
  2443. }
  2444. void MidiOutJack :: openVirtualPort( const std::string &portName )
  2445. {
  2446. JackMidiData *data = static_cast<JackMidiData *> (apiData_);
  2447. connect();
  2448. if ( data->port == NULL )
  2449. data->port = jack_port_register( data->client, portName.c_str(),
  2450. JACK_DEFAULT_MIDI_TYPE, JackPortIsOutput, 0 );
  2451. if ( data->port == NULL ) {
  2452. errorString_ = "MidiOutJack::openVirtualPort: JACK error creating virtual port";
  2453. error( RtMidiError::DRIVER_ERROR, errorString_ );
  2454. }
  2455. }
  2456. unsigned int MidiOutJack :: getPortCount()
  2457. {
  2458. int count = 0;
  2459. JackMidiData *data = static_cast<JackMidiData *> (apiData_);
  2460. connect();
  2461. if ( !data->client )
  2462. return 0;
  2463. // List of available ports
  2464. const char **ports = jack_get_ports( data->client, NULL,
  2465. JACK_DEFAULT_MIDI_TYPE, JackPortIsInput );
  2466. if ( ports == NULL ) return 0;
  2467. while ( ports[count] != NULL )
  2468. count++;
  2469. free( ports );
  2470. return count;
  2471. }
  2472. std::string MidiOutJack :: getPortName( unsigned int portNumber )
  2473. {
  2474. JackMidiData *data = static_cast<JackMidiData *> (apiData_);
  2475. std::string retStr("");
  2476. connect();
  2477. // List of available ports
  2478. const char **ports = jack_get_ports( data->client, NULL,
  2479. JACK_DEFAULT_MIDI_TYPE, JackPortIsInput );
  2480. // Check port validity
  2481. if ( ports == NULL) {
  2482. errorString_ = "MidiOutJack::getPortName: no ports available!";
  2483. error( RtMidiError::WARNING, errorString_ );
  2484. return retStr;
  2485. }
  2486. if ( ports[portNumber] == NULL) {
  2487. std::ostringstream ost;
  2488. ost << "MidiOutJack::getPortName: the 'portNumber' argument (" << portNumber << ") is invalid.";
  2489. errorString_ = ost.str();
  2490. error( RtMidiError::WARNING, errorString_ );
  2491. }
  2492. else retStr.assign( ports[portNumber] );
  2493. free( ports );
  2494. return retStr;
  2495. }
  2496. void MidiOutJack :: closePort()
  2497. {
  2498. JackMidiData *data = static_cast<JackMidiData *> (apiData_);
  2499. if ( data->port == NULL ) return;
  2500. #ifdef HAVE_SEMAPHORE
  2501. struct timespec ts;
  2502. if (clock_gettime(CLOCK_REALTIME, &ts) != -1)
  2503. {
  2504. ts.tv_sec += 1; // wait max one second
  2505. sem_post(&data->sem_needpost);
  2506. sem_timedwait(&data->sem_cleanup, &ts);
  2507. }
  2508. #endif
  2509. jack_port_unregister( data->client, data->port );
  2510. data->port = NULL;
  2511. }
  2512. void MidiOutJack :: sendMessage( const unsigned char *message, size_t size )
  2513. {
  2514. int nBytes = static_cast<int>(size);
  2515. JackMidiData *data = static_cast<JackMidiData *> (apiData_);
  2516. // Write full message to buffer
  2517. jack_ringbuffer_write( data->buffMessage, ( const char * ) message,
  2518. nBytes );
  2519. jack_ringbuffer_write( data->buffSize, ( char * ) &nBytes, sizeof( nBytes ) );
  2520. }
  2521. #endif // __UNIX_JACK__