Audio plugin host https://kx.studio/carla
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2815 lines
89KB

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