/RtMidi.cpp

http://ewitool.googlecode.com/ · C++ · 3747 lines · 2794 code · 575 blank · 378 comment · 588 complexity · b595065c57d234c35379646fa077e891 MD5 · raw file

Large files are truncated click here to view the full file

  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-2012 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. // RtMidi: Version 2.0.1
  32. #include "RtMidi.h"
  33. #include <sstream>
  34. //*********************************************************************//
  35. // RtMidi Definitions
  36. //*********************************************************************//
  37. void RtMidi :: getCompiledApi( std::vector<RtMidi::Api> &apis ) throw()
  38. {
  39. apis.clear();
  40. // The order here will control the order of RtMidi's API search in
  41. // the constructor.
  42. #if defined(__MACOSX_CORE__)
  43. apis.push_back( MACOSX_CORE );
  44. #endif
  45. #if defined(__LINUX_ALSA__)
  46. apis.push_back( LINUX_ALSA );
  47. #endif
  48. #if defined(__UNIX_JACK__)
  49. apis.push_back( UNIX_JACK );
  50. #endif
  51. #if defined(__WINDOWS_MM__)
  52. apis.push_back( WINDOWS_MM );
  53. #endif
  54. #if defined(__WINDOWS_KS__)
  55. apis.push_back( WINDOWS_KS );
  56. #endif
  57. #if defined(__RTMIDI_DUMMY__)
  58. apis.push_back( RTMIDI_DUMMY );
  59. #endif
  60. }
  61. void RtMidi :: error( RtError::Type type, std::string errorString )
  62. {
  63. if (type == RtError::WARNING) {
  64. std::cerr << '\n' << errorString << "\n\n";
  65. }
  66. else if (type == RtError::DEBUG_WARNING) {
  67. #if defined(__RTMIDI_DEBUG__)
  68. std::cerr << '\n' << errorString << "\n\n";
  69. #endif
  70. }
  71. else {
  72. std::cerr << '\n' << errorString << "\n\n";
  73. throw RtError( errorString, type );
  74. }
  75. }
  76. //*********************************************************************//
  77. // RtMidiIn Definitions
  78. //*********************************************************************//
  79. void RtMidiIn :: openMidiApi( RtMidi::Api api, const std::string clientName, unsigned int queueSizeLimit )
  80. {
  81. if ( rtapi_ )
  82. delete rtapi_;
  83. rtapi_ = 0;
  84. #if defined(__UNIX_JACK__)
  85. if ( api == UNIX_JACK )
  86. rtapi_ = new MidiInJack( clientName, queueSizeLimit );
  87. #endif
  88. #if defined(__LINUX_ALSA__)
  89. if ( api == LINUX_ALSA )
  90. rtapi_ = new MidiInAlsa( clientName, queueSizeLimit );
  91. #endif
  92. #if defined(__WINDOWS_MM__)
  93. if ( api == WINDOWS_MM )
  94. rtapi_ = new MidiInWinMM( clientName, queueSizeLimit );
  95. #endif
  96. #if defined(__WINDOWS_KS__)
  97. if ( api == WINDOWS_KS )
  98. rtapi_ = new MidiInWinKS( clientName, queueSizeLimit );
  99. #endif
  100. #if defined(__MACOSX_CORE__)
  101. if ( api == MACOSX_CORE )
  102. rtapi_ = new MidiInCore( clientName, queueSizeLimit );
  103. #endif
  104. #if defined(__RTMIDI_DUMMY__)
  105. if ( api == RTMIDI_DUMMY )
  106. rtapi_ = new MidiInDummy( clientName, queueSizeLimit );
  107. #endif
  108. }
  109. RtMidiIn :: RtMidiIn( RtMidi::Api api, const std::string clientName, unsigned int queueSizeLimit )
  110. {
  111. rtapi_ = 0;
  112. if ( api != UNSPECIFIED ) {
  113. // Attempt to open the specified API.
  114. openMidiApi( api, clientName, queueSizeLimit );
  115. if ( rtapi_ ) return;
  116. // No compiled support for specified API value. Issue a debug
  117. // warning and continue as if no API was specified.
  118. RtMidi::error( RtError::WARNING, "RtMidiIn: no compiled support for specified API argument!" );
  119. }
  120. // Iterate through the compiled APIs and return as soon as we find
  121. // one with at least one port or we reach the end of the list.
  122. std::vector< RtMidi::Api > apis;
  123. getCompiledApi( apis );
  124. for ( unsigned int i=0; i<apis.size(); i++ ) {
  125. openMidiApi( apis[i], clientName, queueSizeLimit );
  126. if ( rtapi_->getPortCount() ) break;
  127. }
  128. if ( rtapi_ ) return;
  129. // It should not be possible to get here because the preprocessor
  130. // definition __RTMIDI_DUMMY__ is automatically defined if no
  131. // API-specific definitions are passed to the compiler. But just in
  132. // case something weird happens, we'll print out an error message.
  133. RtMidi::error( RtError::WARNING, "RtMidiIn: no compiled API support found ... critical error!!" );
  134. }
  135. RtMidiIn :: ~RtMidiIn() throw()
  136. {
  137. delete rtapi_;
  138. }
  139. //*********************************************************************//
  140. // RtMidiOut Definitions
  141. //*********************************************************************//
  142. void RtMidiOut :: openMidiApi( RtMidi::Api api, const std::string clientName )
  143. {
  144. if ( rtapi_ )
  145. delete rtapi_;
  146. rtapi_ = 0;
  147. #if defined(__UNIX_JACK__)
  148. if ( api == UNIX_JACK )
  149. rtapi_ = new MidiOutJack( clientName );
  150. #endif
  151. #if defined(__LINUX_ALSA__)
  152. if ( api == LINUX_ALSA )
  153. rtapi_ = new MidiOutAlsa( clientName );
  154. #endif
  155. #if defined(__WINDOWS_MM__)
  156. if ( api == WINDOWS_MM )
  157. rtapi_ = new MidiOutWinMM( clientName );
  158. #endif
  159. #if defined(__WINDOWS_KS__)
  160. if ( api == WINDOWS_KS )
  161. rtapi_ = new MidiOutWinKS( clientName );
  162. #endif
  163. #if defined(__MACOSX_CORE__)
  164. if ( api == MACOSX_CORE )
  165. rtapi_ = new MidiOutCore( clientName );
  166. #endif
  167. #if defined(__RTMIDI_DUMMY__)
  168. if ( api == RTMIDI_DUMMY )
  169. rtapi_ = new MidiOutDummy( clientName );
  170. #endif
  171. }
  172. RtMidiOut :: RtMidiOut( RtMidi::Api api, const std::string clientName )
  173. {
  174. rtapi_ = 0;
  175. if ( api != UNSPECIFIED ) {
  176. // Attempt to open the specified API.
  177. openMidiApi( api, clientName );
  178. if ( rtapi_ ) return;
  179. // No compiled support for specified API value. Issue a debug
  180. // warning and continue as if no API was specified.
  181. RtMidi::error( RtError::WARNING, "RtMidiOut: no compiled support for specified API argument!" );
  182. }
  183. // Iterate through the compiled APIs and return as soon as we find
  184. // one with at least one port or we reach the end of the list.
  185. std::vector< RtMidi::Api > apis;
  186. getCompiledApi( apis );
  187. for ( unsigned int i=0; i<apis.size(); i++ ) {
  188. openMidiApi( apis[i], clientName );
  189. if ( rtapi_->getPortCount() ) break;
  190. }
  191. if ( rtapi_ ) return;
  192. // It should not be possible to get here because the preprocessor
  193. // definition __RTMIDI_DUMMY__ is automatically defined if no
  194. // API-specific definitions are passed to the compiler. But just in
  195. // case something weird happens, we'll print out an error message.
  196. RtMidi::error( RtError::WARNING, "RtMidiOut: no compiled API support found ... critical error!!" );
  197. }
  198. RtMidiOut :: ~RtMidiOut() throw()
  199. {
  200. delete rtapi_;
  201. }
  202. //*********************************************************************//
  203. // Common MidiInApi Definitions
  204. //*********************************************************************//
  205. MidiInApi :: MidiInApi( unsigned int queueSizeLimit )
  206. : apiData_( 0 ), connected_( false )
  207. {
  208. // Allocate the MIDI queue.
  209. inputData_.queue.ringSize = queueSizeLimit;
  210. if ( inputData_.queue.ringSize > 0 )
  211. inputData_.queue.ring = new MidiMessage[ inputData_.queue.ringSize ];
  212. }
  213. MidiInApi :: ~MidiInApi( void )
  214. {
  215. // Delete the MIDI queue.
  216. if ( inputData_.queue.ringSize > 0 ) delete [] inputData_.queue.ring;
  217. }
  218. void MidiInApi :: setCallback( RtMidiIn::RtMidiCallback callback, void *userData )
  219. {
  220. if ( inputData_.usingCallback ) {
  221. errorString_ = "MidiInApi::setCallback: a callback function is already set!";
  222. RtMidi::error( RtError::WARNING, errorString_ );
  223. return;
  224. }
  225. if ( !callback ) {
  226. errorString_ = "RtMidiIn::setCallback: callback function value is invalid!";
  227. RtMidi::error( RtError::WARNING, errorString_ );
  228. return;
  229. }
  230. inputData_.userCallback = (void *) callback;
  231. inputData_.userData = userData;
  232. inputData_.usingCallback = true;
  233. }
  234. void MidiInApi :: cancelCallback()
  235. {
  236. if ( !inputData_.usingCallback ) {
  237. errorString_ = "RtMidiIn::cancelCallback: no callback function was set!";
  238. RtMidi::error( RtError::WARNING, errorString_ );
  239. return;
  240. }
  241. inputData_.userCallback = 0;
  242. inputData_.userData = 0;
  243. inputData_.usingCallback = false;
  244. }
  245. void MidiInApi :: ignoreTypes( bool midiSysex, bool midiTime, bool midiSense )
  246. {
  247. inputData_.ignoreFlags = 0;
  248. if ( midiSysex ) inputData_.ignoreFlags = 0x01;
  249. if ( midiTime ) inputData_.ignoreFlags |= 0x02;
  250. if ( midiSense ) inputData_.ignoreFlags |= 0x04;
  251. }
  252. double MidiInApi :: getMessage( std::vector<unsigned char> *message )
  253. {
  254. message->clear();
  255. if ( inputData_.usingCallback ) {
  256. errorString_ = "RtMidiIn::getNextMessage: a user callback is currently set for this port.";
  257. RtMidi::error( RtError::WARNING, errorString_ );
  258. return 0.0;
  259. }
  260. if ( inputData_.queue.size == 0 ) return 0.0;
  261. // Copy queued message to the vector pointer argument and then "pop" it.
  262. std::vector<unsigned char> *bytes = &(inputData_.queue.ring[inputData_.queue.front].bytes);
  263. message->assign( bytes->begin(), bytes->end() );
  264. double deltaTime = inputData_.queue.ring[inputData_.queue.front].timeStamp;
  265. inputData_.queue.size--;
  266. inputData_.queue.front++;
  267. if ( inputData_.queue.front == inputData_.queue.ringSize )
  268. inputData_.queue.front = 0;
  269. return deltaTime;
  270. }
  271. //*********************************************************************//
  272. // Common MidiOutApi Definitions
  273. //*********************************************************************//
  274. MidiOutApi :: MidiOutApi( void )
  275. : apiData_( 0 ), connected_( false )
  276. {
  277. }
  278. MidiOutApi :: ~MidiOutApi( void )
  279. {
  280. }
  281. // *************************************************** //
  282. //
  283. // OS/API-specific methods.
  284. //
  285. // *************************************************** //
  286. #if defined(__MACOSX_CORE__)
  287. // The CoreMIDI API is based on the use of a callback function for
  288. // MIDI input. We convert the system specific time stamps to delta
  289. // time values.
  290. // OS-X CoreMIDI header files.
  291. #include <CoreMIDI/CoreMIDI.h>
  292. #include <CoreAudio/HostTime.h>
  293. #include <CoreServices/CoreServices.h>
  294. // A structure to hold variables related to the CoreMIDI API
  295. // implementation.
  296. struct CoreMidiData {
  297. MIDIClientRef client;
  298. MIDIPortRef port;
  299. MIDIEndpointRef endpoint;
  300. MIDIEndpointRef destinationId;
  301. unsigned long long lastTime;
  302. MIDISysexSendRequest sysexreq;
  303. };
  304. //*********************************************************************//
  305. // API: OS-X
  306. // Class Definitions: MidiInCore
  307. //*********************************************************************//
  308. void midiInputCallback( const MIDIPacketList *list, void *procRef, void *srcRef )
  309. {
  310. MidiInApi::RtMidiInData *data = static_cast<MidiInApi::RtMidiInData *> (procRef);
  311. CoreMidiData *apiData = static_cast<CoreMidiData *> (data->apiData);
  312. unsigned char status;
  313. unsigned short nBytes, iByte, size;
  314. unsigned long long time;
  315. bool& continueSysex = data->continueSysex;
  316. MidiInApi::MidiMessage& message = data->message;
  317. const MIDIPacket *packet = &list->packet[0];
  318. for ( unsigned int i=0; i<list->numPackets; ++i ) {
  319. // My interpretation of the CoreMIDI documentation: all message
  320. // types, except sysex, are complete within a packet and there may
  321. // be several of them in a single packet. Sysex messages can be
  322. // broken across multiple packets and PacketLists but are bundled
  323. // alone within each packet (these packets do not contain other
  324. // message types). If sysex messages are split across multiple
  325. // MIDIPacketLists, they must be handled by multiple calls to this
  326. // function.
  327. nBytes = packet->length;
  328. if ( nBytes == 0 ) continue;
  329. // Calculate time stamp.
  330. if ( data->firstMessage ) {
  331. message.timeStamp = 0.0;
  332. data->firstMessage = false;
  333. }
  334. else {
  335. time = packet->timeStamp;
  336. if ( time == 0 ) { // this happens when receiving asynchronous sysex messages
  337. time = AudioGetCurrentHostTime();
  338. }
  339. time -= apiData->lastTime;
  340. time = AudioConvertHostTimeToNanos( time );
  341. if ( !continueSysex )
  342. message.timeStamp = time * 0.000000001;
  343. }
  344. apiData->lastTime = packet->timeStamp;
  345. if ( apiData->lastTime == 0 ) { // this happens when receiving asynchronous sysex messages
  346. apiData->lastTime = AudioGetCurrentHostTime();
  347. }
  348. //std::cout << "TimeStamp = " << packet->timeStamp << std::endl;
  349. iByte = 0;
  350. if ( continueSysex ) {
  351. // We have a continuing, segmented sysex message.
  352. if ( !( data->ignoreFlags & 0x01 ) ) {
  353. // If we're not ignoring sysex messages, copy the entire packet.
  354. for ( unsigned int j=0; j<nBytes; ++j )
  355. message.bytes.push_back( packet->data[j] );
  356. }
  357. continueSysex = packet->data[nBytes-1] != 0xF7;
  358. if ( !continueSysex ) {
  359. // If not a continuing sysex message, invoke the user callback function or queue the message.
  360. if ( data->usingCallback ) {
  361. RtMidiIn::RtMidiCallback callback = (RtMidiIn::RtMidiCallback) data->userCallback;
  362. callback( message.timeStamp, &message.bytes, data->userData );
  363. }
  364. else {
  365. // As long as we haven't reached our queue size limit, push the message.
  366. if ( data->queue.size < data->queue.ringSize ) {
  367. data->queue.ring[data->queue.back++] = message;
  368. if ( data->queue.back == data->queue.ringSize )
  369. data->queue.back = 0;
  370. data->queue.size++;
  371. }
  372. else
  373. std::cerr << "\nMidiInCore: message queue limit reached!!\n\n";
  374. }
  375. message.bytes.clear();
  376. }
  377. }
  378. else {
  379. while ( iByte < nBytes ) {
  380. size = 0;
  381. // We are expecting that the next byte in the packet is a status byte.
  382. status = packet->data[iByte];
  383. if ( !(status & 0x80) ) break;
  384. // Determine the number of bytes in the MIDI message.
  385. if ( status < 0xC0 ) size = 3;
  386. else if ( status < 0xE0 ) size = 2;
  387. else if ( status < 0xF0 ) size = 3;
  388. else if ( status == 0xF0 ) {
  389. // A MIDI sysex
  390. if ( data->ignoreFlags & 0x01 ) {
  391. size = 0;
  392. iByte = nBytes;
  393. }
  394. else size = nBytes - iByte;
  395. continueSysex = packet->data[nBytes-1] != 0xF7;
  396. }
  397. else if ( status == 0xF1 ) {
  398. // A MIDI time code message
  399. if ( data->ignoreFlags & 0x02 ) {
  400. size = 0;
  401. iByte += 2;
  402. }
  403. else size = 2;
  404. }
  405. else if ( status == 0xF2 ) size = 3;
  406. else if ( status == 0xF3 ) size = 2;
  407. else if ( status == 0xF8 && ( data->ignoreFlags & 0x02 ) ) {
  408. // A MIDI timing tick message and we're ignoring it.
  409. size = 0;
  410. iByte += 1;
  411. }
  412. else if ( status == 0xFE && ( data->ignoreFlags & 0x04 ) ) {
  413. // A MIDI active sensing message and we're ignoring it.
  414. size = 0;
  415. iByte += 1;
  416. }
  417. else size = 1;
  418. // Copy the MIDI data to our vector.
  419. if ( size ) {
  420. message.bytes.assign( &packet->data[iByte], &packet->data[iByte+size] );
  421. if ( !continueSysex ) {
  422. // If not a continuing sysex message, invoke the user callback function or queue the message.
  423. if ( data->usingCallback ) {
  424. RtMidiIn::RtMidiCallback callback = (RtMidiIn::RtMidiCallback) data->userCallback;
  425. callback( message.timeStamp, &message.bytes, data->userData );
  426. }
  427. else {
  428. // As long as we haven't reached our queue size limit, push the message.
  429. if ( data->queue.size < data->queue.ringSize ) {
  430. data->queue.ring[data->queue.back++] = message;
  431. if ( data->queue.back == data->queue.ringSize )
  432. data->queue.back = 0;
  433. data->queue.size++;
  434. }
  435. else
  436. std::cerr << "\nMidiInCore: message queue limit reached!!\n\n";
  437. }
  438. message.bytes.clear();
  439. }
  440. iByte += size;
  441. }
  442. }
  443. }
  444. packet = MIDIPacketNext(packet);
  445. }
  446. }
  447. MidiInCore :: MidiInCore( const std::string clientName, unsigned int queueSizeLimit ) : MidiInApi( queueSizeLimit )
  448. {
  449. initialize( clientName );
  450. }
  451. MidiInCore :: ~MidiInCore( void )
  452. {
  453. // Close a connection if it exists.
  454. closePort();
  455. // Cleanup.
  456. CoreMidiData *data = static_cast<CoreMidiData *> (apiData_);
  457. MIDIClientDispose( data->client );
  458. if ( data->endpoint ) MIDIEndpointDispose( data->endpoint );
  459. delete data;
  460. }
  461. void MidiInCore :: initialize( const std::string& clientName )
  462. {
  463. // Set up our client.
  464. MIDIClientRef client;
  465. OSStatus result = MIDIClientCreate( CFStringCreateWithCString( NULL, clientName.c_str(), kCFStringEncodingASCII ), NULL, NULL, &client );
  466. if ( result != noErr ) {
  467. errorString_ = "MidiInCore::initialize: error creating OS-X MIDI client object.";
  468. RtMidi::error( RtError::DRIVER_ERROR, errorString_ );
  469. }
  470. // Save our api-specific connection information.
  471. CoreMidiData *data = (CoreMidiData *) new CoreMidiData;
  472. data->client = client;
  473. data->endpoint = 0;
  474. apiData_ = (void *) data;
  475. inputData_.apiData = (void *) data;
  476. }
  477. void MidiInCore :: openPort( unsigned int portNumber, const std::string portName )
  478. {
  479. if ( connected_ ) {
  480. errorString_ = "MidiInCore::openPort: a valid connection already exists!";
  481. RtMidi::error( RtError::WARNING, errorString_ );
  482. return;
  483. }
  484. unsigned int nSrc = MIDIGetNumberOfSources();
  485. if (nSrc < 1) {
  486. errorString_ = "MidiInCore::openPort: no MIDI input sources found!";
  487. RtMidi::error( RtError::NO_DEVICES_FOUND, errorString_ );
  488. }
  489. std::ostringstream ost;
  490. if ( portNumber >= nSrc ) {
  491. ost << "MidiInCore::openPort: the 'portNumber' argument (" << portNumber << ") is invalid.";
  492. errorString_ = ost.str();
  493. RtMidi::error( RtError::INVALID_PARAMETER, errorString_ );
  494. }
  495. MIDIPortRef port;
  496. CoreMidiData *data = static_cast<CoreMidiData *> (apiData_);
  497. OSStatus result = MIDIInputPortCreate( data->client,
  498. CFStringCreateWithCString( NULL, portName.c_str(), kCFStringEncodingASCII ),
  499. midiInputCallback, (void *)&inputData_, &port );
  500. if ( result != noErr ) {
  501. MIDIClientDispose( data->client );
  502. errorString_ = "MidiInCore::openPort: error creating OS-X MIDI input port.";
  503. RtMidi::error( RtError::DRIVER_ERROR, errorString_ );
  504. }
  505. // Get the desired input source identifier.
  506. MIDIEndpointRef endpoint = MIDIGetSource( portNumber );
  507. if ( endpoint == 0 ) {
  508. MIDIPortDispose( port );
  509. MIDIClientDispose( data->client );
  510. errorString_ = "MidiInCore::openPort: error getting MIDI input source reference.";
  511. RtMidi::error( RtError::DRIVER_ERROR, errorString_ );
  512. }
  513. // Make the connection.
  514. result = MIDIPortConnectSource( port, endpoint, NULL );
  515. if ( result != noErr ) {
  516. MIDIPortDispose( port );
  517. MIDIClientDispose( data->client );
  518. errorString_ = "MidiInCore::openPort: error connecting OS-X MIDI input port.";
  519. RtMidi::error( RtError::DRIVER_ERROR, errorString_ );
  520. }
  521. // Save our api-specific port information.
  522. data->port = port;
  523. connected_ = true;
  524. }
  525. void MidiInCore :: openVirtualPort( const std::string portName )
  526. {
  527. CoreMidiData *data = static_cast<CoreMidiData *> (apiData_);
  528. // Create a virtual MIDI input destination.
  529. MIDIEndpointRef endpoint;
  530. OSStatus result = MIDIDestinationCreate( data->client,
  531. CFStringCreateWithCString( NULL, portName.c_str(), kCFStringEncodingASCII ),
  532. midiInputCallback, (void *)&inputData_, &endpoint );
  533. if ( result != noErr ) {
  534. errorString_ = "MidiInCore::openVirtualPort: error creating virtual OS-X MIDI destination.";
  535. RtMidi::error( RtError::DRIVER_ERROR, errorString_ );
  536. }
  537. // Save our api-specific connection information.
  538. data->endpoint = endpoint;
  539. }
  540. void MidiInCore :: closePort( void )
  541. {
  542. if ( connected_ ) {
  543. CoreMidiData *data = static_cast<CoreMidiData *> (apiData_);
  544. MIDIPortDispose( data->port );
  545. connected_ = false;
  546. }
  547. }
  548. unsigned int MidiInCore :: getPortCount()
  549. {
  550. return MIDIGetNumberOfSources();
  551. }
  552. // This function was submitted by Douglas Casey Tucker and apparently
  553. // derived largely from PortMidi.
  554. CFStringRef EndpointName( MIDIEndpointRef endpoint, bool isExternal )
  555. {
  556. CFMutableStringRef result = CFStringCreateMutable( NULL, 0 );
  557. CFStringRef str;
  558. // Begin with the endpoint's name.
  559. str = NULL;
  560. MIDIObjectGetStringProperty( endpoint, kMIDIPropertyName, &str );
  561. if ( str != NULL ) {
  562. CFStringAppend( result, str );
  563. CFRelease( str );
  564. }
  565. MIDIEntityRef entity = NULL;
  566. MIDIEndpointGetEntity( endpoint, &entity );
  567. if ( entity == 0 )
  568. // probably virtual
  569. return result;
  570. if ( CFStringGetLength( result ) == 0 ) {
  571. // endpoint name has zero length -- try the entity
  572. str = NULL;
  573. MIDIObjectGetStringProperty( entity, kMIDIPropertyName, &str );
  574. if ( str != NULL ) {
  575. CFStringAppend( result, str );
  576. CFRelease( str );
  577. }
  578. }
  579. // now consider the device's name
  580. MIDIDeviceRef device = 0;
  581. MIDIEntityGetDevice( entity, &device );
  582. if ( device == 0 )
  583. return result;
  584. str = NULL;
  585. MIDIObjectGetStringProperty( device, kMIDIPropertyName, &str );
  586. if ( CFStringGetLength( result ) == 0 ) {
  587. CFRelease( result );
  588. return str;
  589. }
  590. if ( str != NULL ) {
  591. // if an external device has only one entity, throw away
  592. // the endpoint name and just use the device name
  593. if ( isExternal && MIDIDeviceGetNumberOfEntities( device ) < 2 ) {
  594. CFRelease( result );
  595. return str;
  596. } else {
  597. if ( CFStringGetLength( str ) == 0 ) {
  598. CFRelease( str );
  599. return result;
  600. }
  601. // does the entity name already start with the device name?
  602. // (some drivers do this though they shouldn't)
  603. // if so, do not prepend
  604. if ( CFStringCompareWithOptions( result, /* endpoint name */
  605. str /* device name */,
  606. CFRangeMake(0, CFStringGetLength( str ) ), 0 ) != kCFCompareEqualTo ) {
  607. // prepend the device name to the entity name
  608. if ( CFStringGetLength( result ) > 0 )
  609. CFStringInsert( result, 0, CFSTR(" ") );
  610. CFStringInsert( result, 0, str );
  611. }
  612. CFRelease( str );
  613. }
  614. }
  615. return result;
  616. }
  617. // This function was submitted by Douglas Casey Tucker and apparently
  618. // derived largely from PortMidi.
  619. static CFStringRef ConnectedEndpointName( MIDIEndpointRef endpoint )
  620. {
  621. CFMutableStringRef result = CFStringCreateMutable( NULL, 0 );
  622. CFStringRef str;
  623. OSStatus err;
  624. int i;
  625. // Does the endpoint have connections?
  626. CFDataRef connections = NULL;
  627. int nConnected = 0;
  628. bool anyStrings = false;
  629. err = MIDIObjectGetDataProperty( endpoint, kMIDIPropertyConnectionUniqueID, &connections );
  630. if ( connections != NULL ) {
  631. // It has connections, follow them
  632. // Concatenate the names of all connected devices
  633. nConnected = CFDataGetLength( connections ) / sizeof(MIDIUniqueID);
  634. if ( nConnected ) {
  635. const SInt32 *pid = (const SInt32 *)(CFDataGetBytePtr(connections));
  636. for ( i=0; i<nConnected; ++i, ++pid ) {
  637. MIDIUniqueID id = EndianS32_BtoN( *pid );
  638. MIDIObjectRef connObject;
  639. MIDIObjectType connObjectType;
  640. err = MIDIObjectFindByUniqueID( id, &connObject, &connObjectType );
  641. if ( err == noErr ) {
  642. if ( connObjectType == kMIDIObjectType_ExternalSource ||
  643. connObjectType == kMIDIObjectType_ExternalDestination ) {
  644. // Connected to an external device's endpoint (10.3 and later).
  645. str = EndpointName( (MIDIEndpointRef)(connObject), true );
  646. } else {
  647. // Connected to an external device (10.2) (or something else, catch-
  648. str = NULL;
  649. MIDIObjectGetStringProperty( connObject, kMIDIPropertyName, &str );
  650. }
  651. if ( str != NULL ) {
  652. if ( anyStrings )
  653. CFStringAppend( result, CFSTR(", ") );
  654. else anyStrings = true;
  655. CFStringAppend( result, str );
  656. CFRelease( str );
  657. }
  658. }
  659. }
  660. }
  661. CFRelease( connections );
  662. }
  663. if ( anyStrings )
  664. return result;
  665. // Here, either the endpoint had no connections, or we failed to obtain names
  666. return EndpointName( endpoint, false );
  667. }
  668. std::string MidiInCore :: getPortName( unsigned int portNumber )
  669. {
  670. CFStringRef nameRef;
  671. MIDIEndpointRef portRef;
  672. std::ostringstream ost;
  673. char name[128];
  674. std::string stringName;
  675. if ( portNumber >= MIDIGetNumberOfSources() ) {
  676. ost << "MidiInCore::getPortName: the 'portNumber' argument (" << portNumber << ") is invalid.";
  677. errorString_ = ost.str();
  678. RtMidi::error( RtError::WARNING, errorString_ );
  679. //RtMidi::error( RtError::INVALID_PARAMETER, errorString_ );
  680. return stringName;
  681. }
  682. portRef = MIDIGetSource( portNumber );
  683. nameRef = ConnectedEndpointName(portRef);
  684. CFStringGetCString( nameRef, name, sizeof(name), 0);
  685. CFRelease( nameRef );
  686. return stringName = name;
  687. }
  688. //*********************************************************************//
  689. // API: OS-X
  690. // Class Definitions: MidiOutCore
  691. //*********************************************************************//
  692. MidiOutCore :: MidiOutCore( const std::string clientName ) : MidiOutApi()
  693. {
  694. initialize( clientName );
  695. }
  696. MidiOutCore :: ~MidiOutCore( void )
  697. {
  698. // Close a connection if it exists.
  699. closePort();
  700. // Cleanup.
  701. CoreMidiData *data = static_cast<CoreMidiData *> (apiData_);
  702. MIDIClientDispose( data->client );
  703. if ( data->endpoint ) MIDIEndpointDispose( data->endpoint );
  704. delete data;
  705. }
  706. void MidiOutCore :: initialize( const std::string& clientName )
  707. {
  708. // Set up our client.
  709. MIDIClientRef client;
  710. OSStatus result = MIDIClientCreate( CFStringCreateWithCString( NULL, clientName.c_str(), kCFStringEncodingASCII ), NULL, NULL, &client );
  711. if ( result != noErr ) {
  712. errorString_ = "MidiOutCore::initialize: error creating OS-X MIDI client object.";
  713. RtMidi::error( RtError::DRIVER_ERROR, errorString_ );
  714. }
  715. // Save our api-specific connection information.
  716. CoreMidiData *data = (CoreMidiData *) new CoreMidiData;
  717. data->client = client;
  718. data->endpoint = 0;
  719. apiData_ = (void *) data;
  720. }
  721. unsigned int MidiOutCore :: getPortCount()
  722. {
  723. return MIDIGetNumberOfDestinations();
  724. }
  725. std::string MidiOutCore :: getPortName( unsigned int portNumber )
  726. {
  727. CFStringRef nameRef;
  728. MIDIEndpointRef portRef;
  729. std::ostringstream ost;
  730. char name[128];
  731. std::string stringName;
  732. if ( portNumber >= MIDIGetNumberOfDestinations() ) {
  733. ost << "MidiOutCore::getPortName: the 'portNumber' argument (" << portNumber << ") is invalid.";
  734. errorString_ = ost.str();
  735. RtMidi::error( RtError::WARNING, errorString_ );
  736. return stringName;
  737. //RtMidi::error( RtError::INVALID_PARAMETER, errorString_ );
  738. }
  739. portRef = MIDIGetDestination( portNumber );
  740. nameRef = ConnectedEndpointName(portRef);
  741. CFStringGetCString( nameRef, name, sizeof(name), 0);
  742. CFRelease( nameRef );
  743. return stringName = name;
  744. }
  745. void MidiOutCore :: openPort( unsigned int portNumber, const std::string portName )
  746. {
  747. if ( connected_ ) {
  748. errorString_ = "MidiOutCore::openPort: a valid connection already exists!";
  749. RtMidi::error( RtError::WARNING, errorString_ );
  750. return;
  751. }
  752. unsigned int nDest = MIDIGetNumberOfDestinations();
  753. if (nDest < 1) {
  754. errorString_ = "MidiOutCore::openPort: no MIDI output destinations found!";
  755. RtMidi::error( RtError::NO_DEVICES_FOUND, errorString_ );
  756. }
  757. std::ostringstream ost;
  758. if ( portNumber >= nDest ) {
  759. ost << "MidiOutCore::openPort: the 'portNumber' argument (" << portNumber << ") is invalid.";
  760. errorString_ = ost.str();
  761. RtMidi::error( RtError::INVALID_PARAMETER, errorString_ );
  762. }
  763. MIDIPortRef port;
  764. CoreMidiData *data = static_cast<CoreMidiData *> (apiData_);
  765. OSStatus result = MIDIOutputPortCreate( data->client,
  766. CFStringCreateWithCString( NULL, portName.c_str(), kCFStringEncodingASCII ),
  767. &port );
  768. if ( result != noErr ) {
  769. MIDIClientDispose( data->client );
  770. errorString_ = "MidiOutCore::openPort: error creating OS-X MIDI output port.";
  771. RtMidi::error( RtError::DRIVER_ERROR, errorString_ );
  772. }
  773. // Get the desired output port identifier.
  774. MIDIEndpointRef destination = MIDIGetDestination( portNumber );
  775. if ( destination == 0 ) {
  776. MIDIPortDispose( port );
  777. MIDIClientDispose( data->client );
  778. errorString_ = "MidiOutCore::openPort: error getting MIDI output destination reference.";
  779. RtMidi::error( RtError::DRIVER_ERROR, errorString_ );
  780. }
  781. // Save our api-specific connection information.
  782. data->port = port;
  783. data->destinationId = destination;
  784. connected_ = true;
  785. }
  786. void MidiOutCore :: closePort( void )
  787. {
  788. if ( connected_ ) {
  789. CoreMidiData *data = static_cast<CoreMidiData *> (apiData_);
  790. MIDIPortDispose( data->port );
  791. connected_ = false;
  792. }
  793. }
  794. void MidiOutCore :: openVirtualPort( std::string portName )
  795. {
  796. CoreMidiData *data = static_cast<CoreMidiData *> (apiData_);
  797. if ( data->endpoint ) {
  798. errorString_ = "MidiOutCore::openVirtualPort: a virtual output port already exists!";
  799. RtMidi::error( RtError::WARNING, errorString_ );
  800. return;
  801. }
  802. // Create a virtual MIDI output source.
  803. MIDIEndpointRef endpoint;
  804. OSStatus result = MIDISourceCreate( data->client,
  805. CFStringCreateWithCString( NULL, portName.c_str(), kCFStringEncodingASCII ),
  806. &endpoint );
  807. if ( result != noErr ) {
  808. errorString_ = "MidiOutCore::initialize: error creating OS-X virtual MIDI source.";
  809. RtMidi::error( RtError::DRIVER_ERROR, errorString_ );
  810. }
  811. // Save our api-specific connection information.
  812. data->endpoint = endpoint;
  813. }
  814. char *sysexBuffer = 0;
  815. void sysexCompletionProc( MIDISysexSendRequest * sreq )
  816. {
  817. //std::cout << "Completed SysEx send\n";
  818. delete sysexBuffer;
  819. sysexBuffer = 0;
  820. }
  821. void MidiOutCore :: sendMessage( std::vector<unsigned char> *message )
  822. {
  823. // We use the MIDISendSysex() function to asynchronously send sysex
  824. // messages. Otherwise, we use a single CoreMidi MIDIPacket.
  825. unsigned int nBytes = message->size();
  826. if ( nBytes == 0 ) {
  827. errorString_ = "MidiOutCore::sendMessage: no data in message argument!";
  828. RtMidi::error( RtError::WARNING, errorString_ );
  829. return;
  830. }
  831. // unsigned int packetBytes, bytesLeft = nBytes;
  832. // unsigned int messageIndex = 0;
  833. MIDITimeStamp timeStamp = AudioGetCurrentHostTime();
  834. CoreMidiData *data = static_cast<CoreMidiData *> (apiData_);
  835. OSStatus result;
  836. if ( message->at(0) == 0xF0 ) {
  837. while ( sysexBuffer != 0 ) usleep( 1000 ); // sleep 1 ms
  838. sysexBuffer = new char[nBytes];
  839. if ( sysexBuffer == NULL ) {
  840. errorString_ = "MidiOutCore::sendMessage: error allocating sysex message memory!";
  841. RtMidi::error( RtError::MEMORY_ERROR, errorString_ );
  842. }
  843. // Copy data to buffer.
  844. for ( unsigned int i=0; i<nBytes; ++i ) sysexBuffer[i] = message->at(i);
  845. data->sysexreq.destination = data->destinationId;
  846. data->sysexreq.data = (Byte *)sysexBuffer;
  847. data->sysexreq.bytesToSend = nBytes;
  848. data->sysexreq.complete = 0;
  849. data->sysexreq.completionProc = sysexCompletionProc;
  850. data->sysexreq.completionRefCon = &(data->sysexreq);
  851. result = MIDISendSysex( &(data->sysexreq) );
  852. if ( result != noErr ) {
  853. errorString_ = "MidiOutCore::sendMessage: error sending MIDI to virtual destinations.";
  854. RtMidi::error( RtError::WARNING, errorString_ );
  855. }
  856. return;
  857. }
  858. else if ( nBytes > 3 ) {
  859. errorString_ = "MidiOutCore::sendMessage: message format problem ... not sysex but > 3 bytes?";
  860. RtMidi::error( RtError::WARNING, errorString_ );
  861. return;
  862. }
  863. MIDIPacketList packetList;
  864. MIDIPacket *packet = MIDIPacketListInit( &packetList );
  865. packet = MIDIPacketListAdd( &packetList, sizeof(packetList), packet, timeStamp, nBytes, (const Byte *) &message->at( 0 ) );
  866. if ( !packet ) {
  867. errorString_ = "MidiOutCore::sendMessage: could not allocate packet list";
  868. RtMidi::error( RtError::DRIVER_ERROR, errorString_ );
  869. }
  870. // Send to any destinations that may have connected to us.
  871. if ( data->endpoint ) {
  872. result = MIDIReceived( data->endpoint, &packetList );
  873. if ( result != noErr ) {
  874. errorString_ = "MidiOutCore::sendMessage: error sending MIDI to virtual destinations.";
  875. RtMidi::error( RtError::WARNING, errorString_ );
  876. }
  877. }
  878. // And send to an explicit destination port if we're connected.
  879. if ( connected_ ) {
  880. result = MIDISend( data->port, data->destinationId, &packetList );
  881. if ( result != noErr ) {
  882. errorString_ = "MidiOutCore::sendMessage: error sending MIDI message to port.";
  883. RtMidi::error( RtError::WARNING, errorString_ );
  884. }
  885. }
  886. }
  887. #endif // __MACOSX_CORE__
  888. //*********************************************************************//
  889. // API: LINUX ALSA SEQUENCER
  890. //*********************************************************************//
  891. // API information found at:
  892. // - http://www.alsa-project.org/documentation.php#Library
  893. #if defined(__LINUX_ALSA__)
  894. // The ALSA Sequencer API is based on the use of a callback function for
  895. // MIDI input.
  896. //
  897. // Thanks to Pedro Lopez-Cabanillas for help with the ALSA sequencer
  898. // time stamps and other assorted fixes!!!
  899. // If you don't need timestamping for incoming MIDI events, define the
  900. // preprocessor definition AVOID_TIMESTAMPING to save resources
  901. // associated with the ALSA sequencer queues.
  902. #include <pthread.h>
  903. #include <sys/time.h>
  904. // ALSA header file.
  905. #include <alsa/asoundlib.h>
  906. // Global sequencer instance created when first In/Out object is
  907. // created, then destroyed when last In/Out is deleted.
  908. static snd_seq_t *s_seq = NULL;
  909. // Variable to keep track of how many ports are open.
  910. static unsigned int s_numPorts = 0;
  911. // The client name to use when creating the sequencer, which is
  912. // currently set on the first call to createSequencer.
  913. static std::string s_clientName = "RtMidi Client";
  914. // A structure to hold variables related to the ALSA API
  915. // implementation.
  916. struct AlsaMidiData {
  917. snd_seq_t *seq;
  918. unsigned int portNum;
  919. int vport;
  920. snd_seq_port_subscribe_t *subscription;
  921. snd_midi_event_t *coder;
  922. unsigned int bufferSize;
  923. unsigned char *buffer;
  924. pthread_t thread;
  925. pthread_t dummy_thread_id;
  926. unsigned long long lastTime;
  927. int queue_id; // an input queue is needed to get timestamped events
  928. int trigger_fds[2];
  929. };
  930. #define PORT_TYPE( pinfo, bits ) ((snd_seq_port_info_get_capability(pinfo) & (bits)) == (bits))
  931. snd_seq_t* createSequencer( const std::string& clientName )
  932. {
  933. // Set up the ALSA sequencer client.
  934. if ( s_seq == NULL ) {
  935. int result = snd_seq_open(&s_seq, "default", SND_SEQ_OPEN_DUPLEX, SND_SEQ_NONBLOCK);
  936. if ( result < 0 ) {
  937. s_seq = NULL;
  938. }
  939. else {
  940. // Set client name, use current name if given string is empty.
  941. if ( clientName != "" ) {
  942. s_clientName = clientName;
  943. }
  944. snd_seq_set_client_name( s_seq, s_clientName.c_str() );
  945. }
  946. }
  947. // Increment port count.
  948. s_numPorts++;
  949. return s_seq;
  950. }
  951. void freeSequencer ( void )
  952. {
  953. s_numPorts--;
  954. if ( s_numPorts == 0 && s_seq != NULL ) {
  955. snd_seq_close( s_seq );
  956. s_seq = NULL;
  957. }
  958. }
  959. //*********************************************************************//
  960. // API: LINUX ALSA
  961. // Class Definitions: MidiInAlsa
  962. //*********************************************************************//
  963. extern "C" void *alsaMidiHandler( void *ptr )
  964. {
  965. MidiInApi::RtMidiInData *data = static_cast<MidiInApi::RtMidiInData *> (ptr);
  966. AlsaMidiData *apiData = static_cast<AlsaMidiData *> (data->apiData);
  967. long nBytes;
  968. unsigned long long time, lastTime;
  969. bool continueSysex = false;
  970. bool doDecode = false;
  971. MidiInApi::MidiMessage message;
  972. int poll_fd_count;
  973. struct pollfd *poll_fds;
  974. snd_seq_event_t *ev;
  975. int result;
  976. apiData->bufferSize = 32;
  977. result = snd_midi_event_new( 0, &apiData->coder );
  978. if ( result < 0 ) {
  979. data->doInput = false;
  980. std::cerr << "\nMidiInAlsa::alsaMidiHandler: error initializing MIDI event parser!\n\n";
  981. return 0;
  982. }
  983. unsigned char *buffer = (unsigned char *) malloc( apiData->bufferSize );
  984. if ( buffer == NULL ) {
  985. data->doInput = false;
  986. snd_midi_event_free( apiData->coder );
  987. apiData->coder = 0;
  988. std::cerr << "\nMidiInAlsa::alsaMidiHandler: error initializing buffer memory!\n\n";
  989. return 0;
  990. }
  991. snd_midi_event_init( apiData->coder );
  992. snd_midi_event_no_status( apiData->coder, 1 ); // suppress running status messages
  993. poll_fd_count = snd_seq_poll_descriptors_count( apiData->seq, POLLIN ) + 1;
  994. poll_fds = (struct pollfd*)alloca( poll_fd_count * sizeof( struct pollfd ));
  995. snd_seq_poll_descriptors( apiData->seq, poll_fds + 1, poll_fd_count - 1, POLLIN );
  996. poll_fds[0].fd = apiData->trigger_fds[0];
  997. poll_fds[0].events = POLLIN;
  998. while ( data->doInput ) {
  999. if ( snd_seq_event_input_pending( apiData->seq, 1 ) == 0 ) {
  1000. // No data pending
  1001. if ( poll( poll_fds, poll_fd_count, -1) >= 0 ) {
  1002. if ( poll_fds[0].revents & POLLIN ) {
  1003. bool dummy;
  1004. int res = read( poll_fds[0].fd, &dummy, sizeof(dummy) );
  1005. (void) res;
  1006. }
  1007. }
  1008. continue;
  1009. }
  1010. // If here, there should be data.
  1011. result = snd_seq_event_input( apiData->seq, &ev );
  1012. if ( result == -ENOSPC ) {
  1013. std::cerr << "\nMidiInAlsa::alsaMidiHandler: MIDI input buffer overrun!\n\n";
  1014. continue;
  1015. }
  1016. else if ( result <= 0 ) {
  1017. std::cerr << "MidiInAlsa::alsaMidiHandler: unknown MIDI input error!\n";
  1018. continue;
  1019. }
  1020. // This is a bit weird, but we now have to decode an ALSA MIDI
  1021. // event (back) into MIDI bytes. We'll ignore non-MIDI types.
  1022. if ( !continueSysex ) message.bytes.clear();
  1023. doDecode = false;
  1024. switch ( ev->type ) {
  1025. case SND_SEQ_EVENT_PORT_SUBSCRIBED:
  1026. #if defined(__RTMIDI_DEBUG__)
  1027. std::cout << "MidiInAlsa::alsaMidiHandler: port connection made!\n";
  1028. #endif
  1029. break;
  1030. case SND_SEQ_EVENT_PORT_UNSUBSCRIBED:
  1031. #if defined(__RTMIDI_DEBUG__)
  1032. std::cerr << "MidiInAlsa::alsaMidiHandler: port connection has closed!\n";
  1033. std::cout << "sender = " << (int) ev->data.connect.sender.client << ":"
  1034. << (int) ev->data.connect.sender.port
  1035. << ", dest = " << (int) ev->data.connect.dest.client << ":"
  1036. << (int) ev->data.connect.dest.port
  1037. << std::endl;
  1038. #endif
  1039. break;
  1040. case SND_SEQ_EVENT_QFRAME: // MIDI time code
  1041. if ( !( data->ignoreFlags & 0x02 ) ) doDecode = true;
  1042. break;
  1043. case SND_SEQ_EVENT_TICK: // MIDI timing tick
  1044. if ( !( data->ignoreFlags & 0x02 ) ) doDecode = true;
  1045. break;
  1046. case SND_SEQ_EVENT_SENSING: // Active sensing
  1047. if ( !( data->ignoreFlags & 0x04 ) ) doDecode = true;
  1048. break;
  1049. case SND_SEQ_EVENT_SYSEX:
  1050. if ( (data->ignoreFlags & 0x01) ) break;
  1051. if ( ev->data.ext.len > apiData->bufferSize ) {
  1052. apiData->bufferSize = ev->data.ext.len;
  1053. free( buffer );
  1054. buffer = (unsigned char *) malloc( apiData->bufferSize );
  1055. if ( buffer == NULL ) {
  1056. data->doInput = false;
  1057. std::cerr << "\nMidiInAlsa::alsaMidiHandler: error resizing buffer memory!\n\n";
  1058. break;
  1059. }
  1060. }
  1061. default:
  1062. doDecode = true;
  1063. }
  1064. if ( doDecode ) {
  1065. nBytes = snd_midi_event_decode( apiData->coder, buffer, apiData->bufferSize, ev );
  1066. if ( nBytes > 0 ) {
  1067. // The ALSA sequencer has a maximum buffer size for MIDI sysex
  1068. // events of 256 bytes. If a device sends sysex messages larger
  1069. // than this, they are segmented into 256 byte chunks. So,
  1070. // we'll watch for this and concatenate sysex chunks into a
  1071. // single sysex message if necessary.
  1072. if ( !continueSysex )
  1073. message.bytes.assign( buffer, &buffer[nBytes] );
  1074. else
  1075. message.bytes.insert( message.bytes.end(), buffer, &buffer[nBytes] );
  1076. continueSysex = ( ( ev->type == SND_SEQ_EVENT_SYSEX ) && ( message.bytes.back() != 0xF7 ) );
  1077. if ( !continueSysex ) {
  1078. // Calculate the time stamp:
  1079. message.timeStamp = 0.0;
  1080. // Method 1: Use the system time.
  1081. //(void)gettimeofday(&tv, (struct timezone *)NULL);
  1082. //time = (tv.tv_sec * 1000000) + tv.tv_usec;
  1083. // Method 2: Use the ALSA sequencer event time data.
  1084. // (thanks to Pedro Lopez-Cabanillas!).
  1085. time = ( ev->time.time.tv_sec * 1000000 ) + ( ev->time.time.tv_nsec/1000 );
  1086. lastTime = time;
  1087. time -= apiData->lastTime;
  1088. apiData->lastTime = lastTime;
  1089. if ( data->firstMessage == true )
  1090. data->firstMessage = false;
  1091. else
  1092. message.timeStamp = time * 0.000001;
  1093. }
  1094. else {
  1095. #if defined(__RTMIDI_DEBUG__)
  1096. std::cerr << "\nMidiInAlsa::alsaMidiHandler: event parsing error or not a MIDI event!\n\n";
  1097. #endif
  1098. }
  1099. }
  1100. }
  1101. snd_seq_free_event( ev );
  1102. if ( message.bytes.size() == 0 || continueSysex ) continue;
  1103. if ( data->usingCallback ) {
  1104. RtMidiIn::RtMidiCallback callback = (RtMidiIn::RtMidiCallback) data->userCallback;
  1105. callback( message.timeStamp, &message.bytes, data->userData );
  1106. }
  1107. else {
  1108. // As long as we haven't reached our queue size limit, push the message.
  1109. if ( data->queue.size < data->queue.ringSize ) {
  1110. data->queue.ring[data->queue.back++] = message;
  1111. if ( data->queue.back == data->queue.ringSize )
  1112. data->queue.back = 0;
  1113. data->queue.size++;
  1114. }
  1115. else
  1116. std::cerr << "\nMidiInAlsa: message queue limit reached!!\n\n";
  1117. }
  1118. }
  1119. if ( buffer ) free( buffer );
  1120. snd_midi_event_free( apiData->coder );
  1121. apiData->coder = 0;
  1122. apiData->thread = apiData->dummy_thread_id;
  1123. return 0;
  1124. }
  1125. MidiInAlsa :: MidiInAlsa( const std::string clientName, unsigned int queueSizeLimit ) : MidiInApi( queueSizeLimit )
  1126. {
  1127. initialize( clientName );
  1128. }
  1129. MidiInAlsa :: ~MidiInAlsa()
  1130. {
  1131. // Close a connection if it exists.
  1132. closePort();
  1133. // Shutdown the input thread.
  1134. AlsaMidiData *data = static_cast<AlsaMidiData *> (apiData_);
  1135. if ( inputData_.doInput ) {
  1136. inputData_.doInput = false;
  1137. int res = write( data->trigger_fds[1], &inputData_.doInput, sizeof(inputData_.doInput) );
  1138. (void) res;
  1139. if ( !pthread_equal(data->thread, data->dummy_thread_id) )
  1140. pthread_join( data->thread, NULL );
  1141. }
  1142. // Cleanup.
  1143. close ( data->trigger_fds[0] );
  1144. close ( data->trigger_fds[1] );
  1145. if ( data->vport >= 0 ) snd_seq_delete_port( data->seq, data->vport );
  1146. #ifndef AVOID_TIMESTAMPING
  1147. snd_seq_free_queue( data->seq, data->queue_id );
  1148. #endif
  1149. freeSequencer();
  1150. delete data;
  1151. }
  1152. void MidiInAlsa :: initialize( const std::string& clientName )
  1153. {
  1154. snd_seq_t* seq = createSequencer( clientName );
  1155. if ( seq == NULL ) {
  1156. s_seq = NULL;
  1157. errorString_ = "MidiInAlsa::initialize: error creating ALSA sequencer client object.";
  1158. RtMidi::error( RtError::DRIVER_ERROR, errorString_ );
  1159. }
  1160. // Save our api-specific connection information.
  1161. AlsaMidiData *data = (AlsaMidiData *) new AlsaMidiData;
  1162. data->seq = seq;
  1163. data->portNum = -1;
  1164. data->vport = -1;
  1165. data->subscription = 0;
  1166. data->dummy_thread_id = pthread_self();
  1167. data->thread = data->dummy_thread_id;
  1168. data->trigger_fds[0] = -1;
  1169. data->trigger_fds[1] = -1;
  1170. apiData_ = (void *) data;
  1171. inputData_.apiData = (void *) data;
  1172. if ( pipe(data->trigger_fds) == -1 ) {
  1173. errorString_ = "MidiInAlsa::initialize: error creating pipe objects.";
  1174. RtMidi::error( RtError::DRIVER_ERROR, errorString_ );
  1175. }
  1176. // Create the input queue
  1177. #ifndef AVOID_TIMESTAMPING
  1178. data->queue_id = snd_seq_alloc_named_queue(s_seq, "RtMidi Queue");
  1179. // Set arbitrary tempo (mm=100) and resolution (240)
  1180. snd_seq_queue_tempo_t *qtempo;
  1181. snd_seq_queue_tempo_alloca(&qtempo);
  1182. snd_seq_queue_tempo_set_tempo(qtempo, 600000);
  1183. snd_seq_queue_tempo_set_ppq(qtempo, 240);
  1184. snd_seq_set_queue_tempo(data->seq, data->queue_id, qtempo);
  1185. snd_seq_drain_output(data->seq);
  1186. #endif
  1187. }
  1188. // This function is used to count or get the pinfo structure for a given port number.
  1189. unsigned int portInfo( snd_seq_t *seq, snd_seq_port_info_t *pinfo, unsigned int type, int portNumber )
  1190. {
  1191. snd_seq_client_info_t *cinfo;
  1192. int client;
  1193. int count = 0;
  1194. snd_seq_client_info_alloca( &cinfo );
  1195. snd_seq_client_info_set_client( cinfo, -1 );
  1196. while ( snd_seq_query_next_client( seq, cinfo ) >= 0 ) {
  1197. client = snd_seq_client_info_get_client( cinfo );
  1198. if ( client == 0 ) continue;
  1199. // Reset query info
  1200. snd_seq_port_info_set_client( pinfo, client );
  1201. snd_seq_port_info_set_port( pinfo, -1 );
  1202. while ( snd_seq_query_next_port( seq, pinfo ) >= 0 ) {
  1203. unsigned int atyp = snd_seq_port_info_get_type( pinfo );
  1204. if ( ( atyp & SND_SEQ_PORT_TYPE_MIDI_GENERIC ) == 0 ) continue;
  1205. unsigned int caps = snd_seq_port_info_get_capability( pinfo );
  1206. if ( ( caps & type ) != type ) continue;
  1207. if ( count == portNumber ) return 1;
  1208. ++count;
  1209. }
  1210. }
  1211. // If a negative portNumber was used, return the port count.
  1212. if ( portNumber < 0 ) return count;
  1213. return 0;
  1214. }
  1215. unsigned int MidiInAlsa :: getPortCount()
  1216. {
  1217. snd_seq_port_info_t *pinfo;
  1218. snd_seq_port_info_alloca( &pinfo );
  1219. AlsaMidiData *data = static_cast<AlsaMidiData *> (apiData_);
  1220. return portInfo( data->seq, pinfo, SND_SEQ_PORT_CAP_READ|SND_SEQ_PORT_CAP_SUBS_READ, -1 );
  1221. }
  1222. std::string MidiInAlsa :: getPortName( unsigned int portNumber )
  1223. {
  1224. snd_seq_client_info_t *cinfo;
  1225. snd_seq_port_info_t *pinfo;
  1226. snd_seq_client_info_alloca( &cinfo );
  1227. snd_seq_port_info_alloca( &pinfo );
  1228. std::string stringName;
  1229. AlsaMidiData *data = static_cast<AlsaMidiData *> (apiData_);
  1230. if ( portInfo( data->seq, pinfo, SND_SEQ_PORT_CAP_READ|SND_SEQ_PORT_CAP_SUBS_READ, (int) portNumber ) ) {
  1231. int cnum = snd_seq_port_info_get_client( pinfo );
  1232. snd_seq_get_any_client_info( data->seq, cnum, cinfo );
  1233. std::ostringstream os;
  1234. os << snd_seq_client_info_get_name( cinfo );
  1235. os << " "; // GO: These lines added to make sure devices are listed
  1236. os << snd_seq_port_info_get_client( pinfo ); // GO: with full portnames added to ensure individual device names
  1237. os << ":";
  1238. os << snd_seq_port_info_get_port( pinfo );
  1239. stringName = os.str();
  1240. return stringName;
  1241. }
  1242. // If we get here, we didn't find a match.
  1243. errorString_ = "MidiInAlsa::getPortName: error looking for port name!";
  1244. RtMidi::error( RtError::WARNING, errorString_ );
  1245. return stringName;
  1246. //RtMidi::error( RtError::INVALID_PARAMETER, errorString_ );
  1247. }
  1248. void MidiInAlsa :: openPort( unsigned int portNumber, const std::string portName )
  1249. {
  1250. if ( connected_ ) {
  1251. errorString_ = "MidiInAlsa::openPort: a valid connection already exists!";
  1252. RtMidi::error( RtError::WARNING, errorString_ );
  1253. return;
  1254. }
  1255. unsigned int nSrc = this->getPortCount();
  1256. if (nSrc < 1) {
  1257. errorString_ = "MidiInAlsa::openPort: no MIDI input sources found!";
  1258. RtMidi::error( RtError::NO_DEVICES_FOUND, errorString_ );
  1259. }
  1260. snd_seq_port_info_t *pinfo;
  1261. snd_seq_port_info_alloca( &pinfo );
  1262. std::ostringstream ost;
  1263. AlsaMidiData *data = static_cast<AlsaMidiData *> (apiData_);
  1264. if ( portInfo( data->seq, pinfo, SND_SEQ_PORT_CAP_READ|SND_SEQ_PORT_CAP_SUBS_READ, (int) portNumber ) == 0 ) {
  1265. ost << "MidiInAlsa::openPort: the 'portNumber' argument (" << portNumber << ") is invalid.";
  1266. errorString_ = ost.str();
  1267. RtMidi::error( RtError::INVALID_PARAMETER, errorString_ );
  1268. }
  1269. snd_seq_addr_t sender, receiver;
  1270. sender.client = snd_seq_port_info_get_client( pinfo );
  1271. sender.port = snd_seq_port_info_get_port( pinfo );
  1272. receiver.client = snd_seq_client_id( data->seq );
  1273. if ( data->vport < 0 ) {
  1274. snd_seq_port_info_set_client( pinfo, 0 );
  1275. snd_seq_port_info_set_port( pinfo, 0 );
  1276. snd_seq_port_info_set_capability( pinfo,
  1277. SND_SEQ_PORT_CAP_WRITE |
  1278. SND_SEQ_PORT_CAP_SUBS_WRITE );
  1279. snd_seq_port_info_set_type( pinfo,
  1280. SND_SEQ_PORT_TYPE_MIDI_GENERIC |
  1281. SND_SEQ_PORT_TYPE_APPLICATION );
  1282. snd_seq_port_info_set_midi_channels(pinfo, 16);
  1283. #ifndef AVOID_TIMESTAMPING
  1284. snd_seq_port_info_set_timestamping(pinfo, 1);
  1285. snd_seq_port_info_set_timestamp_real(pinfo, 1);
  1286. snd_seq_port_info_set_timestamp_queue(pinfo, data->queue_id);
  1287. #endif
  1288. snd_seq_port_info_set_name(pinfo, portName.c_str() );
  1289. data->vport = snd_seq_create_port(data->seq, pinfo);
  1290. if ( data->vport < 0 ) {
  1291. errorString_ = "MidiInAlsa::openPort: ALSA error creating input port.";
  1292. RtMidi::error( RtError::DRIVER_ERROR, errorString_ );
  1293. }
  1294. }
  1295. receiver.port = data->vport;