RtMidi.cpp 78 KB

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