RtMidi.cpp 65 KB

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