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

RtMidi.cpp 94KB

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