Audio plugin host https://kx.studio/carla
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

RtMidi.cpp 92KB

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