PageRenderTime 75ms CodeModel.GetById 24ms RepoModel.GetById 0ms app.codeStats 1ms

/RtMidi.cpp

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