Audio plugin host https://kx.studio/carla
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.

3751 lines
118KB

  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. // not used
  35. #undef __UNIX_JACK__
  36. //*********************************************************************//
  37. // RtMidi Definitions
  38. //*********************************************************************//
  39. void RtMidi :: getCompiledApi( std::vector<RtMidi::Api> &apis ) throw()
  40. {
  41. apis.clear();
  42. // The order here will control the order of RtMidi's API search in
  43. // the constructor.
  44. #if defined(__MACOSX_CORE__)
  45. apis.push_back( MACOSX_CORE );
  46. #endif
  47. #if defined(__LINUX_ALSA__)
  48. apis.push_back( LINUX_ALSA );
  49. #endif
  50. #if defined(__UNIX_JACK__)
  51. apis.push_back( UNIX_JACK );
  52. #endif
  53. #if defined(__WINDOWS_MM__)
  54. apis.push_back( WINDOWS_MM );
  55. #endif
  56. #if defined(__WINDOWS_KS__)
  57. apis.push_back( WINDOWS_KS );
  58. #endif
  59. #if defined(__RTMIDI_DUMMY__)
  60. apis.push_back( RTMIDI_DUMMY );
  61. #endif
  62. }
  63. void RtMidi :: error( RtError::Type type, std::string errorString )
  64. {
  65. if (type == RtError::WARNING) {
  66. std::cerr << '\n' << errorString << "\n\n";
  67. }
  68. else if (type == RtError::DEBUG_WARNING) {
  69. #if defined(__RTMIDI_DEBUG__)
  70. std::cerr << '\n' << errorString << "\n\n";
  71. #endif
  72. }
  73. else {
  74. std::cerr << '\n' << errorString << "\n\n";
  75. throw RtError( errorString, type );
  76. }
  77. }
  78. //*********************************************************************//
  79. // RtMidiIn Definitions
  80. //*********************************************************************//
  81. void RtMidiIn :: openMidiApi( RtMidi::Api api, const std::string clientName, unsigned int queueSizeLimit )
  82. {
  83. if ( rtapi_ )
  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(__WINDOWS_KS__)
  99. if ( api == WINDOWS_KS )
  100. rtapi_ = new MidiInWinKS( clientName, queueSizeLimit );
  101. #endif
  102. #if defined(__MACOSX_CORE__)
  103. if ( api == MACOSX_CORE )
  104. rtapi_ = new MidiInCore( clientName, queueSizeLimit );
  105. #endif
  106. #if defined(__RTMIDI_DUMMY__)
  107. if ( api == RTMIDI_DUMMY )
  108. rtapi_ = new MidiInDummy( clientName, queueSizeLimit );
  109. #endif
  110. }
  111. RtMidiIn :: RtMidiIn( RtMidi::Api api, const std::string clientName, unsigned int queueSizeLimit )
  112. {
  113. rtapi_ = 0;
  114. if ( api != UNSPECIFIED ) {
  115. // Attempt to open the specified API.
  116. openMidiApi( api, clientName, queueSizeLimit );
  117. if ( rtapi_ ) return;
  118. // No compiled support for specified API value. Issue a debug
  119. // warning and continue as if no API was specified.
  120. RtMidi::error( RtError::WARNING, "RtMidiIn: no compiled support for specified API argument!" );
  121. }
  122. // Iterate through the compiled APIs and return as soon as we find
  123. // one with at least one port or we reach the end of the list.
  124. std::vector< RtMidi::Api > apis;
  125. getCompiledApi( apis );
  126. for ( unsigned int i=0; i<apis.size(); i++ ) {
  127. openMidiApi( apis[i], clientName, queueSizeLimit );
  128. if ( rtapi_->getPortCount() ) break;
  129. }
  130. if ( rtapi_ ) return;
  131. // It should not be possible to get here because the preprocessor
  132. // definition __RTMIDI_DUMMY__ is automatically defined if no
  133. // API-specific definitions are passed to the compiler. But just in
  134. // case something weird happens, we'll print out an error message.
  135. RtMidi::error( RtError::WARNING, "RtMidiIn: no compiled API support found ... critical error!!" );
  136. }
  137. RtMidiIn :: ~RtMidiIn() throw()
  138. {
  139. delete rtapi_;
  140. }
  141. //*********************************************************************//
  142. // RtMidiOut Definitions
  143. //*********************************************************************//
  144. void RtMidiOut :: openMidiApi( RtMidi::Api api, const std::string clientName )
  145. {
  146. if ( rtapi_ )
  147. delete rtapi_;
  148. rtapi_ = 0;
  149. #if defined(__UNIX_JACK__)
  150. if ( api == UNIX_JACK )
  151. rtapi_ = new MidiOutJack( clientName );
  152. #endif
  153. #if defined(__LINUX_ALSA__)
  154. if ( api == LINUX_ALSA )
  155. rtapi_ = new MidiOutAlsa( clientName );
  156. #endif
  157. #if defined(__WINDOWS_MM__)
  158. if ( api == WINDOWS_MM )
  159. rtapi_ = new MidiOutWinMM( clientName );
  160. #endif
  161. #if defined(__WINDOWS_KS__)
  162. if ( api == WINDOWS_KS )
  163. rtapi_ = new MidiOutWinKS( clientName );
  164. #endif
  165. #if defined(__MACOSX_CORE__)
  166. if ( api == MACOSX_CORE )
  167. rtapi_ = new MidiOutCore( clientName );
  168. #endif
  169. #if defined(__RTMIDI_DUMMY__)
  170. if ( api == RTMIDI_DUMMY )
  171. rtapi_ = new MidiOutDummy( clientName );
  172. #endif
  173. }
  174. RtMidiOut :: RtMidiOut( RtMidi::Api api, const std::string clientName )
  175. {
  176. rtapi_ = 0;
  177. if ( api != UNSPECIFIED ) {
  178. // Attempt to open the specified API.
  179. openMidiApi( api, clientName );
  180. if ( rtapi_ ) return;
  181. // No compiled support for specified API value. Issue a debug
  182. // warning and continue as if no API was specified.
  183. RtMidi::error( RtError::WARNING, "RtMidiOut: no compiled support for specified API argument!" );
  184. }
  185. // Iterate through the compiled APIs and return as soon as we find
  186. // one with at least one port or we reach the end of the list.
  187. std::vector< RtMidi::Api > apis;
  188. getCompiledApi( apis );
  189. for ( unsigned int i=0; i<apis.size(); i++ ) {
  190. openMidiApi( apis[i], clientName );
  191. if ( rtapi_->getPortCount() ) break;
  192. }
  193. if ( rtapi_ ) return;
  194. // It should not be possible to get here because the preprocessor
  195. // definition __RTMIDI_DUMMY__ is automatically defined if no
  196. // API-specific definitions are passed to the compiler. But just in
  197. // case something weird happens, we'll print out an error message.
  198. RtMidi::error( RtError::WARNING, "RtMidiOut: no compiled API support found ... critical error!!" );
  199. }
  200. RtMidiOut :: ~RtMidiOut() throw()
  201. {
  202. delete rtapi_;
  203. }
  204. //*********************************************************************//
  205. // Common MidiInApi Definitions
  206. //*********************************************************************//
  207. MidiInApi :: MidiInApi( unsigned int queueSizeLimit )
  208. : apiData_( 0 ), connected_( false )
  209. {
  210. // Allocate the MIDI queue.
  211. inputData_.queue.ringSize = queueSizeLimit;
  212. if ( inputData_.queue.ringSize > 0 )
  213. inputData_.queue.ring = new MidiMessage[ inputData_.queue.ringSize ];
  214. }
  215. MidiInApi :: ~MidiInApi( void )
  216. {
  217. // Delete the MIDI queue.
  218. if ( inputData_.queue.ringSize > 0 ) delete [] inputData_.queue.ring;
  219. }
  220. void MidiInApi :: setCallback( RtMidiIn::RtMidiCallback callback, void *userData )
  221. {
  222. if ( inputData_.usingCallback ) {
  223. errorString_ = "MidiInApi::setCallback: a callback function is already set!";
  224. RtMidi::error( RtError::WARNING, errorString_ );
  225. return;
  226. }
  227. if ( !callback ) {
  228. errorString_ = "RtMidiIn::setCallback: callback function value is invalid!";
  229. RtMidi::error( RtError::WARNING, errorString_ );
  230. return;
  231. }
  232. inputData_.userCallback = (void *) callback;
  233. inputData_.userData = userData;
  234. inputData_.usingCallback = true;
  235. }
  236. void MidiInApi :: cancelCallback()
  237. {
  238. if ( !inputData_.usingCallback ) {
  239. errorString_ = "RtMidiIn::cancelCallback: no callback function was set!";
  240. RtMidi::error( RtError::WARNING, errorString_ );
  241. return;
  242. }
  243. inputData_.userCallback = 0;
  244. inputData_.userData = 0;
  245. inputData_.usingCallback = false;
  246. }
  247. void MidiInApi :: ignoreTypes( bool midiSysex, bool midiTime, bool midiSense )
  248. {
  249. inputData_.ignoreFlags = 0;
  250. if ( midiSysex ) inputData_.ignoreFlags = 0x01;
  251. if ( midiTime ) inputData_.ignoreFlags |= 0x02;
  252. if ( midiSense ) inputData_.ignoreFlags |= 0x04;
  253. }
  254. double MidiInApi :: getMessage( std::vector<unsigned char> *message )
  255. {
  256. message->clear();
  257. if ( inputData_.usingCallback ) {
  258. errorString_ = "RtMidiIn::getNextMessage: a user callback is currently set for this port.";
  259. RtMidi::error( RtError::WARNING, errorString_ );
  260. return 0.0;
  261. }
  262. if ( inputData_.queue.size == 0 ) return 0.0;
  263. // Copy queued message to the vector pointer argument and then "pop" it.
  264. std::vector<unsigned char> *bytes = &(inputData_.queue.ring[inputData_.queue.front].bytes);
  265. message->assign( bytes->begin(), bytes->end() );
  266. double deltaTime = inputData_.queue.ring[inputData_.queue.front].timeStamp;
  267. inputData_.queue.size--;
  268. inputData_.queue.front++;
  269. if ( inputData_.queue.front == inputData_.queue.ringSize )
  270. inputData_.queue.front = 0;
  271. return deltaTime;
  272. }
  273. //*********************************************************************//
  274. // Common MidiOutApi Definitions
  275. //*********************************************************************//
  276. MidiOutApi :: MidiOutApi( void )
  277. : apiData_( 0 ), connected_( false )
  278. {
  279. }
  280. MidiOutApi :: ~MidiOutApi( void )
  281. {
  282. }
  283. // *************************************************** //
  284. //
  285. // OS/API-specific methods.
  286. //
  287. // *************************************************** //
  288. #if defined(__MACOSX_CORE__)
  289. // The CoreMIDI API is based on the use of a callback function for
  290. // MIDI input. We convert the system specific time stamps to delta
  291. // time values.
  292. // OS-X CoreMIDI header files.
  293. #include <CoreMIDI/CoreMIDI.h>
  294. #include <CoreAudio/HostTime.h>
  295. #include <CoreServices/CoreServices.h>
  296. // A structure to hold variables related to the CoreMIDI API
  297. // implementation.
  298. struct CoreMidiData {
  299. MIDIClientRef client;
  300. MIDIPortRef port;
  301. MIDIEndpointRef endpoint;
  302. MIDIEndpointRef destinationId;
  303. unsigned long long lastTime;
  304. MIDISysexSendRequest sysexreq;
  305. };
  306. //*********************************************************************//
  307. // API: OS-X
  308. // Class Definitions: MidiInCore
  309. //*********************************************************************//
  310. void midiInputCallback( const MIDIPacketList *list, void *procRef, void *srcRef )
  311. {
  312. MidiInApi::RtMidiInData *data = static_cast<MidiInApi::RtMidiInData *> (procRef);
  313. CoreMidiData *apiData = static_cast<CoreMidiData *> (data->apiData);
  314. unsigned char status;
  315. unsigned short nBytes, iByte, size;
  316. unsigned long long time;
  317. bool& continueSysex = data->continueSysex;
  318. MidiInApi::MidiMessage& message = data->message;
  319. const MIDIPacket *packet = &list->packet[0];
  320. for ( unsigned int i=0; i<list->numPackets; ++i ) {
  321. // My interpretation of the CoreMIDI documentation: all message
  322. // types, except sysex, are complete within a packet and there may
  323. // be several of them in a single packet. Sysex messages can be
  324. // broken across multiple packets and PacketLists but are bundled
  325. // alone within each packet (these packets do not contain other
  326. // message types). If sysex messages are split across multiple
  327. // MIDIPacketLists, they must be handled by multiple calls to this
  328. // function.
  329. nBytes = packet->length;
  330. if ( nBytes == 0 ) continue;
  331. // Calculate time stamp.
  332. if ( data->firstMessage ) {
  333. message.timeStamp = 0.0;
  334. data->firstMessage = false;
  335. }
  336. else {
  337. time = packet->timeStamp;
  338. if ( time == 0 ) { // this happens when receiving asynchronous sysex messages
  339. time = AudioGetCurrentHostTime();
  340. }
  341. time -= apiData->lastTime;
  342. time = AudioConvertHostTimeToNanos( time );
  343. if ( !continueSysex )
  344. message.timeStamp = time * 0.000000001;
  345. }
  346. apiData->lastTime = packet->timeStamp;
  347. if ( apiData->lastTime == 0 ) { // this happens when receiving asynchronous sysex messages
  348. apiData->lastTime = AudioGetCurrentHostTime();
  349. }
  350. //std::cout << "TimeStamp = " << packet->timeStamp << std::endl;
  351. iByte = 0;
  352. if ( continueSysex ) {
  353. // We have a continuing, segmented sysex message.
  354. if ( !( data->ignoreFlags & 0x01 ) ) {
  355. // If we're not ignoring sysex messages, copy the entire packet.
  356. for ( unsigned int j=0; j<nBytes; ++j )
  357. message.bytes.push_back( packet->data[j] );
  358. }
  359. continueSysex = packet->data[nBytes-1] != 0xF7;
  360. if ( !continueSysex ) {
  361. // If not a continuing sysex message, invoke the user callback function or queue the message.
  362. if ( data->usingCallback ) {
  363. RtMidiIn::RtMidiCallback callback = (RtMidiIn::RtMidiCallback) data->userCallback;
  364. callback( message.timeStamp, &message.bytes, data->userData );
  365. }
  366. else {
  367. // As long as we haven't reached our queue size limit, push the message.
  368. if ( data->queue.size < data->queue.ringSize ) {
  369. data->queue.ring[data->queue.back++] = message;
  370. if ( data->queue.back == data->queue.ringSize )
  371. data->queue.back = 0;
  372. data->queue.size++;
  373. }
  374. else
  375. std::cerr << "\nMidiInCore: message queue limit reached!!\n\n";
  376. }
  377. message.bytes.clear();
  378. }
  379. }
  380. else {
  381. while ( iByte < nBytes ) {
  382. size = 0;
  383. // We are expecting that the next byte in the packet is a status byte.
  384. status = packet->data[iByte];
  385. if ( !(status & 0x80) ) break;
  386. // Determine the number of bytes in the MIDI message.
  387. if ( status < 0xC0 ) size = 3;
  388. else if ( status < 0xE0 ) size = 2;
  389. else if ( status < 0xF0 ) size = 3;
  390. else if ( status == 0xF0 ) {
  391. // A MIDI sysex
  392. if ( data->ignoreFlags & 0x01 ) {
  393. size = 0;
  394. iByte = nBytes;
  395. }
  396. else size = nBytes - iByte;
  397. continueSysex = packet->data[nBytes-1] != 0xF7;
  398. }
  399. else if ( status == 0xF1 ) {
  400. // A MIDI time code message
  401. if ( data->ignoreFlags & 0x02 ) {
  402. size = 0;
  403. iByte += 2;
  404. }
  405. else size = 2;
  406. }
  407. else if ( status == 0xF2 ) size = 3;
  408. else if ( status == 0xF3 ) size = 2;
  409. else if ( status == 0xF8 && ( data->ignoreFlags & 0x02 ) ) {
  410. // A MIDI timing tick message and we're ignoring it.
  411. size = 0;
  412. iByte += 1;
  413. }
  414. else if ( status == 0xFE && ( data->ignoreFlags & 0x04 ) ) {
  415. // A MIDI active sensing message and we're ignoring it.
  416. size = 0;
  417. iByte += 1;
  418. }
  419. else size = 1;
  420. // Copy the MIDI data to our vector.
  421. if ( size ) {
  422. message.bytes.assign( &packet->data[iByte], &packet->data[iByte+size] );
  423. if ( !continueSysex ) {
  424. // If not a continuing sysex message, invoke the user callback function or queue the message.
  425. if ( data->usingCallback ) {
  426. RtMidiIn::RtMidiCallback callback = (RtMidiIn::RtMidiCallback) data->userCallback;
  427. callback( message.timeStamp, &message.bytes, data->userData );
  428. }
  429. else {
  430. // As long as we haven't reached our queue size limit, push the message.
  431. if ( data->queue.size < data->queue.ringSize ) {
  432. data->queue.ring[data->queue.back++] = message;
  433. if ( data->queue.back == data->queue.ringSize )
  434. data->queue.back = 0;
  435. data->queue.size++;
  436. }
  437. else
  438. std::cerr << "\nMidiInCore: message queue limit reached!!\n\n";
  439. }
  440. message.bytes.clear();
  441. }
  442. iByte += size;
  443. }
  444. }
  445. }
  446. packet = MIDIPacketNext(packet);
  447. }
  448. }
  449. MidiInCore :: MidiInCore( const std::string clientName, unsigned int queueSizeLimit ) : MidiInApi( queueSizeLimit )
  450. {
  451. initialize( clientName );
  452. }
  453. MidiInCore :: ~MidiInCore( void )
  454. {
  455. // Close a connection if it exists.
  456. closePort();
  457. // Cleanup.
  458. CoreMidiData *data = static_cast<CoreMidiData *> (apiData_);
  459. MIDIClientDispose( data->client );
  460. if ( data->endpoint ) MIDIEndpointDispose( data->endpoint );
  461. delete data;
  462. }
  463. void MidiInCore :: initialize( const std::string& clientName )
  464. {
  465. // Set up our client.
  466. MIDIClientRef client;
  467. OSStatus result = MIDIClientCreate( CFStringCreateWithCString( NULL, clientName.c_str(), kCFStringEncodingASCII ), NULL, NULL, &client );
  468. if ( result != noErr ) {
  469. errorString_ = "MidiInCore::initialize: error creating OS-X MIDI client object.";
  470. RtMidi::error( RtError::DRIVER_ERROR, errorString_ );
  471. }
  472. // Save our api-specific connection information.
  473. CoreMidiData *data = (CoreMidiData *) new CoreMidiData;
  474. data->client = client;
  475. data->endpoint = 0;
  476. apiData_ = (void *) data;
  477. inputData_.apiData = (void *) data;
  478. }
  479. void MidiInCore :: openPort( unsigned int portNumber, const std::string portName )
  480. {
  481. if ( connected_ ) {
  482. errorString_ = "MidiInCore::openPort: a valid connection already exists!";
  483. RtMidi::error( RtError::WARNING, errorString_ );
  484. return;
  485. }
  486. unsigned int nSrc = MIDIGetNumberOfSources();
  487. if (nSrc < 1) {
  488. errorString_ = "MidiInCore::openPort: no MIDI input sources found!";
  489. RtMidi::error( RtError::NO_DEVICES_FOUND, errorString_ );
  490. }
  491. std::ostringstream ost;
  492. if ( portNumber >= nSrc ) {
  493. ost << "MidiInCore::openPort: the 'portNumber' argument (" << portNumber << ") is invalid.";
  494. errorString_ = ost.str();
  495. RtMidi::error( RtError::INVALID_PARAMETER, errorString_ );
  496. }
  497. MIDIPortRef port;
  498. CoreMidiData *data = static_cast<CoreMidiData *> (apiData_);
  499. OSStatus result = MIDIInputPortCreate( data->client,
  500. CFStringCreateWithCString( NULL, portName.c_str(), kCFStringEncodingASCII ),
  501. midiInputCallback, (void *)&inputData_, &port );
  502. if ( result != noErr ) {
  503. MIDIClientDispose( data->client );
  504. errorString_ = "MidiInCore::openPort: error creating OS-X MIDI input port.";
  505. RtMidi::error( RtError::DRIVER_ERROR, errorString_ );
  506. }
  507. // Get the desired input source identifier.
  508. MIDIEndpointRef endpoint = MIDIGetSource( portNumber );
  509. if ( endpoint == 0 ) {
  510. MIDIPortDispose( port );
  511. MIDIClientDispose( data->client );
  512. errorString_ = "MidiInCore::openPort: error getting MIDI input source reference.";
  513. RtMidi::error( RtError::DRIVER_ERROR, errorString_ );
  514. }
  515. // Make the connection.
  516. result = MIDIPortConnectSource( port, endpoint, NULL );
  517. if ( result != noErr ) {
  518. MIDIPortDispose( port );
  519. MIDIClientDispose( data->client );
  520. errorString_ = "MidiInCore::openPort: error connecting OS-X MIDI input port.";
  521. RtMidi::error( RtError::DRIVER_ERROR, errorString_ );
  522. }
  523. // Save our api-specific port information.
  524. data->port = port;
  525. connected_ = true;
  526. }
  527. void MidiInCore :: openVirtualPort( const std::string portName )
  528. {
  529. CoreMidiData *data = static_cast<CoreMidiData *> (apiData_);
  530. // Create a virtual MIDI input destination.
  531. MIDIEndpointRef endpoint;
  532. OSStatus result = MIDIDestinationCreate( data->client,
  533. CFStringCreateWithCString( NULL, portName.c_str(), kCFStringEncodingASCII ),
  534. midiInputCallback, (void *)&inputData_, &endpoint );
  535. if ( result != noErr ) {
  536. errorString_ = "MidiInCore::openVirtualPort: error creating virtual OS-X MIDI destination.";
  537. RtMidi::error( RtError::DRIVER_ERROR, errorString_ );
  538. }
  539. // Save our api-specific connection information.
  540. data->endpoint = endpoint;
  541. }
  542. void MidiInCore :: closePort( void )
  543. {
  544. if ( connected_ ) {
  545. CoreMidiData *data = static_cast<CoreMidiData *> (apiData_);
  546. MIDIPortDispose( data->port );
  547. connected_ = false;
  548. }
  549. }
  550. unsigned int MidiInCore :: getPortCount()
  551. {
  552. return MIDIGetNumberOfSources();
  553. }
  554. // This function was submitted by Douglas Casey Tucker and apparently
  555. // derived largely from PortMidi.
  556. CFStringRef EndpointName( MIDIEndpointRef endpoint, bool isExternal )
  557. {
  558. CFMutableStringRef result = CFStringCreateMutable( NULL, 0 );
  559. CFStringRef str;
  560. // Begin with the endpoint's name.
  561. str = NULL;
  562. MIDIObjectGetStringProperty( endpoint, kMIDIPropertyName, &str );
  563. if ( str != NULL ) {
  564. CFStringAppend( result, str );
  565. CFRelease( str );
  566. }
  567. MIDIEntityRef entity = NULL;
  568. MIDIEndpointGetEntity( endpoint, &entity );
  569. if ( entity == 0 )
  570. // probably virtual
  571. return result;
  572. if ( CFStringGetLength( result ) == 0 ) {
  573. // endpoint name has zero length -- try the entity
  574. str = NULL;
  575. MIDIObjectGetStringProperty( entity, kMIDIPropertyName, &str );
  576. if ( str != NULL ) {
  577. CFStringAppend( result, str );
  578. CFRelease( str );
  579. }
  580. }
  581. // now consider the device's name
  582. MIDIDeviceRef device = 0;
  583. MIDIEntityGetDevice( entity, &device );
  584. if ( device == 0 )
  585. return result;
  586. str = NULL;
  587. MIDIObjectGetStringProperty( device, kMIDIPropertyName, &str );
  588. if ( CFStringGetLength( result ) == 0 ) {
  589. CFRelease( result );
  590. return str;
  591. }
  592. if ( str != NULL ) {
  593. // if an external device has only one entity, throw away
  594. // the endpoint name and just use the device name
  595. if ( isExternal && MIDIDeviceGetNumberOfEntities( device ) < 2 ) {
  596. CFRelease( result );
  597. return str;
  598. } else {
  599. if ( CFStringGetLength( str ) == 0 ) {
  600. CFRelease( str );
  601. return result;
  602. }
  603. // does the entity name already start with the device name?
  604. // (some drivers do this though they shouldn't)
  605. // if so, do not prepend
  606. if ( CFStringCompareWithOptions( result, /* endpoint name */
  607. str /* device name */,
  608. CFRangeMake(0, CFStringGetLength( str ) ), 0 ) != kCFCompareEqualTo ) {
  609. // prepend the device name to the entity name
  610. if ( CFStringGetLength( result ) > 0 )
  611. CFStringInsert( result, 0, CFSTR(" ") );
  612. CFStringInsert( result, 0, str );
  613. }
  614. CFRelease( str );
  615. }
  616. }
  617. return result;
  618. }
  619. // This function was submitted by Douglas Casey Tucker and apparently
  620. // derived largely from PortMidi.
  621. static CFStringRef ConnectedEndpointName( MIDIEndpointRef endpoint )
  622. {
  623. CFMutableStringRef result = CFStringCreateMutable( NULL, 0 );
  624. CFStringRef str;
  625. OSStatus err;
  626. int i;
  627. // Does the endpoint have connections?
  628. CFDataRef connections = NULL;
  629. int nConnected = 0;
  630. bool anyStrings = false;
  631. err = MIDIObjectGetDataProperty( endpoint, kMIDIPropertyConnectionUniqueID, &connections );
  632. if ( connections != NULL ) {
  633. // It has connections, follow them
  634. // Concatenate the names of all connected devices
  635. nConnected = CFDataGetLength( connections ) / sizeof(MIDIUniqueID);
  636. if ( nConnected ) {
  637. const SInt32 *pid = (const SInt32 *)(CFDataGetBytePtr(connections));
  638. for ( i=0; i<nConnected; ++i, ++pid ) {
  639. MIDIUniqueID id = EndianS32_BtoN( *pid );
  640. MIDIObjectRef connObject;
  641. MIDIObjectType connObjectType;
  642. err = MIDIObjectFindByUniqueID( id, &connObject, &connObjectType );
  643. if ( err == noErr ) {
  644. if ( connObjectType == kMIDIObjectType_ExternalSource ||
  645. connObjectType == kMIDIObjectType_ExternalDestination ) {
  646. // Connected to an external device's endpoint (10.3 and later).
  647. str = EndpointName( (MIDIEndpointRef)(connObject), true );
  648. } else {
  649. // Connected to an external device (10.2) (or something else, catch-
  650. str = NULL;
  651. MIDIObjectGetStringProperty( connObject, kMIDIPropertyName, &str );
  652. }
  653. if ( str != NULL ) {
  654. if ( anyStrings )
  655. CFStringAppend( result, CFSTR(", ") );
  656. else anyStrings = true;
  657. CFStringAppend( result, str );
  658. CFRelease( str );
  659. }
  660. }
  661. }
  662. }
  663. CFRelease( connections );
  664. }
  665. if ( anyStrings )
  666. return result;
  667. // Here, either the endpoint had no connections, or we failed to obtain names
  668. return EndpointName( endpoint, false );
  669. }
  670. std::string MidiInCore :: getPortName( unsigned int portNumber )
  671. {
  672. CFStringRef nameRef;
  673. MIDIEndpointRef portRef;
  674. std::ostringstream ost;
  675. char name[128];
  676. std::string stringName;
  677. if ( portNumber >= MIDIGetNumberOfSources() ) {
  678. ost << "MidiInCore::getPortName: the 'portNumber' argument (" << portNumber << ") is invalid.";
  679. errorString_ = ost.str();
  680. RtMidi::error( RtError::WARNING, errorString_ );
  681. //RtMidi::error( RtError::INVALID_PARAMETER, errorString_ );
  682. return stringName;
  683. }
  684. portRef = MIDIGetSource( portNumber );
  685. nameRef = ConnectedEndpointName(portRef);
  686. CFStringGetCString( nameRef, name, sizeof(name), 0);
  687. CFRelease( nameRef );
  688. return stringName = name;
  689. }
  690. //*********************************************************************//
  691. // API: OS-X
  692. // Class Definitions: MidiOutCore
  693. //*********************************************************************//
  694. MidiOutCore :: MidiOutCore( const std::string clientName ) : MidiOutApi()
  695. {
  696. initialize( clientName );
  697. }
  698. MidiOutCore :: ~MidiOutCore( void )
  699. {
  700. // Close a connection if it exists.
  701. closePort();
  702. // Cleanup.
  703. CoreMidiData *data = static_cast<CoreMidiData *> (apiData_);
  704. MIDIClientDispose( data->client );
  705. if ( data->endpoint ) MIDIEndpointDispose( data->endpoint );
  706. delete data;
  707. }
  708. void MidiOutCore :: initialize( const std::string& clientName )
  709. {
  710. // Set up our client.
  711. MIDIClientRef client;
  712. OSStatus result = MIDIClientCreate( CFStringCreateWithCString( NULL, clientName.c_str(), kCFStringEncodingASCII ), NULL, NULL, &client );
  713. if ( result != noErr ) {
  714. errorString_ = "MidiOutCore::initialize: error creating OS-X MIDI client object.";
  715. RtMidi::error( RtError::DRIVER_ERROR, errorString_ );
  716. }
  717. // Save our api-specific connection information.
  718. CoreMidiData *data = (CoreMidiData *) new CoreMidiData;
  719. data->client = client;
  720. data->endpoint = 0;
  721. apiData_ = (void *) data;
  722. }
  723. unsigned int MidiOutCore :: getPortCount()
  724. {
  725. return MIDIGetNumberOfDestinations();
  726. }
  727. std::string MidiOutCore :: getPortName( unsigned int portNumber )
  728. {
  729. CFStringRef nameRef;
  730. MIDIEndpointRef portRef;
  731. std::ostringstream ost;
  732. char name[128];
  733. std::string stringName;
  734. if ( portNumber >= MIDIGetNumberOfDestinations() ) {
  735. ost << "MidiOutCore::getPortName: the 'portNumber' argument (" << portNumber << ") is invalid.";
  736. errorString_ = ost.str();
  737. RtMidi::error( RtError::WARNING, errorString_ );
  738. return stringName;
  739. //RtMidi::error( RtError::INVALID_PARAMETER, errorString_ );
  740. }
  741. portRef = MIDIGetDestination( portNumber );
  742. nameRef = ConnectedEndpointName(portRef);
  743. CFStringGetCString( nameRef, name, sizeof(name), 0);
  744. CFRelease( nameRef );
  745. return stringName = name;
  746. }
  747. void MidiOutCore :: openPort( unsigned int portNumber, const std::string portName )
  748. {
  749. if ( connected_ ) {
  750. errorString_ = "MidiOutCore::openPort: a valid connection already exists!";
  751. RtMidi::error( RtError::WARNING, errorString_ );
  752. return;
  753. }
  754. unsigned int nDest = MIDIGetNumberOfDestinations();
  755. if (nDest < 1) {
  756. errorString_ = "MidiOutCore::openPort: no MIDI output destinations found!";
  757. RtMidi::error( RtError::NO_DEVICES_FOUND, errorString_ );
  758. }
  759. std::ostringstream ost;
  760. if ( portNumber >= nDest ) {
  761. ost << "MidiOutCore::openPort: the 'portNumber' argument (" << portNumber << ") is invalid.";
  762. errorString_ = ost.str();
  763. RtMidi::error( RtError::INVALID_PARAMETER, errorString_ );
  764. }
  765. MIDIPortRef port;
  766. CoreMidiData *data = static_cast<CoreMidiData *> (apiData_);
  767. OSStatus result = MIDIOutputPortCreate( data->client,
  768. CFStringCreateWithCString( NULL, portName.c_str(), kCFStringEncodingASCII ),
  769. &port );
  770. if ( result != noErr ) {
  771. MIDIClientDispose( data->client );
  772. errorString_ = "MidiOutCore::openPort: error creating OS-X MIDI output port.";
  773. RtMidi::error( RtError::DRIVER_ERROR, errorString_ );
  774. }
  775. // Get the desired output port identifier.
  776. MIDIEndpointRef destination = MIDIGetDestination( portNumber );
  777. if ( destination == 0 ) {
  778. MIDIPortDispose( port );
  779. MIDIClientDispose( data->client );
  780. errorString_ = "MidiOutCore::openPort: error getting MIDI output destination reference.";
  781. RtMidi::error( RtError::DRIVER_ERROR, errorString_ );
  782. }
  783. // Save our api-specific connection information.
  784. data->port = port;
  785. data->destinationId = destination;
  786. connected_ = true;
  787. }
  788. void MidiOutCore :: closePort( void )
  789. {
  790. if ( connected_ ) {
  791. CoreMidiData *data = static_cast<CoreMidiData *> (apiData_);
  792. MIDIPortDispose( data->port );
  793. connected_ = false;
  794. }
  795. }
  796. void MidiOutCore :: openVirtualPort( std::string portName )
  797. {
  798. CoreMidiData *data = static_cast<CoreMidiData *> (apiData_);
  799. if ( data->endpoint ) {
  800. errorString_ = "MidiOutCore::openVirtualPort: a virtual output port already exists!";
  801. RtMidi::error( RtError::WARNING, errorString_ );
  802. return;
  803. }
  804. // Create a virtual MIDI output source.
  805. MIDIEndpointRef endpoint;
  806. OSStatus result = MIDISourceCreate( data->client,
  807. CFStringCreateWithCString( NULL, portName.c_str(), kCFStringEncodingASCII ),
  808. &endpoint );
  809. if ( result != noErr ) {
  810. errorString_ = "MidiOutCore::initialize: error creating OS-X virtual MIDI source.";
  811. RtMidi::error( RtError::DRIVER_ERROR, errorString_ );
  812. }
  813. // Save our api-specific connection information.
  814. data->endpoint = endpoint;
  815. }
  816. char *sysexBuffer = 0;
  817. void sysexCompletionProc( MIDISysexSendRequest * sreq )
  818. {
  819. //std::cout << "Completed SysEx send\n";
  820. delete sysexBuffer;
  821. sysexBuffer = 0;
  822. }
  823. void MidiOutCore :: sendMessage( std::vector<unsigned char> *message )
  824. {
  825. // We use the MIDISendSysex() function to asynchronously send sysex
  826. // messages. Otherwise, we use a single CoreMidi MIDIPacket.
  827. unsigned int nBytes = message->size();
  828. if ( nBytes == 0 ) {
  829. errorString_ = "MidiOutCore::sendMessage: no data in message argument!";
  830. RtMidi::error( RtError::WARNING, errorString_ );
  831. return;
  832. }
  833. // unsigned int packetBytes, bytesLeft = nBytes;
  834. // unsigned int messageIndex = 0;
  835. MIDITimeStamp timeStamp = AudioGetCurrentHostTime();
  836. CoreMidiData *data = static_cast<CoreMidiData *> (apiData_);
  837. OSStatus result;
  838. if ( message->at(0) == 0xF0 ) {
  839. while ( sysexBuffer != 0 ) usleep( 1000 ); // sleep 1 ms
  840. sysexBuffer = new char[nBytes];
  841. if ( sysexBuffer == NULL ) {
  842. errorString_ = "MidiOutCore::sendMessage: error allocating sysex message memory!";
  843. RtMidi::error( RtError::MEMORY_ERROR, errorString_ );
  844. }
  845. // Copy data to buffer.
  846. for ( unsigned int i=0; i<nBytes; ++i ) sysexBuffer[i] = message->at(i);
  847. data->sysexreq.destination = data->destinationId;
  848. data->sysexreq.data = (Byte *)sysexBuffer;
  849. data->sysexreq.bytesToSend = nBytes;
  850. data->sysexreq.complete = 0;
  851. data->sysexreq.completionProc = sysexCompletionProc;
  852. data->sysexreq.completionRefCon = &(data->sysexreq);
  853. result = MIDISendSysex( &(data->sysexreq) );
  854. if ( result != noErr ) {
  855. errorString_ = "MidiOutCore::sendMessage: error sending MIDI to virtual destinations.";
  856. RtMidi::error( RtError::WARNING, errorString_ );
  857. }
  858. return;
  859. }
  860. else if ( nBytes > 3 ) {
  861. errorString_ = "MidiOutCore::sendMessage: message format problem ... not sysex but > 3 bytes?";
  862. RtMidi::error( RtError::WARNING, errorString_ );
  863. return;
  864. }
  865. MIDIPacketList packetList;
  866. MIDIPacket *packet = MIDIPacketListInit( &packetList );
  867. packet = MIDIPacketListAdd( &packetList, sizeof(packetList), packet, timeStamp, nBytes, (const Byte *) &message->at( 0 ) );
  868. if ( !packet ) {
  869. errorString_ = "MidiOutCore::sendMessage: could not allocate packet list";
  870. RtMidi::error( RtError::DRIVER_ERROR, errorString_ );
  871. }
  872. // Send to any destinations that may have connected to us.
  873. if ( data->endpoint ) {
  874. result = MIDIReceived( data->endpoint, &packetList );
  875. if ( result != noErr ) {
  876. errorString_ = "MidiOutCore::sendMessage: error sending MIDI to virtual destinations.";
  877. RtMidi::error( RtError::WARNING, errorString_ );
  878. }
  879. }
  880. // And send to an explicit destination port if we're connected.
  881. if ( connected_ ) {
  882. result = MIDISend( data->port, data->destinationId, &packetList );
  883. if ( result != noErr ) {
  884. errorString_ = "MidiOutCore::sendMessage: error sending MIDI message to port.";
  885. RtMidi::error( RtError::WARNING, errorString_ );
  886. }
  887. }
  888. }
  889. #endif // __MACOSX_CORE__
  890. //*********************************************************************//
  891. // API: LINUX ALSA SEQUENCER
  892. //*********************************************************************//
  893. // API information found at:
  894. // - http://www.alsa-project.org/documentation.php#Library
  895. #if defined(__LINUX_ALSA__)
  896. // The ALSA Sequencer API is based on the use of a callback function for
  897. // MIDI input.
  898. //
  899. // Thanks to Pedro Lopez-Cabanillas for help with the ALSA sequencer
  900. // time stamps and other assorted fixes!!!
  901. // If you don't need timestamping for incoming MIDI events, define the
  902. // preprocessor definition AVOID_TIMESTAMPING to save resources
  903. // associated with the ALSA sequencer queues.
  904. #include <pthread.h>
  905. #include <sys/time.h>
  906. // ALSA header file.
  907. #include <alsa/asoundlib.h>
  908. // Global sequencer instance created when first In/Out object is
  909. // created, then destroyed when last In/Out is deleted.
  910. static snd_seq_t *s_seq = NULL;
  911. // Variable to keep track of how many ports are open.
  912. static unsigned int s_numPorts = 0;
  913. // The client name to use when creating the sequencer, which is
  914. // currently set on the first call to createSequencer.
  915. static std::string s_clientName = "RtMidi Client";
  916. // A structure to hold variables related to the ALSA API
  917. // implementation.
  918. struct AlsaMidiData {
  919. snd_seq_t *seq;
  920. unsigned int portNum;
  921. int vport;
  922. snd_seq_port_subscribe_t *subscription;
  923. snd_midi_event_t *coder;
  924. unsigned int bufferSize;
  925. unsigned char *buffer;
  926. pthread_t thread;
  927. pthread_t dummy_thread_id;
  928. unsigned long long lastTime;
  929. int queue_id; // an input queue is needed to get timestamped events
  930. int trigger_fds[2];
  931. };
  932. #define PORT_TYPE( pinfo, bits ) ((snd_seq_port_info_get_capability(pinfo) & (bits)) == (bits))
  933. snd_seq_t* createSequencer( const std::string& clientName )
  934. {
  935. // Set up the ALSA sequencer client.
  936. if ( s_seq == NULL ) {
  937. int result = snd_seq_open(&s_seq, "default", SND_SEQ_OPEN_DUPLEX, SND_SEQ_NONBLOCK);
  938. if ( result < 0 ) {
  939. s_seq = NULL;
  940. }
  941. else {
  942. // Set client name, use current name if given string is empty.
  943. if ( clientName != "" ) {
  944. s_clientName = clientName;
  945. }
  946. snd_seq_set_client_name( s_seq, s_clientName.c_str() );
  947. }
  948. }
  949. // Increment port count.
  950. s_numPorts++;
  951. return s_seq;
  952. }
  953. void freeSequencer ( void )
  954. {
  955. s_numPorts--;
  956. if ( s_numPorts == 0 && s_seq != NULL ) {
  957. snd_seq_close( s_seq );
  958. s_seq = NULL;
  959. }
  960. }
  961. //*********************************************************************//
  962. // API: LINUX ALSA
  963. // Class Definitions: MidiInAlsa
  964. //*********************************************************************//
  965. extern "C" void *alsaMidiHandler( void *ptr )
  966. {
  967. MidiInApi::RtMidiInData *data = static_cast<MidiInApi::RtMidiInData *> (ptr);
  968. AlsaMidiData *apiData = static_cast<AlsaMidiData *> (data->apiData);
  969. long nBytes;
  970. unsigned long long time, lastTime;
  971. bool continueSysex = false;
  972. bool doDecode = false;
  973. MidiInApi::MidiMessage message;
  974. int poll_fd_count;
  975. struct pollfd *poll_fds;
  976. snd_seq_event_t *ev;
  977. int result;
  978. apiData->bufferSize = 32;
  979. result = snd_midi_event_new( 0, &apiData->coder );
  980. if ( result < 0 ) {
  981. data->doInput = false;
  982. std::cerr << "\nMidiInAlsa::alsaMidiHandler: error initializing MIDI event parser!\n\n";
  983. return 0;
  984. }
  985. unsigned char *buffer = (unsigned char *) malloc( apiData->bufferSize );
  986. if ( buffer == NULL ) {
  987. data->doInput = false;
  988. snd_midi_event_free( apiData->coder );
  989. apiData->coder = 0;
  990. std::cerr << "\nMidiInAlsa::alsaMidiHandler: error initializing buffer memory!\n\n";
  991. return 0;
  992. }
  993. snd_midi_event_init( apiData->coder );
  994. snd_midi_event_no_status( apiData->coder, 1 ); // suppress running status messages
  995. poll_fd_count = snd_seq_poll_descriptors_count( apiData->seq, POLLIN ) + 1;
  996. poll_fds = (struct pollfd*)alloca( poll_fd_count * sizeof( struct pollfd ));
  997. snd_seq_poll_descriptors( apiData->seq, poll_fds + 1, poll_fd_count - 1, POLLIN );
  998. poll_fds[0].fd = apiData->trigger_fds[0];
  999. poll_fds[0].events = POLLIN;
  1000. while ( data->doInput ) {
  1001. if ( snd_seq_event_input_pending( apiData->seq, 1 ) == 0 ) {
  1002. // No data pending
  1003. if ( poll( poll_fds, poll_fd_count, -1) >= 0 ) {
  1004. if ( poll_fds[0].revents & POLLIN ) {
  1005. bool dummy;
  1006. int res = read( poll_fds[0].fd, &dummy, sizeof(dummy) );
  1007. (void) res;
  1008. }
  1009. }
  1010. continue;
  1011. }
  1012. // If here, there should be data.
  1013. result = snd_seq_event_input( apiData->seq, &ev );
  1014. if ( result == -ENOSPC ) {
  1015. std::cerr << "\nMidiInAlsa::alsaMidiHandler: MIDI input buffer overrun!\n\n";
  1016. continue;
  1017. }
  1018. else if ( result <= 0 ) {
  1019. std::cerr << "MidiInAlsa::alsaMidiHandler: unknown MIDI input error!\n";
  1020. continue;
  1021. }
  1022. // This is a bit weird, but we now have to decode an ALSA MIDI
  1023. // event (back) into MIDI bytes. We'll ignore non-MIDI types.
  1024. if ( !continueSysex ) message.bytes.clear();
  1025. doDecode = false;
  1026. switch ( ev->type ) {
  1027. case SND_SEQ_EVENT_PORT_SUBSCRIBED:
  1028. #if defined(__RTMIDI_DEBUG__)
  1029. std::cout << "MidiInAlsa::alsaMidiHandler: port connection made!\n";
  1030. #endif
  1031. break;
  1032. case SND_SEQ_EVENT_PORT_UNSUBSCRIBED:
  1033. #if defined(__RTMIDI_DEBUG__)
  1034. std::cerr << "MidiInAlsa::alsaMidiHandler: port connection has closed!\n";
  1035. std::cout << "sender = " << (int) ev->data.connect.sender.client << ":"
  1036. << (int) ev->data.connect.sender.port
  1037. << ", dest = " << (int) ev->data.connect.dest.client << ":"
  1038. << (int) ev->data.connect.dest.port
  1039. << std::endl;
  1040. #endif
  1041. break;
  1042. case SND_SEQ_EVENT_QFRAME: // MIDI time code
  1043. if ( !( data->ignoreFlags & 0x02 ) ) doDecode = true;
  1044. break;
  1045. case SND_SEQ_EVENT_TICK: // MIDI timing tick
  1046. if ( !( data->ignoreFlags & 0x02 ) ) doDecode = true;
  1047. break;
  1048. case SND_SEQ_EVENT_SENSING: // Active sensing
  1049. if ( !( data->ignoreFlags & 0x04 ) ) doDecode = true;
  1050. break;
  1051. case SND_SEQ_EVENT_SYSEX:
  1052. if ( (data->ignoreFlags & 0x01) ) break;
  1053. if ( ev->data.ext.len > apiData->bufferSize ) {
  1054. apiData->bufferSize = ev->data.ext.len;
  1055. free( buffer );
  1056. buffer = (unsigned char *) malloc( apiData->bufferSize );
  1057. if ( buffer == NULL ) {
  1058. data->doInput = false;
  1059. std::cerr << "\nMidiInAlsa::alsaMidiHandler: error resizing buffer memory!\n\n";
  1060. break;
  1061. }
  1062. }
  1063. default:
  1064. doDecode = true;
  1065. }
  1066. if ( doDecode ) {
  1067. nBytes = snd_midi_event_decode( apiData->coder, buffer, apiData->bufferSize, ev );
  1068. if ( nBytes > 0 ) {
  1069. // The ALSA sequencer has a maximum buffer size for MIDI sysex
  1070. // events of 256 bytes. If a device sends sysex messages larger
  1071. // than this, they are segmented into 256 byte chunks. So,
  1072. // we'll watch for this and concatenate sysex chunks into a
  1073. // single sysex message if necessary.
  1074. if ( !continueSysex )
  1075. message.bytes.assign( buffer, &buffer[nBytes] );
  1076. else
  1077. message.bytes.insert( message.bytes.end(), buffer, &buffer[nBytes] );
  1078. continueSysex = ( ( ev->type == SND_SEQ_EVENT_SYSEX ) && ( message.bytes.back() != 0xF7 ) );
  1079. if ( !continueSysex ) {
  1080. // Calculate the time stamp:
  1081. message.timeStamp = 0.0;
  1082. // Method 1: Use the system time.
  1083. //(void)gettimeofday(&tv, (struct timezone *)NULL);
  1084. //time = (tv.tv_sec * 1000000) + tv.tv_usec;
  1085. // Method 2: Use the ALSA sequencer event time data.
  1086. // (thanks to Pedro Lopez-Cabanillas!).
  1087. time = ( ev->time.time.tv_sec * 1000000 ) + ( ev->time.time.tv_nsec/1000 );
  1088. lastTime = time;
  1089. time -= apiData->lastTime;
  1090. apiData->lastTime = lastTime;
  1091. if ( data->firstMessage == true )
  1092. data->firstMessage = false;
  1093. else
  1094. message.timeStamp = time * 0.000001;
  1095. }
  1096. else {
  1097. #if defined(__RTMIDI_DEBUG__)
  1098. std::cerr << "\nMidiInAlsa::alsaMidiHandler: event parsing error or not a MIDI event!\n\n";
  1099. #endif
  1100. }
  1101. }
  1102. }
  1103. snd_seq_free_event( ev );
  1104. if ( message.bytes.size() == 0 || continueSysex ) continue;
  1105. if ( data->usingCallback ) {
  1106. RtMidiIn::RtMidiCallback callback = (RtMidiIn::RtMidiCallback) data->userCallback;
  1107. callback( message.timeStamp, &message.bytes, data->userData );
  1108. }
  1109. else {
  1110. // As long as we haven't reached our queue size limit, push the message.
  1111. if ( data->queue.size < data->queue.ringSize ) {
  1112. data->queue.ring[data->queue.back++] = message;
  1113. if ( data->queue.back == data->queue.ringSize )
  1114. data->queue.back = 0;
  1115. data->queue.size++;
  1116. }
  1117. else
  1118. std::cerr << "\nMidiInAlsa: message queue limit reached!!\n\n";
  1119. }
  1120. }
  1121. if ( buffer ) free( buffer );
  1122. snd_midi_event_free( apiData->coder );
  1123. apiData->coder = 0;
  1124. apiData->thread = apiData->dummy_thread_id;
  1125. return 0;
  1126. }
  1127. MidiInAlsa :: MidiInAlsa( const std::string clientName, unsigned int queueSizeLimit ) : MidiInApi( queueSizeLimit )
  1128. {
  1129. initialize( clientName );
  1130. }
  1131. MidiInAlsa :: ~MidiInAlsa()
  1132. {
  1133. // Close a connection if it exists.
  1134. closePort();
  1135. // Shutdown the input thread.
  1136. AlsaMidiData *data = static_cast<AlsaMidiData *> (apiData_);
  1137. if ( inputData_.doInput ) {
  1138. inputData_.doInput = false;
  1139. int res = write( data->trigger_fds[1], &inputData_.doInput, sizeof(inputData_.doInput) );
  1140. (void) res;
  1141. if ( !pthread_equal(data->thread, data->dummy_thread_id) )
  1142. pthread_join( data->thread, NULL );
  1143. }
  1144. // Cleanup.
  1145. close ( data->trigger_fds[0] );
  1146. close ( data->trigger_fds[1] );
  1147. if ( data->vport >= 0 ) snd_seq_delete_port( data->seq, data->vport );
  1148. #ifndef AVOID_TIMESTAMPING
  1149. snd_seq_free_queue( data->seq, data->queue_id );
  1150. #endif
  1151. freeSequencer();
  1152. delete data;
  1153. }
  1154. void MidiInAlsa :: initialize( const std::string& clientName )
  1155. {
  1156. snd_seq_t* seq = createSequencer( clientName );
  1157. if ( seq == NULL ) {
  1158. s_seq = NULL;
  1159. errorString_ = "MidiInAlsa::initialize: error creating ALSA sequencer client object.";
  1160. RtMidi::error( RtError::DRIVER_ERROR, errorString_ );
  1161. }
  1162. // Save our api-specific connection information.
  1163. AlsaMidiData *data = (AlsaMidiData *) new AlsaMidiData;
  1164. data->seq = seq;
  1165. data->portNum = -1;
  1166. data->vport = -1;
  1167. data->subscription = 0;
  1168. data->dummy_thread_id = pthread_self();
  1169. data->thread = data->dummy_thread_id;
  1170. data->trigger_fds[0] = -1;
  1171. data->trigger_fds[1] = -1;
  1172. apiData_ = (void *) data;
  1173. inputData_.apiData = (void *) data;
  1174. if ( pipe(data->trigger_fds) == -1 ) {
  1175. errorString_ = "MidiInAlsa::initialize: error creating pipe objects.";
  1176. RtMidi::error( RtError::DRIVER_ERROR, errorString_ );
  1177. }
  1178. // Create the input queue
  1179. #ifndef AVOID_TIMESTAMPING
  1180. data->queue_id = snd_seq_alloc_named_queue(s_seq, "RtMidi Queue");
  1181. // Set arbitrary tempo (mm=100) and resolution (240)
  1182. snd_seq_queue_tempo_t *qtempo;
  1183. snd_seq_queue_tempo_alloca(&qtempo);
  1184. snd_seq_queue_tempo_set_tempo(qtempo, 600000);
  1185. snd_seq_queue_tempo_set_ppq(qtempo, 240);
  1186. snd_seq_set_queue_tempo(data->seq, data->queue_id, qtempo);
  1187. snd_seq_drain_output(data->seq);
  1188. #endif
  1189. }
  1190. // This function is used to count or get the pinfo structure for a given port number.
  1191. unsigned int portInfo( snd_seq_t *seq, snd_seq_port_info_t *pinfo, unsigned int type, int portNumber )
  1192. {
  1193. snd_seq_client_info_t *cinfo;
  1194. int client;
  1195. int count = 0;
  1196. snd_seq_client_info_alloca( &cinfo );
  1197. snd_seq_client_info_set_client( cinfo, -1 );
  1198. while ( snd_seq_query_next_client( seq, cinfo ) >= 0 ) {
  1199. client = snd_seq_client_info_get_client( cinfo );
  1200. if ( client == 0 ) continue;
  1201. // Reset query info
  1202. snd_seq_port_info_set_client( pinfo, client );
  1203. snd_seq_port_info_set_port( pinfo, -1 );
  1204. while ( snd_seq_query_next_port( seq, pinfo ) >= 0 ) {
  1205. unsigned int atyp = snd_seq_port_info_get_type( pinfo );
  1206. if ( ( atyp & SND_SEQ_PORT_TYPE_MIDI_GENERIC ) == 0 ) continue;
  1207. unsigned int caps = snd_seq_port_info_get_capability( pinfo );
  1208. if ( ( caps & type ) != type ) continue;
  1209. if ( count == portNumber ) return 1;
  1210. ++count;
  1211. }
  1212. }
  1213. // If a negative portNumber was used, return the port count.
  1214. if ( portNumber < 0 ) return count;
  1215. return 0;
  1216. }
  1217. unsigned int MidiInAlsa :: getPortCount()
  1218. {
  1219. snd_seq_port_info_t *pinfo;
  1220. snd_seq_port_info_alloca( &pinfo );
  1221. AlsaMidiData *data = static_cast<AlsaMidiData *> (apiData_);
  1222. return portInfo( data->seq, pinfo, SND_SEQ_PORT_CAP_READ|SND_SEQ_PORT_CAP_SUBS_READ, -1 );
  1223. }
  1224. std::string MidiInAlsa :: getPortName( unsigned int portNumber )
  1225. {
  1226. snd_seq_client_info_t *cinfo;
  1227. snd_seq_port_info_t *pinfo;
  1228. snd_seq_client_info_alloca( &cinfo );
  1229. snd_seq_port_info_alloca( &pinfo );
  1230. std::string stringName;
  1231. AlsaMidiData *data = static_cast<AlsaMidiData *> (apiData_);
  1232. if ( portInfo( data->seq, pinfo, SND_SEQ_PORT_CAP_READ|SND_SEQ_PORT_CAP_SUBS_READ, (int) portNumber ) ) {
  1233. int cnum = snd_seq_port_info_get_client( pinfo );
  1234. snd_seq_get_any_client_info( data->seq, cnum, cinfo );
  1235. std::ostringstream os;
  1236. os << snd_seq_client_info_get_name( cinfo );
  1237. os << " "; // GO: These lines added to make sure devices are listed
  1238. os << snd_seq_port_info_get_client( pinfo ); // GO: with full portnames added to ensure individual device names
  1239. os << ":";
  1240. os << snd_seq_port_info_get_port( pinfo );
  1241. stringName = os.str();
  1242. return stringName;
  1243. }
  1244. // If we get here, we didn't find a match.
  1245. errorString_ = "MidiInAlsa::getPortName: error looking for port name!";
  1246. RtMidi::error( RtError::WARNING, errorString_ );
  1247. return stringName;
  1248. //RtMidi::error( RtError::INVALID_PARAMETER, errorString_ );
  1249. }
  1250. void MidiInAlsa :: openPort( unsigned int portNumber, const std::string portName )
  1251. {
  1252. if ( connected_ ) {
  1253. errorString_ = "MidiInAlsa::openPort: a valid connection already exists!";
  1254. RtMidi::error( RtError::WARNING, errorString_ );
  1255. return;
  1256. }
  1257. unsigned int nSrc = this->getPortCount();
  1258. if (nSrc < 1) {
  1259. errorString_ = "MidiInAlsa::openPort: no MIDI input sources found!";
  1260. RtMidi::error( RtError::NO_DEVICES_FOUND, errorString_ );
  1261. }
  1262. snd_seq_port_info_t *pinfo;
  1263. snd_seq_port_info_alloca( &pinfo );
  1264. std::ostringstream ost;
  1265. AlsaMidiData *data = static_cast<AlsaMidiData *> (apiData_);
  1266. if ( portInfo( data->seq, pinfo, SND_SEQ_PORT_CAP_READ|SND_SEQ_PORT_CAP_SUBS_READ, (int) portNumber ) == 0 ) {
  1267. ost << "MidiInAlsa::openPort: the 'portNumber' argument (" << portNumber << ") is invalid.";
  1268. errorString_ = ost.str();
  1269. RtMidi::error( RtError::INVALID_PARAMETER, errorString_ );
  1270. }
  1271. snd_seq_addr_t sender, receiver;
  1272. sender.client = snd_seq_port_info_get_client( pinfo );
  1273. sender.port = snd_seq_port_info_get_port( pinfo );
  1274. receiver.client = snd_seq_client_id( data->seq );
  1275. if ( data->vport < 0 ) {
  1276. snd_seq_port_info_set_client( pinfo, 0 );
  1277. snd_seq_port_info_set_port( pinfo, 0 );
  1278. snd_seq_port_info_set_capability( pinfo,
  1279. SND_SEQ_PORT_CAP_WRITE |
  1280. SND_SEQ_PORT_CAP_SUBS_WRITE );
  1281. snd_seq_port_info_set_type( pinfo,
  1282. SND_SEQ_PORT_TYPE_MIDI_GENERIC |
  1283. SND_SEQ_PORT_TYPE_APPLICATION );
  1284. snd_seq_port_info_set_midi_channels(pinfo, 16);
  1285. #ifndef AVOID_TIMESTAMPING
  1286. snd_seq_port_info_set_timestamping(pinfo, 1);
  1287. snd_seq_port_info_set_timestamp_real(pinfo, 1);
  1288. snd_seq_port_info_set_timestamp_queue(pinfo, data->queue_id);
  1289. #endif
  1290. snd_seq_port_info_set_name(pinfo, portName.c_str() );
  1291. data->vport = snd_seq_create_port(data->seq, pinfo);
  1292. if ( data->vport < 0 ) {
  1293. errorString_ = "MidiInAlsa::openPort: ALSA error creating input port.";
  1294. RtMidi::error( RtError::DRIVER_ERROR, errorString_ );
  1295. }
  1296. }
  1297. receiver.port = data->vport;
  1298. if ( !data->subscription ) {
  1299. // Make subscription
  1300. if (snd_seq_port_subscribe_malloc( &data->subscription ) < 0) {
  1301. errorString_ = "MidiInAlsa::openPort: ALSA error allocation port subscription.";
  1302. RtMidi::error( RtError::DRIVER_ERROR, errorString_ );
  1303. }
  1304. snd_seq_port_subscribe_set_sender(data->subscription, &sender);
  1305. snd_seq_port_subscribe_set_dest(data->subscription, &receiver);
  1306. if ( snd_seq_subscribe_port(data->seq, data->subscription) ) {
  1307. snd_seq_port_subscribe_free( data->subscription );
  1308. data->subscription = 0;
  1309. errorString_ = "MidiInAlsa::openPort: ALSA error making port connection.";
  1310. RtMidi::error( RtError::DRIVER_ERROR, errorString_ );
  1311. }
  1312. }
  1313. if ( inputData_.doInput == false ) {
  1314. // Start the input queue
  1315. #ifndef AVOID_TIMESTAMPING
  1316. snd_seq_start_queue( data->seq, data->queue_id, NULL );
  1317. snd_seq_drain_output( data->seq );
  1318. #endif
  1319. // Start our MIDI input thread.
  1320. pthread_attr_t attr;
  1321. pthread_attr_init(&attr);
  1322. pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
  1323. pthread_attr_setschedpolicy(&attr, SCHED_OTHER);
  1324. inputData_.doInput = true;
  1325. int err = pthread_create(&data->thread, &attr, alsaMidiHandler, &inputData_);
  1326. pthread_attr_destroy(&attr);
  1327. if ( err ) {
  1328. snd_seq_unsubscribe_port( data->seq, data->subscription );
  1329. snd_seq_port_subscribe_free( data->subscription );
  1330. data->subscription = 0;
  1331. inputData_.doInput = false;
  1332. errorString_ = "MidiInAlsa::openPort: error starting MIDI input thread!";
  1333. RtMidi::error( RtError::THREAD_ERROR, errorString_ );
  1334. }
  1335. }
  1336. connected_ = true;
  1337. }
  1338. void MidiInAlsa :: openVirtualPort( std::string portName )
  1339. {
  1340. AlsaMidiData *data = static_cast<AlsaMidiData *> (apiData_);
  1341. if ( data->vport < 0 ) {
  1342. snd_seq_port_info_t *pinfo;
  1343. snd_seq_port_info_alloca( &pinfo );
  1344. snd_seq_port_info_set_capability( pinfo,
  1345. SND_SEQ_PORT_CAP_WRITE |
  1346. SND_SEQ_PORT_CAP_SUBS_WRITE );
  1347. snd_seq_port_info_set_type( pinfo,
  1348. SND_SEQ_PORT_TYPE_MIDI_GENERIC |
  1349. SND_SEQ_PORT_TYPE_APPLICATION );
  1350. snd_seq_port_info_set_midi_channels(pinfo, 16);
  1351. #ifndef AVOID_TIMESTAMPING
  1352. snd_seq_port_info_set_timestamping(pinfo, 1);
  1353. snd_seq_port_info_set_timestamp_real(pinfo, 1);
  1354. snd_seq_port_info_set_timestamp_queue(pinfo, data->queue_id);
  1355. #endif
  1356. snd_seq_port_info_set_name(pinfo, portName.c_str());
  1357. data->vport = snd_seq_create_port(data->seq, pinfo);
  1358. if ( data->vport < 0 ) {
  1359. errorString_ = "MidiInAlsa::openVirtualPort: ALSA error creating virtual port.";
  1360. RtMidi::error( RtError::DRIVER_ERROR, errorString_ );
  1361. }
  1362. }
  1363. if ( inputData_.doInput == false ) {
  1364. // Wait for old thread to stop, if still running
  1365. if ( !pthread_equal(data->thread, data->dummy_thread_id) )
  1366. pthread_join( data->thread, NULL );
  1367. // Start the input queue
  1368. #ifndef AVOID_TIMESTAMPING
  1369. snd_seq_start_queue( data->seq, data->queue_id, NULL );
  1370. snd_seq_drain_output( data->seq );
  1371. #endif
  1372. // Start our MIDI input thread.
  1373. pthread_attr_t attr;
  1374. pthread_attr_init(&attr);
  1375. pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
  1376. pthread_attr_setschedpolicy(&attr, SCHED_OTHER);
  1377. inputData_.doInput = true;
  1378. int err = pthread_create(&data->thread, &attr, alsaMidiHandler, &inputData_);
  1379. pthread_attr_destroy(&attr);
  1380. if ( err ) {
  1381. if ( data->subscription ) {
  1382. snd_seq_unsubscribe_port( data->seq, data->subscription );
  1383. snd_seq_port_subscribe_free( data->subscription );
  1384. data->subscription = 0;
  1385. }
  1386. inputData_.doInput = false;
  1387. errorString_ = "MidiInAlsa::openPort: error starting MIDI input thread!";
  1388. RtMidi::error( RtError::THREAD_ERROR, errorString_ );
  1389. }
  1390. }
  1391. }
  1392. void MidiInAlsa :: closePort( void )
  1393. {
  1394. AlsaMidiData *data = static_cast<AlsaMidiData *> (apiData_);
  1395. if ( connected_ ) {
  1396. if ( data->subscription ) {
  1397. snd_seq_unsubscribe_port( data->seq, data->subscription );
  1398. snd_seq_port_subscribe_free( data->subscription );
  1399. data->subscription = 0;
  1400. }
  1401. // Stop the input queue
  1402. #ifndef AVOID_TIMESTAMPING
  1403. snd_seq_stop_queue( data->seq, data->queue_id, NULL );
  1404. snd_seq_drain_output( data->seq );
  1405. #endif
  1406. connected_ = false;
  1407. }
  1408. // Stop thread to avoid triggering the callback, while the port is intended to be closed
  1409. if ( inputData_.doInput ) {
  1410. inputData_.doInput = false;
  1411. int res = write( data->trigger_fds[1], &inputData_.doInput, sizeof(inputData_.doInput) );
  1412. (void) res;
  1413. if ( !pthread_equal(data->thread, data->dummy_thread_id) )
  1414. pthread_join( data->thread, NULL );
  1415. }
  1416. }
  1417. //*********************************************************************//
  1418. // API: LINUX ALSA
  1419. // Class Definitions: MidiOutAlsa
  1420. //*********************************************************************//
  1421. MidiOutAlsa :: MidiOutAlsa( const std::string clientName ) : MidiOutApi()
  1422. {
  1423. initialize( clientName );
  1424. }
  1425. MidiOutAlsa :: ~MidiOutAlsa()
  1426. {
  1427. // Close a connection if it exists.
  1428. closePort();
  1429. // Cleanup.
  1430. AlsaMidiData *data = static_cast<AlsaMidiData *> (apiData_);
  1431. if ( data->vport >= 0 ) snd_seq_delete_port( data->seq, data->vport );
  1432. if ( data->coder ) snd_midi_event_free( data->coder );
  1433. if ( data->buffer ) free( data->buffer );
  1434. freeSequencer();
  1435. delete data;
  1436. }
  1437. void MidiOutAlsa :: initialize( const std::string& clientName )
  1438. {
  1439. snd_seq_t* seq = createSequencer( clientName );
  1440. if ( seq == NULL ) {
  1441. s_seq = NULL;
  1442. errorString_ = "MidiOutAlsa::initialize: error creating ALSA sequencer client object.";
  1443. RtMidi::error( RtError::DRIVER_ERROR, errorString_ );
  1444. }
  1445. // Save our api-specific connection information.
  1446. AlsaMidiData *data = (AlsaMidiData *) new AlsaMidiData;
  1447. data->seq = seq;
  1448. data->portNum = -1;
  1449. data->vport = -1;
  1450. data->bufferSize = 32;
  1451. data->coder = 0;
  1452. data->buffer = 0;
  1453. int result = snd_midi_event_new( data->bufferSize, &data->coder );
  1454. if ( result < 0 ) {
  1455. delete data;
  1456. errorString_ = "MidiOutAlsa::initialize: error initializing MIDI event parser!\n\n";
  1457. RtMidi::error( RtError::DRIVER_ERROR, errorString_ );
  1458. }
  1459. data->buffer = (unsigned char *) malloc( data->bufferSize );
  1460. if ( data->buffer == NULL ) {
  1461. delete data;
  1462. errorString_ = "MidiOutAlsa::initialize: error allocating buffer memory!\n\n";
  1463. RtMidi::error( RtError::MEMORY_ERROR, errorString_ );
  1464. }
  1465. snd_midi_event_init( data->coder );
  1466. apiData_ = (void *) data;
  1467. }
  1468. unsigned int MidiOutAlsa :: getPortCount()
  1469. {
  1470. snd_seq_port_info_t *pinfo;
  1471. snd_seq_port_info_alloca( &pinfo );
  1472. AlsaMidiData *data = static_cast<AlsaMidiData *> (apiData_);
  1473. return portInfo( data->seq, pinfo, SND_SEQ_PORT_CAP_WRITE|SND_SEQ_PORT_CAP_SUBS_WRITE, -1 );
  1474. }
  1475. std::string MidiOutAlsa :: getPortName( unsigned int portNumber )
  1476. {
  1477. snd_seq_client_info_t *cinfo;
  1478. snd_seq_port_info_t *pinfo;
  1479. snd_seq_client_info_alloca( &cinfo );
  1480. snd_seq_port_info_alloca( &pinfo );
  1481. std::string stringName;
  1482. AlsaMidiData *data = static_cast<AlsaMidiData *> (apiData_);
  1483. if ( portInfo( data->seq, pinfo, SND_SEQ_PORT_CAP_WRITE|SND_SEQ_PORT_CAP_SUBS_WRITE, (int) portNumber ) ) {
  1484. int cnum = snd_seq_port_info_get_client(pinfo);
  1485. snd_seq_get_any_client_info( data->seq, cnum, cinfo );
  1486. std::ostringstream os;
  1487. os << snd_seq_client_info_get_name(cinfo);
  1488. os << ":";
  1489. os << snd_seq_port_info_get_port(pinfo);
  1490. stringName = os.str();
  1491. return stringName;
  1492. }
  1493. // If we get here, we didn't find a match.
  1494. errorString_ = "MidiOutAlsa::getPortName: error looking for port name!";
  1495. //RtMidi::error( RtError::INVALID_PARAMETER, errorString_ );
  1496. RtMidi::error( RtError::WARNING, errorString_ );
  1497. return stringName;
  1498. }
  1499. void MidiOutAlsa :: openPort( unsigned int portNumber, const std::string portName )
  1500. {
  1501. if ( connected_ ) {
  1502. errorString_ = "MidiOutAlsa::openPort: a valid connection already exists!";
  1503. RtMidi::error( RtError::WARNING, errorString_ );
  1504. return;
  1505. }
  1506. unsigned int nSrc = this->getPortCount();
  1507. if (nSrc < 1) {
  1508. errorString_ = "MidiOutAlsa::openPort: no MIDI output sources found!";
  1509. RtMidi::error( RtError::NO_DEVICES_FOUND, errorString_ );
  1510. }
  1511. snd_seq_port_info_t *pinfo;
  1512. snd_seq_port_info_alloca( &pinfo );
  1513. std::ostringstream ost;
  1514. AlsaMidiData *data = static_cast<AlsaMidiData *> (apiData_);
  1515. if ( portInfo( data->seq, pinfo, SND_SEQ_PORT_CAP_WRITE|SND_SEQ_PORT_CAP_SUBS_WRITE, (int) portNumber ) == 0 ) {
  1516. ost << "MidiOutAlsa::openPort: the 'portNumber' argument (" << portNumber << ") is invalid.";
  1517. errorString_ = ost.str();
  1518. RtMidi::error( RtError::INVALID_PARAMETER, errorString_ );
  1519. }
  1520. snd_seq_addr_t sender, receiver;
  1521. receiver.client = snd_seq_port_info_get_client( pinfo );
  1522. receiver.port = snd_seq_port_info_get_port( pinfo );
  1523. sender.client = snd_seq_client_id( data->seq );
  1524. if ( data->vport < 0 ) {
  1525. data->vport = snd_seq_create_simple_port( data->seq, portName.c_str(),
  1526. SND_SEQ_PORT_CAP_READ|SND_SEQ_PORT_CAP_SUBS_READ,
  1527. SND_SEQ_PORT_TYPE_MIDI_GENERIC|SND_SEQ_PORT_TYPE_APPLICATION );
  1528. if ( data->vport < 0 ) {
  1529. errorString_ = "MidiOutAlsa::openPort: ALSA error creating output port.";
  1530. RtMidi::error( RtError::DRIVER_ERROR, errorString_ );
  1531. }
  1532. }
  1533. sender.port = data->vport;
  1534. // Make subscription
  1535. if (snd_seq_port_subscribe_malloc( &data->subscription ) < 0) {
  1536. snd_seq_port_subscribe_free( data->subscription );
  1537. errorString_ = "MidiOutAlsa::openPort: error allocation port subscribtion.";
  1538. RtMidi::error( RtError::DRIVER_ERROR, errorString_ );
  1539. }
  1540. snd_seq_port_subscribe_set_sender(data->subscription, &sender);
  1541. snd_seq_port_subscribe_set_dest(data->subscription, &receiver);
  1542. snd_seq_port_subscribe_set_time_update(data->subscription, 1);
  1543. snd_seq_port_subscribe_set_time_real(data->subscription, 1);
  1544. if ( snd_seq_subscribe_port(data->seq, data->subscription) ) {
  1545. snd_seq_port_subscribe_free( data->subscription );
  1546. errorString_ = "MidiOutAlsa::openPort: ALSA error making port connection.";
  1547. RtMidi::error( RtError::DRIVER_ERROR, errorString_ );
  1548. }
  1549. connected_ = true;
  1550. }
  1551. void MidiOutAlsa :: closePort( void )
  1552. {
  1553. if ( connected_ ) {
  1554. AlsaMidiData *data = static_cast<AlsaMidiData *> (apiData_);
  1555. snd_seq_unsubscribe_port( data->seq, data->subscription );
  1556. snd_seq_port_subscribe_free( data->subscription );
  1557. connected_ = false;
  1558. }
  1559. }
  1560. void MidiOutAlsa :: openVirtualPort( std::string portName )
  1561. {
  1562. AlsaMidiData *data = static_cast<AlsaMidiData *> (apiData_);
  1563. if ( data->vport < 0 ) {
  1564. data->vport = snd_seq_create_simple_port( data->seq, portName.c_str(),
  1565. SND_SEQ_PORT_CAP_READ|SND_SEQ_PORT_CAP_SUBS_READ,
  1566. SND_SEQ_PORT_TYPE_MIDI_GENERIC|SND_SEQ_PORT_TYPE_APPLICATION );
  1567. if ( data->vport < 0 ) {
  1568. errorString_ = "MidiOutAlsa::openVirtualPort: ALSA error creating virtual port.";
  1569. RtMidi::error( RtError::DRIVER_ERROR, errorString_ );
  1570. }
  1571. }
  1572. }
  1573. void MidiOutAlsa :: sendMessage( std::vector<unsigned char> *message )
  1574. {
  1575. int result;
  1576. AlsaMidiData *data = static_cast<AlsaMidiData *> (apiData_);
  1577. unsigned int nBytes = message->size();
  1578. if ( nBytes > data->bufferSize ) {
  1579. data->bufferSize = nBytes;
  1580. result = snd_midi_event_resize_buffer ( data->coder, nBytes);
  1581. if ( result != 0 ) {
  1582. errorString_ = "MidiOutAlsa::sendMessage: ALSA error resizing MIDI event buffer.";
  1583. RtMidi::error( RtError::DRIVER_ERROR, errorString_ );
  1584. }
  1585. free (data->buffer);
  1586. data->buffer = (unsigned char *) malloc( data->bufferSize );
  1587. if ( data->buffer == NULL ) {
  1588. errorString_ = "MidiOutAlsa::initialize: error allocating buffer memory!\n\n";
  1589. RtMidi::error( RtError::MEMORY_ERROR, errorString_ );
  1590. }
  1591. }
  1592. snd_seq_event_t ev;
  1593. snd_seq_ev_clear(&ev);
  1594. snd_seq_ev_set_source(&ev, data->vport);
  1595. snd_seq_ev_set_subs(&ev);
  1596. snd_seq_ev_set_direct(&ev);
  1597. for ( unsigned int i=0; i<nBytes; ++i ) data->buffer[i] = message->at(i);
  1598. result = snd_midi_event_encode( data->coder, data->buffer, (long)nBytes, &ev );
  1599. if ( result < (int)nBytes ) {
  1600. errorString_ = "MidiOutAlsa::sendMessage: event parsing error!";
  1601. RtMidi::error( RtError::WARNING, errorString_ );
  1602. return;
  1603. }
  1604. // Send the event.
  1605. result = snd_seq_event_output(data->seq, &ev);
  1606. if ( result < 0 ) {
  1607. errorString_ = "MidiOutAlsa::sendMessage: error sending MIDI message to port.";
  1608. RtMidi::error( RtError::WARNING, errorString_ );
  1609. }
  1610. snd_seq_drain_output(data->seq);
  1611. }
  1612. #endif // __LINUX_ALSA__
  1613. //*********************************************************************//
  1614. // API: Windows Multimedia Library (MM)
  1615. //*********************************************************************//
  1616. // API information deciphered from:
  1617. // - http://msdn.microsoft.com/library/default.asp?url=/library/en-us/multimed/htm/_win32_midi_reference.asp
  1618. // Thanks to Jean-Baptiste Berruchon for the sysex code.
  1619. #if defined(__WINDOWS_MM__)
  1620. // The Windows MM API is based on the use of a callback function for
  1621. // MIDI input. We convert the system specific time stamps to delta
  1622. // time values.
  1623. // Windows MM MIDI header files.
  1624. #include <windows.h>
  1625. #include <mmsystem.h>
  1626. #define RT_SYSEX_BUFFER_SIZE 1024
  1627. #define RT_SYSEX_BUFFER_COUNT 4
  1628. // A structure to hold variables related to the CoreMIDI API
  1629. // implementation.
  1630. struct WinMidiData {
  1631. HMIDIIN inHandle; // Handle to Midi Input Device
  1632. HMIDIOUT outHandle; // Handle to Midi Output Device
  1633. DWORD lastTime;
  1634. MidiInApi::MidiMessage message;
  1635. LPMIDIHDR sysexBuffer[RT_SYSEX_BUFFER_COUNT];
  1636. };
  1637. //*********************************************************************//
  1638. // API: Windows MM
  1639. // Class Definitions: MidiInWinMM
  1640. //*********************************************************************//
  1641. static void CALLBACK midiInputCallback( HMIDIIN hmin,
  1642. UINT inputStatus,
  1643. DWORD_PTR instancePtr,
  1644. DWORD_PTR midiMessage,
  1645. DWORD timestamp )
  1646. {
  1647. if ( inputStatus != MIM_DATA && inputStatus != MIM_LONGDATA && inputStatus != MIM_LONGERROR ) return;
  1648. //MidiInApi::RtMidiInData *data = static_cast<MidiInApi::RtMidiInData *> (instancePtr);
  1649. MidiInApi::RtMidiInData *data = (MidiInApi::RtMidiInData *)instancePtr;
  1650. WinMidiData *apiData = static_cast<WinMidiData *> (data->apiData);
  1651. // Calculate time stamp.
  1652. if ( data->firstMessage == true ) {
  1653. apiData->message.timeStamp = 0.0;
  1654. data->firstMessage = false;
  1655. }
  1656. else apiData->message.timeStamp = (double) ( timestamp - apiData->lastTime ) * 0.001;
  1657. apiData->lastTime = timestamp;
  1658. if ( inputStatus == MIM_DATA ) { // Channel or system message
  1659. // Make sure the first byte is a status byte.
  1660. unsigned char status = (unsigned char) (midiMessage & 0x000000FF);
  1661. if ( !(status & 0x80) ) return;
  1662. // Determine the number of bytes in the MIDI message.
  1663. unsigned short nBytes = 1;
  1664. if ( status < 0xC0 ) nBytes = 3;
  1665. else if ( status < 0xE0 ) nBytes = 2;
  1666. else if ( status < 0xF0 ) nBytes = 3;
  1667. else if ( status == 0xF1 ) {
  1668. if ( data->ignoreFlags & 0x02 ) return;
  1669. else nBytes = 2;
  1670. }
  1671. else if ( status == 0xF2 ) nBytes = 3;
  1672. else if ( status == 0xF3 ) nBytes = 2;
  1673. else if ( status == 0xF8 && (data->ignoreFlags & 0x02) ) {
  1674. // A MIDI timing tick message and we're ignoring it.
  1675. return;
  1676. }
  1677. else if ( status == 0xFE && (data->ignoreFlags & 0x04) ) {
  1678. // A MIDI active sensing message and we're ignoring it.
  1679. return;
  1680. }
  1681. // Copy bytes to our MIDI message.
  1682. unsigned char *ptr = (unsigned char *) &midiMessage;
  1683. for ( int i=0; i<nBytes; ++i ) apiData->message.bytes.push_back( *ptr++ );
  1684. }
  1685. else { // Sysex message ( MIM_LONGDATA or MIM_LONGERROR )
  1686. MIDIHDR *sysex = ( MIDIHDR *) midiMessage;
  1687. if ( !( data->ignoreFlags & 0x01 ) && inputStatus != MIM_LONGERROR ) {
  1688. // Sysex message and we're not ignoring it
  1689. for ( int i=0; i<(int)sysex->dwBytesRecorded; ++i )
  1690. apiData->message.bytes.push_back( sysex->lpData[i] );
  1691. }
  1692. // The WinMM API requires that the sysex buffer be requeued after
  1693. // input of each sysex message. Even if we are ignoring sysex
  1694. // messages, we still need to requeue the buffer in case the user
  1695. // decides to not ignore sysex messages in the future. However,
  1696. // it seems that WinMM calls this function with an empty sysex
  1697. // buffer when an application closes and in this case, we should
  1698. // avoid requeueing it, else the computer suddenly reboots after
  1699. // one or two minutes.
  1700. if ( apiData->sysexBuffer[sysex->dwUser]->dwBytesRecorded > 0 ) {
  1701. //if ( sysex->dwBytesRecorded > 0 ) {
  1702. MMRESULT result = midiInAddBuffer( apiData->inHandle, apiData->sysexBuffer[sysex->dwUser], sizeof(MIDIHDR) );
  1703. if ( result != MMSYSERR_NOERROR )
  1704. std::cerr << "\nRtMidiIn::midiInputCallback: error sending sysex to Midi device!!\n\n";
  1705. if ( data->ignoreFlags & 0x01 ) return;
  1706. }
  1707. else return;
  1708. }
  1709. if ( data->usingCallback ) {
  1710. RtMidiIn::RtMidiCallback callback = (RtMidiIn::RtMidiCallback) data->userCallback;
  1711. callback( apiData->message.timeStamp, &apiData->message.bytes, data->userData );
  1712. }
  1713. else {
  1714. // As long as we haven't reached our queue size limit, push the message.
  1715. if ( data->queue.size < data->queue.ringSize ) {
  1716. data->queue.ring[data->queue.back++] = apiData->message;
  1717. if ( data->queue.back == data->queue.ringSize )
  1718. data->queue.back = 0;
  1719. data->queue.size++;
  1720. }
  1721. else
  1722. std::cerr << "\nRtMidiIn: message queue limit reached!!\n\n";
  1723. }
  1724. // Clear the vector for the next input message.
  1725. apiData->message.bytes.clear();
  1726. }
  1727. MidiInWinMM :: MidiInWinMM( const std::string clientName, unsigned int queueSizeLimit ) : MidiInApi( queueSizeLimit )
  1728. {
  1729. initialize( clientName );
  1730. }
  1731. MidiInWinMM :: ~MidiInWinMM()
  1732. {
  1733. // Close a connection if it exists.
  1734. closePort();
  1735. // Cleanup.
  1736. WinMidiData *data = static_cast<WinMidiData *> (apiData_);
  1737. delete data;
  1738. }
  1739. void MidiInWinMM :: initialize( const std::string& /*clientName*/ )
  1740. {
  1741. // We'll issue a warning here if no devices are available but not
  1742. // throw an error since the user can plugin something later.
  1743. unsigned int nDevices = midiInGetNumDevs();
  1744. if ( nDevices == 0 ) {
  1745. errorString_ = "MidiInWinMM::initialize: no MIDI input devices currently available.";
  1746. RtMidi::error( RtError::WARNING, errorString_ );
  1747. }
  1748. // Save our api-specific connection information.
  1749. WinMidiData *data = (WinMidiData *) new WinMidiData;
  1750. apiData_ = (void *) data;
  1751. inputData_.apiData = (void *) data;
  1752. data->message.bytes.clear(); // needs to be empty for first input message
  1753. }
  1754. void MidiInWinMM :: openPort( unsigned int portNumber, const std::string /*portName*/ )
  1755. {
  1756. if ( connected_ ) {
  1757. errorString_ = "MidiInWinMM::openPort: a valid connection already exists!";
  1758. RtMidi::error( RtError::WARNING, errorString_ );
  1759. return;
  1760. }
  1761. unsigned int nDevices = midiInGetNumDevs();
  1762. if (nDevices == 0) {
  1763. errorString_ = "MidiInWinMM::openPort: no MIDI input sources found!";
  1764. RtMidi::error( RtError::NO_DEVICES_FOUND, errorString_ );
  1765. }
  1766. std::ostringstream ost;
  1767. if ( portNumber >= nDevices ) {
  1768. ost << "MidiInWinMM::openPort: the 'portNumber' argument (" << portNumber << ") is invalid.";
  1769. errorString_ = ost.str();
  1770. RtMidi::error( RtError::INVALID_PARAMETER, errorString_ );
  1771. }
  1772. WinMidiData *data = static_cast<WinMidiData *> (apiData_);
  1773. MMRESULT result = midiInOpen( &data->inHandle,
  1774. portNumber,
  1775. (DWORD_PTR)&midiInputCallback,
  1776. (DWORD_PTR)&inputData_,
  1777. CALLBACK_FUNCTION );
  1778. if ( result != MMSYSERR_NOERROR ) {
  1779. errorString_ = "MidiInWinMM::openPort: error creating Windows MM MIDI input port.";
  1780. RtMidi::error( RtError::DRIVER_ERROR, errorString_ );
  1781. }
  1782. // Allocate and init the sysex buffers.
  1783. for ( int i=0; i<RT_SYSEX_BUFFER_COUNT; ++i ) {
  1784. data->sysexBuffer[i] = (MIDIHDR*) new char[ sizeof(MIDIHDR) ];
  1785. data->sysexBuffer[i]->lpData = new char[ RT_SYSEX_BUFFER_SIZE ];
  1786. data->sysexBuffer[i]->dwBufferLength = RT_SYSEX_BUFFER_SIZE;
  1787. data->sysexBuffer[i]->dwUser = i; // We use the dwUser parameter as buffer indicator
  1788. data->sysexBuffer[i]->dwFlags = 0;
  1789. result = midiInPrepareHeader( data->inHandle, data->sysexBuffer[i], sizeof(MIDIHDR) );
  1790. if ( result != MMSYSERR_NOERROR ) {
  1791. midiInClose( data->inHandle );
  1792. errorString_ = "MidiInWinMM::openPort: error starting Windows MM MIDI input port (PrepareHeader).";
  1793. RtMidi::error( RtError::DRIVER_ERROR, errorString_ );
  1794. }
  1795. // Register the buffer.
  1796. result = midiInAddBuffer( data->inHandle, data->sysexBuffer[i], sizeof(MIDIHDR) );
  1797. if ( result != MMSYSERR_NOERROR ) {
  1798. midiInClose( data->inHandle );
  1799. errorString_ = "MidiInWinMM::openPort: error starting Windows MM MIDI input port (AddBuffer).";
  1800. RtMidi::error( RtError::DRIVER_ERROR, errorString_ );
  1801. }
  1802. }
  1803. result = midiInStart( data->inHandle );
  1804. if ( result != MMSYSERR_NOERROR ) {
  1805. midiInClose( data->inHandle );
  1806. errorString_ = "MidiInWinMM::openPort: error starting Windows MM MIDI input port.";
  1807. RtMidi::error( RtError::DRIVER_ERROR, errorString_ );
  1808. }
  1809. connected_ = true;
  1810. }
  1811. void MidiInWinMM :: openVirtualPort( std::string portName )
  1812. {
  1813. // This function cannot be implemented for the Windows MM MIDI API.
  1814. errorString_ = "MidiInWinMM::openVirtualPort: cannot be implemented in Windows MM MIDI API!";
  1815. RtMidi::error( RtError::WARNING, errorString_ );
  1816. }
  1817. void MidiInWinMM :: closePort( void )
  1818. {
  1819. if ( connected_ ) {
  1820. WinMidiData *data = static_cast<WinMidiData *> (apiData_);
  1821. midiInReset( data->inHandle );
  1822. midiInStop( data->inHandle );
  1823. for ( int i=0; i<RT_SYSEX_BUFFER_COUNT; ++i ) {
  1824. int result = midiInUnprepareHeader(data->inHandle, data->sysexBuffer[i], sizeof(MIDIHDR));
  1825. delete [] data->sysexBuffer[i]->lpData;
  1826. delete [] data->sysexBuffer[i];
  1827. if ( result != MMSYSERR_NOERROR ) {
  1828. midiInClose( data->inHandle );
  1829. errorString_ = "MidiInWinMM::openPort: error closing Windows MM MIDI input port (midiInUnprepareHeader).";
  1830. RtMidi::error( RtError::DRIVER_ERROR, errorString_ );
  1831. }
  1832. }
  1833. midiInClose( data->inHandle );
  1834. connected_ = false;
  1835. }
  1836. }
  1837. unsigned int MidiInWinMM :: getPortCount()
  1838. {
  1839. return midiInGetNumDevs();
  1840. }
  1841. std::string MidiInWinMM :: getPortName( unsigned int portNumber )
  1842. {
  1843. std::string stringName;
  1844. unsigned int nDevices = midiInGetNumDevs();
  1845. if ( portNumber >= nDevices ) {
  1846. std::ostringstream ost;
  1847. ost << "MidiInWinMM::getPortName: the 'portNumber' argument (" << portNumber << ") is invalid.";
  1848. errorString_ = ost.str();
  1849. //RtMidi::error( RtError::INVALID_PARAMETER, errorString_ );
  1850. RtMidi::error( RtError::WARNING, errorString_ );
  1851. return stringName;
  1852. }
  1853. MIDIINCAPS deviceCaps;
  1854. midiInGetDevCaps( portNumber, &deviceCaps, sizeof(MIDIINCAPS));
  1855. #if defined( UNICODE ) || defined( _UNICODE )
  1856. int length = WideCharToMultiByte(CP_UTF8, 0, deviceCaps.szPname, -1, NULL, 0, NULL, NULL);
  1857. stringName.assign( length, 0 );
  1858. length = WideCharToMultiByte(CP_UTF8, 0, deviceCaps.szPname, wcslen(deviceCaps.szPname), &stringName[0], length, NULL, NULL);
  1859. #else
  1860. stringName = std::string( deviceCaps.szPname );
  1861. #endif
  1862. // Next lines added to add the portNumber to the name so that
  1863. // the device's names are sure to be listed with individual names
  1864. // even when they have the same brand name
  1865. std::ostringstream os;
  1866. os << " ";
  1867. os << portNumber;
  1868. stringName += os.str();
  1869. return stringName;
  1870. }
  1871. //*********************************************************************//
  1872. // API: Windows MM
  1873. // Class Definitions: MidiOutWinMM
  1874. //*********************************************************************//
  1875. MidiOutWinMM :: MidiOutWinMM( const std::string clientName ) : MidiOutApi()
  1876. {
  1877. initialize( clientName );
  1878. }
  1879. MidiOutWinMM :: ~MidiOutWinMM()
  1880. {
  1881. // Close a connection if it exists.
  1882. closePort();
  1883. // Cleanup.
  1884. WinMidiData *data = static_cast<WinMidiData *> (apiData_);
  1885. delete data;
  1886. }
  1887. void MidiOutWinMM :: initialize( const std::string& /*clientName*/ )
  1888. {
  1889. // We'll issue a warning here if no devices are available but not
  1890. // throw an error since the user can plug something in later.
  1891. unsigned int nDevices = midiOutGetNumDevs();
  1892. if ( nDevices == 0 ) {
  1893. errorString_ = "MidiOutWinMM::initialize: no MIDI output devices currently available.";
  1894. RtMidi::error( RtError::WARNING, errorString_ );
  1895. }
  1896. // Save our api-specific connection information.
  1897. WinMidiData *data = (WinMidiData *) new WinMidiData;
  1898. apiData_ = (void *) data;
  1899. }
  1900. unsigned int MidiOutWinMM :: getPortCount()
  1901. {
  1902. return midiOutGetNumDevs();
  1903. }
  1904. std::string MidiOutWinMM :: getPortName( unsigned int portNumber )
  1905. {
  1906. std::string stringName;
  1907. unsigned int nDevices = midiOutGetNumDevs();
  1908. if ( portNumber >= nDevices ) {
  1909. std::ostringstream ost;
  1910. ost << "MidiOutWinMM::getPortName: the 'portNumber' argument (" << portNumber << ") is invalid.";
  1911. errorString_ = ost.str();
  1912. //RtMidi::error( RtError::INVALID_PARAMETER, errorString_ );
  1913. RtMidi::error( RtError::WARNING, errorString_ );
  1914. return stringName;
  1915. }
  1916. MIDIOUTCAPS deviceCaps;
  1917. midiOutGetDevCaps( portNumber, &deviceCaps, sizeof(MIDIOUTCAPS));
  1918. #if defined( UNICODE ) || defined( _UNICODE )
  1919. int length = WideCharToMultiByte(CP_UTF8, 0, deviceCaps.szPname, -1, NULL, 0, NULL, NULL);
  1920. stringName.assign( length, 0 );
  1921. length = WideCharToMultiByte(CP_UTF8, 0, deviceCaps.szPname, wcslen(deviceCaps.szPname), &stringName[0], length, NULL, NULL);
  1922. #else
  1923. stringName = std::string( deviceCaps.szPname );
  1924. #endif
  1925. return stringName;
  1926. }
  1927. void MidiOutWinMM :: openPort( unsigned int portNumber, const std::string /*portName*/ )
  1928. {
  1929. if ( connected_ ) {
  1930. errorString_ = "MidiOutWinMM::openPort: a valid connection already exists!";
  1931. RtMidi::error( RtError::WARNING, errorString_ );
  1932. return;
  1933. }
  1934. unsigned int nDevices = midiOutGetNumDevs();
  1935. if (nDevices < 1) {
  1936. errorString_ = "MidiOutWinMM::openPort: no MIDI output destinations found!";
  1937. RtMidi::error( RtError::NO_DEVICES_FOUND, errorString_ );
  1938. }
  1939. std::ostringstream ost;
  1940. if ( portNumber >= nDevices ) {
  1941. ost << "MidiOutWinMM::openPort: the 'portNumber' argument (" << portNumber << ") is invalid.";
  1942. errorString_ = ost.str();
  1943. RtMidi::error( RtError::INVALID_PARAMETER, errorString_ );
  1944. }
  1945. WinMidiData *data = static_cast<WinMidiData *> (apiData_);
  1946. MMRESULT result = midiOutOpen( &data->outHandle,
  1947. portNumber,
  1948. (DWORD)NULL,
  1949. (DWORD)NULL,
  1950. CALLBACK_NULL );
  1951. if ( result != MMSYSERR_NOERROR ) {
  1952. errorString_ = "MidiOutWinMM::openPort: error creating Windows MM MIDI output port.";
  1953. RtMidi::error( RtError::DRIVER_ERROR, errorString_ );
  1954. }
  1955. connected_ = true;
  1956. }
  1957. void MidiOutWinMM :: closePort( void )
  1958. {
  1959. if ( connected_ ) {
  1960. WinMidiData *data = static_cast<WinMidiData *> (apiData_);
  1961. midiOutReset( data->outHandle );
  1962. midiOutClose( data->outHandle );
  1963. connected_ = false;
  1964. }
  1965. }
  1966. void MidiOutWinMM :: openVirtualPort( std::string portName )
  1967. {
  1968. // This function cannot be implemented for the Windows MM MIDI API.
  1969. errorString_ = "MidiOutWinMM::openVirtualPort: cannot be implemented in Windows MM MIDI API!";
  1970. RtMidi::error( RtError::WARNING, errorString_ );
  1971. }
  1972. void MidiOutWinMM :: sendMessage( std::vector<unsigned char> *message )
  1973. {
  1974. unsigned int nBytes = static_cast<unsigned int>(message->size());
  1975. if ( nBytes == 0 ) {
  1976. errorString_ = "MidiOutWinMM::sendMessage: message argument is empty!";
  1977. RtMidi::error( RtError::WARNING, errorString_ );
  1978. return;
  1979. }
  1980. MMRESULT result;
  1981. WinMidiData *data = static_cast<WinMidiData *> (apiData_);
  1982. if ( message->at(0) == 0xF0 ) { // Sysex message
  1983. // Allocate buffer for sysex data.
  1984. char *buffer = (char *) malloc( nBytes );
  1985. if ( buffer == NULL ) {
  1986. errorString_ = "MidiOutWinMM::sendMessage: error allocating sysex message memory!";
  1987. RtMidi::error( RtError::MEMORY_ERROR, errorString_ );
  1988. }
  1989. // Copy data to buffer.
  1990. for ( unsigned int i=0; i<nBytes; ++i ) buffer[i] = message->at(i);
  1991. // Create and prepare MIDIHDR structure.
  1992. MIDIHDR sysex;
  1993. sysex.lpData = (LPSTR) buffer;
  1994. sysex.dwBufferLength = nBytes;
  1995. sysex.dwFlags = 0;
  1996. result = midiOutPrepareHeader( data->outHandle, &sysex, sizeof(MIDIHDR) );
  1997. if ( result != MMSYSERR_NOERROR ) {
  1998. free( buffer );
  1999. errorString_ = "MidiOutWinMM::sendMessage: error preparing sysex header.";
  2000. RtMidi::error( RtError::DRIVER_ERROR, errorString_ );
  2001. }
  2002. // Send the message.
  2003. result = midiOutLongMsg( data->outHandle, &sysex, sizeof(MIDIHDR) );
  2004. if ( result != MMSYSERR_NOERROR ) {
  2005. free( buffer );
  2006. errorString_ = "MidiOutWinMM::sendMessage: error sending sysex message.";
  2007. RtMidi::error( RtError::DRIVER_ERROR, errorString_ );
  2008. }
  2009. // Unprepare the buffer and MIDIHDR.
  2010. while ( MIDIERR_STILLPLAYING == midiOutUnprepareHeader( data->outHandle, &sysex, sizeof (MIDIHDR) ) ) Sleep( 1 );
  2011. free( buffer );
  2012. }
  2013. else { // Channel or system message.
  2014. // Make sure the message size isn't too big.
  2015. if ( nBytes > 3 ) {
  2016. errorString_ = "MidiOutWinMM::sendMessage: message size is greater than 3 bytes (and not sysex)!";
  2017. RtMidi::error( RtError::WARNING, errorString_ );
  2018. return;
  2019. }
  2020. // Pack MIDI bytes into double word.
  2021. DWORD packet;
  2022. unsigned char *ptr = (unsigned char *) &packet;
  2023. for ( unsigned int i=0; i<nBytes; ++i ) {
  2024. *ptr = message->at(i);
  2025. ++ptr;
  2026. }
  2027. // Send the message immediately.
  2028. result = midiOutShortMsg( data->outHandle, packet );
  2029. if ( result != MMSYSERR_NOERROR ) {
  2030. errorString_ = "MidiOutWinMM::sendMessage: error sending MIDI message.";
  2031. RtMidi::error( RtError::DRIVER_ERROR, errorString_ );
  2032. }
  2033. }
  2034. }
  2035. #endif // __WINDOWS_MM__
  2036. // *********************************************************************//
  2037. // API: WINDOWS Kernel Streaming
  2038. //
  2039. // Written by Sebastien Alaiwan, 2012.
  2040. //
  2041. // NOTE BY GARY: much of the KS-specific code below probably should go in a separate file.
  2042. //
  2043. // *********************************************************************//
  2044. #if defined(__WINDOWS_KS__)
  2045. #include <string>
  2046. #include <vector>
  2047. #include <memory>
  2048. #include <stdexcept>
  2049. #include <sstream>
  2050. #include <windows.h>
  2051. #include <setupapi.h>
  2052. #include <mmsystem.h>
  2053. #include "ks.h"
  2054. #include "ksmedia.h"
  2055. #define INSTANTIATE_GUID(a) GUID const a = { STATIC_ ## a }
  2056. INSTANTIATE_GUID(GUID_NULL);
  2057. INSTANTIATE_GUID(KSPROPSETID_Pin);
  2058. INSTANTIATE_GUID(KSPROPSETID_Connection);
  2059. INSTANTIATE_GUID(KSPROPSETID_Topology);
  2060. INSTANTIATE_GUID(KSINTERFACESETID_Standard);
  2061. INSTANTIATE_GUID(KSMEDIUMSETID_Standard);
  2062. INSTANTIATE_GUID(KSDATAFORMAT_TYPE_MUSIC);
  2063. INSTANTIATE_GUID(KSDATAFORMAT_SUBTYPE_MIDI);
  2064. INSTANTIATE_GUID(KSDATAFORMAT_SPECIFIER_NONE);
  2065. #undef INSTANTIATE_GUID
  2066. typedef std::basic_string<TCHAR> tstring;
  2067. inline bool IsValid(HANDLE handle)
  2068. {
  2069. return handle != NULL && handle != INVALID_HANDLE_VALUE;
  2070. }
  2071. class ComException : public std::runtime_error
  2072. {
  2073. private:
  2074. static std::string MakeString(std::string const& s, HRESULT hr)
  2075. {
  2076. std::stringstream ss;
  2077. ss << "(error 0x" << std::hex << hr << ")";
  2078. return s + ss.str();
  2079. }
  2080. public:
  2081. ComException(std::string const& s, HRESULT hr) :
  2082. std::runtime_error(MakeString(s, hr))
  2083. {
  2084. }
  2085. };
  2086. template<typename TFilterType>
  2087. class CKsEnumFilters
  2088. {
  2089. public:
  2090. ~CKsEnumFilters()
  2091. {
  2092. DestroyLists();
  2093. }
  2094. void EnumFilters(GUID const* categories, size_t numCategories)
  2095. {
  2096. DestroyLists();
  2097. if (categories == 0)
  2098. throw std::runtime_error("CKsEnumFilters: invalid argument");
  2099. // Get a handle to the device set specified by the guid
  2100. HDEVINFO hDevInfo = ::SetupDiGetClassDevs(&categories[0], NULL, NULL, DIGCF_PRESENT | DIGCF_DEVICEINTERFACE);
  2101. if (!IsValid(hDevInfo))
  2102. throw std::runtime_error("CKsEnumFilters: no devices found");
  2103. // Loop through members of the set and get details for each
  2104. for (int iClassMember=0;;iClassMember++) {
  2105. try {
  2106. SP_DEVICE_INTERFACE_DATA DID;
  2107. DID.cbSize = sizeof(DID);
  2108. DID.Reserved = 0;
  2109. bool fRes = ::SetupDiEnumDeviceInterfaces(hDevInfo, NULL, &categories[0], iClassMember, &DID);
  2110. if (!fRes)
  2111. break;
  2112. // Get filter friendly name
  2113. HKEY hRegKey = ::SetupDiOpenDeviceInterfaceRegKey(hDevInfo, &DID, 0, KEY_READ);
  2114. if (hRegKey == INVALID_HANDLE_VALUE)
  2115. throw std::runtime_error("CKsEnumFilters: interface has no registry");
  2116. char friendlyName[256];
  2117. DWORD dwSize = sizeof friendlyName;
  2118. LONG lval = ::RegQueryValueEx(hRegKey, TEXT("FriendlyName"), NULL, NULL, (LPBYTE)friendlyName, &dwSize);
  2119. ::RegCloseKey(hRegKey);
  2120. if (lval != ERROR_SUCCESS)
  2121. throw std::runtime_error("CKsEnumFilters: interface has no friendly name");
  2122. // Get details for the device registered in this class
  2123. DWORD const cbItfDetails = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA) + MAX_PATH * sizeof(WCHAR);
  2124. std::vector<BYTE> buffer(cbItfDetails);
  2125. SP_DEVICE_INTERFACE_DETAIL_DATA* pDevInterfaceDetails = reinterpret_cast<SP_DEVICE_INTERFACE_DETAIL_DATA*>(&buffer[0]);
  2126. pDevInterfaceDetails->cbSize = sizeof(*pDevInterfaceDetails);
  2127. SP_DEVINFO_DATA DevInfoData;
  2128. DevInfoData.cbSize = sizeof(DevInfoData);
  2129. DevInfoData.Reserved = 0;
  2130. fRes = ::SetupDiGetDeviceInterfaceDetail(hDevInfo, &DID, pDevInterfaceDetails, cbItfDetails, NULL, &DevInfoData);
  2131. if (!fRes)
  2132. throw std::runtime_error("CKsEnumFilters: could not get interface details");
  2133. // check additional category guids which may (or may not) have been supplied
  2134. for (size_t i=1; i < numCategories; ++i) {
  2135. SP_DEVICE_INTERFACE_DATA DIDAlias;
  2136. DIDAlias.cbSize = sizeof(DIDAlias);
  2137. DIDAlias.Reserved = 0;
  2138. fRes = ::SetupDiGetDeviceInterfaceAlias(hDevInfo, &DID, &categories[i], &DIDAlias);
  2139. if (!fRes)
  2140. throw std::runtime_error("CKsEnumFilters: could not get interface alias");
  2141. // Check if the this interface alias is enabled.
  2142. if (!DIDAlias.Flags || (DIDAlias.Flags & SPINT_REMOVED))
  2143. throw std::runtime_error("CKsEnumFilters: interface alias is not enabled");
  2144. }
  2145. std::auto_ptr<TFilterType> pFilter(new TFilterType(pDevInterfaceDetails->DevicePath, friendlyName));
  2146. pFilter->Instantiate();
  2147. pFilter->FindMidiPins();
  2148. pFilter->Validate();
  2149. m_Filters.push_back(pFilter.release());
  2150. }
  2151. catch (std::runtime_error const& e) {
  2152. }
  2153. }
  2154. ::SetupDiDestroyDeviceInfoList(hDevInfo);
  2155. }
  2156. private:
  2157. void DestroyLists()
  2158. {
  2159. for (size_t i=0;i < m_Filters.size();++i)
  2160. delete m_Filters[i];
  2161. m_Filters.clear();
  2162. }
  2163. public:
  2164. // TODO: make this private.
  2165. std::vector<TFilterType*> m_Filters;
  2166. };
  2167. class CKsObject
  2168. {
  2169. public:
  2170. CKsObject(HANDLE handle) : m_handle(handle)
  2171. {
  2172. }
  2173. protected:
  2174. HANDLE m_handle;
  2175. void SetProperty(REFGUID guidPropertySet, ULONG nProperty, void* pvValue, ULONG cbValue)
  2176. {
  2177. KSPROPERTY ksProperty;
  2178. memset(&ksProperty, 0, sizeof ksProperty);
  2179. ksProperty.Set = guidPropertySet;
  2180. ksProperty.Id = nProperty;
  2181. ksProperty.Flags = KSPROPERTY_TYPE_SET;
  2182. HRESULT hr = DeviceIoControlKsProperty(ksProperty, pvValue, cbValue);
  2183. if (FAILED(hr))
  2184. throw ComException("CKsObject::SetProperty: could not set property", hr);
  2185. }
  2186. private:
  2187. HRESULT DeviceIoControlKsProperty(KSPROPERTY& ksProperty, void* pvValue, ULONG cbValue)
  2188. {
  2189. ULONG ulReturned;
  2190. return ::DeviceIoControl(
  2191. m_handle,
  2192. IOCTL_KS_PROPERTY,
  2193. &ksProperty,
  2194. sizeof(ksProperty),
  2195. pvValue,
  2196. cbValue,
  2197. &ulReturned,
  2198. NULL);
  2199. }
  2200. };
  2201. class CKsPin;
  2202. class CKsFilter : public CKsObject
  2203. {
  2204. friend class CKsPin;
  2205. public:
  2206. CKsFilter(tstring const& name, std::string const& sFriendlyName);
  2207. virtual ~CKsFilter();
  2208. virtual void Instantiate();
  2209. template<typename T>
  2210. T GetPinProperty(ULONG nPinId, ULONG nProperty)
  2211. {
  2212. ULONG ulReturned = 0;
  2213. T value;
  2214. KSP_PIN ksPProp;
  2215. ksPProp.Property.Set = KSPROPSETID_Pin;
  2216. ksPProp.Property.Id = nProperty;
  2217. ksPProp.Property.Flags = KSPROPERTY_TYPE_GET;
  2218. ksPProp.PinId = nPinId;
  2219. ksPProp.Reserved = 0;
  2220. HRESULT hr = ::DeviceIoControl(
  2221. m_handle,
  2222. IOCTL_KS_PROPERTY,
  2223. &ksPProp,
  2224. sizeof(KSP_PIN),
  2225. &value,
  2226. sizeof(value),
  2227. &ulReturned,
  2228. NULL);
  2229. if (FAILED(hr))
  2230. throw ComException("CKsFilter::GetPinProperty: failed to retrieve property", hr);
  2231. return value;
  2232. }
  2233. void GetPinPropertyMulti(ULONG nPinId, REFGUID guidPropertySet, ULONG nProperty, PKSMULTIPLE_ITEM* ppKsMultipleItem)
  2234. {
  2235. HRESULT hr;
  2236. KSP_PIN ksPProp;
  2237. ksPProp.Property.Set = guidPropertySet;
  2238. ksPProp.Property.Id = nProperty;
  2239. ksPProp.Property.Flags = KSPROPERTY_TYPE_GET;
  2240. ksPProp.PinId = nPinId;
  2241. ksPProp.Reserved = 0;
  2242. ULONG cbMultipleItem = 0;
  2243. hr = ::DeviceIoControl(m_handle,
  2244. IOCTL_KS_PROPERTY,
  2245. &ksPProp.Property,
  2246. sizeof(KSP_PIN),
  2247. NULL,
  2248. 0,
  2249. &cbMultipleItem,
  2250. NULL);
  2251. if (FAILED(hr))
  2252. throw ComException("CKsFilter::GetPinPropertyMulti: cannot get property", hr);
  2253. *ppKsMultipleItem = (PKSMULTIPLE_ITEM) new BYTE[cbMultipleItem];
  2254. ULONG ulReturned = 0;
  2255. hr = ::DeviceIoControl(
  2256. m_handle,
  2257. IOCTL_KS_PROPERTY,
  2258. &ksPProp,
  2259. sizeof(KSP_PIN),
  2260. (PVOID)*ppKsMultipleItem,
  2261. cbMultipleItem,
  2262. &ulReturned,
  2263. NULL);
  2264. if (FAILED(hr))
  2265. throw ComException("CKsFilter::GetPinPropertyMulti: cannot get property", hr);
  2266. }
  2267. std::string const& GetFriendlyName() const
  2268. {
  2269. return m_sFriendlyName;
  2270. }
  2271. protected:
  2272. std::vector<CKsPin*> m_Pins; // this list owns the pins.
  2273. std::vector<CKsPin*> m_RenderPins;
  2274. std::vector<CKsPin*> m_CapturePins;
  2275. private:
  2276. std::string const m_sFriendlyName; // friendly name eg "Virus TI Synth"
  2277. tstring const m_sName; // Filter path, eg "\\?\usb#vid_133e&pid_0815...\vtimidi02"
  2278. };
  2279. class CKsPin : public CKsObject
  2280. {
  2281. public:
  2282. CKsPin(CKsFilter* pFilter, ULONG nId);
  2283. virtual ~CKsPin();
  2284. virtual void Instantiate();
  2285. void ClosePin();
  2286. void SetState(KSSTATE ksState);
  2287. void WriteData(KSSTREAM_HEADER* pKSSTREAM_HEADER, OVERLAPPED* pOVERLAPPED);
  2288. void ReadData(KSSTREAM_HEADER* pKSSTREAM_HEADER, OVERLAPPED* pOVERLAPPED);
  2289. KSPIN_DATAFLOW GetDataFlow() const
  2290. {
  2291. return m_DataFlow;
  2292. }
  2293. bool IsSink() const
  2294. {
  2295. return m_Communication == KSPIN_COMMUNICATION_SINK
  2296. || m_Communication == KSPIN_COMMUNICATION_BOTH;
  2297. }
  2298. protected:
  2299. PKSPIN_CONNECT m_pKsPinConnect; // creation parameters of pin
  2300. CKsFilter* const m_pFilter;
  2301. ULONG m_cInterfaces;
  2302. PKSIDENTIFIER m_pInterfaces;
  2303. PKSMULTIPLE_ITEM m_pmiInterfaces;
  2304. ULONG m_cMediums;
  2305. PKSIDENTIFIER m_pMediums;
  2306. PKSMULTIPLE_ITEM m_pmiMediums;
  2307. ULONG m_cDataRanges;
  2308. PKSDATARANGE m_pDataRanges;
  2309. PKSMULTIPLE_ITEM m_pmiDataRanges;
  2310. KSPIN_DATAFLOW m_DataFlow;
  2311. KSPIN_COMMUNICATION m_Communication;
  2312. };
  2313. CKsFilter::CKsFilter(tstring const& sName, std::string const& sFriendlyName) :
  2314. CKsObject(INVALID_HANDLE_VALUE),
  2315. m_sFriendlyName(sFriendlyName),
  2316. m_sName(sName)
  2317. {
  2318. if (sName.empty())
  2319. throw std::runtime_error("CKsFilter::CKsFilter: name can't be empty");
  2320. }
  2321. CKsFilter::~CKsFilter()
  2322. {
  2323. for (size_t i=0;i < m_Pins.size();++i)
  2324. delete m_Pins[i];
  2325. if (IsValid(m_handle))
  2326. ::CloseHandle(m_handle);
  2327. }
  2328. void CKsFilter::Instantiate()
  2329. {
  2330. m_handle = CreateFile(
  2331. m_sName.c_str(),
  2332. GENERIC_READ | GENERIC_WRITE,
  2333. 0,
  2334. NULL,
  2335. OPEN_EXISTING,
  2336. FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED,
  2337. NULL);
  2338. if (!IsValid(m_handle))
  2339. {
  2340. DWORD const dwError = GetLastError();
  2341. throw ComException("CKsFilter::Instantiate: can't open driver", HRESULT_FROM_WIN32(dwError));
  2342. }
  2343. }
  2344. CKsPin::CKsPin(CKsFilter* pFilter, ULONG PinId) :
  2345. CKsObject(INVALID_HANDLE_VALUE),
  2346. m_pKsPinConnect(NULL),
  2347. m_pFilter(pFilter)
  2348. {
  2349. m_Communication = m_pFilter->GetPinProperty<KSPIN_COMMUNICATION>(PinId, KSPROPERTY_PIN_COMMUNICATION);
  2350. m_DataFlow = m_pFilter->GetPinProperty<KSPIN_DATAFLOW>(PinId, KSPROPERTY_PIN_DATAFLOW);
  2351. // Interfaces
  2352. m_pFilter->GetPinPropertyMulti(
  2353. PinId,
  2354. KSPROPSETID_Pin,
  2355. KSPROPERTY_PIN_INTERFACES,
  2356. &m_pmiInterfaces);
  2357. m_cInterfaces = m_pmiInterfaces->Count;
  2358. m_pInterfaces = (PKSPIN_INTERFACE)(m_pmiInterfaces + 1);
  2359. // Mediums
  2360. m_pFilter->GetPinPropertyMulti(
  2361. PinId,
  2362. KSPROPSETID_Pin,
  2363. KSPROPERTY_PIN_MEDIUMS,
  2364. &m_pmiMediums);
  2365. m_cMediums = m_pmiMediums->Count;
  2366. m_pMediums = (PKSPIN_MEDIUM)(m_pmiMediums + 1);
  2367. // Data ranges
  2368. m_pFilter->GetPinPropertyMulti(
  2369. PinId,
  2370. KSPROPSETID_Pin,
  2371. KSPROPERTY_PIN_DATARANGES,
  2372. &m_pmiDataRanges);
  2373. m_cDataRanges = m_pmiDataRanges->Count;
  2374. m_pDataRanges = (PKSDATARANGE)(m_pmiDataRanges + 1);
  2375. }
  2376. CKsPin::~CKsPin()
  2377. {
  2378. ClosePin();
  2379. delete[] (BYTE*)m_pKsPinConnect;
  2380. delete[] (BYTE*)m_pmiDataRanges;
  2381. delete[] (BYTE*)m_pmiInterfaces;
  2382. delete[] (BYTE*)m_pmiMediums;
  2383. }
  2384. void CKsPin::ClosePin()
  2385. {
  2386. if (IsValid(m_handle)) {
  2387. SetState(KSSTATE_STOP);
  2388. ::CloseHandle(m_handle);
  2389. }
  2390. m_handle = INVALID_HANDLE_VALUE;
  2391. }
  2392. void CKsPin::SetState(KSSTATE ksState)
  2393. {
  2394. SetProperty(KSPROPSETID_Connection, KSPROPERTY_CONNECTION_STATE, &ksState, sizeof(ksState));
  2395. }
  2396. void CKsPin::Instantiate()
  2397. {
  2398. if (!m_pKsPinConnect)
  2399. throw std::runtime_error("CKsPin::Instanciate: abstract pin");
  2400. DWORD const dwResult = KsCreatePin(m_pFilter->m_handle, m_pKsPinConnect, GENERIC_WRITE | GENERIC_READ, &m_handle);
  2401. if (dwResult != ERROR_SUCCESS)
  2402. throw ComException("CKsMidiCapFilter::CreateRenderPin: Pin instanciation failed", HRESULT_FROM_WIN32(dwResult));
  2403. }
  2404. void CKsPin::WriteData(KSSTREAM_HEADER* pKSSTREAM_HEADER, OVERLAPPED* pOVERLAPPED)
  2405. {
  2406. DWORD cbWritten;
  2407. BOOL fRes = ::DeviceIoControl(
  2408. m_handle,
  2409. IOCTL_KS_WRITE_STREAM,
  2410. NULL,
  2411. 0,
  2412. pKSSTREAM_HEADER,
  2413. pKSSTREAM_HEADER->Size,
  2414. &cbWritten,
  2415. pOVERLAPPED);
  2416. if (!fRes) {
  2417. DWORD const dwError = GetLastError();
  2418. if (dwError != ERROR_IO_PENDING)
  2419. throw ComException("CKsPin::WriteData: DeviceIoControl failed", HRESULT_FROM_WIN32(dwError));
  2420. }
  2421. }
  2422. void CKsPin::ReadData(KSSTREAM_HEADER* pKSSTREAM_HEADER, OVERLAPPED* pOVERLAPPED)
  2423. {
  2424. DWORD cbReturned;
  2425. BOOL fRes = ::DeviceIoControl(
  2426. m_handle,
  2427. IOCTL_KS_READ_STREAM,
  2428. NULL,
  2429. 0,
  2430. pKSSTREAM_HEADER,
  2431. pKSSTREAM_HEADER->Size,
  2432. &cbReturned,
  2433. pOVERLAPPED);
  2434. if (!fRes) {
  2435. DWORD const dwError = GetLastError();
  2436. if (dwError != ERROR_IO_PENDING)
  2437. throw ComException("CKsPin::ReadData: DeviceIoControl failed", HRESULT_FROM_WIN32(dwError));
  2438. }
  2439. }
  2440. class CKsMidiFilter : public CKsFilter
  2441. {
  2442. public:
  2443. void FindMidiPins();
  2444. protected:
  2445. CKsMidiFilter(tstring const& sPath, std::string const& sFriendlyName);
  2446. };
  2447. class CKsMidiPin : public CKsPin
  2448. {
  2449. public:
  2450. CKsMidiPin(CKsFilter* pFilter, ULONG nId);
  2451. };
  2452. class CKsMidiRenFilter : public CKsMidiFilter
  2453. {
  2454. public:
  2455. CKsMidiRenFilter(tstring const& sPath, std::string const& sFriendlyName);
  2456. CKsMidiPin* CreateRenderPin();
  2457. void Validate()
  2458. {
  2459. if (m_RenderPins.empty())
  2460. throw std::runtime_error("Could not find a MIDI render pin");
  2461. }
  2462. };
  2463. class CKsMidiCapFilter : public CKsMidiFilter
  2464. {
  2465. public:
  2466. CKsMidiCapFilter(tstring const& sPath, std::string const& sFriendlyName);
  2467. CKsMidiPin* CreateCapturePin();
  2468. void Validate()
  2469. {
  2470. if (m_CapturePins.empty())
  2471. throw std::runtime_error("Could not find a MIDI capture pin");
  2472. }
  2473. };
  2474. CKsMidiFilter::CKsMidiFilter(tstring const& sPath, std::string const& sFriendlyName) :
  2475. CKsFilter(sPath, sFriendlyName)
  2476. {
  2477. }
  2478. void CKsMidiFilter::FindMidiPins()
  2479. {
  2480. ULONG numPins = GetPinProperty<ULONG>(0, KSPROPERTY_PIN_CTYPES);
  2481. for (ULONG iPin = 0; iPin < numPins; ++iPin) {
  2482. try {
  2483. KSPIN_COMMUNICATION com = GetPinProperty<KSPIN_COMMUNICATION>(iPin, KSPROPERTY_PIN_COMMUNICATION);
  2484. if (com != KSPIN_COMMUNICATION_SINK && com != KSPIN_COMMUNICATION_BOTH)
  2485. throw std::runtime_error("Unknown pin communication value");
  2486. m_Pins.push_back(new CKsMidiPin(this, iPin));
  2487. }
  2488. catch (std::runtime_error const&) {
  2489. // pin instanciation has failed, continue to the next pin.
  2490. }
  2491. }
  2492. m_RenderPins.clear();
  2493. m_CapturePins.clear();
  2494. for (size_t i = 0; i < m_Pins.size(); ++i) {
  2495. CKsPin* const pPin = m_Pins[i];
  2496. if (pPin->IsSink()) {
  2497. if (pPin->GetDataFlow() == KSPIN_DATAFLOW_IN)
  2498. m_RenderPins.push_back(pPin);
  2499. else
  2500. m_CapturePins.push_back(pPin);
  2501. }
  2502. }
  2503. if (m_RenderPins.empty() && m_CapturePins.empty())
  2504. throw std::runtime_error("No valid pins found on the filter.");
  2505. }
  2506. CKsMidiRenFilter::CKsMidiRenFilter(tstring const& sPath, std::string const& sFriendlyName) :
  2507. CKsMidiFilter(sPath, sFriendlyName)
  2508. {
  2509. }
  2510. CKsMidiPin* CKsMidiRenFilter::CreateRenderPin()
  2511. {
  2512. if (m_RenderPins.empty())
  2513. throw std::runtime_error("Could not find a MIDI render pin");
  2514. CKsMidiPin* pPin = (CKsMidiPin*)m_RenderPins[0];
  2515. pPin->Instantiate();
  2516. return pPin;
  2517. }
  2518. CKsMidiCapFilter::CKsMidiCapFilter(tstring const& sPath, std::string const& sFriendlyName) :
  2519. CKsMidiFilter(sPath, sFriendlyName)
  2520. {
  2521. }
  2522. CKsMidiPin* CKsMidiCapFilter::CreateCapturePin()
  2523. {
  2524. if (m_CapturePins.empty())
  2525. throw std::runtime_error("Could not find a MIDI capture pin");
  2526. CKsMidiPin* pPin = (CKsMidiPin*)m_CapturePins[0];
  2527. pPin->Instantiate();
  2528. return pPin;
  2529. }
  2530. CKsMidiPin::CKsMidiPin(CKsFilter* pFilter, ULONG nId) :
  2531. CKsPin(pFilter, nId)
  2532. {
  2533. DWORD const cbPinCreateSize = sizeof(KSPIN_CONNECT) + sizeof(KSDATAFORMAT);
  2534. m_pKsPinConnect = (PKSPIN_CONNECT) new BYTE[cbPinCreateSize];
  2535. m_pKsPinConnect->Interface.Set = KSINTERFACESETID_Standard;
  2536. m_pKsPinConnect->Interface.Id = KSINTERFACE_STANDARD_STREAMING;
  2537. m_pKsPinConnect->Interface.Flags = 0;
  2538. m_pKsPinConnect->Medium.Set = KSMEDIUMSETID_Standard;
  2539. m_pKsPinConnect->Medium.Id = KSMEDIUM_TYPE_ANYINSTANCE;
  2540. m_pKsPinConnect->Medium.Flags = 0;
  2541. m_pKsPinConnect->PinId = nId;
  2542. m_pKsPinConnect->PinToHandle = NULL;
  2543. m_pKsPinConnect->Priority.PriorityClass = KSPRIORITY_NORMAL;
  2544. m_pKsPinConnect->Priority.PrioritySubClass = 1;
  2545. // point m_pDataFormat to just after the pConnect struct
  2546. KSDATAFORMAT* m_pDataFormat = (KSDATAFORMAT*)(m_pKsPinConnect + 1);
  2547. m_pDataFormat->FormatSize = sizeof(KSDATAFORMAT);
  2548. m_pDataFormat->Flags = 0;
  2549. m_pDataFormat->SampleSize = 0;
  2550. m_pDataFormat->Reserved = 0;
  2551. m_pDataFormat->MajorFormat = GUID(KSDATAFORMAT_TYPE_MUSIC);
  2552. m_pDataFormat->SubFormat = GUID(KSDATAFORMAT_SUBTYPE_MIDI);
  2553. m_pDataFormat->Specifier = GUID(KSDATAFORMAT_SPECIFIER_NONE);
  2554. bool hasStdStreamingInterface = false;
  2555. bool hasStdStreamingMedium = false;
  2556. for ( ULONG i = 0; i < m_cInterfaces; i++ ) {
  2557. if (m_pInterfaces[i].Set == KSINTERFACESETID_Standard
  2558. && m_pInterfaces[i].Id == KSINTERFACE_STANDARD_STREAMING)
  2559. hasStdStreamingInterface = true;
  2560. }
  2561. for (ULONG i = 0; i < m_cMediums; i++) {
  2562. if (m_pMediums[i].Set == KSMEDIUMSETID_Standard
  2563. && m_pMediums[i].Id == KSMEDIUM_STANDARD_DEVIO)
  2564. hasStdStreamingMedium = true;
  2565. }
  2566. if (!hasStdStreamingInterface) // No standard streaming interfaces on the pin
  2567. throw std::runtime_error("CKsMidiPin::CKsMidiPin: no standard streaming interface");
  2568. if (!hasStdStreamingMedium) // No standard streaming mediums on the pin
  2569. throw std::runtime_error("CKsMidiPin::CKsMidiPin: no standard streaming medium");
  2570. bool hasMidiDataRange = false;
  2571. BYTE const* pDataRangePtr = reinterpret_cast<BYTE const*>(m_pDataRanges);
  2572. for (ULONG i = 0; i < m_cDataRanges; ++i) {
  2573. KSDATARANGE const* pDataRange = reinterpret_cast<KSDATARANGE const*>(pDataRangePtr);
  2574. if (pDataRange->SubFormat == KSDATAFORMAT_SUBTYPE_MIDI) {
  2575. hasMidiDataRange = true;
  2576. break;
  2577. }
  2578. pDataRangePtr += pDataRange->FormatSize;
  2579. }
  2580. if (!hasMidiDataRange) // No MIDI dataranges on the pin
  2581. throw std::runtime_error("CKsMidiPin::CKsMidiPin: no MIDI datarange");
  2582. }
  2583. struct WindowsKsData
  2584. {
  2585. WindowsKsData() : m_pPin(NULL), m_Buffer(1024), m_hInputThread(NULL)
  2586. {
  2587. memset(&overlapped, 0, sizeof(OVERLAPPED));
  2588. m_hExitEvent = ::CreateEvent(NULL, FALSE, FALSE, NULL);
  2589. overlapped.hEvent = ::CreateEvent(NULL, FALSE, FALSE, NULL);
  2590. m_hInputThread = NULL;
  2591. }
  2592. ~WindowsKsData()
  2593. {
  2594. ::CloseHandle(overlapped.hEvent);
  2595. ::CloseHandle(m_hExitEvent);
  2596. }
  2597. OVERLAPPED overlapped;
  2598. CKsPin* m_pPin;
  2599. std::vector<unsigned char> m_Buffer;
  2600. std::auto_ptr<CKsEnumFilters<CKsMidiCapFilter> > m_pCaptureEnum;
  2601. std::auto_ptr<CKsEnumFilters<CKsMidiRenFilter> > m_pRenderEnum;
  2602. HANDLE m_hInputThread;
  2603. HANDLE m_hExitEvent;
  2604. };
  2605. // *********************************************************************//
  2606. // API: WINDOWS Kernel Streaming
  2607. // Class Definitions: MidiInWinKS
  2608. // *********************************************************************//
  2609. DWORD WINAPI midiKsInputThread(VOID* pUser)
  2610. {
  2611. MidiInApi::RtMidiInData* data = static_cast<MidiInApi::RtMidiInData*>(pUser);
  2612. WindowsKsData* apiData = static_cast<WindowsKsData*>(data->apiData);
  2613. HANDLE hEvents[] = { apiData->overlapped.hEvent, apiData->m_hExitEvent };
  2614. while ( true ) {
  2615. KSSTREAM_HEADER packet;
  2616. memset(&packet, 0, sizeof packet);
  2617. packet.Size = sizeof(KSSTREAM_HEADER);
  2618. packet.PresentationTime.Time = 0;
  2619. packet.PresentationTime.Numerator = 1;
  2620. packet.PresentationTime.Denominator = 1;
  2621. packet.Data = &apiData->m_Buffer[0];
  2622. packet.DataUsed = 0;
  2623. packet.FrameExtent = apiData->m_Buffer.size();
  2624. apiData->m_pPin->ReadData(&packet, &apiData->overlapped);
  2625. DWORD dwRet = ::WaitForMultipleObjects(2, hEvents, FALSE, INFINITE);
  2626. if ( dwRet == WAIT_OBJECT_0 ) {
  2627. // parse packet
  2628. unsigned char* pData = (unsigned char*)packet.Data;
  2629. unsigned int iOffset = 0;
  2630. while ( iOffset < packet.DataUsed ) {
  2631. KSMUSICFORMAT* pMusic = (KSMUSICFORMAT*)&pData[iOffset];
  2632. iOffset += sizeof(KSMUSICFORMAT);
  2633. MidiInApi::MidiMessage message;
  2634. message.timeStamp = 0;
  2635. for(size_t i=0;i < pMusic->ByteCount;++i)
  2636. message.bytes.push_back(pData[iOffset+i]);
  2637. if ( data->usingCallback ) {
  2638. RtMidiIn::RtMidiCallback callback = (RtMidiIn::RtMidiCallback)data->userCallback;
  2639. callback(message.timeStamp, &message.bytes, data->userData);
  2640. }
  2641. else {
  2642. // As long as we haven't reached our queue size limit, push the message.
  2643. if ( data->queue.size < data->queue.ringSize ) {
  2644. data->queue.ring[data->queue.back++] = message;
  2645. if(data->queue.back == data->queue.ringSize)
  2646. data->queue.back = 0;
  2647. data->queue.size++;
  2648. }
  2649. else
  2650. std::cerr << "\nRtMidiIn: message queue limit reached!!\n\n";
  2651. }
  2652. iOffset += pMusic->ByteCount;
  2653. // re-align on 32 bits
  2654. if ( iOffset % 4 != 0 )
  2655. iOffset += (4 - iOffset % 4);
  2656. }
  2657. }
  2658. else
  2659. break;
  2660. }
  2661. return 0;
  2662. }
  2663. MidiInWinKS :: MidiInWinKS( const std::string clientName, unsigned int queueSizeLimit ) : MidiInApi( queueSizeLimit )
  2664. {
  2665. initialize( clientName );
  2666. }
  2667. void MidiInWinKS :: initialize( const std::string& clientName )
  2668. {
  2669. WindowsKsData* data = new WindowsKsData;
  2670. apiData_ = (void*)data;
  2671. inputData_.apiData = data;
  2672. GUID const aguidEnumCats[] =
  2673. {
  2674. { STATIC_KSCATEGORY_AUDIO }, { STATIC_KSCATEGORY_CAPTURE }
  2675. };
  2676. data->m_pCaptureEnum.reset(new CKsEnumFilters<CKsMidiCapFilter> );
  2677. data->m_pCaptureEnum->EnumFilters(aguidEnumCats, 2);
  2678. }
  2679. MidiInWinKS :: ~MidiInWinKS()
  2680. {
  2681. WindowsKsData* data = static_cast<WindowsKsData*>(apiData_);
  2682. try {
  2683. if ( data->m_pPin )
  2684. closePort();
  2685. }
  2686. catch(...) {
  2687. }
  2688. delete data;
  2689. }
  2690. void MidiInWinKS :: openPort( unsigned int portNumber, const std::string portName )
  2691. {
  2692. WindowsKsData* data = static_cast<WindowsKsData*>(apiData_);
  2693. if ( portNumber < 0 || portNumber >= data->m_pCaptureEnum->m_Filters.size() ) {
  2694. std::stringstream ost;
  2695. ost << "MidiInWinKS::openPort: the 'portNumber' argument (" << portNumber << ") is invalid.";
  2696. errorString_ = ost.str();
  2697. RtMidi::error( RtError::WARNING, errorString_ );
  2698. }
  2699. CKsMidiCapFilter* pFilter = data->m_pCaptureEnum->m_Filters[portNumber];
  2700. data->m_pPin = pFilter->CreateCapturePin();
  2701. if ( data->m_pPin == NULL ) {
  2702. std::stringstream ost;
  2703. ost << "MidiInWinKS::openPort: KS error opening port (could not create pin)";
  2704. errorString_ = ost.str();
  2705. RtMidi::error( RtError::WARNING, errorString_ );
  2706. }
  2707. data->m_pPin->SetState(KSSTATE_RUN);
  2708. DWORD threadId;
  2709. data->m_hInputThread = ::CreateThread(NULL, 0, &midiKsInputThread, &inputData_, 0, &threadId);
  2710. if ( data->m_hInputThread == NULL ) {
  2711. std::stringstream ost;
  2712. ost << "MidiInWinKS::initialize: Could not create input thread : Windows error " << GetLastError() << std::endl;;
  2713. errorString_ = ost.str();
  2714. RtMidi::error( RtError::WARNING, errorString_ );
  2715. }
  2716. connected_ = true;
  2717. }
  2718. void MidiInWinKS :: openVirtualPort( const std::string portName )
  2719. {
  2720. // This function cannot be implemented for the Windows KS MIDI API.
  2721. errorString_ = "MidiInWinKS::openVirtualPort: cannot be implemented in Windows KS MIDI API!";
  2722. RtMidi::error( RtError::WARNING, errorString_ );
  2723. }
  2724. unsigned int MidiInWinKS :: getPortCount()
  2725. {
  2726. WindowsKsData* data = static_cast<WindowsKsData*>(apiData_);
  2727. return (unsigned int)data->m_pCaptureEnum->m_Filters.size();
  2728. }
  2729. std::string MidiInWinKS :: getPortName(unsigned int portNumber)
  2730. {
  2731. WindowsKsData* data = static_cast<WindowsKsData*>(apiData_);
  2732. if(portNumber < 0 || portNumber >= data->m_pCaptureEnum->m_Filters.size()) {
  2733. std::stringstream ost;
  2734. ost << "MidiInWinKS::getPortName: the 'portNumber' argument (" << portNumber << ") is invalid.";
  2735. errorString_ = ost.str();
  2736. RtMidi::error( RtError::WARNING, errorString_ );
  2737. }
  2738. CKsMidiCapFilter* pFilter = data->m_pCaptureEnum->m_Filters[portNumber];
  2739. return pFilter->GetFriendlyName();
  2740. }
  2741. void MidiInWinKS :: closePort()
  2742. {
  2743. WindowsKsData* data = static_cast<WindowsKsData*>(apiData_);
  2744. connected_ = false;
  2745. if(data->m_hInputThread) {
  2746. ::SignalObjectAndWait(data->m_hExitEvent, data->m_hInputThread, INFINITE, FALSE);
  2747. ::CloseHandle(data->m_hInputThread);
  2748. }
  2749. if(data->m_pPin) {
  2750. data->m_pPin->SetState(KSSTATE_PAUSE);
  2751. data->m_pPin->SetState(KSSTATE_STOP);
  2752. data->m_pPin->ClosePin();
  2753. data->m_pPin = NULL;
  2754. }
  2755. }
  2756. // *********************************************************************//
  2757. // API: WINDOWS Kernel Streaming
  2758. // Class Definitions: MidiOutWinKS
  2759. // *********************************************************************//
  2760. MidiOutWinKS :: MidiOutWinKS( const std::string clientName ) : MidiOutApi()
  2761. {
  2762. initialize( clientName );
  2763. }
  2764. void MidiOutWinKS :: initialize( const std::string& clientName )
  2765. {
  2766. WindowsKsData* data = new WindowsKsData;
  2767. data->m_pPin = NULL;
  2768. data->m_pRenderEnum.reset(new CKsEnumFilters<CKsMidiRenFilter> );
  2769. GUID const aguidEnumCats[] =
  2770. {
  2771. { STATIC_KSCATEGORY_AUDIO }, { STATIC_KSCATEGORY_RENDER }
  2772. };
  2773. data->m_pRenderEnum->EnumFilters(aguidEnumCats, 2);
  2774. apiData_ = (void*)data;
  2775. }
  2776. MidiOutWinKS :: ~MidiOutWinKS()
  2777. {
  2778. // Close a connection if it exists.
  2779. closePort();
  2780. // Cleanup.
  2781. WindowsKsData* data = static_cast<WindowsKsData*>(apiData_);
  2782. delete data;
  2783. }
  2784. void MidiOutWinKS :: openPort( unsigned int portNumber, const std::string portName )
  2785. {
  2786. WindowsKsData* data = static_cast<WindowsKsData*>(apiData_);
  2787. if(portNumber < 0 || portNumber >= data->m_pRenderEnum->m_Filters.size()) {
  2788. std::stringstream ost;
  2789. ost << "MidiOutWinKS::openPort: the 'portNumber' argument (" << portNumber << ") is invalid.";
  2790. errorString_ = ost.str();
  2791. RtMidi::error( RtError::WARNING, errorString_ );
  2792. }
  2793. CKsMidiRenFilter* pFilter = data->m_pRenderEnum->m_Filters[portNumber];
  2794. data->m_pPin = pFilter->CreateRenderPin();
  2795. if(data->m_pPin == NULL) {
  2796. std::stringstream ost;
  2797. ost << "MidiOutWinKS::openPort: KS error opening port (could not create pin)";
  2798. errorString_ = ost.str();
  2799. RtMidi::error( RtError::WARNING, errorString_ );
  2800. }
  2801. data->m_pPin->SetState(KSSTATE_RUN);
  2802. connected_ = true;
  2803. }
  2804. void MidiOutWinKS :: openVirtualPort( const std::string portName )
  2805. {
  2806. // This function cannot be implemented for the Windows KS MIDI API.
  2807. errorString_ = "MidiOutWinKS::openVirtualPort: cannot be implemented in Windows KS MIDI API!";
  2808. RtMidi::error( RtError::WARNING, errorString_ );
  2809. }
  2810. unsigned int MidiOutWinKS :: getPortCount()
  2811. {
  2812. WindowsKsData* data = static_cast<WindowsKsData*>(apiData_);
  2813. return (unsigned int)data->m_pRenderEnum->m_Filters.size();
  2814. }
  2815. std::string MidiOutWinKS :: getPortName( unsigned int portNumber )
  2816. {
  2817. WindowsKsData* data = static_cast<WindowsKsData*>(apiData_);
  2818. if ( portNumber < 0 || portNumber >= data->m_pRenderEnum->m_Filters.size() ) {
  2819. std::stringstream ost;
  2820. ost << "MidiOutWinKS::getPortName: the 'portNumber' argument (" << portNumber << ") is invalid.";
  2821. errorString_ = ost.str();
  2822. RtMidi::error( RtError::WARNING, errorString_ );
  2823. }
  2824. CKsMidiRenFilter* pFilter = data->m_pRenderEnum->m_Filters[portNumber];
  2825. return pFilter->GetFriendlyName();
  2826. }
  2827. void MidiOutWinKS :: closePort()
  2828. {
  2829. WindowsKsData* data = static_cast<WindowsKsData*>(apiData_);
  2830. connected_ = false;
  2831. if ( data->m_pPin ) {
  2832. data->m_pPin->SetState(KSSTATE_PAUSE);
  2833. data->m_pPin->SetState(KSSTATE_STOP);
  2834. data->m_pPin->ClosePin();
  2835. data->m_pPin = NULL;
  2836. }
  2837. }
  2838. void MidiOutWinKS :: sendMessage(std::vector<unsigned char>* pMessage)
  2839. {
  2840. std::vector<unsigned char> const& msg = *pMessage;
  2841. WindowsKsData* data = static_cast<WindowsKsData*>(apiData_);
  2842. size_t iNumMidiBytes = msg.size();
  2843. size_t pos = 0;
  2844. // write header
  2845. KSMUSICFORMAT* pKsMusicFormat = reinterpret_cast<KSMUSICFORMAT*>(&data->m_Buffer[pos]);
  2846. pKsMusicFormat->TimeDeltaMs = 0;
  2847. pKsMusicFormat->ByteCount = iNumMidiBytes;
  2848. pos += sizeof(KSMUSICFORMAT);
  2849. // write MIDI bytes
  2850. if ( pos + iNumMidiBytes > data->m_Buffer.size() ) {
  2851. std::stringstream ost;
  2852. ost << "KsMidiInput::Write: MIDI buffer too small. Required " << pos + iNumMidiBytes << " bytes, only has " << data->m_Buffer.size();
  2853. errorString_ = ost.str();
  2854. RtMidi::error( RtError::WARNING, errorString_ );
  2855. }
  2856. if ( data->m_pPin == NULL ) {
  2857. std::stringstream ost;
  2858. ost << "MidiOutWinKS::sendMessage: port is not open";
  2859. errorString_ = ost.str();
  2860. RtMidi::error( RtError::WARNING, errorString_ );
  2861. }
  2862. memcpy(&data->m_Buffer[pos], &msg[0], iNumMidiBytes);
  2863. pos += iNumMidiBytes;
  2864. KSSTREAM_HEADER packet;
  2865. memset(&packet, 0, sizeof packet);
  2866. packet.Size = sizeof(packet);
  2867. packet.PresentationTime.Time = 0;
  2868. packet.PresentationTime.Numerator = 1;
  2869. packet.PresentationTime.Denominator = 1;
  2870. packet.Data = const_cast<unsigned char*>(&data->m_Buffer[0]);
  2871. packet.DataUsed = ((pos+3)/4)*4;
  2872. packet.FrameExtent = data->m_Buffer.size();
  2873. data->m_pPin->WriteData(&packet, NULL);
  2874. }
  2875. #endif // __WINDOWS_KS__
  2876. //*********************************************************************//
  2877. // API: UNIX JACK
  2878. //
  2879. // Written primarily by Alexander Svetalkin, with updates for delta
  2880. // time by Gary Scavone, April 2011.
  2881. //
  2882. // *********************************************************************//
  2883. #if defined(__UNIX_JACK__)
  2884. // JACK header files
  2885. #include <jack/jack.h>
  2886. #include <jack/midiport.h>
  2887. #include <jack/ringbuffer.h>
  2888. #define JACK_RINGBUFFER_SIZE 16384 // Default size for ringbuffer
  2889. struct JackMidiData {
  2890. jack_client_t *client;
  2891. jack_port_t *port;
  2892. jack_ringbuffer_t *buffSize;
  2893. jack_ringbuffer_t *buffMessage;
  2894. jack_time_t lastTime;
  2895. MidiInApi :: RtMidiInData *rtMidiIn;
  2896. };
  2897. //*********************************************************************//
  2898. // API: JACK
  2899. // Class Definitions: MidiInJack
  2900. //*********************************************************************//
  2901. int jackProcessIn( jack_nframes_t nframes, void *arg )
  2902. {
  2903. JackMidiData *jData = (JackMidiData *) arg;
  2904. MidiInApi :: RtMidiInData *rtData = jData->rtMidiIn;
  2905. jack_midi_event_t event;
  2906. jack_time_t time;
  2907. // Is port created?
  2908. if ( jData->port == NULL ) return 0;
  2909. void *buff = jack_port_get_buffer( jData->port, nframes );
  2910. // We have midi events in buffer
  2911. int evCount = jack_midi_get_event_count( buff );
  2912. if ( evCount > 0 ) {
  2913. MidiInApi::MidiMessage message;
  2914. message.bytes.clear();
  2915. jack_midi_event_get( &event, buff, 0 );
  2916. for (unsigned int i = 0; i < event.size; i++ )
  2917. message.bytes.push_back( event.buffer[i] );
  2918. // Compute the delta time.
  2919. time = jack_get_time();
  2920. if ( rtData->firstMessage == true )
  2921. rtData->firstMessage = false;
  2922. else
  2923. message.timeStamp = ( time - jData->lastTime ) * 0.000001;
  2924. jData->lastTime = time;
  2925. if ( !rtData->continueSysex ) {
  2926. if ( rtData->usingCallback ) {
  2927. RtMidiIn::RtMidiCallback callback = (RtMidiIn::RtMidiCallback) rtData->userCallback;
  2928. callback( message.timeStamp, &message.bytes, rtData->userData );
  2929. }
  2930. else {
  2931. // As long as we haven't reached our queue size limit, push the message.
  2932. if ( rtData->queue.size < rtData->queue.ringSize ) {
  2933. rtData->queue.ring[rtData->queue.back++] = message;
  2934. if ( rtData->queue.back == rtData->queue.ringSize )
  2935. rtData->queue.back = 0;
  2936. rtData->queue.size++;
  2937. }
  2938. else
  2939. std::cerr << "\nMidiInJack: message queue limit reached!!\n\n";
  2940. }
  2941. }
  2942. }
  2943. return 0;
  2944. }
  2945. MidiInJack :: MidiInJack( const std::string clientName, unsigned int queueSizeLimit ) : MidiInApi( queueSizeLimit )
  2946. {
  2947. initialize( clientName );
  2948. }
  2949. void MidiInJack :: initialize( const std::string& clientName )
  2950. {
  2951. JackMidiData *data = new JackMidiData;
  2952. apiData_ = (void *) data;
  2953. // Initialize JACK client
  2954. if (( data->client = jack_client_open( clientName.c_str(), JackNullOption, NULL )) == 0) {
  2955. errorString_ = "MidiInJack::initialize: JACK server not running?";
  2956. RtMidi::error( RtError::DRIVER_ERROR, errorString_ );
  2957. return;
  2958. }
  2959. data->rtMidiIn = &inputData_;
  2960. data->port = NULL;
  2961. jack_set_process_callback( data->client, jackProcessIn, data );
  2962. jack_activate( data->client );
  2963. }
  2964. MidiInJack :: ~MidiInJack()
  2965. {
  2966. JackMidiData *data = static_cast<JackMidiData *> (apiData_);
  2967. closePort();
  2968. jack_client_close( data->client );
  2969. }
  2970. void MidiInJack :: openPort( unsigned int portNumber, const std::string portName )
  2971. {
  2972. JackMidiData *data = static_cast<JackMidiData *> (apiData_);
  2973. // Creating new port
  2974. if ( data->port == NULL)
  2975. data->port = jack_port_register( data->client, portName.c_str(),
  2976. JACK_DEFAULT_MIDI_TYPE, JackPortIsInput, 0 );
  2977. if ( data->port == NULL) {
  2978. errorString_ = "MidiInJack::openVirtualPort: JACK error creating virtual port";
  2979. RtMidi::error( RtError::DRIVER_ERROR, errorString_ );
  2980. }
  2981. // Connecting to the output
  2982. std::string name = getPortName( portNumber );
  2983. jack_connect( data->client, name.c_str(), jack_port_name( data->port ) );
  2984. }
  2985. void MidiInJack :: openVirtualPort( const std::string portName )
  2986. {
  2987. JackMidiData *data = static_cast<JackMidiData *> (apiData_);
  2988. if ( data->port == NULL )
  2989. data->port = jack_port_register( data->client, portName.c_str(),
  2990. JACK_DEFAULT_MIDI_TYPE, JackPortIsInput, 0 );
  2991. if ( data->port == NULL ) {
  2992. errorString_ = "MidiInJack::openVirtualPort: JACK error creating virtual port";
  2993. RtMidi::error( RtError::DRIVER_ERROR, errorString_ );
  2994. }
  2995. }
  2996. unsigned int MidiInJack :: getPortCount()
  2997. {
  2998. int count = 0;
  2999. JackMidiData *data = static_cast<JackMidiData *> (apiData_);
  3000. // List of available ports
  3001. const char **ports = jack_get_ports( data->client, NULL, JACK_DEFAULT_MIDI_TYPE, JackPortIsOutput );
  3002. if ( ports == NULL ) return 0;
  3003. while ( ports[count] != NULL )
  3004. count++;
  3005. free( ports );
  3006. return count;
  3007. }
  3008. std::string MidiInJack :: getPortName( unsigned int portNumber )
  3009. {
  3010. JackMidiData *data = static_cast<JackMidiData *> (apiData_);
  3011. std::ostringstream ost;
  3012. std::string retStr("");
  3013. // List of available ports
  3014. const char **ports = jack_get_ports( data->client, NULL,
  3015. JACK_DEFAULT_MIDI_TYPE, JackPortIsOutput );
  3016. // Check port validity
  3017. if ( ports == NULL ) {
  3018. errorString_ = "MidiInJack::getPortName: no ports available!";
  3019. RtMidi::error( RtError::WARNING, errorString_ );
  3020. return retStr;
  3021. }
  3022. if ( ports[portNumber] == NULL ) {
  3023. ost << "MidiInJack::getPortName: the 'portNumber' argument (" << portNumber << ") is invalid.";
  3024. errorString_ = ost.str();
  3025. RtMidi::error( RtError::WARNING, errorString_ );
  3026. }
  3027. else retStr.assign( ports[portNumber] );
  3028. free( ports );
  3029. return retStr;
  3030. }
  3031. void MidiInJack :: closePort()
  3032. {
  3033. JackMidiData *data = static_cast<JackMidiData *> (apiData_);
  3034. if ( data->port == NULL ) return;
  3035. jack_port_unregister( data->client, data->port );
  3036. data->port = NULL;
  3037. }
  3038. //*********************************************************************//
  3039. // API: JACK
  3040. // Class Definitions: MidiOutJack
  3041. //*********************************************************************//
  3042. // Jack process callback
  3043. int jackProcessOut( jack_nframes_t nframes, void *arg )
  3044. {
  3045. JackMidiData *data = (JackMidiData *) arg;
  3046. jack_midi_data_t *midiData;
  3047. int space;
  3048. // Is port created?
  3049. if ( data->port == NULL ) return 0;
  3050. void *buff = jack_port_get_buffer( data->port, nframes );
  3051. jack_midi_clear_buffer( buff );
  3052. while ( jack_ringbuffer_read_space( data->buffSize ) > 0 ) {
  3053. jack_ringbuffer_read( data->buffSize, (char *) &space, (size_t) sizeof(space) );
  3054. midiData = jack_midi_event_reserve( buff, 0, space );
  3055. jack_ringbuffer_read( data->buffMessage, (char *) midiData, (size_t) space );
  3056. }
  3057. return 0;
  3058. }
  3059. MidiOutJack :: MidiOutJack( const std::string clientName ) : MidiOutApi()
  3060. {
  3061. initialize( clientName );
  3062. }
  3063. void MidiOutJack :: initialize( const std::string& clientName )
  3064. {
  3065. JackMidiData *data = new JackMidiData;
  3066. data->port = NULL;
  3067. // Initialize JACK client
  3068. if (( data->client = jack_client_open( clientName.c_str(), JackNullOption, NULL )) == 0) {
  3069. errorString_ = "MidiOutJack::initialize: JACK server not running?";
  3070. RtMidi::error( RtError::DRIVER_ERROR, errorString_ );
  3071. return;
  3072. }
  3073. jack_set_process_callback( data->client, jackProcessOut, data );
  3074. data->buffSize = jack_ringbuffer_create( JACK_RINGBUFFER_SIZE );
  3075. data->buffMessage = jack_ringbuffer_create( JACK_RINGBUFFER_SIZE );
  3076. jack_activate( data->client );
  3077. apiData_ = (void *) data;
  3078. }
  3079. MidiOutJack :: ~MidiOutJack()
  3080. {
  3081. JackMidiData *data = static_cast<JackMidiData *> (apiData_);
  3082. closePort();
  3083. // Cleanup
  3084. jack_client_close( data->client );
  3085. jack_ringbuffer_free( data->buffSize );
  3086. jack_ringbuffer_free( data->buffMessage );
  3087. delete data;
  3088. }
  3089. void MidiOutJack :: openPort( unsigned int portNumber, const std::string portName )
  3090. {
  3091. JackMidiData *data = static_cast<JackMidiData *> (apiData_);
  3092. // Creating new port
  3093. if ( data->port == NULL )
  3094. data->port = jack_port_register( data->client, portName.c_str(),
  3095. JACK_DEFAULT_MIDI_TYPE, JackPortIsOutput, 0 );
  3096. if ( data->port == NULL ) {
  3097. errorString_ = "MidiOutJack::openVirtualPort: JACK error creating virtual port";
  3098. RtMidi::error( RtError::DRIVER_ERROR, errorString_ );
  3099. }
  3100. // Connecting to the output
  3101. std::string name = getPortName( portNumber );
  3102. jack_connect( data->client, jack_port_name( data->port ), name.c_str() );
  3103. }
  3104. void MidiOutJack :: openVirtualPort( const std::string portName )
  3105. {
  3106. JackMidiData *data = static_cast<JackMidiData *> (apiData_);
  3107. if ( data->port == NULL )
  3108. data->port = jack_port_register( data->client, portName.c_str(),
  3109. JACK_DEFAULT_MIDI_TYPE, JackPortIsOutput, 0 );
  3110. if ( data->port == NULL ) {
  3111. errorString_ = "MidiOutJack::openVirtualPort: JACK error creating virtual port";
  3112. RtMidi::error( RtError::DRIVER_ERROR, errorString_ );
  3113. }
  3114. }
  3115. unsigned int MidiOutJack :: getPortCount()
  3116. {
  3117. int count = 0;
  3118. JackMidiData *data = static_cast<JackMidiData *> (apiData_);
  3119. // List of available ports
  3120. const char **ports = jack_get_ports( data->client, NULL,
  3121. JACK_DEFAULT_MIDI_TYPE, JackPortIsInput );
  3122. if ( ports == NULL ) return 0;
  3123. while ( ports[count] != NULL )
  3124. count++;
  3125. free( ports );
  3126. return count;
  3127. }
  3128. std::string MidiOutJack :: getPortName( unsigned int portNumber )
  3129. {
  3130. JackMidiData *data = static_cast<JackMidiData *> (apiData_);
  3131. std::ostringstream ost;
  3132. std::string retStr("");
  3133. // List of available ports
  3134. const char **ports = jack_get_ports( data->client, NULL,
  3135. JACK_DEFAULT_MIDI_TYPE, JackPortIsInput );
  3136. // Check port validity
  3137. if ( ports == NULL) {
  3138. errorString_ = "MidiOutJack::getPortName: no ports available!";
  3139. RtMidi::error( RtError::WARNING, errorString_ );
  3140. return retStr;
  3141. }
  3142. if ( ports[portNumber] == NULL) {
  3143. ost << "MidiOutJack::getPortName: the 'portNumber' argument (" << portNumber << ") is invalid.";
  3144. errorString_ = ost.str();
  3145. RtMidi::error( RtError::WARNING, errorString_ );
  3146. }
  3147. else retStr.assign( ports[portNumber] );
  3148. free( ports );
  3149. return retStr;
  3150. }
  3151. void MidiOutJack :: closePort()
  3152. {
  3153. JackMidiData *data = static_cast<JackMidiData *> (apiData_);
  3154. if ( data->port == NULL ) return;
  3155. jack_port_unregister( data->client, data->port );
  3156. data->port = NULL;
  3157. }
  3158. void MidiOutJack :: sendMessage( std::vector<unsigned char> *message )
  3159. {
  3160. int nBytes = message->size();
  3161. JackMidiData *data = static_cast<JackMidiData *> (apiData_);
  3162. // Write full message to buffer
  3163. jack_ringbuffer_write( data->buffMessage, ( const char * ) &( *message )[0],
  3164. message->size() );
  3165. jack_ringbuffer_write( data->buffSize, ( char * ) &nBytes, sizeof( nBytes ) );
  3166. }
  3167. #endif // __UNIX_JACK__