RtMidi.cpp 91 KB

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