RtMidi.cpp 91 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818
  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-2014 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. asked to send the modifications to the original developer so that
  20. they can be incorporated into the canonical version. This is,
  21. however, not a binding provision of this license.
  22. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  23. EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  24. MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
  25. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
  26. ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
  27. CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  28. WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  29. */
  30. /**********************************************************************/
  31. #include "RtMidi.h"
  32. #include <sstream>
  33. //*********************************************************************//
  34. // RtMidi Definitions
  35. //*********************************************************************//
  36. RtMidi :: RtMidi()
  37. : rtapi_(0)
  38. {
  39. }
  40. RtMidi :: ~RtMidi()
  41. {
  42. if ( rtapi_ )
  43. delete rtapi_;
  44. rtapi_ = 0;
  45. }
  46. std::string RtMidi :: getVersion( void ) throw()
  47. {
  48. return std::string( RTMIDI_VERSION );
  49. }
  50. void RtMidi :: getCompiledApi( std::vector<RtMidi::Api> &apis ) throw()
  51. {
  52. apis.clear();
  53. // The order here will control the order of RtMidi's API search in
  54. // the constructor.
  55. #if defined(__MACOSX_CORE__)
  56. apis.push_back( MACOSX_CORE );
  57. #endif
  58. #if defined(__LINUX_ALSA__)
  59. apis.push_back( LINUX_ALSA );
  60. #endif
  61. #if defined(__UNIX_JACK__)
  62. apis.push_back( UNIX_JACK );
  63. #endif
  64. #if defined(__WINDOWS_MM__)
  65. apis.push_back( WINDOWS_MM );
  66. #endif
  67. #if defined(__RTMIDI_DUMMY__)
  68. apis.push_back( RTMIDI_DUMMY );
  69. #endif
  70. }
  71. //*********************************************************************//
  72. // RtMidiIn Definitions
  73. //*********************************************************************//
  74. void RtMidiIn :: openMidiApi( RtMidi::Api api, const std::string clientName, unsigned int queueSizeLimit )
  75. {
  76. if ( rtapi_ )
  77. delete rtapi_;
  78. rtapi_ = 0;
  79. #if defined(__UNIX_JACK__)
  80. if ( api == UNIX_JACK )
  81. rtapi_ = new MidiInJack( clientName, queueSizeLimit );
  82. #endif
  83. #if defined(__LINUX_ALSA__)
  84. if ( api == LINUX_ALSA )
  85. rtapi_ = new MidiInAlsa( clientName, queueSizeLimit );
  86. #endif
  87. #if defined(__WINDOWS_MM__)
  88. if ( api == WINDOWS_MM )
  89. rtapi_ = new MidiInWinMM( clientName, queueSizeLimit );
  90. #endif
  91. #if defined(__MACOSX_CORE__)
  92. if ( api == MACOSX_CORE )
  93. rtapi_ = new MidiInCore( clientName, queueSizeLimit );
  94. #endif
  95. #if defined(__RTMIDI_DUMMY__)
  96. if ( api == RTMIDI_DUMMY )
  97. rtapi_ = new MidiInDummy( clientName, queueSizeLimit );
  98. #endif
  99. }
  100. RtMidiIn :: RtMidiIn( RtMidi::Api api, const std::string clientName, unsigned int queueSizeLimit )
  101. : RtMidi()
  102. {
  103. if ( api != UNSPECIFIED ) {
  104. // Attempt to open the specified API.
  105. openMidiApi( api, clientName, queueSizeLimit );
  106. if ( rtapi_ ) return;
  107. // No compiled support for specified API value. Issue a warning
  108. // and continue as if no API was specified.
  109. std::cerr << "\nRtMidiIn: no compiled support for specified API argument!\n\n" << std::endl;
  110. }
  111. // Iterate through the compiled APIs and return as soon as we find
  112. // one with at least one port or we reach the end of the list.
  113. std::vector< RtMidi::Api > apis;
  114. getCompiledApi( apis );
  115. for ( unsigned int i=0; i<apis.size(); i++ ) {
  116. openMidiApi( apis[i], clientName, queueSizeLimit );
  117. if ( rtapi_->getPortCount() ) break;
  118. }
  119. if ( rtapi_ ) return;
  120. // It should not be possible to get here because the preprocessor
  121. // definition __RTMIDI_DUMMY__ is automatically defined if no
  122. // API-specific definitions are passed to the compiler. But just in
  123. // case something weird happens, we'll throw an error.
  124. std::string errorText = "RtMidiIn: no compiled API support found ... critical error!!";
  125. throw( RtMidiError( errorText, RtMidiError::UNSPECIFIED ) );
  126. }
  127. RtMidiIn :: ~RtMidiIn() throw()
  128. {
  129. }
  130. //*********************************************************************//
  131. // RtMidiOut Definitions
  132. //*********************************************************************//
  133. void RtMidiOut :: openMidiApi( RtMidi::Api api, const std::string clientName )
  134. {
  135. if ( rtapi_ )
  136. delete rtapi_;
  137. rtapi_ = 0;
  138. #if defined(__UNIX_JACK__)
  139. if ( api == UNIX_JACK )
  140. rtapi_ = new MidiOutJack( clientName );
  141. #endif
  142. #if defined(__LINUX_ALSA__)
  143. if ( api == LINUX_ALSA )
  144. rtapi_ = new MidiOutAlsa( clientName );
  145. #endif
  146. #if defined(__WINDOWS_MM__)
  147. if ( api == WINDOWS_MM )
  148. rtapi_ = new MidiOutWinMM( clientName );
  149. #endif
  150. #if defined(__MACOSX_CORE__)
  151. if ( api == MACOSX_CORE )
  152. rtapi_ = new MidiOutCore( clientName );
  153. #endif
  154. #if defined(__RTMIDI_DUMMY__)
  155. if ( api == RTMIDI_DUMMY )
  156. rtapi_ = new MidiOutDummy( clientName );
  157. #endif
  158. }
  159. RtMidiOut :: RtMidiOut( RtMidi::Api api, const std::string clientName )
  160. {
  161. if ( api != UNSPECIFIED ) {
  162. // Attempt to open the specified API.
  163. openMidiApi( api, clientName );
  164. if ( rtapi_ ) return;
  165. // No compiled support for specified API value. Issue a warning
  166. // and continue as if no API was specified.
  167. std::cerr << "\nRtMidiOut: no compiled support for specified API argument!\n\n" << std::endl;
  168. }
  169. // Iterate through the compiled APIs and return as soon as we find
  170. // one with at least one port or we reach the end of the list.
  171. std::vector< RtMidi::Api > apis;
  172. getCompiledApi( apis );
  173. for ( unsigned int i=0; i<apis.size(); i++ ) {
  174. openMidiApi( apis[i], clientName );
  175. if ( rtapi_->getPortCount() ) break;
  176. }
  177. if ( rtapi_ ) return;
  178. // It should not be possible to get here because the preprocessor
  179. // definition __RTMIDI_DUMMY__ is automatically defined if no
  180. // API-specific definitions are passed to the compiler. But just in
  181. // case something weird happens, we'll thrown an error.
  182. std::string errorText = "RtMidiOut: no compiled API support found ... critical error!!";
  183. throw( RtMidiError( errorText, RtMidiError::UNSPECIFIED ) );
  184. }
  185. RtMidiOut :: ~RtMidiOut() throw()
  186. {
  187. }
  188. //*********************************************************************//
  189. // Common MidiApi Definitions
  190. //*********************************************************************//
  191. MidiApi :: MidiApi( void )
  192. : apiData_( 0 ), connected_( false ), errorCallback_(0), errorCallbackUserData_(0)
  193. {
  194. }
  195. MidiApi :: ~MidiApi( void )
  196. {
  197. }
  198. void MidiApi :: setErrorCallback( RtMidiErrorCallback errorCallback, void *userData = 0 )
  199. {
  200. errorCallback_ = errorCallback;
  201. errorCallbackUserData_ = userData;
  202. }
  203. void MidiApi :: error( RtMidiError::Type type, std::string errorString )
  204. {
  205. if ( errorCallback_ ) {
  206. if ( firstErrorOccurred_ )
  207. return;
  208. firstErrorOccurred_ = true;
  209. const std::string errorMessage = errorString;
  210. errorCallback_( type, errorMessage, errorCallbackUserData_);
  211. firstErrorOccurred_ = false;
  212. return;
  213. }
  214. if ( type == RtMidiError::WARNING ) {
  215. std::cerr << '\n' << errorString << "\n\n";
  216. }
  217. else if ( type == RtMidiError::DEBUG_WARNING ) {
  218. #if defined(__RTMIDI_DEBUG__)
  219. std::cerr << '\n' << errorString << "\n\n";
  220. #endif
  221. }
  222. else {
  223. std::cerr << '\n' << errorString << "\n\n";
  224. throw RtMidiError( errorString, type );
  225. }
  226. }
  227. //*********************************************************************//
  228. // Common MidiInApi Definitions
  229. //*********************************************************************//
  230. MidiInApi :: MidiInApi( unsigned int queueSizeLimit )
  231. : MidiApi()
  232. {
  233. // Allocate the MIDI queue.
  234. inputData_.queue.ringSize = queueSizeLimit;
  235. if ( inputData_.queue.ringSize > 0 )
  236. inputData_.queue.ring = new MidiMessage[ inputData_.queue.ringSize ];
  237. }
  238. MidiInApi :: ~MidiInApi( void )
  239. {
  240. // Delete the MIDI queue.
  241. if ( inputData_.queue.ringSize > 0 ) delete [] inputData_.queue.ring;
  242. }
  243. void MidiInApi :: setCallback( RtMidiIn::RtMidiCallback callback, void *userData )
  244. {
  245. if ( inputData_.usingCallback ) {
  246. errorString_ = "MidiInApi::setCallback: a callback function is already set!";
  247. error( RtMidiError::WARNING, errorString_ );
  248. return;
  249. }
  250. if ( !callback ) {
  251. errorString_ = "RtMidiIn::setCallback: callback function value is invalid!";
  252. error( RtMidiError::WARNING, errorString_ );
  253. return;
  254. }
  255. inputData_.userCallback = callback;
  256. inputData_.userData = userData;
  257. inputData_.usingCallback = true;
  258. }
  259. void MidiInApi :: cancelCallback()
  260. {
  261. if ( !inputData_.usingCallback ) {
  262. errorString_ = "RtMidiIn::cancelCallback: no callback function was set!";
  263. error( RtMidiError::WARNING, errorString_ );
  264. return;
  265. }
  266. inputData_.userCallback = 0;
  267. inputData_.userData = 0;
  268. inputData_.usingCallback = false;
  269. }
  270. void MidiInApi :: ignoreTypes( bool midiSysex, bool midiTime, bool midiSense )
  271. {
  272. inputData_.ignoreFlags = 0;
  273. if ( midiSysex ) inputData_.ignoreFlags = 0x01;
  274. if ( midiTime ) inputData_.ignoreFlags |= 0x02;
  275. if ( midiSense ) inputData_.ignoreFlags |= 0x04;
  276. }
  277. double MidiInApi :: getMessage( std::vector<unsigned char> *message )
  278. {
  279. message->clear();
  280. if ( inputData_.usingCallback ) {
  281. errorString_ = "RtMidiIn::getNextMessage: a user callback is currently set for this port.";
  282. error( RtMidiError::WARNING, errorString_ );
  283. return 0.0;
  284. }
  285. if ( inputData_.queue.size == 0 ) return 0.0;
  286. // Copy queued message to the vector pointer argument and then "pop" it.
  287. std::vector<unsigned char> *bytes = &(inputData_.queue.ring[inputData_.queue.front].bytes);
  288. message->assign( bytes->begin(), bytes->end() );
  289. double deltaTime = inputData_.queue.ring[inputData_.queue.front].timeStamp;
  290. inputData_.queue.size--;
  291. inputData_.queue.front++;
  292. if ( inputData_.queue.front == inputData_.queue.ringSize )
  293. inputData_.queue.front = 0;
  294. return deltaTime;
  295. }
  296. //*********************************************************************//
  297. // Common MidiOutApi Definitions
  298. //*********************************************************************//
  299. MidiOutApi :: MidiOutApi( void )
  300. : MidiApi()
  301. {
  302. }
  303. MidiOutApi :: ~MidiOutApi( void )
  304. {
  305. }
  306. // *************************************************** //
  307. //
  308. // OS/API-specific methods.
  309. //
  310. // *************************************************** //
  311. #if defined(__MACOSX_CORE__)
  312. // The CoreMIDI API is based on the use of a callback function for
  313. // MIDI input. We convert the system specific time stamps to delta
  314. // time values.
  315. // OS-X CoreMIDI header files.
  316. #include <CoreMIDI/CoreMIDI.h>
  317. #include <CoreAudio/HostTime.h>
  318. #include <CoreServices/CoreServices.h>
  319. // A structure to hold variables related to the CoreMIDI API
  320. // implementation.
  321. struct CoreMidiData {
  322. MIDIClientRef client;
  323. MIDIPortRef port;
  324. MIDIEndpointRef endpoint;
  325. MIDIEndpointRef destinationId;
  326. unsigned long long lastTime;
  327. MIDISysexSendRequest sysexreq;
  328. };
  329. //*********************************************************************//
  330. // API: OS-X
  331. // Class Definitions: MidiInCore
  332. //*********************************************************************//
  333. static void midiInputCallback( const MIDIPacketList *list, void *procRef, void */*srcRef*/ )
  334. {
  335. MidiInApi::RtMidiInData *data = static_cast<MidiInApi::RtMidiInData *> (procRef);
  336. CoreMidiData *apiData = static_cast<CoreMidiData *> (data->apiData);
  337. unsigned char status;
  338. unsigned short nBytes, iByte, size;
  339. unsigned long long time;
  340. bool& continueSysex = data->continueSysex;
  341. MidiInApi::MidiMessage& message = data->message;
  342. const MIDIPacket *packet = &list->packet[0];
  343. for ( unsigned int i=0; i<list->numPackets; ++i ) {
  344. // My interpretation of the CoreMIDI documentation: all message
  345. // types, except sysex, are complete within a packet and there may
  346. // be several of them in a single packet. Sysex messages can be
  347. // broken across multiple packets and PacketLists but are bundled
  348. // alone within each packet (these packets do not contain other
  349. // message types). If sysex messages are split across multiple
  350. // MIDIPacketLists, they must be handled by multiple calls to this
  351. // function.
  352. nBytes = packet->length;
  353. if ( nBytes == 0 ) continue;
  354. // Calculate time stamp.
  355. if ( data->firstMessage ) {
  356. message.timeStamp = 0.0;
  357. data->firstMessage = false;
  358. }
  359. else {
  360. time = packet->timeStamp;
  361. if ( time == 0 ) { // this happens when receiving asynchronous sysex messages
  362. time = AudioGetCurrentHostTime();
  363. }
  364. time -= apiData->lastTime;
  365. time = AudioConvertHostTimeToNanos( time );
  366. if ( !continueSysex )
  367. message.timeStamp = time * 0.000000001;
  368. }
  369. apiData->lastTime = packet->timeStamp;
  370. if ( apiData->lastTime == 0 ) { // this happens when receiving asynchronous sysex messages
  371. apiData->lastTime = AudioGetCurrentHostTime();
  372. }
  373. //std::cout << "TimeStamp = " << packet->timeStamp << std::endl;
  374. iByte = 0;
  375. if ( continueSysex ) {
  376. // We have a continuing, segmented sysex message.
  377. if ( !( data->ignoreFlags & 0x01 ) ) {
  378. // If we're not ignoring sysex messages, copy the entire packet.
  379. for ( unsigned int j=0; j<nBytes; ++j )
  380. message.bytes.push_back( packet->data[j] );
  381. }
  382. continueSysex = packet->data[nBytes-1] != 0xF7;
  383. if ( !( data->ignoreFlags & 0x01 ) && !continueSysex ) {
  384. // If not a continuing sysex message, invoke the user callback function or queue the message.
  385. if ( data->usingCallback ) {
  386. RtMidiIn::RtMidiCallback callback = (RtMidiIn::RtMidiCallback) data->userCallback;
  387. callback( message.timeStamp, &message.bytes, data->userData );
  388. }
  389. else {
  390. // As long as we haven't reached our queue size limit, push the message.
  391. if ( data->queue.size < data->queue.ringSize ) {
  392. data->queue.ring[data->queue.back++] = message;
  393. if ( data->queue.back == data->queue.ringSize )
  394. data->queue.back = 0;
  395. data->queue.size++;
  396. }
  397. else
  398. std::cerr << "\nMidiInCore: message queue limit reached!!\n\n";
  399. }
  400. message.bytes.clear();
  401. }
  402. }
  403. else {
  404. while ( iByte < nBytes ) {
  405. size = 0;
  406. // We are expecting that the next byte in the packet is a status byte.
  407. status = packet->data[iByte];
  408. if ( !(status & 0x80) ) break;
  409. // Determine the number of bytes in the MIDI message.
  410. if ( status < 0xC0 ) size = 3;
  411. else if ( status < 0xE0 ) size = 2;
  412. else if ( status < 0xF0 ) size = 3;
  413. else if ( status == 0xF0 ) {
  414. // A MIDI sysex
  415. if ( data->ignoreFlags & 0x01 ) {
  416. size = 0;
  417. iByte = nBytes;
  418. }
  419. else size = nBytes - iByte;
  420. continueSysex = packet->data[nBytes-1] != 0xF7;
  421. }
  422. else if ( status == 0xF1 ) {
  423. // A MIDI time code message
  424. if ( data->ignoreFlags & 0x02 ) {
  425. size = 0;
  426. iByte += 2;
  427. }
  428. else size = 2;
  429. }
  430. else if ( status == 0xF2 ) size = 3;
  431. else if ( status == 0xF3 ) size = 2;
  432. else if ( status == 0xF8 && ( data->ignoreFlags & 0x02 ) ) {
  433. // A MIDI timing tick message and we're ignoring it.
  434. size = 0;
  435. iByte += 1;
  436. }
  437. else if ( status == 0xFE && ( data->ignoreFlags & 0x04 ) ) {
  438. // A MIDI active sensing message and we're ignoring it.
  439. size = 0;
  440. iByte += 1;
  441. }
  442. else size = 1;
  443. // Copy the MIDI data to our vector.
  444. if ( size ) {
  445. message.bytes.assign( &packet->data[iByte], &packet->data[iByte+size] );
  446. if ( !continueSysex ) {
  447. // If not a continuing sysex message, invoke the user callback function or queue the message.
  448. if ( data->usingCallback ) {
  449. RtMidiIn::RtMidiCallback callback = (RtMidiIn::RtMidiCallback) data->userCallback;
  450. callback( message.timeStamp, &message.bytes, data->userData );
  451. }
  452. else {
  453. // As long as we haven't reached our queue size limit, push the message.
  454. if ( data->queue.size < data->queue.ringSize ) {
  455. data->queue.ring[data->queue.back++] = message;
  456. if ( data->queue.back == data->queue.ringSize )
  457. data->queue.back = 0;
  458. data->queue.size++;
  459. }
  460. else
  461. std::cerr << "\nMidiInCore: message queue limit reached!!\n\n";
  462. }
  463. message.bytes.clear();
  464. }
  465. iByte += size;
  466. }
  467. }
  468. }
  469. packet = MIDIPacketNext(packet);
  470. }
  471. }
  472. MidiInCore :: MidiInCore( const std::string clientName, unsigned int queueSizeLimit ) : MidiInApi( queueSizeLimit )
  473. {
  474. initialize( clientName );
  475. }
  476. MidiInCore :: ~MidiInCore( void )
  477. {
  478. // Close a connection if it exists.
  479. closePort();
  480. // Cleanup.
  481. CoreMidiData *data = static_cast<CoreMidiData *> (apiData_);
  482. MIDIClientDispose( data->client );
  483. if ( data->endpoint ) MIDIEndpointDispose( data->endpoint );
  484. delete data;
  485. }
  486. void MidiInCore :: initialize( const std::string& clientName )
  487. {
  488. // Set up our client.
  489. MIDIClientRef client;
  490. CFStringRef name = CFStringCreateWithCString( NULL, clientName.c_str(), kCFStringEncodingASCII );
  491. OSStatus result = MIDIClientCreate(name, NULL, NULL, &client );
  492. if ( result != noErr ) {
  493. errorString_ = "MidiInCore::initialize: error creating OS-X MIDI client object.";
  494. error( RtMidiError::DRIVER_ERROR, errorString_ );
  495. return;
  496. }
  497. // Save our api-specific connection information.
  498. CoreMidiData *data = (CoreMidiData *) new CoreMidiData;
  499. data->client = client;
  500. data->endpoint = 0;
  501. apiData_ = (void *) data;
  502. inputData_.apiData = (void *) data;
  503. CFRelease(name);
  504. }
  505. void MidiInCore :: openPort( unsigned int portNumber, const std::string portName )
  506. {
  507. if ( connected_ ) {
  508. errorString_ = "MidiInCore::openPort: a valid connection already exists!";
  509. error( RtMidiError::WARNING, errorString_ );
  510. return;
  511. }
  512. CFRunLoopRunInMode( kCFRunLoopDefaultMode, 0, false );
  513. unsigned int nSrc = MIDIGetNumberOfSources();
  514. if (nSrc < 1) {
  515. errorString_ = "MidiInCore::openPort: no MIDI input sources found!";
  516. error( RtMidiError::NO_DEVICES_FOUND, errorString_ );
  517. return;
  518. }
  519. if ( portNumber >= nSrc ) {
  520. std::ostringstream ost;
  521. ost << "MidiInCore::openPort: the 'portNumber' argument (" << portNumber << ") is invalid.";
  522. errorString_ = ost.str();
  523. error( RtMidiError::INVALID_PARAMETER, errorString_ );
  524. return;
  525. }
  526. MIDIPortRef port;
  527. CoreMidiData *data = static_cast<CoreMidiData *> (apiData_);
  528. OSStatus result = MIDIInputPortCreate( data->client,
  529. CFStringCreateWithCString( NULL, portName.c_str(), kCFStringEncodingASCII ),
  530. midiInputCallback, (void *)&inputData_, &port );
  531. if ( result != noErr ) {
  532. MIDIClientDispose( data->client );
  533. errorString_ = "MidiInCore::openPort: error creating OS-X MIDI input port.";
  534. error( RtMidiError::DRIVER_ERROR, errorString_ );
  535. return;
  536. }
  537. // Get the desired input source identifier.
  538. MIDIEndpointRef endpoint = MIDIGetSource( portNumber );
  539. if ( endpoint == 0 ) {
  540. MIDIPortDispose( port );
  541. MIDIClientDispose( data->client );
  542. errorString_ = "MidiInCore::openPort: error getting MIDI input source reference.";
  543. error( RtMidiError::DRIVER_ERROR, errorString_ );
  544. return;
  545. }
  546. // Make the connection.
  547. result = MIDIPortConnectSource( port, endpoint, NULL );
  548. if ( result != noErr ) {
  549. MIDIPortDispose( port );
  550. MIDIClientDispose( data->client );
  551. errorString_ = "MidiInCore::openPort: error connecting OS-X MIDI input port.";
  552. error( RtMidiError::DRIVER_ERROR, errorString_ );
  553. return;
  554. }
  555. // Save our api-specific port information.
  556. data->port = port;
  557. connected_ = true;
  558. }
  559. void MidiInCore :: openVirtualPort( const std::string portName )
  560. {
  561. CoreMidiData *data = static_cast<CoreMidiData *> (apiData_);
  562. // Create a virtual MIDI input destination.
  563. MIDIEndpointRef endpoint;
  564. OSStatus result = MIDIDestinationCreate( data->client,
  565. CFStringCreateWithCString( NULL, portName.c_str(), kCFStringEncodingASCII ),
  566. midiInputCallback, (void *)&inputData_, &endpoint );
  567. if ( result != noErr ) {
  568. errorString_ = "MidiInCore::openVirtualPort: error creating virtual OS-X MIDI destination.";
  569. error( RtMidiError::DRIVER_ERROR, errorString_ );
  570. return;
  571. }
  572. // Save our api-specific connection information.
  573. data->endpoint = endpoint;
  574. }
  575. void MidiInCore :: closePort( void )
  576. {
  577. if ( connected_ ) {
  578. CoreMidiData *data = static_cast<CoreMidiData *> (apiData_);
  579. MIDIPortDispose( data->port );
  580. connected_ = false;
  581. }
  582. }
  583. unsigned int MidiInCore :: getPortCount()
  584. {
  585. CFRunLoopRunInMode( kCFRunLoopDefaultMode, 0, false );
  586. return MIDIGetNumberOfSources();
  587. }
  588. // This function was submitted by Douglas Casey Tucker and apparently
  589. // derived largely from PortMidi.
  590. CFStringRef EndpointName( MIDIEndpointRef endpoint, bool isExternal )
  591. {
  592. CFMutableStringRef result = CFStringCreateMutable( NULL, 0 );
  593. CFStringRef str;
  594. // Begin with the endpoint's name.
  595. str = NULL;
  596. MIDIObjectGetStringProperty( endpoint, kMIDIPropertyName, &str );
  597. if ( str != NULL ) {
  598. CFStringAppend( result, str );
  599. CFRelease( str );
  600. }
  601. MIDIEntityRef entity = 0;
  602. MIDIEndpointGetEntity( endpoint, &entity );
  603. if ( entity == 0 )
  604. // probably virtual
  605. return result;
  606. if ( CFStringGetLength( result ) == 0 ) {
  607. // endpoint name has zero length -- try the entity
  608. str = NULL;
  609. MIDIObjectGetStringProperty( entity, kMIDIPropertyName, &str );
  610. if ( str != NULL ) {
  611. CFStringAppend( result, str );
  612. CFRelease( str );
  613. }
  614. }
  615. // now consider the device's name
  616. MIDIDeviceRef device = 0;
  617. MIDIEntityGetDevice( entity, &device );
  618. if ( device == 0 )
  619. return result;
  620. str = NULL;
  621. MIDIObjectGetStringProperty( device, kMIDIPropertyName, &str );
  622. if ( CFStringGetLength( result ) == 0 ) {
  623. CFRelease( result );
  624. return str;
  625. }
  626. if ( str != NULL ) {
  627. // if an external device has only one entity, throw away
  628. // the endpoint name and just use the device name
  629. if ( isExternal && MIDIDeviceGetNumberOfEntities( device ) < 2 ) {
  630. CFRelease( result );
  631. return str;
  632. } else {
  633. if ( CFStringGetLength( str ) == 0 ) {
  634. CFRelease( str );
  635. return result;
  636. }
  637. // does the entity name already start with the device name?
  638. // (some drivers do this though they shouldn't)
  639. // if so, do not prepend
  640. if ( CFStringCompareWithOptions( result, /* endpoint name */
  641. str /* device name */,
  642. CFRangeMake(0, CFStringGetLength( str ) ), 0 ) != kCFCompareEqualTo ) {
  643. // prepend the device name to the entity name
  644. if ( CFStringGetLength( result ) > 0 )
  645. CFStringInsert( result, 0, CFSTR(" ") );
  646. CFStringInsert( result, 0, str );
  647. }
  648. CFRelease( str );
  649. }
  650. }
  651. return result;
  652. }
  653. // This function was submitted by Douglas Casey Tucker and apparently
  654. // derived largely from PortMidi.
  655. static CFStringRef ConnectedEndpointName( MIDIEndpointRef endpoint )
  656. {
  657. CFMutableStringRef result = CFStringCreateMutable( NULL, 0 );
  658. CFStringRef str;
  659. OSStatus err;
  660. int i;
  661. // Does the endpoint have connections?
  662. CFDataRef connections = NULL;
  663. int nConnected = 0;
  664. bool anyStrings = false;
  665. err = MIDIObjectGetDataProperty( endpoint, kMIDIPropertyConnectionUniqueID, &connections );
  666. if ( connections != NULL ) {
  667. // It has connections, follow them
  668. // Concatenate the names of all connected devices
  669. nConnected = CFDataGetLength( connections ) / sizeof(MIDIUniqueID);
  670. if ( nConnected ) {
  671. const SInt32 *pid = (const SInt32 *)(CFDataGetBytePtr(connections));
  672. for ( i=0; i<nConnected; ++i, ++pid ) {
  673. MIDIUniqueID id = EndianS32_BtoN( *pid );
  674. MIDIObjectRef connObject;
  675. MIDIObjectType connObjectType;
  676. err = MIDIObjectFindByUniqueID( id, &connObject, &connObjectType );
  677. if ( err == noErr ) {
  678. if ( connObjectType == kMIDIObjectType_ExternalSource ||
  679. connObjectType == kMIDIObjectType_ExternalDestination ) {
  680. // Connected to an external device's endpoint (10.3 and later).
  681. str = EndpointName( (MIDIEndpointRef)(connObject), true );
  682. } else {
  683. // Connected to an external device (10.2) (or something else, catch-
  684. str = NULL;
  685. MIDIObjectGetStringProperty( connObject, kMIDIPropertyName, &str );
  686. }
  687. if ( str != NULL ) {
  688. if ( anyStrings )
  689. CFStringAppend( result, CFSTR(", ") );
  690. else anyStrings = true;
  691. CFStringAppend( result, str );
  692. CFRelease( str );
  693. }
  694. }
  695. }
  696. }
  697. CFRelease( connections );
  698. }
  699. if ( anyStrings )
  700. return result;
  701. CFRelease( result );
  702. // Here, either the endpoint had no connections, or we failed to obtain names
  703. return EndpointName( endpoint, false );
  704. }
  705. std::string MidiInCore :: getPortName( unsigned int portNumber )
  706. {
  707. CFStringRef nameRef;
  708. MIDIEndpointRef portRef;
  709. char name[128];
  710. std::string stringName;
  711. CFRunLoopRunInMode( kCFRunLoopDefaultMode, 0, false );
  712. if ( portNumber >= MIDIGetNumberOfSources() ) {
  713. std::ostringstream ost;
  714. ost << "MidiInCore::getPortName: the 'portNumber' argument (" << portNumber << ") is invalid.";
  715. errorString_ = ost.str();
  716. error( RtMidiError::WARNING, errorString_ );
  717. return stringName;
  718. }
  719. portRef = MIDIGetSource( portNumber );
  720. nameRef = ConnectedEndpointName(portRef);
  721. CFStringGetCString( nameRef, name, sizeof(name), CFStringGetSystemEncoding());
  722. CFRelease( nameRef );
  723. return stringName = name;
  724. }
  725. //*********************************************************************//
  726. // API: OS-X
  727. // Class Definitions: MidiOutCore
  728. //*********************************************************************//
  729. MidiOutCore :: MidiOutCore( const std::string clientName ) : MidiOutApi()
  730. {
  731. initialize( clientName );
  732. }
  733. MidiOutCore :: ~MidiOutCore( void )
  734. {
  735. // Close a connection if it exists.
  736. closePort();
  737. // Cleanup.
  738. CoreMidiData *data = static_cast<CoreMidiData *> (apiData_);
  739. MIDIClientDispose( data->client );
  740. if ( data->endpoint ) MIDIEndpointDispose( data->endpoint );
  741. delete data;
  742. }
  743. void MidiOutCore :: initialize( const std::string& clientName )
  744. {
  745. // Set up our client.
  746. MIDIClientRef client;
  747. CFStringRef name = CFStringCreateWithCString( NULL, clientName.c_str(), kCFStringEncodingASCII );
  748. OSStatus result = MIDIClientCreate(name, NULL, NULL, &client );
  749. if ( result != noErr ) {
  750. errorString_ = "MidiOutCore::initialize: error creating OS-X MIDI client object.";
  751. error( RtMidiError::DRIVER_ERROR, errorString_ );
  752. return;
  753. }
  754. // Save our api-specific connection information.
  755. CoreMidiData *data = (CoreMidiData *) new CoreMidiData;
  756. data->client = client;
  757. data->endpoint = 0;
  758. apiData_ = (void *) data;
  759. CFRelease( name );
  760. }
  761. unsigned int MidiOutCore :: getPortCount()
  762. {
  763. CFRunLoopRunInMode( kCFRunLoopDefaultMode, 0, false );
  764. return MIDIGetNumberOfDestinations();
  765. }
  766. std::string MidiOutCore :: getPortName( unsigned int portNumber )
  767. {
  768. CFStringRef nameRef;
  769. MIDIEndpointRef portRef;
  770. char name[128];
  771. std::string stringName;
  772. CFRunLoopRunInMode( kCFRunLoopDefaultMode, 0, false );
  773. if ( portNumber >= MIDIGetNumberOfDestinations() ) {
  774. std::ostringstream ost;
  775. ost << "MidiOutCore::getPortName: the 'portNumber' argument (" << portNumber << ") is invalid.";
  776. errorString_ = ost.str();
  777. error( RtMidiError::WARNING, errorString_ );
  778. return stringName;
  779. }
  780. portRef = MIDIGetDestination( portNumber );
  781. nameRef = ConnectedEndpointName(portRef);
  782. CFStringGetCString( nameRef, name, sizeof(name), CFStringGetSystemEncoding());
  783. CFRelease( nameRef );
  784. return stringName = name;
  785. }
  786. void MidiOutCore :: openPort( unsigned int portNumber, const std::string portName )
  787. {
  788. if ( connected_ ) {
  789. errorString_ = "MidiOutCore::openPort: a valid connection already exists!";
  790. error( RtMidiError::WARNING, errorString_ );
  791. return;
  792. }
  793. CFRunLoopRunInMode( kCFRunLoopDefaultMode, 0, false );
  794. unsigned int nDest = MIDIGetNumberOfDestinations();
  795. if (nDest < 1) {
  796. errorString_ = "MidiOutCore::openPort: no MIDI output destinations found!";
  797. error( RtMidiError::NO_DEVICES_FOUND, errorString_ );
  798. return;
  799. }
  800. if ( portNumber >= nDest ) {
  801. std::ostringstream ost;
  802. ost << "MidiOutCore::openPort: the 'portNumber' argument (" << portNumber << ") is invalid.";
  803. errorString_ = ost.str();
  804. error( RtMidiError::INVALID_PARAMETER, errorString_ );
  805. return;
  806. }
  807. MIDIPortRef port;
  808. CoreMidiData *data = static_cast<CoreMidiData *> (apiData_);
  809. OSStatus result = MIDIOutputPortCreate( data->client,
  810. CFStringCreateWithCString( NULL, portName.c_str(), kCFStringEncodingASCII ),
  811. &port );
  812. if ( result != noErr ) {
  813. MIDIClientDispose( data->client );
  814. errorString_ = "MidiOutCore::openPort: error creating OS-X MIDI output port.";
  815. error( RtMidiError::DRIVER_ERROR, errorString_ );
  816. return;
  817. }
  818. // Get the desired output port identifier.
  819. MIDIEndpointRef destination = MIDIGetDestination( portNumber );
  820. if ( destination == 0 ) {
  821. MIDIPortDispose( port );
  822. MIDIClientDispose( data->client );
  823. errorString_ = "MidiOutCore::openPort: error getting MIDI output destination reference.";
  824. error( RtMidiError::DRIVER_ERROR, errorString_ );
  825. return;
  826. }
  827. // Save our api-specific connection information.
  828. data->port = port;
  829. data->destinationId = destination;
  830. connected_ = true;
  831. }
  832. void MidiOutCore :: closePort( void )
  833. {
  834. if ( connected_ ) {
  835. CoreMidiData *data = static_cast<CoreMidiData *> (apiData_);
  836. MIDIPortDispose( data->port );
  837. connected_ = false;
  838. }
  839. }
  840. void MidiOutCore :: openVirtualPort( std::string portName )
  841. {
  842. CoreMidiData *data = static_cast<CoreMidiData *> (apiData_);
  843. if ( data->endpoint ) {
  844. errorString_ = "MidiOutCore::openVirtualPort: a virtual output port already exists!";
  845. error( RtMidiError::WARNING, errorString_ );
  846. return;
  847. }
  848. // Create a virtual MIDI output source.
  849. MIDIEndpointRef endpoint;
  850. OSStatus result = MIDISourceCreate( data->client,
  851. CFStringCreateWithCString( NULL, portName.c_str(), kCFStringEncodingASCII ),
  852. &endpoint );
  853. if ( result != noErr ) {
  854. errorString_ = "MidiOutCore::initialize: error creating OS-X virtual MIDI source.";
  855. error( RtMidiError::DRIVER_ERROR, errorString_ );
  856. return;
  857. }
  858. // Save our api-specific connection information.
  859. data->endpoint = endpoint;
  860. }
  861. void MidiOutCore :: sendMessage( std::vector<unsigned char> *message )
  862. {
  863. // We use the MIDISendSysex() function to asynchronously send sysex
  864. // messages. Otherwise, we use a single CoreMidi MIDIPacket.
  865. unsigned int nBytes = message->size();
  866. if ( nBytes == 0 ) {
  867. errorString_ = "MidiOutCore::sendMessage: no data in message argument!";
  868. error( RtMidiError::WARNING, errorString_ );
  869. return;
  870. }
  871. MIDITimeStamp timeStamp = AudioGetCurrentHostTime();
  872. CoreMidiData *data = static_cast<CoreMidiData *> (apiData_);
  873. OSStatus result;
  874. if ( message->at(0) != 0xF0 && nBytes > 3 ) {
  875. errorString_ = "MidiOutCore::sendMessage: message format problem ... not sysex but > 3 bytes?";
  876. error( RtMidiError::WARNING, errorString_ );
  877. return;
  878. }
  879. Byte buffer[nBytes+(sizeof(MIDIPacketList))];
  880. ByteCount listSize = sizeof(buffer);
  881. MIDIPacketList *packetList = (MIDIPacketList*)buffer;
  882. MIDIPacket *packet = MIDIPacketListInit( packetList );
  883. ByteCount remainingBytes = nBytes;
  884. while (remainingBytes && packet) {
  885. ByteCount bytesForPacket = remainingBytes > 65535 ? 65535 : remainingBytes; // 65535 = maximum size of a MIDIPacket
  886. const Byte* dataStartPtr = (const Byte *) &message->at( nBytes - remainingBytes );
  887. packet = MIDIPacketListAdd( packetList, listSize, packet, timeStamp, bytesForPacket, dataStartPtr);
  888. remainingBytes -= bytesForPacket;
  889. }
  890. if ( !packet ) {
  891. errorString_ = "MidiOutCore::sendMessage: could not allocate packet list";
  892. error( RtMidiError::DRIVER_ERROR, errorString_ );
  893. return;
  894. }
  895. // Send to any destinations that may have connected to us.
  896. if ( data->endpoint ) {
  897. result = MIDIReceived( data->endpoint, packetList );
  898. if ( result != noErr ) {
  899. errorString_ = "MidiOutCore::sendMessage: error sending MIDI to virtual destinations.";
  900. error( RtMidiError::WARNING, errorString_ );
  901. }
  902. }
  903. // And send to an explicit destination port if we're connected.
  904. if ( connected_ ) {
  905. result = MIDISend( data->port, data->destinationId, packetList );
  906. if ( result != noErr ) {
  907. errorString_ = "MidiOutCore::sendMessage: error sending MIDI message to port.";
  908. error( RtMidiError::WARNING, errorString_ );
  909. }
  910. }
  911. }
  912. #endif // __MACOSX_CORE__
  913. //*********************************************************************//
  914. // API: LINUX ALSA SEQUENCER
  915. //*********************************************************************//
  916. // API information found at:
  917. // - http://www.alsa-project.org/documentation.php#Library
  918. #if defined(__LINUX_ALSA__)
  919. // The ALSA Sequencer API is based on the use of a callback function for
  920. // MIDI input.
  921. //
  922. // Thanks to Pedro Lopez-Cabanillas for help with the ALSA sequencer
  923. // time stamps and other assorted fixes!!!
  924. // If you don't need timestamping for incoming MIDI events, define the
  925. // preprocessor definition AVOID_TIMESTAMPING to save resources
  926. // associated with the ALSA sequencer queues.
  927. #include <pthread.h>
  928. #include <sys/time.h>
  929. // ALSA header file.
  930. #include <alsa/asoundlib.h>
  931. // A structure to hold variables related to the ALSA API
  932. // implementation.
  933. struct AlsaMidiData {
  934. snd_seq_t *seq;
  935. unsigned int portNum;
  936. int vport;
  937. snd_seq_port_subscribe_t *subscription;
  938. snd_midi_event_t *coder;
  939. unsigned int bufferSize;
  940. unsigned char *buffer;
  941. pthread_t thread;
  942. pthread_t dummy_thread_id;
  943. unsigned long long lastTime;
  944. int queue_id; // an input queue is needed to get timestamped events
  945. int trigger_fds[2];
  946. };
  947. #define PORT_TYPE( pinfo, bits ) ((snd_seq_port_info_get_capability(pinfo) & (bits)) == (bits))
  948. //*********************************************************************//
  949. // API: LINUX ALSA
  950. // Class Definitions: MidiInAlsa
  951. //*********************************************************************//
  952. static void *alsaMidiHandler( void *ptr )
  953. {
  954. MidiInApi::RtMidiInData *data = static_cast<MidiInApi::RtMidiInData *> (ptr);
  955. AlsaMidiData *apiData = static_cast<AlsaMidiData *> (data->apiData);
  956. long nBytes;
  957. unsigned long long time, lastTime;
  958. bool continueSysex = false;
  959. bool doDecode = false;
  960. MidiInApi::MidiMessage message;
  961. int poll_fd_count;
  962. struct pollfd *poll_fds;
  963. snd_seq_event_t *ev;
  964. int result;
  965. apiData->bufferSize = 32;
  966. result = snd_midi_event_new( 0, &apiData->coder );
  967. if ( result < 0 ) {
  968. data->doInput = false;
  969. std::cerr << "\nMidiInAlsa::alsaMidiHandler: error initializing MIDI event parser!\n\n";
  970. return 0;
  971. }
  972. unsigned char *buffer = (unsigned char *) malloc( apiData->bufferSize );
  973. if ( buffer == NULL ) {
  974. data->doInput = false;
  975. snd_midi_event_free( apiData->coder );
  976. apiData->coder = 0;
  977. std::cerr << "\nMidiInAlsa::alsaMidiHandler: error initializing buffer memory!\n\n";
  978. return 0;
  979. }
  980. snd_midi_event_init( apiData->coder );
  981. snd_midi_event_no_status( apiData->coder, 1 ); // suppress running status messages
  982. poll_fd_count = snd_seq_poll_descriptors_count( apiData->seq, POLLIN ) + 1;
  983. poll_fds = (struct pollfd*)alloca( poll_fd_count * sizeof( struct pollfd ));
  984. snd_seq_poll_descriptors( apiData->seq, poll_fds + 1, poll_fd_count - 1, POLLIN );
  985. poll_fds[0].fd = apiData->trigger_fds[0];
  986. poll_fds[0].events = POLLIN;
  987. while ( data->doInput ) {
  988. if ( snd_seq_event_input_pending( apiData->seq, 1 ) == 0 ) {
  989. // No data pending
  990. if ( poll( poll_fds, poll_fd_count, -1) >= 0 ) {
  991. if ( poll_fds[0].revents & POLLIN ) {
  992. bool dummy;
  993. int res = read( poll_fds[0].fd, &dummy, sizeof(dummy) );
  994. (void) res;
  995. }
  996. }
  997. continue;
  998. }
  999. // If here, there should be data.
  1000. result = snd_seq_event_input( apiData->seq, &ev );
  1001. if ( result == -ENOSPC ) {
  1002. std::cerr << "\nMidiInAlsa::alsaMidiHandler: MIDI input buffer overrun!\n\n";
  1003. continue;
  1004. }
  1005. else if ( result <= 0 ) {
  1006. std::cerr << "\nMidiInAlsa::alsaMidiHandler: unknown MIDI input error!\n";
  1007. perror("System reports");
  1008. continue;
  1009. }
  1010. // This is a bit weird, but we now have to decode an ALSA MIDI
  1011. // event (back) into MIDI bytes. We'll ignore non-MIDI types.
  1012. if ( !continueSysex ) message.bytes.clear();
  1013. doDecode = false;
  1014. switch ( ev->type ) {
  1015. case SND_SEQ_EVENT_PORT_SUBSCRIBED:
  1016. #if defined(__RTMIDI_DEBUG__)
  1017. std::cout << "MidiInAlsa::alsaMidiHandler: port connection made!\n";
  1018. #endif
  1019. break;
  1020. case SND_SEQ_EVENT_PORT_UNSUBSCRIBED:
  1021. #if defined(__RTMIDI_DEBUG__)
  1022. std::cerr << "MidiInAlsa::alsaMidiHandler: port connection has closed!\n";
  1023. std::cout << "sender = " << (int) ev->data.connect.sender.client << ":"
  1024. << (int) ev->data.connect.sender.port
  1025. << ", dest = " << (int) ev->data.connect.dest.client << ":"
  1026. << (int) ev->data.connect.dest.port
  1027. << std::endl;
  1028. #endif
  1029. break;
  1030. case SND_SEQ_EVENT_QFRAME: // MIDI time code
  1031. if ( !( data->ignoreFlags & 0x02 ) ) doDecode = true;
  1032. break;
  1033. case SND_SEQ_EVENT_TICK: // 0xF9 ... MIDI timing tick
  1034. if ( !( data->ignoreFlags & 0x02 ) ) doDecode = true;
  1035. break;
  1036. case SND_SEQ_EVENT_CLOCK: // 0xF8 ... MIDI timing (clock) tick
  1037. if ( !( data->ignoreFlags & 0x02 ) ) doDecode = true;
  1038. break;
  1039. case SND_SEQ_EVENT_SENSING: // Active sensing
  1040. if ( !( data->ignoreFlags & 0x04 ) ) doDecode = true;
  1041. break;
  1042. case SND_SEQ_EVENT_SYSEX:
  1043. if ( (data->ignoreFlags & 0x01) ) break;
  1044. if ( ev->data.ext.len > apiData->bufferSize ) {
  1045. apiData->bufferSize = ev->data.ext.len;
  1046. free( buffer );
  1047. buffer = (unsigned char *) malloc( apiData->bufferSize );
  1048. if ( buffer == NULL ) {
  1049. data->doInput = false;
  1050. std::cerr << "\nMidiInAlsa::alsaMidiHandler: error resizing buffer memory!\n\n";
  1051. break;
  1052. }
  1053. }
  1054. default:
  1055. doDecode = true;
  1056. }
  1057. if ( doDecode ) {
  1058. nBytes = snd_midi_event_decode( apiData->coder, buffer, apiData->bufferSize, ev );
  1059. if ( nBytes > 0 ) {
  1060. // The ALSA sequencer has a maximum buffer size for MIDI sysex
  1061. // events of 256 bytes. If a device sends sysex messages larger
  1062. // than this, they are segmented into 256 byte chunks. So,
  1063. // we'll watch for this and concatenate sysex chunks into a
  1064. // single sysex message if necessary.
  1065. if ( !continueSysex )
  1066. message.bytes.assign( buffer, &buffer[nBytes] );
  1067. else
  1068. message.bytes.insert( message.bytes.end(), buffer, &buffer[nBytes] );
  1069. continueSysex = ( ( ev->type == SND_SEQ_EVENT_SYSEX ) && ( message.bytes.back() != 0xF7 ) );
  1070. if ( !continueSysex ) {
  1071. // Calculate the time stamp:
  1072. message.timeStamp = 0.0;
  1073. // Method 1: Use the system time.
  1074. //(void)gettimeofday(&tv, (struct timezone *)NULL);
  1075. //time = (tv.tv_sec * 1000000) + tv.tv_usec;
  1076. // Method 2: Use the ALSA sequencer event time data.
  1077. // (thanks to Pedro Lopez-Cabanillas!).
  1078. time = ( ev->time.time.tv_sec * 1000000 ) + ( ev->time.time.tv_nsec/1000 );
  1079. lastTime = time;
  1080. time -= apiData->lastTime;
  1081. apiData->lastTime = lastTime;
  1082. if ( data->firstMessage == true )
  1083. data->firstMessage = false;
  1084. else
  1085. message.timeStamp = time * 0.000001;
  1086. }
  1087. else {
  1088. #if defined(__RTMIDI_DEBUG__)
  1089. std::cerr << "\nMidiInAlsa::alsaMidiHandler: event parsing error or not a MIDI event!\n\n";
  1090. #endif
  1091. }
  1092. }
  1093. }
  1094. snd_seq_free_event( ev );
  1095. if ( message.bytes.size() == 0 || continueSysex ) continue;
  1096. if ( data->usingCallback ) {
  1097. RtMidiIn::RtMidiCallback callback = (RtMidiIn::RtMidiCallback) data->userCallback;
  1098. callback( message.timeStamp, &message.bytes, data->userData );
  1099. }
  1100. else {
  1101. // As long as we haven't reached our queue size limit, push the message.
  1102. if ( data->queue.size < data->queue.ringSize ) {
  1103. data->queue.ring[data->queue.back++] = message;
  1104. if ( data->queue.back == data->queue.ringSize )
  1105. data->queue.back = 0;
  1106. data->queue.size++;
  1107. }
  1108. else
  1109. std::cerr << "\nMidiInAlsa: message queue limit reached!!\n\n";
  1110. }
  1111. }
  1112. if ( buffer ) free( buffer );
  1113. snd_midi_event_free( apiData->coder );
  1114. apiData->coder = 0;
  1115. apiData->thread = apiData->dummy_thread_id;
  1116. return 0;
  1117. }
  1118. MidiInAlsa :: MidiInAlsa( const std::string clientName, unsigned int queueSizeLimit ) : MidiInApi( queueSizeLimit )
  1119. {
  1120. initialize( clientName );
  1121. }
  1122. MidiInAlsa :: ~MidiInAlsa()
  1123. {
  1124. // Close a connection if it exists.
  1125. closePort();
  1126. // Shutdown the input thread.
  1127. AlsaMidiData *data = static_cast<AlsaMidiData *> (apiData_);
  1128. if ( inputData_.doInput ) {
  1129. inputData_.doInput = false;
  1130. int res = write( data->trigger_fds[1], &inputData_.doInput, sizeof(inputData_.doInput) );
  1131. (void) res;
  1132. if ( !pthread_equal(data->thread, data->dummy_thread_id) )
  1133. pthread_join( data->thread, NULL );
  1134. }
  1135. // Cleanup.
  1136. close ( data->trigger_fds[0] );
  1137. close ( data->trigger_fds[1] );
  1138. if ( data->vport >= 0 ) snd_seq_delete_port( data->seq, data->vport );
  1139. #ifndef AVOID_TIMESTAMPING
  1140. snd_seq_free_queue( data->seq, data->queue_id );
  1141. #endif
  1142. snd_seq_close( data->seq );
  1143. delete data;
  1144. }
  1145. void MidiInAlsa :: initialize( const std::string& clientName )
  1146. {
  1147. // Set up the ALSA sequencer client.
  1148. snd_seq_t *seq;
  1149. int result = snd_seq_open(&seq, "default", SND_SEQ_OPEN_DUPLEX, SND_SEQ_NONBLOCK);
  1150. if ( result < 0 ) {
  1151. errorString_ = "MidiInAlsa::initialize: error creating ALSA sequencer client object.";
  1152. error( RtMidiError::DRIVER_ERROR, errorString_ );
  1153. return;
  1154. }
  1155. // Set client name.
  1156. snd_seq_set_client_name( seq, clientName.c_str() );
  1157. // Save our api-specific connection information.
  1158. AlsaMidiData *data = (AlsaMidiData *) new AlsaMidiData;
  1159. data->seq = seq;
  1160. data->portNum = -1;
  1161. data->vport = -1;
  1162. data->subscription = 0;
  1163. data->dummy_thread_id = pthread_self();
  1164. data->thread = data->dummy_thread_id;
  1165. data->trigger_fds[0] = -1;
  1166. data->trigger_fds[1] = -1;
  1167. apiData_ = (void *) data;
  1168. inputData_.apiData = (void *) data;
  1169. if ( pipe(data->trigger_fds) == -1 ) {
  1170. errorString_ = "MidiInAlsa::initialize: error creating pipe objects.";
  1171. error( RtMidiError::DRIVER_ERROR, errorString_ );
  1172. return;
  1173. }
  1174. // Create the input queue
  1175. #ifndef AVOID_TIMESTAMPING
  1176. data->queue_id = snd_seq_alloc_named_queue(seq, "RtMidi Queue");
  1177. // Set arbitrary tempo (mm=100) and resolution (240)
  1178. snd_seq_queue_tempo_t *qtempo;
  1179. snd_seq_queue_tempo_alloca(&qtempo);
  1180. snd_seq_queue_tempo_set_tempo(qtempo, 600000);
  1181. snd_seq_queue_tempo_set_ppq(qtempo, 240);
  1182. snd_seq_set_queue_tempo(data->seq, data->queue_id, qtempo);
  1183. snd_seq_drain_output(data->seq);
  1184. #endif
  1185. }
  1186. // This function is used to count or get the pinfo structure for a given port number.
  1187. unsigned int portInfo( snd_seq_t *seq, snd_seq_port_info_t *pinfo, unsigned int type, int portNumber )
  1188. {
  1189. snd_seq_client_info_t *cinfo;
  1190. int client;
  1191. int count = 0;
  1192. snd_seq_client_info_alloca( &cinfo );
  1193. snd_seq_client_info_set_client( cinfo, -1 );
  1194. while ( snd_seq_query_next_client( seq, cinfo ) >= 0 ) {
  1195. client = snd_seq_client_info_get_client( cinfo );
  1196. if ( client == 0 ) continue;
  1197. // Reset query info
  1198. snd_seq_port_info_set_client( pinfo, client );
  1199. snd_seq_port_info_set_port( pinfo, -1 );
  1200. while ( snd_seq_query_next_port( seq, pinfo ) >= 0 ) {
  1201. unsigned int atyp = snd_seq_port_info_get_type( pinfo );
  1202. if ( ( ( atyp & SND_SEQ_PORT_TYPE_MIDI_GENERIC ) == 0 ) &&
  1203. ( ( atyp & SND_SEQ_PORT_TYPE_SYNTH ) == 0 ) ) continue;
  1204. unsigned int caps = snd_seq_port_info_get_capability( pinfo );
  1205. if ( ( caps & type ) != type ) continue;
  1206. if ( count == portNumber ) return 1;
  1207. ++count;
  1208. }
  1209. }
  1210. // If a negative portNumber was used, return the port count.
  1211. if ( portNumber < 0 ) return count;
  1212. return 0;
  1213. }
  1214. unsigned int MidiInAlsa :: getPortCount()
  1215. {
  1216. snd_seq_port_info_t *pinfo;
  1217. snd_seq_port_info_alloca( &pinfo );
  1218. AlsaMidiData *data = static_cast<AlsaMidiData *> (apiData_);
  1219. return portInfo( data->seq, pinfo, SND_SEQ_PORT_CAP_READ|SND_SEQ_PORT_CAP_SUBS_READ, -1 );
  1220. }
  1221. std::string MidiInAlsa :: getPortName( unsigned int portNumber )
  1222. {
  1223. snd_seq_client_info_t *cinfo;
  1224. snd_seq_port_info_t *pinfo;
  1225. snd_seq_client_info_alloca( &cinfo );
  1226. snd_seq_port_info_alloca( &pinfo );
  1227. std::string stringName;
  1228. AlsaMidiData *data = static_cast<AlsaMidiData *> (apiData_);
  1229. if ( portInfo( data->seq, pinfo, SND_SEQ_PORT_CAP_READ|SND_SEQ_PORT_CAP_SUBS_READ, (int) portNumber ) ) {
  1230. int cnum = snd_seq_port_info_get_client( pinfo );
  1231. snd_seq_get_any_client_info( data->seq, cnum, cinfo );
  1232. std::ostringstream os;
  1233. os << snd_seq_client_info_get_name( cinfo );
  1234. os << " "; // These lines added to make sure devices are listed
  1235. os << snd_seq_port_info_get_client( pinfo ); // with full portnames added to ensure individual device names
  1236. os << ":";
  1237. os << snd_seq_port_info_get_port( pinfo );
  1238. stringName = os.str();
  1239. return stringName;
  1240. }
  1241. // If we get here, we didn't find a match.
  1242. errorString_ = "MidiInAlsa::getPortName: error looking for port name!";
  1243. error( RtMidiError::WARNING, errorString_ );
  1244. return stringName;
  1245. }
  1246. void MidiInAlsa :: openPort( unsigned int portNumber, const std::string portName )
  1247. {
  1248. if ( connected_ ) {
  1249. errorString_ = "MidiInAlsa::openPort: a valid connection already exists!";
  1250. error( RtMidiError::WARNING, errorString_ );
  1251. return;
  1252. }
  1253. unsigned int nSrc = this->getPortCount();
  1254. if ( nSrc < 1 ) {
  1255. errorString_ = "MidiInAlsa::openPort: no MIDI input sources found!";
  1256. error( RtMidiError::NO_DEVICES_FOUND, errorString_ );
  1257. return;
  1258. }
  1259. snd_seq_port_info_t *src_pinfo;
  1260. snd_seq_port_info_alloca( &src_pinfo );
  1261. AlsaMidiData *data = static_cast<AlsaMidiData *> (apiData_);
  1262. if ( portInfo( data->seq, src_pinfo, SND_SEQ_PORT_CAP_READ|SND_SEQ_PORT_CAP_SUBS_READ, (int) portNumber ) == 0 ) {
  1263. std::ostringstream ost;
  1264. ost << "MidiInAlsa::openPort: the 'portNumber' argument (" << portNumber << ") is invalid.";
  1265. errorString_ = ost.str();
  1266. error( RtMidiError::INVALID_PARAMETER, errorString_ );
  1267. return;
  1268. }
  1269. snd_seq_addr_t sender, receiver;
  1270. sender.client = snd_seq_port_info_get_client( src_pinfo );
  1271. sender.port = snd_seq_port_info_get_port( src_pinfo );
  1272. receiver.client = snd_seq_client_id( data->seq );
  1273. snd_seq_port_info_t *pinfo;
  1274. snd_seq_port_info_alloca( &pinfo );
  1275. if ( data->vport < 0 ) {
  1276. snd_seq_port_info_set_client( pinfo, 0 );
  1277. snd_seq_port_info_set_port( pinfo, 0 );
  1278. snd_seq_port_info_set_capability( pinfo,
  1279. SND_SEQ_PORT_CAP_WRITE |
  1280. SND_SEQ_PORT_CAP_SUBS_WRITE );
  1281. snd_seq_port_info_set_type( pinfo,
  1282. SND_SEQ_PORT_TYPE_MIDI_GENERIC |
  1283. SND_SEQ_PORT_TYPE_APPLICATION );
  1284. snd_seq_port_info_set_midi_channels(pinfo, 16);
  1285. #ifndef AVOID_TIMESTAMPING
  1286. snd_seq_port_info_set_timestamping(pinfo, 1);
  1287. snd_seq_port_info_set_timestamp_real(pinfo, 1);
  1288. snd_seq_port_info_set_timestamp_queue(pinfo, data->queue_id);
  1289. #endif
  1290. snd_seq_port_info_set_name(pinfo, portName.c_str() );
  1291. data->vport = snd_seq_create_port(data->seq, pinfo);
  1292. if ( data->vport < 0 ) {
  1293. errorString_ = "MidiInAlsa::openPort: ALSA error creating input port.";
  1294. error( RtMidiError::DRIVER_ERROR, errorString_ );
  1295. return;
  1296. }
  1297. data->vport = snd_seq_port_info_get_port(pinfo);
  1298. }
  1299. receiver.port = data->vport;
  1300. if ( !data->subscription ) {
  1301. // Make subscription
  1302. if (snd_seq_port_subscribe_malloc( &data->subscription ) < 0) {
  1303. errorString_ = "MidiInAlsa::openPort: ALSA error allocation port subscription.";
  1304. error( RtMidiError::DRIVER_ERROR, errorString_ );
  1305. return;
  1306. }
  1307. snd_seq_port_subscribe_set_sender(data->subscription, &sender);
  1308. snd_seq_port_subscribe_set_dest(data->subscription, &receiver);
  1309. if ( snd_seq_subscribe_port(data->seq, data->subscription) ) {
  1310. snd_seq_port_subscribe_free( data->subscription );
  1311. data->subscription = 0;
  1312. errorString_ = "MidiInAlsa::openPort: ALSA error making port connection.";
  1313. error( RtMidiError::DRIVER_ERROR, errorString_ );
  1314. return;
  1315. }
  1316. }
  1317. if ( inputData_.doInput == false ) {
  1318. // Start the input queue
  1319. #ifndef AVOID_TIMESTAMPING
  1320. snd_seq_start_queue( data->seq, data->queue_id, NULL );
  1321. snd_seq_drain_output( data->seq );
  1322. #endif
  1323. // Start our MIDI input thread.
  1324. pthread_attr_t attr;
  1325. pthread_attr_init(&attr);
  1326. pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
  1327. pthread_attr_setschedpolicy(&attr, SCHED_OTHER);
  1328. inputData_.doInput = true;
  1329. int err = pthread_create(&data->thread, &attr, alsaMidiHandler, &inputData_);
  1330. pthread_attr_destroy(&attr);
  1331. if ( err ) {
  1332. snd_seq_unsubscribe_port( data->seq, data->subscription );
  1333. snd_seq_port_subscribe_free( data->subscription );
  1334. data->subscription = 0;
  1335. inputData_.doInput = false;
  1336. errorString_ = "MidiInAlsa::openPort: error starting MIDI input thread!";
  1337. error( RtMidiError::THREAD_ERROR, errorString_ );
  1338. return;
  1339. }
  1340. }
  1341. connected_ = true;
  1342. }
  1343. void MidiInAlsa :: openVirtualPort( std::string portName )
  1344. {
  1345. AlsaMidiData *data = static_cast<AlsaMidiData *> (apiData_);
  1346. if ( data->vport < 0 ) {
  1347. snd_seq_port_info_t *pinfo;
  1348. snd_seq_port_info_alloca( &pinfo );
  1349. snd_seq_port_info_set_capability( pinfo,
  1350. SND_SEQ_PORT_CAP_WRITE |
  1351. SND_SEQ_PORT_CAP_SUBS_WRITE );
  1352. snd_seq_port_info_set_type( pinfo,
  1353. SND_SEQ_PORT_TYPE_MIDI_GENERIC |
  1354. SND_SEQ_PORT_TYPE_APPLICATION );
  1355. snd_seq_port_info_set_midi_channels(pinfo, 16);
  1356. #ifndef AVOID_TIMESTAMPING
  1357. snd_seq_port_info_set_timestamping(pinfo, 1);
  1358. snd_seq_port_info_set_timestamp_real(pinfo, 1);
  1359. snd_seq_port_info_set_timestamp_queue(pinfo, data->queue_id);
  1360. #endif
  1361. snd_seq_port_info_set_name(pinfo, portName.c_str());
  1362. data->vport = snd_seq_create_port(data->seq, pinfo);
  1363. if ( data->vport < 0 ) {
  1364. errorString_ = "MidiInAlsa::openVirtualPort: ALSA error creating virtual port.";
  1365. error( RtMidiError::DRIVER_ERROR, errorString_ );
  1366. return;
  1367. }
  1368. data->vport = snd_seq_port_info_get_port(pinfo);
  1369. }
  1370. if ( inputData_.doInput == false ) {
  1371. // Wait for old thread to stop, if still running
  1372. if ( !pthread_equal(data->thread, data->dummy_thread_id) )
  1373. pthread_join( data->thread, NULL );
  1374. // Start the input queue
  1375. #ifndef AVOID_TIMESTAMPING
  1376. snd_seq_start_queue( data->seq, data->queue_id, NULL );
  1377. snd_seq_drain_output( data->seq );
  1378. #endif
  1379. // Start our MIDI input thread.
  1380. pthread_attr_t attr;
  1381. pthread_attr_init(&attr);
  1382. pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
  1383. pthread_attr_setschedpolicy(&attr, SCHED_OTHER);
  1384. inputData_.doInput = true;
  1385. int err = pthread_create(&data->thread, &attr, alsaMidiHandler, &inputData_);
  1386. pthread_attr_destroy(&attr);
  1387. if ( err ) {
  1388. if ( data->subscription ) {
  1389. snd_seq_unsubscribe_port( data->seq, data->subscription );
  1390. snd_seq_port_subscribe_free( data->subscription );
  1391. data->subscription = 0;
  1392. }
  1393. inputData_.doInput = false;
  1394. errorString_ = "MidiInAlsa::openPort: error starting MIDI input thread!";
  1395. error( RtMidiError::THREAD_ERROR, errorString_ );
  1396. return;
  1397. }
  1398. }
  1399. }
  1400. void MidiInAlsa :: closePort( void )
  1401. {
  1402. AlsaMidiData *data = static_cast<AlsaMidiData *> (apiData_);
  1403. if ( connected_ ) {
  1404. if ( data->subscription ) {
  1405. snd_seq_unsubscribe_port( data->seq, data->subscription );
  1406. snd_seq_port_subscribe_free( data->subscription );
  1407. data->subscription = 0;
  1408. }
  1409. // Stop the input queue
  1410. #ifndef AVOID_TIMESTAMPING
  1411. snd_seq_stop_queue( data->seq, data->queue_id, NULL );
  1412. snd_seq_drain_output( data->seq );
  1413. #endif
  1414. connected_ = false;
  1415. }
  1416. // Stop thread to avoid triggering the callback, while the port is intended to be closed
  1417. if ( inputData_.doInput ) {
  1418. inputData_.doInput = false;
  1419. int res = write( data->trigger_fds[1], &inputData_.doInput, sizeof(inputData_.doInput) );
  1420. (void) res;
  1421. if ( !pthread_equal(data->thread, data->dummy_thread_id) )
  1422. pthread_join( data->thread, NULL );
  1423. }
  1424. }
  1425. //*********************************************************************//
  1426. // API: LINUX ALSA
  1427. // Class Definitions: MidiOutAlsa
  1428. //*********************************************************************//
  1429. MidiOutAlsa :: MidiOutAlsa( const std::string clientName ) : MidiOutApi()
  1430. {
  1431. initialize( clientName );
  1432. }
  1433. MidiOutAlsa :: ~MidiOutAlsa()
  1434. {
  1435. // Close a connection if it exists.
  1436. closePort();
  1437. // Cleanup.
  1438. AlsaMidiData *data = static_cast<AlsaMidiData *> (apiData_);
  1439. if ( data->vport >= 0 ) snd_seq_delete_port( data->seq, data->vport );
  1440. if ( data->coder ) snd_midi_event_free( data->coder );
  1441. if ( data->buffer ) free( data->buffer );
  1442. snd_seq_close( data->seq );
  1443. delete data;
  1444. }
  1445. void MidiOutAlsa :: initialize( const std::string& clientName )
  1446. {
  1447. // Set up the ALSA sequencer client.
  1448. snd_seq_t *seq;
  1449. int result1 = snd_seq_open( &seq, "default", SND_SEQ_OPEN_OUTPUT, SND_SEQ_NONBLOCK );
  1450. if ( result1 < 0 ) {
  1451. errorString_ = "MidiOutAlsa::initialize: error creating ALSA sequencer client object.";
  1452. error( RtMidiError::DRIVER_ERROR, errorString_ );
  1453. return;
  1454. }
  1455. // Set client name.
  1456. snd_seq_set_client_name( seq, clientName.c_str() );
  1457. // Save our api-specific connection information.
  1458. AlsaMidiData *data = (AlsaMidiData *) new AlsaMidiData;
  1459. data->seq = seq;
  1460. data->portNum = -1;
  1461. data->vport = -1;
  1462. data->bufferSize = 32;
  1463. data->coder = 0;
  1464. data->buffer = 0;
  1465. int result = snd_midi_event_new( data->bufferSize, &data->coder );
  1466. if ( result < 0 ) {
  1467. delete data;
  1468. errorString_ = "MidiOutAlsa::initialize: error initializing MIDI event parser!\n\n";
  1469. error( RtMidiError::DRIVER_ERROR, errorString_ );
  1470. return;
  1471. }
  1472. data->buffer = (unsigned char *) malloc( data->bufferSize );
  1473. if ( data->buffer == NULL ) {
  1474. delete data;
  1475. errorString_ = "MidiOutAlsa::initialize: error allocating buffer memory!\n\n";
  1476. error( RtMidiError::MEMORY_ERROR, errorString_ );
  1477. return;
  1478. }
  1479. snd_midi_event_init( data->coder );
  1480. apiData_ = (void *) data;
  1481. }
  1482. unsigned int MidiOutAlsa :: getPortCount()
  1483. {
  1484. snd_seq_port_info_t *pinfo;
  1485. snd_seq_port_info_alloca( &pinfo );
  1486. AlsaMidiData *data = static_cast<AlsaMidiData *> (apiData_);
  1487. return portInfo( data->seq, pinfo, SND_SEQ_PORT_CAP_WRITE|SND_SEQ_PORT_CAP_SUBS_WRITE, -1 );
  1488. }
  1489. std::string MidiOutAlsa :: getPortName( unsigned int portNumber )
  1490. {
  1491. snd_seq_client_info_t *cinfo;
  1492. snd_seq_port_info_t *pinfo;
  1493. snd_seq_client_info_alloca( &cinfo );
  1494. snd_seq_port_info_alloca( &pinfo );
  1495. std::string stringName;
  1496. AlsaMidiData *data = static_cast<AlsaMidiData *> (apiData_);
  1497. if ( portInfo( data->seq, pinfo, SND_SEQ_PORT_CAP_WRITE|SND_SEQ_PORT_CAP_SUBS_WRITE, (int) portNumber ) ) {
  1498. int cnum = snd_seq_port_info_get_client(pinfo);
  1499. snd_seq_get_any_client_info( data->seq, cnum, cinfo );
  1500. std::ostringstream os;
  1501. os << snd_seq_client_info_get_name(cinfo);
  1502. os << " "; // These lines added to make sure devices are listed
  1503. os << snd_seq_port_info_get_client( pinfo ); // with full portnames added to ensure individual device names
  1504. os << ":";
  1505. os << snd_seq_port_info_get_port(pinfo);
  1506. stringName = os.str();
  1507. return stringName;
  1508. }
  1509. // If we get here, we didn't find a match.
  1510. errorString_ = "MidiOutAlsa::getPortName: error looking for port name!";
  1511. error( RtMidiError::WARNING, errorString_ );
  1512. return stringName;
  1513. }
  1514. void MidiOutAlsa :: openPort( unsigned int portNumber, const std::string portName )
  1515. {
  1516. if ( connected_ ) {
  1517. errorString_ = "MidiOutAlsa::openPort: a valid connection already exists!";
  1518. error( RtMidiError::WARNING, errorString_ );
  1519. return;
  1520. }
  1521. unsigned int nSrc = this->getPortCount();
  1522. if (nSrc < 1) {
  1523. errorString_ = "MidiOutAlsa::openPort: no MIDI output sources found!";
  1524. error( RtMidiError::NO_DEVICES_FOUND, errorString_ );
  1525. return;
  1526. }
  1527. snd_seq_port_info_t *pinfo;
  1528. snd_seq_port_info_alloca( &pinfo );
  1529. AlsaMidiData *data = static_cast<AlsaMidiData *> (apiData_);
  1530. if ( portInfo( data->seq, pinfo, SND_SEQ_PORT_CAP_WRITE|SND_SEQ_PORT_CAP_SUBS_WRITE, (int) portNumber ) == 0 ) {
  1531. std::ostringstream ost;
  1532. ost << "MidiOutAlsa::openPort: the 'portNumber' argument (" << portNumber << ") is invalid.";
  1533. errorString_ = ost.str();
  1534. error( RtMidiError::INVALID_PARAMETER, errorString_ );
  1535. return;
  1536. }
  1537. snd_seq_addr_t sender, receiver;
  1538. receiver.client = snd_seq_port_info_get_client( pinfo );
  1539. receiver.port = snd_seq_port_info_get_port( pinfo );
  1540. sender.client = snd_seq_client_id( data->seq );
  1541. if ( data->vport < 0 ) {
  1542. data->vport = snd_seq_create_simple_port( data->seq, portName.c_str(),
  1543. SND_SEQ_PORT_CAP_READ|SND_SEQ_PORT_CAP_SUBS_READ,
  1544. SND_SEQ_PORT_TYPE_MIDI_GENERIC|SND_SEQ_PORT_TYPE_APPLICATION );
  1545. if ( data->vport < 0 ) {
  1546. errorString_ = "MidiOutAlsa::openPort: ALSA error creating output port.";
  1547. error( RtMidiError::DRIVER_ERROR, errorString_ );
  1548. return;
  1549. }
  1550. }
  1551. sender.port = data->vport;
  1552. // Make subscription
  1553. if (snd_seq_port_subscribe_malloc( &data->subscription ) < 0) {
  1554. snd_seq_port_subscribe_free( data->subscription );
  1555. errorString_ = "MidiOutAlsa::openPort: error allocating port subscription.";
  1556. error( RtMidiError::DRIVER_ERROR, errorString_ );
  1557. return;
  1558. }
  1559. snd_seq_port_subscribe_set_sender(data->subscription, &sender);
  1560. snd_seq_port_subscribe_set_dest(data->subscription, &receiver);
  1561. snd_seq_port_subscribe_set_time_update(data->subscription, 1);
  1562. snd_seq_port_subscribe_set_time_real(data->subscription, 1);
  1563. if ( snd_seq_subscribe_port(data->seq, data->subscription) ) {
  1564. snd_seq_port_subscribe_free( data->subscription );
  1565. errorString_ = "MidiOutAlsa::openPort: ALSA error making port connection.";
  1566. error( RtMidiError::DRIVER_ERROR, errorString_ );
  1567. return;
  1568. }
  1569. connected_ = true;
  1570. }
  1571. void MidiOutAlsa :: closePort( void )
  1572. {
  1573. if ( connected_ ) {
  1574. AlsaMidiData *data = static_cast<AlsaMidiData *> (apiData_);
  1575. snd_seq_unsubscribe_port( data->seq, data->subscription );
  1576. snd_seq_port_subscribe_free( data->subscription );
  1577. connected_ = false;
  1578. }
  1579. }
  1580. void MidiOutAlsa :: openVirtualPort( std::string portName )
  1581. {
  1582. AlsaMidiData *data = static_cast<AlsaMidiData *> (apiData_);
  1583. if ( data->vport < 0 ) {
  1584. data->vport = snd_seq_create_simple_port( data->seq, portName.c_str(),
  1585. SND_SEQ_PORT_CAP_READ|SND_SEQ_PORT_CAP_SUBS_READ,
  1586. SND_SEQ_PORT_TYPE_MIDI_GENERIC|SND_SEQ_PORT_TYPE_APPLICATION );
  1587. if ( data->vport < 0 ) {
  1588. errorString_ = "MidiOutAlsa::openVirtualPort: ALSA error creating virtual port.";
  1589. error( RtMidiError::DRIVER_ERROR, errorString_ );
  1590. }
  1591. }
  1592. }
  1593. void MidiOutAlsa :: sendMessage( std::vector<unsigned char> *message )
  1594. {
  1595. int result;
  1596. AlsaMidiData *data = static_cast<AlsaMidiData *> (apiData_);
  1597. unsigned int nBytes = message->size();
  1598. if ( nBytes > data->bufferSize ) {
  1599. data->bufferSize = nBytes;
  1600. result = snd_midi_event_resize_buffer ( data->coder, nBytes);
  1601. if ( result != 0 ) {
  1602. errorString_ = "MidiOutAlsa::sendMessage: ALSA error resizing MIDI event buffer.";
  1603. error( RtMidiError::DRIVER_ERROR, errorString_ );
  1604. return;
  1605. }
  1606. free (data->buffer);
  1607. data->buffer = (unsigned char *) malloc( data->bufferSize );
  1608. if ( data->buffer == NULL ) {
  1609. errorString_ = "MidiOutAlsa::initialize: error allocating buffer memory!\n\n";
  1610. error( RtMidiError::MEMORY_ERROR, errorString_ );
  1611. return;
  1612. }
  1613. }
  1614. snd_seq_event_t ev;
  1615. snd_seq_ev_clear(&ev);
  1616. snd_seq_ev_set_source(&ev, data->vport);
  1617. snd_seq_ev_set_subs(&ev);
  1618. snd_seq_ev_set_direct(&ev);
  1619. for ( unsigned int i=0; i<nBytes; ++i ) data->buffer[i] = message->at(i);
  1620. result = snd_midi_event_encode( data->coder, data->buffer, (long)nBytes, &ev );
  1621. if ( result < (int)nBytes ) {
  1622. errorString_ = "MidiOutAlsa::sendMessage: event parsing error!";
  1623. error( RtMidiError::WARNING, errorString_ );
  1624. return;
  1625. }
  1626. // Send the event.
  1627. result = snd_seq_event_output(data->seq, &ev);
  1628. if ( result < 0 ) {
  1629. errorString_ = "MidiOutAlsa::sendMessage: error sending MIDI message to port.";
  1630. error( RtMidiError::WARNING, errorString_ );
  1631. return;
  1632. }
  1633. snd_seq_drain_output(data->seq);
  1634. }
  1635. #endif // __LINUX_ALSA__
  1636. //*********************************************************************//
  1637. // API: Windows Multimedia Library (MM)
  1638. //*********************************************************************//
  1639. // API information deciphered from:
  1640. // - http://msdn.microsoft.com/library/default.asp?url=/library/en-us/multimed/htm/_win32_midi_reference.asp
  1641. // Thanks to Jean-Baptiste Berruchon for the sysex code.
  1642. #if defined(__WINDOWS_MM__)
  1643. // The Windows MM API is based on the use of a callback function for
  1644. // MIDI input. We convert the system specific time stamps to delta
  1645. // time values.
  1646. // Windows MM MIDI header files.
  1647. #include <windows.h>
  1648. #include <mmsystem.h>
  1649. #define RT_SYSEX_BUFFER_SIZE 1024
  1650. #define RT_SYSEX_BUFFER_COUNT 4
  1651. // A structure to hold variables related to the CoreMIDI API
  1652. // implementation.
  1653. struct WinMidiData {
  1654. HMIDIIN inHandle; // Handle to Midi Input Device
  1655. HMIDIOUT outHandle; // Handle to Midi Output Device
  1656. DWORD lastTime;
  1657. MidiInApi::MidiMessage message;
  1658. LPMIDIHDR sysexBuffer[RT_SYSEX_BUFFER_COUNT];
  1659. CRITICAL_SECTION _mutex; // [Patrice] see https://groups.google.com/forum/#!topic/mididev/6OUjHutMpEo
  1660. };
  1661. //*********************************************************************//
  1662. // API: Windows MM
  1663. // Class Definitions: MidiInWinMM
  1664. //*********************************************************************//
  1665. static void CALLBACK midiInputCallback( HMIDIIN /*hmin*/,
  1666. UINT inputStatus,
  1667. DWORD_PTR instancePtr,
  1668. DWORD_PTR midiMessage,
  1669. DWORD timestamp )
  1670. {
  1671. if ( inputStatus != MIM_DATA && inputStatus != MIM_LONGDATA && inputStatus != MIM_LONGERROR ) return;
  1672. //MidiInApi::RtMidiInData *data = static_cast<MidiInApi::RtMidiInData *> (instancePtr);
  1673. MidiInApi::RtMidiInData *data = (MidiInApi::RtMidiInData *)instancePtr;
  1674. WinMidiData *apiData = static_cast<WinMidiData *> (data->apiData);
  1675. // Calculate time stamp.
  1676. if ( data->firstMessage == true ) {
  1677. apiData->message.timeStamp = 0.0;
  1678. data->firstMessage = false;
  1679. }
  1680. else apiData->message.timeStamp = (double) ( timestamp - apiData->lastTime ) * 0.001;
  1681. apiData->lastTime = timestamp;
  1682. if ( inputStatus == MIM_DATA ) { // Channel or system message
  1683. // Make sure the first byte is a status byte.
  1684. unsigned char status = (unsigned char) (midiMessage & 0x000000FF);
  1685. if ( !(status & 0x80) ) return;
  1686. // Determine the number of bytes in the MIDI message.
  1687. unsigned short nBytes = 1;
  1688. if ( status < 0xC0 ) nBytes = 3;
  1689. else if ( status < 0xE0 ) nBytes = 2;
  1690. else if ( status < 0xF0 ) nBytes = 3;
  1691. else if ( status == 0xF1 ) {
  1692. if ( data->ignoreFlags & 0x02 ) return;
  1693. else nBytes = 2;
  1694. }
  1695. else if ( status == 0xF2 ) nBytes = 3;
  1696. else if ( status == 0xF3 ) nBytes = 2;
  1697. else if ( status == 0xF8 && (data->ignoreFlags & 0x02) ) {
  1698. // A MIDI timing tick message and we're ignoring it.
  1699. return;
  1700. }
  1701. else if ( status == 0xFE && (data->ignoreFlags & 0x04) ) {
  1702. // A MIDI active sensing message and we're ignoring it.
  1703. return;
  1704. }
  1705. // Copy bytes to our MIDI message.
  1706. unsigned char *ptr = (unsigned char *) &midiMessage;
  1707. for ( int i=0; i<nBytes; ++i ) apiData->message.bytes.push_back( *ptr++ );
  1708. }
  1709. else { // Sysex message ( MIM_LONGDATA or MIM_LONGERROR )
  1710. MIDIHDR *sysex = ( MIDIHDR *) midiMessage;
  1711. if ( !( data->ignoreFlags & 0x01 ) && inputStatus != MIM_LONGERROR ) {
  1712. // Sysex message and we're not ignoring it
  1713. for ( int i=0; i<(int)sysex->dwBytesRecorded; ++i )
  1714. apiData->message.bytes.push_back( sysex->lpData[i] );
  1715. }
  1716. // The WinMM API requires that the sysex buffer be requeued after
  1717. // input of each sysex message. Even if we are ignoring sysex
  1718. // messages, we still need to requeue the buffer in case the user
  1719. // decides to not ignore sysex messages in the future. However,
  1720. // it seems that WinMM calls this function with an empty sysex
  1721. // buffer when an application closes and in this case, we should
  1722. // avoid requeueing it, else the computer suddenly reboots after
  1723. // one or two minutes.
  1724. if ( apiData->sysexBuffer[sysex->dwUser]->dwBytesRecorded > 0 ) {
  1725. //if ( sysex->dwBytesRecorded > 0 ) {
  1726. EnterCriticalSection( &(apiData->_mutex) );
  1727. MMRESULT result = midiInAddBuffer( apiData->inHandle, apiData->sysexBuffer[sysex->dwUser], sizeof(MIDIHDR) );
  1728. LeaveCriticalSection( &(apiData->_mutex) );
  1729. if ( result != MMSYSERR_NOERROR )
  1730. std::cerr << "\nRtMidiIn::midiInputCallback: error sending sysex to Midi device!!\n\n";
  1731. if ( data->ignoreFlags & 0x01 ) return;
  1732. }
  1733. else return;
  1734. }
  1735. if ( data->usingCallback ) {
  1736. RtMidiIn::RtMidiCallback callback = (RtMidiIn::RtMidiCallback) data->userCallback;
  1737. callback( apiData->message.timeStamp, &apiData->message.bytes, data->userData );
  1738. }
  1739. else {
  1740. // As long as we haven't reached our queue size limit, push the message.
  1741. if ( data->queue.size < data->queue.ringSize ) {
  1742. data->queue.ring[data->queue.back++] = apiData->message;
  1743. if ( data->queue.back == data->queue.ringSize )
  1744. data->queue.back = 0;
  1745. data->queue.size++;
  1746. }
  1747. else
  1748. std::cerr << "\nRtMidiIn: message queue limit reached!!\n\n";
  1749. }
  1750. // Clear the vector for the next input message.
  1751. apiData->message.bytes.clear();
  1752. }
  1753. MidiInWinMM :: MidiInWinMM( const std::string clientName, unsigned int queueSizeLimit ) : MidiInApi( queueSizeLimit )
  1754. {
  1755. initialize( clientName );
  1756. }
  1757. MidiInWinMM :: ~MidiInWinMM()
  1758. {
  1759. // Close a connection if it exists.
  1760. closePort();
  1761. WinMidiData *data = static_cast<WinMidiData *> (apiData_);
  1762. DeleteCriticalSection( &(data->_mutex) );
  1763. // Cleanup.
  1764. delete data;
  1765. }
  1766. void MidiInWinMM :: initialize( const std::string& /*clientName*/ )
  1767. {
  1768. // We'll issue a warning here if no devices are available but not
  1769. // throw an error since the user can plugin something later.
  1770. unsigned int nDevices = midiInGetNumDevs();
  1771. if ( nDevices == 0 ) {
  1772. errorString_ = "MidiInWinMM::initialize: no MIDI input devices currently available.";
  1773. error( RtMidiError::WARNING, errorString_ );
  1774. }
  1775. // Save our api-specific connection information.
  1776. WinMidiData *data = (WinMidiData *) new WinMidiData;
  1777. apiData_ = (void *) data;
  1778. inputData_.apiData = (void *) data;
  1779. data->message.bytes.clear(); // needs to be empty for first input message
  1780. if ( !InitializeCriticalSectionAndSpinCount(&(data->_mutex), 0x00000400) ) {
  1781. errorString_ = "MidiInWinMM::initialize: InitializeCriticalSectionAndSpinCount failed.";
  1782. error( RtMidiError::WARNING, errorString_ );
  1783. }
  1784. }
  1785. void MidiInWinMM :: openPort( unsigned int portNumber, const std::string /*portName*/ )
  1786. {
  1787. if ( connected_ ) {
  1788. errorString_ = "MidiInWinMM::openPort: a valid connection already exists!";
  1789. error( RtMidiError::WARNING, errorString_ );
  1790. return;
  1791. }
  1792. unsigned int nDevices = midiInGetNumDevs();
  1793. if (nDevices == 0) {
  1794. errorString_ = "MidiInWinMM::openPort: no MIDI input sources found!";
  1795. error( RtMidiError::NO_DEVICES_FOUND, errorString_ );
  1796. return;
  1797. }
  1798. if ( portNumber >= nDevices ) {
  1799. std::ostringstream ost;
  1800. ost << "MidiInWinMM::openPort: the 'portNumber' argument (" << portNumber << ") is invalid.";
  1801. errorString_ = ost.str();
  1802. error( RtMidiError::INVALID_PARAMETER, errorString_ );
  1803. return;
  1804. }
  1805. WinMidiData *data = static_cast<WinMidiData *> (apiData_);
  1806. MMRESULT result = midiInOpen( &data->inHandle,
  1807. portNumber,
  1808. (DWORD_PTR)&midiInputCallback,
  1809. (DWORD_PTR)&inputData_,
  1810. CALLBACK_FUNCTION );
  1811. if ( result != MMSYSERR_NOERROR ) {
  1812. errorString_ = "MidiInWinMM::openPort: error creating Windows MM MIDI input port.";
  1813. error( RtMidiError::DRIVER_ERROR, errorString_ );
  1814. return;
  1815. }
  1816. // Allocate and init the sysex buffers.
  1817. for ( int i=0; i<RT_SYSEX_BUFFER_COUNT; ++i ) {
  1818. data->sysexBuffer[i] = (MIDIHDR*) new char[ sizeof(MIDIHDR) ];
  1819. data->sysexBuffer[i]->lpData = new char[ RT_SYSEX_BUFFER_SIZE ];
  1820. data->sysexBuffer[i]->dwBufferLength = RT_SYSEX_BUFFER_SIZE;
  1821. data->sysexBuffer[i]->dwUser = i; // We use the dwUser parameter as buffer indicator
  1822. data->sysexBuffer[i]->dwFlags = 0;
  1823. result = midiInPrepareHeader( data->inHandle, data->sysexBuffer[i], sizeof(MIDIHDR) );
  1824. if ( result != MMSYSERR_NOERROR ) {
  1825. midiInClose( data->inHandle );
  1826. errorString_ = "MidiInWinMM::openPort: error starting Windows MM MIDI input port (PrepareHeader).";
  1827. error( RtMidiError::DRIVER_ERROR, errorString_ );
  1828. return;
  1829. }
  1830. // Register the buffer.
  1831. result = midiInAddBuffer( data->inHandle, data->sysexBuffer[i], sizeof(MIDIHDR) );
  1832. if ( result != MMSYSERR_NOERROR ) {
  1833. midiInClose( data->inHandle );
  1834. errorString_ = "MidiInWinMM::openPort: error starting Windows MM MIDI input port (AddBuffer).";
  1835. error( RtMidiError::DRIVER_ERROR, errorString_ );
  1836. return;
  1837. }
  1838. }
  1839. result = midiInStart( data->inHandle );
  1840. if ( result != MMSYSERR_NOERROR ) {
  1841. midiInClose( data->inHandle );
  1842. errorString_ = "MidiInWinMM::openPort: error starting Windows MM MIDI input port.";
  1843. error( RtMidiError::DRIVER_ERROR, errorString_ );
  1844. return;
  1845. }
  1846. connected_ = true;
  1847. }
  1848. void MidiInWinMM :: openVirtualPort( std::string /*portName*/ )
  1849. {
  1850. // This function cannot be implemented for the Windows MM MIDI API.
  1851. errorString_ = "MidiInWinMM::openVirtualPort: cannot be implemented in Windows MM MIDI API!";
  1852. error( RtMidiError::WARNING, errorString_ );
  1853. }
  1854. void MidiInWinMM :: closePort( void )
  1855. {
  1856. if ( connected_ ) {
  1857. WinMidiData *data = static_cast<WinMidiData *> (apiData_);
  1858. EnterCriticalSection( &(data->_mutex) );
  1859. midiInReset( data->inHandle );
  1860. midiInStop( data->inHandle );
  1861. for ( int i=0; i<RT_SYSEX_BUFFER_COUNT; ++i ) {
  1862. int result = midiInUnprepareHeader(data->inHandle, data->sysexBuffer[i], sizeof(MIDIHDR));
  1863. delete [] data->sysexBuffer[i]->lpData;
  1864. delete [] data->sysexBuffer[i];
  1865. if ( result != MMSYSERR_NOERROR ) {
  1866. midiInClose( data->inHandle );
  1867. errorString_ = "MidiInWinMM::openPort: error closing Windows MM MIDI input port (midiInUnprepareHeader).";
  1868. error( RtMidiError::DRIVER_ERROR, errorString_ );
  1869. return;
  1870. }
  1871. }
  1872. midiInClose( data->inHandle );
  1873. connected_ = false;
  1874. LeaveCriticalSection( &(data->_mutex) );
  1875. }
  1876. }
  1877. unsigned int MidiInWinMM :: getPortCount()
  1878. {
  1879. return midiInGetNumDevs();
  1880. }
  1881. std::string MidiInWinMM :: getPortName( unsigned int portNumber )
  1882. {
  1883. std::string stringName;
  1884. unsigned int nDevices = midiInGetNumDevs();
  1885. if ( portNumber >= nDevices ) {
  1886. std::ostringstream ost;
  1887. ost << "MidiInWinMM::getPortName: the 'portNumber' argument (" << portNumber << ") is invalid.";
  1888. errorString_ = ost.str();
  1889. error( RtMidiError::WARNING, errorString_ );
  1890. return stringName;
  1891. }
  1892. MIDIINCAPS deviceCaps;
  1893. midiInGetDevCaps( portNumber, &deviceCaps, sizeof(MIDIINCAPS));
  1894. #if defined( UNICODE ) || defined( _UNICODE )
  1895. int length = WideCharToMultiByte(CP_UTF8, 0, deviceCaps.szPname, -1, NULL, 0, NULL, NULL) - 1;
  1896. stringName.assign( length, 0 );
  1897. length = WideCharToMultiByte(CP_UTF8, 0, deviceCaps.szPname, static_cast<int>(wcslen(deviceCaps.szPname)), &stringName[0], length, NULL, NULL);
  1898. #else
  1899. stringName = std::string( deviceCaps.szPname );
  1900. #endif
  1901. // Next lines added to add the portNumber to the name so that
  1902. // the device's names are sure to be listed with individual names
  1903. // even when they have the same brand name
  1904. std::ostringstream os;
  1905. os << " ";
  1906. os << portNumber;
  1907. stringName += os.str();
  1908. return stringName;
  1909. }
  1910. //*********************************************************************//
  1911. // API: Windows MM
  1912. // Class Definitions: MidiOutWinMM
  1913. //*********************************************************************//
  1914. MidiOutWinMM :: MidiOutWinMM( const std::string clientName ) : MidiOutApi()
  1915. {
  1916. initialize( clientName );
  1917. }
  1918. MidiOutWinMM :: ~MidiOutWinMM()
  1919. {
  1920. // Close a connection if it exists.
  1921. closePort();
  1922. // Cleanup.
  1923. WinMidiData *data = static_cast<WinMidiData *> (apiData_);
  1924. delete data;
  1925. }
  1926. void MidiOutWinMM :: initialize( const std::string& /*clientName*/ )
  1927. {
  1928. // We'll issue a warning here if no devices are available but not
  1929. // throw an error since the user can plug something in later.
  1930. unsigned int nDevices = midiOutGetNumDevs();
  1931. if ( nDevices == 0 ) {
  1932. errorString_ = "MidiOutWinMM::initialize: no MIDI output devices currently available.";
  1933. error( RtMidiError::WARNING, errorString_ );
  1934. }
  1935. // Save our api-specific connection information.
  1936. WinMidiData *data = (WinMidiData *) new WinMidiData;
  1937. apiData_ = (void *) data;
  1938. }
  1939. unsigned int MidiOutWinMM :: getPortCount()
  1940. {
  1941. return midiOutGetNumDevs();
  1942. }
  1943. std::string MidiOutWinMM :: getPortName( unsigned int portNumber )
  1944. {
  1945. std::string stringName;
  1946. unsigned int nDevices = midiOutGetNumDevs();
  1947. if ( portNumber >= nDevices ) {
  1948. std::ostringstream ost;
  1949. ost << "MidiOutWinMM::getPortName: the 'portNumber' argument (" << portNumber << ") is invalid.";
  1950. errorString_ = ost.str();
  1951. error( RtMidiError::WARNING, errorString_ );
  1952. return stringName;
  1953. }
  1954. MIDIOUTCAPS deviceCaps;
  1955. midiOutGetDevCaps( portNumber, &deviceCaps, sizeof(MIDIOUTCAPS));
  1956. #if defined( UNICODE ) || defined( _UNICODE )
  1957. int length = WideCharToMultiByte(CP_UTF8, 0, deviceCaps.szPname, -1, NULL, 0, NULL, NULL) - 1;
  1958. stringName.assign( length, 0 );
  1959. length = WideCharToMultiByte(CP_UTF8, 0, deviceCaps.szPname, static_cast<int>(wcslen(deviceCaps.szPname)), &stringName[0], length, NULL, NULL);
  1960. #else
  1961. stringName = std::string( deviceCaps.szPname );
  1962. #endif
  1963. // Next lines added to add the portNumber to the name so that
  1964. // the device's names are sure to be listed with individual names
  1965. // even when they have the same brand name
  1966. std::ostringstream os;
  1967. os << " ";
  1968. os << portNumber;
  1969. stringName += os.str();
  1970. return stringName;
  1971. }
  1972. void MidiOutWinMM :: openPort( unsigned int portNumber, const std::string /*portName*/ )
  1973. {
  1974. if ( connected_ ) {
  1975. errorString_ = "MidiOutWinMM::openPort: a valid connection already exists!";
  1976. error( RtMidiError::WARNING, errorString_ );
  1977. return;
  1978. }
  1979. unsigned int nDevices = midiOutGetNumDevs();
  1980. if (nDevices < 1) {
  1981. errorString_ = "MidiOutWinMM::openPort: no MIDI output destinations found!";
  1982. error( RtMidiError::NO_DEVICES_FOUND, errorString_ );
  1983. return;
  1984. }
  1985. if ( portNumber >= nDevices ) {
  1986. std::ostringstream ost;
  1987. ost << "MidiOutWinMM::openPort: the 'portNumber' argument (" << portNumber << ") is invalid.";
  1988. errorString_ = ost.str();
  1989. error( RtMidiError::INVALID_PARAMETER, errorString_ );
  1990. return;
  1991. }
  1992. WinMidiData *data = static_cast<WinMidiData *> (apiData_);
  1993. MMRESULT result = midiOutOpen( &data->outHandle,
  1994. portNumber,
  1995. (DWORD)NULL,
  1996. (DWORD)NULL,
  1997. CALLBACK_NULL );
  1998. if ( result != MMSYSERR_NOERROR ) {
  1999. errorString_ = "MidiOutWinMM::openPort: error creating Windows MM MIDI output port.";
  2000. error( RtMidiError::DRIVER_ERROR, errorString_ );
  2001. return;
  2002. }
  2003. connected_ = true;
  2004. }
  2005. void MidiOutWinMM :: closePort( void )
  2006. {
  2007. if ( connected_ ) {
  2008. WinMidiData *data = static_cast<WinMidiData *> (apiData_);
  2009. midiOutReset( data->outHandle );
  2010. midiOutClose( data->outHandle );
  2011. connected_ = false;
  2012. }
  2013. }
  2014. void MidiOutWinMM :: openVirtualPort( std::string /*portName*/ )
  2015. {
  2016. // This function cannot be implemented for the Windows MM MIDI API.
  2017. errorString_ = "MidiOutWinMM::openVirtualPort: cannot be implemented in Windows MM MIDI API!";
  2018. error( RtMidiError::WARNING, errorString_ );
  2019. }
  2020. void MidiOutWinMM :: sendMessage( std::vector<unsigned char> *message )
  2021. {
  2022. if ( !connected_ ) return;
  2023. unsigned int nBytes = static_cast<unsigned int>(message->size());
  2024. if ( nBytes == 0 ) {
  2025. errorString_ = "MidiOutWinMM::sendMessage: message argument is empty!";
  2026. error( RtMidiError::WARNING, errorString_ );
  2027. return;
  2028. }
  2029. MMRESULT result;
  2030. WinMidiData *data = static_cast<WinMidiData *> (apiData_);
  2031. if ( message->at(0) == 0xF0 ) { // Sysex message
  2032. // Allocate buffer for sysex data.
  2033. char *buffer = (char *) malloc( nBytes );
  2034. if ( buffer == NULL ) {
  2035. errorString_ = "MidiOutWinMM::sendMessage: error allocating sysex message memory!";
  2036. error( RtMidiError::MEMORY_ERROR, errorString_ );
  2037. return;
  2038. }
  2039. // Copy data to buffer.
  2040. for ( unsigned int i=0; i<nBytes; ++i ) buffer[i] = message->at(i);
  2041. // Create and prepare MIDIHDR structure.
  2042. MIDIHDR sysex;
  2043. sysex.lpData = (LPSTR) buffer;
  2044. sysex.dwBufferLength = nBytes;
  2045. sysex.dwFlags = 0;
  2046. result = midiOutPrepareHeader( data->outHandle, &sysex, sizeof(MIDIHDR) );
  2047. if ( result != MMSYSERR_NOERROR ) {
  2048. free( buffer );
  2049. errorString_ = "MidiOutWinMM::sendMessage: error preparing sysex header.";
  2050. error( RtMidiError::DRIVER_ERROR, errorString_ );
  2051. return;
  2052. }
  2053. // Send the message.
  2054. result = midiOutLongMsg( data->outHandle, &sysex, sizeof(MIDIHDR) );
  2055. if ( result != MMSYSERR_NOERROR ) {
  2056. free( buffer );
  2057. errorString_ = "MidiOutWinMM::sendMessage: error sending sysex message.";
  2058. error( RtMidiError::DRIVER_ERROR, errorString_ );
  2059. return;
  2060. }
  2061. // Unprepare the buffer and MIDIHDR.
  2062. while ( MIDIERR_STILLPLAYING == midiOutUnprepareHeader( data->outHandle, &sysex, sizeof (MIDIHDR) ) ) Sleep( 1 );
  2063. free( buffer );
  2064. }
  2065. else { // Channel or system message.
  2066. // Make sure the message size isn't too big.
  2067. if ( nBytes > 3 ) {
  2068. errorString_ = "MidiOutWinMM::sendMessage: message size is greater than 3 bytes (and not sysex)!";
  2069. error( RtMidiError::WARNING, errorString_ );
  2070. return;
  2071. }
  2072. // Pack MIDI bytes into double word.
  2073. DWORD packet;
  2074. unsigned char *ptr = (unsigned char *) &packet;
  2075. for ( unsigned int i=0; i<nBytes; ++i ) {
  2076. *ptr = message->at(i);
  2077. ++ptr;
  2078. }
  2079. // Send the message immediately.
  2080. result = midiOutShortMsg( data->outHandle, packet );
  2081. if ( result != MMSYSERR_NOERROR ) {
  2082. errorString_ = "MidiOutWinMM::sendMessage: error sending MIDI message.";
  2083. error( RtMidiError::DRIVER_ERROR, errorString_ );
  2084. }
  2085. }
  2086. }
  2087. #endif // __WINDOWS_MM__
  2088. //*********************************************************************//
  2089. // API: UNIX JACK
  2090. //
  2091. // Written primarily by Alexander Svetalkin, with updates for delta
  2092. // time by Gary Scavone, April 2011.
  2093. //
  2094. // *********************************************************************//
  2095. #if defined(__UNIX_JACK__)
  2096. // JACK header files
  2097. #include <jack/jack.h>
  2098. #include <jack/midiport.h>
  2099. #include <jack/ringbuffer.h>
  2100. #define JACK_RINGBUFFER_SIZE 16384 // Default size for ringbuffer
  2101. struct JackMidiData {
  2102. jack_client_t *client;
  2103. jack_port_t *port;
  2104. jack_ringbuffer_t *buffSize;
  2105. jack_ringbuffer_t *buffMessage;
  2106. jack_time_t lastTime;
  2107. MidiInApi :: RtMidiInData *rtMidiIn;
  2108. };
  2109. //*********************************************************************//
  2110. // API: JACK
  2111. // Class Definitions: MidiInJack
  2112. //*********************************************************************//
  2113. static int jackProcessIn( jack_nframes_t nframes, void *arg )
  2114. {
  2115. JackMidiData *jData = (JackMidiData *) arg;
  2116. MidiInApi :: RtMidiInData *rtData = jData->rtMidiIn;
  2117. jack_midi_event_t event;
  2118. jack_time_t time;
  2119. // Is port created?
  2120. if ( jData->port == NULL ) return 0;
  2121. void *buff = jack_port_get_buffer( jData->port, nframes );
  2122. // We have midi events in buffer
  2123. int evCount = jack_midi_get_event_count( buff );
  2124. for (int j = 0; j < evCount; j++) {
  2125. MidiInApi::MidiMessage message;
  2126. message.bytes.clear();
  2127. jack_midi_event_get( &event, buff, j );
  2128. for ( unsigned int i = 0; i < event.size; i++ )
  2129. message.bytes.push_back( event.buffer[i] );
  2130. // Compute the delta time.
  2131. time = jack_get_time();
  2132. if ( rtData->firstMessage == true )
  2133. rtData->firstMessage = false;
  2134. else
  2135. message.timeStamp = ( time - jData->lastTime ) * 0.000001;
  2136. jData->lastTime = time;
  2137. if ( !rtData->continueSysex ) {
  2138. if ( rtData->usingCallback ) {
  2139. RtMidiIn::RtMidiCallback callback = (RtMidiIn::RtMidiCallback) rtData->userCallback;
  2140. callback( message.timeStamp, &message.bytes, rtData->userData );
  2141. }
  2142. else {
  2143. // As long as we haven't reached our queue size limit, push the message.
  2144. if ( rtData->queue.size < rtData->queue.ringSize ) {
  2145. rtData->queue.ring[rtData->queue.back++] = message;
  2146. if ( rtData->queue.back == rtData->queue.ringSize )
  2147. rtData->queue.back = 0;
  2148. rtData->queue.size++;
  2149. }
  2150. else
  2151. std::cerr << "\nMidiInJack: message queue limit reached!!\n\n";
  2152. }
  2153. }
  2154. }
  2155. return 0;
  2156. }
  2157. MidiInJack :: MidiInJack( const std::string clientName, unsigned int queueSizeLimit ) : MidiInApi( queueSizeLimit )
  2158. {
  2159. initialize( clientName );
  2160. }
  2161. void MidiInJack :: initialize( const std::string& clientName )
  2162. {
  2163. JackMidiData *data = new JackMidiData;
  2164. apiData_ = (void *) data;
  2165. data->rtMidiIn = &inputData_;
  2166. data->port = NULL;
  2167. data->client = NULL;
  2168. this->clientName = clientName;
  2169. connect();
  2170. }
  2171. void MidiInJack :: connect()
  2172. {
  2173. JackMidiData *data = static_cast<JackMidiData *> (apiData_);
  2174. if ( data->client )
  2175. return;
  2176. // Initialize JACK client
  2177. if (( data->client = jack_client_open( clientName.c_str(), JackNoStartServer, NULL )) == 0) {
  2178. errorString_ = "MidiInJack::initialize: JACK server not running?";
  2179. error( RtMidiError::WARNING, errorString_ );
  2180. return;
  2181. }
  2182. jack_set_process_callback( data->client, jackProcessIn, data );
  2183. jack_activate( data->client );
  2184. }
  2185. MidiInJack :: ~MidiInJack()
  2186. {
  2187. JackMidiData *data = static_cast<JackMidiData *> (apiData_);
  2188. closePort();
  2189. if ( data->client )
  2190. jack_client_close( data->client );
  2191. delete data;
  2192. }
  2193. void MidiInJack :: openPort( unsigned int portNumber, const std::string portName )
  2194. {
  2195. JackMidiData *data = static_cast<JackMidiData *> (apiData_);
  2196. connect();
  2197. // Creating new port
  2198. if ( data->port == NULL)
  2199. data->port = jack_port_register( data->client, portName.c_str(),
  2200. JACK_DEFAULT_MIDI_TYPE, JackPortIsInput, 0 );
  2201. if ( data->port == NULL) {
  2202. errorString_ = "MidiInJack::openPort: JACK error creating port";
  2203. error( RtMidiError::DRIVER_ERROR, errorString_ );
  2204. return;
  2205. }
  2206. // Connecting to the output
  2207. std::string name = getPortName( portNumber );
  2208. jack_connect( data->client, name.c_str(), jack_port_name( data->port ) );
  2209. }
  2210. void MidiInJack :: openVirtualPort( const std::string portName )
  2211. {
  2212. JackMidiData *data = static_cast<JackMidiData *> (apiData_);
  2213. connect();
  2214. if ( data->port == NULL )
  2215. data->port = jack_port_register( data->client, portName.c_str(),
  2216. JACK_DEFAULT_MIDI_TYPE, JackPortIsInput, 0 );
  2217. if ( data->port == NULL ) {
  2218. errorString_ = "MidiInJack::openVirtualPort: JACK error creating virtual port";
  2219. error( RtMidiError::DRIVER_ERROR, errorString_ );
  2220. }
  2221. }
  2222. unsigned int MidiInJack :: getPortCount()
  2223. {
  2224. int count = 0;
  2225. JackMidiData *data = static_cast<JackMidiData *> (apiData_);
  2226. connect();
  2227. if ( !data->client )
  2228. return 0;
  2229. // List of available ports
  2230. const char **ports = jack_get_ports( data->client, NULL, JACK_DEFAULT_MIDI_TYPE, JackPortIsOutput );
  2231. if ( ports == NULL ) return 0;
  2232. while ( ports[count] != NULL )
  2233. count++;
  2234. free( ports );
  2235. return count;
  2236. }
  2237. std::string MidiInJack :: getPortName( unsigned int portNumber )
  2238. {
  2239. JackMidiData *data = static_cast<JackMidiData *> (apiData_);
  2240. std::string retStr("");
  2241. connect();
  2242. // List of available ports
  2243. const char **ports = jack_get_ports( data->client, NULL,
  2244. JACK_DEFAULT_MIDI_TYPE, JackPortIsOutput );
  2245. // Check port validity
  2246. if ( ports == NULL ) {
  2247. errorString_ = "MidiInJack::getPortName: no ports available!";
  2248. error( RtMidiError::WARNING, errorString_ );
  2249. return retStr;
  2250. }
  2251. if ( ports[portNumber] == NULL ) {
  2252. std::ostringstream ost;
  2253. ost << "MidiInJack::getPortName: the 'portNumber' argument (" << portNumber << ") is invalid.";
  2254. errorString_ = ost.str();
  2255. error( RtMidiError::WARNING, errorString_ );
  2256. }
  2257. else retStr.assign( ports[portNumber] );
  2258. free( ports );
  2259. return retStr;
  2260. }
  2261. void MidiInJack :: closePort()
  2262. {
  2263. JackMidiData *data = static_cast<JackMidiData *> (apiData_);
  2264. if ( data->port == NULL ) return;
  2265. jack_port_unregister( data->client, data->port );
  2266. data->port = NULL;
  2267. }
  2268. //*********************************************************************//
  2269. // API: JACK
  2270. // Class Definitions: MidiOutJack
  2271. //*********************************************************************//
  2272. // Jack process callback
  2273. static int jackProcessOut( jack_nframes_t nframes, void *arg )
  2274. {
  2275. JackMidiData *data = (JackMidiData *) arg;
  2276. jack_midi_data_t *midiData;
  2277. int space;
  2278. // Is port created?
  2279. if ( data->port == NULL ) return 0;
  2280. void *buff = jack_port_get_buffer( data->port, nframes );
  2281. jack_midi_clear_buffer( buff );
  2282. while ( jack_ringbuffer_read_space( data->buffSize ) > 0 ) {
  2283. jack_ringbuffer_read( data->buffSize, (char *) &space, (size_t) sizeof(space) );
  2284. midiData = jack_midi_event_reserve( buff, 0, space );
  2285. jack_ringbuffer_read( data->buffMessage, (char *) midiData, (size_t) space );
  2286. }
  2287. return 0;
  2288. }
  2289. MidiOutJack :: MidiOutJack( const std::string clientName ) : MidiOutApi()
  2290. {
  2291. initialize( clientName );
  2292. }
  2293. void MidiOutJack :: initialize( const std::string& clientName )
  2294. {
  2295. JackMidiData *data = new JackMidiData;
  2296. apiData_ = (void *) data;
  2297. data->port = NULL;
  2298. data->client = NULL;
  2299. this->clientName = clientName;
  2300. connect();
  2301. }
  2302. void MidiOutJack :: connect()
  2303. {
  2304. JackMidiData *data = static_cast<JackMidiData *> (apiData_);
  2305. if ( data->client )
  2306. return;
  2307. // Initialize JACK client
  2308. if (( data->client = jack_client_open( clientName.c_str(), JackNoStartServer, NULL )) == 0) {
  2309. errorString_ = "MidiOutJack::initialize: JACK server not running?";
  2310. error( RtMidiError::WARNING, errorString_ );
  2311. return;
  2312. }
  2313. jack_set_process_callback( data->client, jackProcessOut, data );
  2314. data->buffSize = jack_ringbuffer_create( JACK_RINGBUFFER_SIZE );
  2315. data->buffMessage = jack_ringbuffer_create( JACK_RINGBUFFER_SIZE );
  2316. jack_activate( data->client );
  2317. }
  2318. MidiOutJack :: ~MidiOutJack()
  2319. {
  2320. JackMidiData *data = static_cast<JackMidiData *> (apiData_);
  2321. closePort();
  2322. if ( data->client ) {
  2323. // Cleanup
  2324. jack_client_close( data->client );
  2325. jack_ringbuffer_free( data->buffSize );
  2326. jack_ringbuffer_free( data->buffMessage );
  2327. }
  2328. delete data;
  2329. }
  2330. void MidiOutJack :: openPort( unsigned int portNumber, const std::string portName )
  2331. {
  2332. JackMidiData *data = static_cast<JackMidiData *> (apiData_);
  2333. connect();
  2334. // Creating new port
  2335. if ( data->port == NULL )
  2336. data->port = jack_port_register( data->client, portName.c_str(),
  2337. JACK_DEFAULT_MIDI_TYPE, JackPortIsOutput, 0 );
  2338. if ( data->port == NULL ) {
  2339. errorString_ = "MidiOutJack::openPort: JACK error creating port";
  2340. error( RtMidiError::DRIVER_ERROR, errorString_ );
  2341. return;
  2342. }
  2343. // Connecting to the output
  2344. std::string name = getPortName( portNumber );
  2345. jack_connect( data->client, jack_port_name( data->port ), name.c_str() );
  2346. }
  2347. void MidiOutJack :: openVirtualPort( const std::string portName )
  2348. {
  2349. JackMidiData *data = static_cast<JackMidiData *> (apiData_);
  2350. connect();
  2351. if ( data->port == NULL )
  2352. data->port = jack_port_register( data->client, portName.c_str(),
  2353. JACK_DEFAULT_MIDI_TYPE, JackPortIsOutput, 0 );
  2354. if ( data->port == NULL ) {
  2355. errorString_ = "MidiOutJack::openVirtualPort: JACK error creating virtual port";
  2356. error( RtMidiError::DRIVER_ERROR, errorString_ );
  2357. }
  2358. }
  2359. unsigned int MidiOutJack :: getPortCount()
  2360. {
  2361. int count = 0;
  2362. JackMidiData *data = static_cast<JackMidiData *> (apiData_);
  2363. connect();
  2364. if ( !data->client )
  2365. return 0;
  2366. // List of available ports
  2367. const char **ports = jack_get_ports( data->client, NULL,
  2368. JACK_DEFAULT_MIDI_TYPE, JackPortIsInput );
  2369. if ( ports == NULL ) return 0;
  2370. while ( ports[count] != NULL )
  2371. count++;
  2372. free( ports );
  2373. return count;
  2374. }
  2375. std::string MidiOutJack :: getPortName( unsigned int portNumber )
  2376. {
  2377. JackMidiData *data = static_cast<JackMidiData *> (apiData_);
  2378. std::string retStr("");
  2379. connect();
  2380. // List of available ports
  2381. const char **ports = jack_get_ports( data->client, NULL,
  2382. JACK_DEFAULT_MIDI_TYPE, JackPortIsInput );
  2383. // Check port validity
  2384. if ( ports == NULL) {
  2385. errorString_ = "MidiOutJack::getPortName: no ports available!";
  2386. error( RtMidiError::WARNING, errorString_ );
  2387. return retStr;
  2388. }
  2389. if ( ports[portNumber] == NULL) {
  2390. std::ostringstream ost;
  2391. ost << "MidiOutJack::getPortName: the 'portNumber' argument (" << portNumber << ") is invalid.";
  2392. errorString_ = ost.str();
  2393. error( RtMidiError::WARNING, errorString_ );
  2394. }
  2395. else retStr.assign( ports[portNumber] );
  2396. free( ports );
  2397. return retStr;
  2398. }
  2399. void MidiOutJack :: closePort()
  2400. {
  2401. JackMidiData *data = static_cast<JackMidiData *> (apiData_);
  2402. if ( data->port == NULL ) return;
  2403. jack_port_unregister( data->client, data->port );
  2404. data->port = NULL;
  2405. }
  2406. void MidiOutJack :: sendMessage( std::vector<unsigned char> *message )
  2407. {
  2408. int nBytes = message->size();
  2409. JackMidiData *data = static_cast<JackMidiData *> (apiData_);
  2410. // Write full message to buffer
  2411. jack_ringbuffer_write( data->buffMessage, ( const char * ) &( *message )[0],
  2412. message->size() );
  2413. jack_ringbuffer_write( data->buffSize, ( char * ) &nBytes, sizeof( nBytes ) );
  2414. }
  2415. #endif // __UNIX_JACK__