RtMidi.cpp 71 KB

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