RtMidi.cpp 76 KB

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