RtMidi.cpp 76 KB

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