RtMidi.cpp 120 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879
  1. /**********************************************************************/
  2. /*! \class RtMidi
  3. \brief An abstract base class for realtime MIDI input/output.
  4. This class implements some common functionality for the realtime
  5. MIDI input/output subclasses RtMidiIn and RtMidiOut.
  6. RtMidi WWW site: http://music.mcgill.ca/~gary/rtmidi/
  7. RtMidi: realtime MIDI i/o C++ classes
  8. Copyright (c) 2003-2014 Gary P. Scavone
  9. Permission is hereby granted, free of charge, to any person
  10. obtaining a copy of this software and associated documentation files
  11. (the "Software"), to deal in the Software without restriction,
  12. including without limitation the rights to use, copy, modify, merge,
  13. publish, distribute, sublicense, and/or sell copies of the Software,
  14. and to permit persons to whom the Software is furnished to do so,
  15. subject to the following conditions:
  16. The above copyright notice and this permission notice shall be
  17. included in all copies or substantial portions of the Software.
  18. Any person wishing to distribute modifications to the Software is
  19. asked to send the modifications to the original developer so that
  20. they can be incorporated into the canonical version. This is,
  21. however, not a binding provision of this license.
  22. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  23. EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  24. MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
  25. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
  26. ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
  27. CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  28. WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  29. */
  30. /**********************************************************************/
  31. #include "RtMidi.h"
  32. #include <sstream>
  33. //*********************************************************************//
  34. // RtMidi Definitions
  35. //*********************************************************************//
  36. RtMidi :: RtMidi()
  37. : rtapi_(0)
  38. {
  39. }
  40. RtMidi :: ~RtMidi()
  41. {
  42. if ( rtapi_ )
  43. delete rtapi_;
  44. rtapi_ = 0;
  45. }
  46. std::string RtMidi :: getVersion( void ) throw()
  47. {
  48. return std::string( RTMIDI_VERSION );
  49. }
  50. void RtMidi :: getCompiledApi( std::vector<RtMidi::Api> &apis ) throw()
  51. {
  52. apis.clear();
  53. // The order here will control the order of RtMidi's API search in
  54. // the constructor.
  55. #if defined(__MACOSX_CORE__)
  56. apis.push_back( MACOSX_CORE );
  57. #endif
  58. #if defined(__LINUX_ALSA__)
  59. apis.push_back( LINUX_ALSA );
  60. #endif
  61. #if defined(__UNIX_JACK__)
  62. apis.push_back( UNIX_JACK );
  63. #endif
  64. #if defined(__WINDOWS_MM__)
  65. apis.push_back( WINDOWS_MM );
  66. #endif
  67. #if defined(__WINDOWS_KS__)
  68. apis.push_back( WINDOWS_KS );
  69. #endif
  70. #if defined(__RTMIDI_DUMMY__)
  71. apis.push_back( RTMIDI_DUMMY );
  72. #endif
  73. }
  74. //*********************************************************************//
  75. // RtMidiIn Definitions
  76. //*********************************************************************//
  77. void RtMidiIn :: openMidiApi( RtMidi::Api api, const std::string clientName, unsigned int queueSizeLimit )
  78. {
  79. if ( rtapi_ )
  80. delete rtapi_;
  81. rtapi_ = 0;
  82. #if defined(__UNIX_JACK__)
  83. if ( api == UNIX_JACK )
  84. rtapi_ = new MidiInJack( clientName, queueSizeLimit );
  85. #endif
  86. #if defined(__LINUX_ALSA__)
  87. if ( api == LINUX_ALSA )
  88. rtapi_ = new MidiInAlsa( clientName, queueSizeLimit );
  89. #endif
  90. #if defined(__WINDOWS_MM__)
  91. if ( api == WINDOWS_MM )
  92. rtapi_ = new MidiInWinMM( clientName, queueSizeLimit );
  93. #endif
  94. #if defined(__WINDOWS_KS__)
  95. if ( api == WINDOWS_KS )
  96. rtapi_ = new MidiInWinKS( 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. 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_->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. if ( rtapi_ )
  143. delete rtapi_;
  144. rtapi_ = 0;
  145. #if defined(__UNIX_JACK__)
  146. if ( api == UNIX_JACK )
  147. rtapi_ = new MidiOutJack( clientName );
  148. #endif
  149. #if defined(__LINUX_ALSA__)
  150. if ( api == LINUX_ALSA )
  151. rtapi_ = new MidiOutAlsa( clientName );
  152. #endif
  153. #if defined(__WINDOWS_MM__)
  154. if ( api == WINDOWS_MM )
  155. rtapi_ = new MidiOutWinMM( clientName );
  156. #endif
  157. #if defined(__WINDOWS_KS__)
  158. if ( api == WINDOWS_KS )
  159. rtapi_ = new MidiOutWinKS( clientName );
  160. #endif
  161. #if defined(__MACOSX_CORE__)
  162. if ( api == MACOSX_CORE )
  163. rtapi_ = new MidiOutCore( clientName );
  164. #endif
  165. #if defined(__RTMIDI_DUMMY__)
  166. if ( api == RTMIDI_DUMMY )
  167. rtapi_ = new MidiOutDummy( clientName );
  168. #endif
  169. }
  170. RtMidiOut :: RtMidiOut( RtMidi::Api api, const std::string clientName )
  171. {
  172. if ( api != UNSPECIFIED ) {
  173. // Attempt to open the specified API.
  174. openMidiApi( api, clientName );
  175. if ( rtapi_ ) return;
  176. // No compiled support for specified API value. Issue a warning
  177. // and continue as if no API was specified.
  178. std::cerr << "\nRtMidiOut: no compiled support for specified API argument!\n\n" << std::endl;
  179. }
  180. // Iterate through the compiled APIs and return as soon as we find
  181. // one with at least one port or we reach the end of the list.
  182. std::vector< RtMidi::Api > apis;
  183. getCompiledApi( apis );
  184. for ( unsigned int i=0; i<apis.size(); i++ ) {
  185. openMidiApi( apis[i], clientName );
  186. if ( rtapi_->getPortCount() ) break;
  187. }
  188. if ( rtapi_ ) return;
  189. // It should not be possible to get here because the preprocessor
  190. // definition __RTMIDI_DUMMY__ is automatically defined if no
  191. // API-specific definitions are passed to the compiler. But just in
  192. // case something weird happens, we'll thrown an error.
  193. std::string errorText = "RtMidiOut: no compiled API support found ... critical error!!";
  194. throw( RtMidiError( errorText, RtMidiError::UNSPECIFIED ) );
  195. }
  196. RtMidiOut :: ~RtMidiOut() throw()
  197. {
  198. }
  199. //*********************************************************************//
  200. // Common MidiApi Definitions
  201. //*********************************************************************//
  202. MidiApi :: MidiApi( void )
  203. : apiData_( 0 ), connected_( false ), errorCallback_(0)
  204. {
  205. }
  206. MidiApi :: ~MidiApi( void )
  207. {
  208. }
  209. void MidiApi :: setErrorCallback( RtMidiErrorCallback errorCallback )
  210. {
  211. errorCallback_ = errorCallback;
  212. }
  213. void MidiApi :: error( RtMidiError::Type type, std::string errorString )
  214. {
  215. if ( errorCallback_ ) {
  216. static bool firstErrorOccured = false;
  217. if ( firstErrorOccured )
  218. return;
  219. firstErrorOccured = true;
  220. const std::string errorMessage = errorString;
  221. errorCallback_( type, errorMessage );
  222. firstErrorOccured = false;
  223. return;
  224. }
  225. if ( type == RtMidiError::WARNING ) {
  226. std::cerr << '\n' << errorString << "\n\n";
  227. }
  228. else if ( type == RtMidiError::DEBUG_WARNING ) {
  229. #if defined(__RTMIDI_DEBUG__)
  230. std::cerr << '\n' << errorString << "\n\n";
  231. #endif
  232. }
  233. else {
  234. std::cerr << '\n' << errorString << "\n\n";
  235. throw RtMidiError( errorString, type );
  236. }
  237. }
  238. //*********************************************************************//
  239. // Common MidiInApi Definitions
  240. //*********************************************************************//
  241. MidiInApi :: MidiInApi( unsigned int queueSizeLimit )
  242. : MidiApi()
  243. {
  244. // Allocate the MIDI queue.
  245. inputData_.queue.ringSize = queueSizeLimit;
  246. if ( inputData_.queue.ringSize > 0 )
  247. inputData_.queue.ring = new MidiMessage[ inputData_.queue.ringSize ];
  248. }
  249. MidiInApi :: ~MidiInApi( void )
  250. {
  251. // Delete the MIDI queue.
  252. if ( inputData_.queue.ringSize > 0 ) delete [] inputData_.queue.ring;
  253. }
  254. void MidiInApi :: setCallback( RtMidiIn::RtMidiCallback callback, void *userData )
  255. {
  256. if ( inputData_.usingCallback ) {
  257. errorString_ = "MidiInApi::setCallback: a callback function is already set!";
  258. error( RtMidiError::WARNING, errorString_ );
  259. return;
  260. }
  261. if ( !callback ) {
  262. errorString_ = "RtMidiIn::setCallback: callback function value is invalid!";
  263. error( RtMidiError::WARNING, errorString_ );
  264. return;
  265. }
  266. inputData_.userCallback = callback;
  267. inputData_.userData = userData;
  268. inputData_.usingCallback = true;
  269. }
  270. void MidiInApi :: cancelCallback()
  271. {
  272. if ( !inputData_.usingCallback ) {
  273. errorString_ = "RtMidiIn::cancelCallback: no callback function was set!";
  274. error( RtMidiError::WARNING, errorString_ );
  275. return;
  276. }
  277. inputData_.userCallback = 0;
  278. inputData_.userData = 0;
  279. inputData_.usingCallback = false;
  280. }
  281. void MidiInApi :: ignoreTypes( bool midiSysex, bool midiTime, bool midiSense )
  282. {
  283. inputData_.ignoreFlags = 0;
  284. if ( midiSysex ) inputData_.ignoreFlags = 0x01;
  285. if ( midiTime ) inputData_.ignoreFlags |= 0x02;
  286. if ( midiSense ) inputData_.ignoreFlags |= 0x04;
  287. }
  288. double MidiInApi :: getMessage( std::vector<unsigned char> *message )
  289. {
  290. message->clear();
  291. if ( inputData_.usingCallback ) {
  292. errorString_ = "RtMidiIn::getNextMessage: a user callback is currently set for this port.";
  293. error( RtMidiError::WARNING, errorString_ );
  294. return 0.0;
  295. }
  296. if ( inputData_.queue.size == 0 ) return 0.0;
  297. // Copy queued message to the vector pointer argument and then "pop" it.
  298. std::vector<unsigned char> *bytes = &(inputData_.queue.ring[inputData_.queue.front].bytes);
  299. message->assign( bytes->begin(), bytes->end() );
  300. double deltaTime = inputData_.queue.ring[inputData_.queue.front].timeStamp;
  301. inputData_.queue.size--;
  302. inputData_.queue.front++;
  303. if ( inputData_.queue.front == inputData_.queue.ringSize )
  304. inputData_.queue.front = 0;
  305. return deltaTime;
  306. }
  307. //*********************************************************************//
  308. // Common MidiOutApi Definitions
  309. //*********************************************************************//
  310. MidiOutApi :: MidiOutApi( void )
  311. : MidiApi()
  312. {
  313. }
  314. MidiOutApi :: ~MidiOutApi( void )
  315. {
  316. }
  317. // *************************************************** //
  318. //
  319. // OS/API-specific methods.
  320. //
  321. // *************************************************** //
  322. #if defined(__MACOSX_CORE__)
  323. // The CoreMIDI API is based on the use of a callback function for
  324. // MIDI input. We convert the system specific time stamps to delta
  325. // time values.
  326. // OS-X CoreMIDI header files.
  327. #include <CoreMIDI/CoreMIDI.h>
  328. #include <CoreAudio/HostTime.h>
  329. #include <CoreServices/CoreServices.h>
  330. // A structure to hold variables related to the CoreMIDI API
  331. // implementation.
  332. struct CoreMidiData {
  333. MIDIClientRef client;
  334. MIDIPortRef port;
  335. MIDIEndpointRef endpoint;
  336. MIDIEndpointRef destinationId;
  337. unsigned long long lastTime;
  338. MIDISysexSendRequest sysexreq;
  339. };
  340. //*********************************************************************//
  341. // API: OS-X
  342. // Class Definitions: MidiInCore
  343. //*********************************************************************//
  344. static void midiInputCallback( const MIDIPacketList *list, void *procRef, void */*srcRef*/ )
  345. {
  346. MidiInApi::RtMidiInData *data = static_cast<MidiInApi::RtMidiInData *> (procRef);
  347. CoreMidiData *apiData = static_cast<CoreMidiData *> (data->apiData);
  348. unsigned char status;
  349. unsigned short nBytes, iByte, size;
  350. unsigned long long time;
  351. bool& continueSysex = data->continueSysex;
  352. MidiInApi::MidiMessage& message = data->message;
  353. const MIDIPacket *packet = &list->packet[0];
  354. for ( unsigned int i=0; i<list->numPackets; ++i ) {
  355. // My interpretation of the CoreMIDI documentation: all message
  356. // types, except sysex, are complete within a packet and there may
  357. // be several of them in a single packet. Sysex messages can be
  358. // broken across multiple packets and PacketLists but are bundled
  359. // alone within each packet (these packets do not contain other
  360. // message types). If sysex messages are split across multiple
  361. // MIDIPacketLists, they must be handled by multiple calls to this
  362. // function.
  363. nBytes = packet->length;
  364. if ( nBytes == 0 ) continue;
  365. // Calculate time stamp.
  366. if ( data->firstMessage ) {
  367. message.timeStamp = 0.0;
  368. data->firstMessage = false;
  369. }
  370. else {
  371. time = packet->timeStamp;
  372. if ( time == 0 ) { // this happens when receiving asynchronous sysex messages
  373. time = AudioGetCurrentHostTime();
  374. }
  375. time -= apiData->lastTime;
  376. time = AudioConvertHostTimeToNanos( time );
  377. if ( !continueSysex )
  378. message.timeStamp = time * 0.000000001;
  379. }
  380. apiData->lastTime = packet->timeStamp;
  381. if ( apiData->lastTime == 0 ) { // this happens when receiving asynchronous sysex messages
  382. apiData->lastTime = AudioGetCurrentHostTime();
  383. }
  384. //std::cout << "TimeStamp = " << packet->timeStamp << std::endl;
  385. iByte = 0;
  386. if ( continueSysex ) {
  387. // We have a continuing, segmented sysex message.
  388. if ( !( data->ignoreFlags & 0x01 ) ) {
  389. // If we're not ignoring sysex messages, copy the entire packet.
  390. for ( unsigned int j=0; j<nBytes; ++j )
  391. message.bytes.push_back( packet->data[j] );
  392. }
  393. continueSysex = packet->data[nBytes-1] != 0xF7;
  394. if ( !( data->ignoreFlags & 0x01 ) && !continueSysex ) {
  395. // If not a continuing sysex message, invoke the user callback function or queue the message.
  396. if ( data->usingCallback ) {
  397. RtMidiIn::RtMidiCallback callback = (RtMidiIn::RtMidiCallback) data->userCallback;
  398. callback( message.timeStamp, &message.bytes, data->userData );
  399. }
  400. else {
  401. // As long as we haven't reached our queue size limit, push the message.
  402. if ( data->queue.size < data->queue.ringSize ) {
  403. data->queue.ring[data->queue.back++] = message;
  404. if ( data->queue.back == data->queue.ringSize )
  405. data->queue.back = 0;
  406. data->queue.size++;
  407. }
  408. else
  409. std::cerr << "\nMidiInCore: message queue limit reached!!\n\n";
  410. }
  411. message.bytes.clear();
  412. }
  413. }
  414. else {
  415. while ( iByte < nBytes ) {
  416. size = 0;
  417. // We are expecting that the next byte in the packet is a status byte.
  418. status = packet->data[iByte];
  419. if ( !(status & 0x80) ) break;
  420. // Determine the number of bytes in the MIDI message.
  421. if ( status < 0xC0 ) size = 3;
  422. else if ( status < 0xE0 ) size = 2;
  423. else if ( status < 0xF0 ) size = 3;
  424. else if ( status == 0xF0 ) {
  425. // A MIDI sysex
  426. if ( data->ignoreFlags & 0x01 ) {
  427. size = 0;
  428. iByte = nBytes;
  429. }
  430. else size = nBytes - iByte;
  431. continueSysex = packet->data[nBytes-1] != 0xF7;
  432. }
  433. else if ( status == 0xF1 ) {
  434. // A MIDI time code message
  435. if ( data->ignoreFlags & 0x02 ) {
  436. size = 0;
  437. iByte += 2;
  438. }
  439. else size = 2;
  440. }
  441. else if ( status == 0xF2 ) size = 3;
  442. else if ( status == 0xF3 ) size = 2;
  443. else if ( status == 0xF8 && ( data->ignoreFlags & 0x02 ) ) {
  444. // A MIDI timing tick message and we're ignoring it.
  445. size = 0;
  446. iByte += 1;
  447. }
  448. else if ( status == 0xFE && ( data->ignoreFlags & 0x04 ) ) {
  449. // A MIDI active sensing message and we're ignoring it.
  450. size = 0;
  451. iByte += 1;
  452. }
  453. else size = 1;
  454. // Copy the MIDI data to our vector.
  455. if ( size ) {
  456. message.bytes.assign( &packet->data[iByte], &packet->data[iByte+size] );
  457. if ( !continueSysex ) {
  458. // If not a continuing sysex message, invoke the user callback function or queue the message.
  459. if ( data->usingCallback ) {
  460. RtMidiIn::RtMidiCallback callback = (RtMidiIn::RtMidiCallback) data->userCallback;
  461. callback( message.timeStamp, &message.bytes, data->userData );
  462. }
  463. else {
  464. // As long as we haven't reached our queue size limit, push the message.
  465. if ( data->queue.size < data->queue.ringSize ) {
  466. data->queue.ring[data->queue.back++] = message;
  467. if ( data->queue.back == data->queue.ringSize )
  468. data->queue.back = 0;
  469. data->queue.size++;
  470. }
  471. else
  472. std::cerr << "\nMidiInCore: message queue limit reached!!\n\n";
  473. }
  474. message.bytes.clear();
  475. }
  476. iByte += size;
  477. }
  478. }
  479. }
  480. packet = MIDIPacketNext(packet);
  481. }
  482. }
  483. MidiInCore :: MidiInCore( const std::string clientName, unsigned int queueSizeLimit ) : MidiInApi( queueSizeLimit )
  484. {
  485. initialize( clientName );
  486. }
  487. MidiInCore :: ~MidiInCore( void )
  488. {
  489. // Close a connection if it exists.
  490. closePort();
  491. // Cleanup.
  492. CoreMidiData *data = static_cast<CoreMidiData *> (apiData_);
  493. MIDIClientDispose( data->client );
  494. if ( data->endpoint ) MIDIEndpointDispose( data->endpoint );
  495. delete data;
  496. }
  497. void MidiInCore :: initialize( const std::string& clientName )
  498. {
  499. // Set up our client.
  500. MIDIClientRef client;
  501. OSStatus result = MIDIClientCreate( CFStringCreateWithCString( NULL, clientName.c_str(), kCFStringEncodingASCII ), NULL, NULL, &client );
  502. if ( result != noErr ) {
  503. errorString_ = "MidiInCore::initialize: error creating OS-X MIDI client object.";
  504. error( RtMidiError::DRIVER_ERROR, errorString_ );
  505. return;
  506. }
  507. // Save our api-specific connection information.
  508. CoreMidiData *data = (CoreMidiData *) new CoreMidiData;
  509. data->client = client;
  510. data->endpoint = 0;
  511. apiData_ = (void *) data;
  512. inputData_.apiData = (void *) data;
  513. }
  514. void MidiInCore :: openPort( unsigned int portNumber, const std::string portName )
  515. {
  516. if ( connected_ ) {
  517. errorString_ = "MidiInCore::openPort: a valid connection already exists!";
  518. error( RtMidiError::WARNING, errorString_ );
  519. return;
  520. }
  521. CFRunLoopRunInMode( kCFRunLoopDefaultMode, 0, false );
  522. unsigned int nSrc = MIDIGetNumberOfSources();
  523. if (nSrc < 1) {
  524. errorString_ = "MidiInCore::openPort: no MIDI input sources found!";
  525. error( RtMidiError::NO_DEVICES_FOUND, errorString_ );
  526. return;
  527. }
  528. if ( portNumber >= nSrc ) {
  529. std::ostringstream ost;
  530. ost << "MidiInCore::openPort: the 'portNumber' argument (" << portNumber << ") is invalid.";
  531. errorString_ = ost.str();
  532. error( RtMidiError::INVALID_PARAMETER, errorString_ );
  533. return;
  534. }
  535. MIDIPortRef port;
  536. CoreMidiData *data = static_cast<CoreMidiData *> (apiData_);
  537. OSStatus result = MIDIInputPortCreate( data->client,
  538. CFStringCreateWithCString( NULL, portName.c_str(), kCFStringEncodingASCII ),
  539. midiInputCallback, (void *)&inputData_, &port );
  540. if ( result != noErr ) {
  541. MIDIClientDispose( data->client );
  542. errorString_ = "MidiInCore::openPort: error creating OS-X MIDI input port.";
  543. error( RtMidiError::DRIVER_ERROR, errorString_ );
  544. return;
  545. }
  546. // Get the desired input source identifier.
  547. MIDIEndpointRef endpoint = MIDIGetSource( portNumber );
  548. if ( endpoint == 0 ) {
  549. MIDIPortDispose( port );
  550. MIDIClientDispose( data->client );
  551. errorString_ = "MidiInCore::openPort: error getting MIDI input source reference.";
  552. error( RtMidiError::DRIVER_ERROR, errorString_ );
  553. return;
  554. }
  555. // Make the connection.
  556. result = MIDIPortConnectSource( port, endpoint, NULL );
  557. if ( result != noErr ) {
  558. MIDIPortDispose( port );
  559. MIDIClientDispose( data->client );
  560. errorString_ = "MidiInCore::openPort: error connecting OS-X MIDI input port.";
  561. error( RtMidiError::DRIVER_ERROR, errorString_ );
  562. return;
  563. }
  564. // Save our api-specific port information.
  565. data->port = port;
  566. connected_ = true;
  567. }
  568. void MidiInCore :: openVirtualPort( const std::string portName )
  569. {
  570. CoreMidiData *data = static_cast<CoreMidiData *> (apiData_);
  571. // Create a virtual MIDI input destination.
  572. MIDIEndpointRef endpoint;
  573. OSStatus result = MIDIDestinationCreate( data->client,
  574. CFStringCreateWithCString( NULL, portName.c_str(), kCFStringEncodingASCII ),
  575. midiInputCallback, (void *)&inputData_, &endpoint );
  576. if ( result != noErr ) {
  577. errorString_ = "MidiInCore::openVirtualPort: error creating virtual OS-X MIDI destination.";
  578. error( RtMidiError::DRIVER_ERROR, errorString_ );
  579. return;
  580. }
  581. // Save our api-specific connection information.
  582. data->endpoint = endpoint;
  583. }
  584. void MidiInCore :: closePort( void )
  585. {
  586. if ( connected_ ) {
  587. CoreMidiData *data = static_cast<CoreMidiData *> (apiData_);
  588. MIDIPortDispose( data->port );
  589. connected_ = false;
  590. }
  591. }
  592. unsigned int MidiInCore :: getPortCount()
  593. {
  594. CFRunLoopRunInMode( kCFRunLoopDefaultMode, 0, false );
  595. return MIDIGetNumberOfSources();
  596. }
  597. // This function was submitted by Douglas Casey Tucker and apparently
  598. // derived largely from PortMidi.
  599. CFStringRef EndpointName( MIDIEndpointRef endpoint, bool isExternal )
  600. {
  601. CFMutableStringRef result = CFStringCreateMutable( NULL, 0 );
  602. CFStringRef str;
  603. // Begin with the endpoint's name.
  604. str = NULL;
  605. MIDIObjectGetStringProperty( endpoint, kMIDIPropertyName, &str );
  606. if ( str != NULL ) {
  607. CFStringAppend( result, str );
  608. CFRelease( str );
  609. }
  610. MIDIEntityRef entity = 0;
  611. MIDIEndpointGetEntity( endpoint, &entity );
  612. if ( entity == 0 )
  613. // probably virtual
  614. return result;
  615. if ( CFStringGetLength( result ) == 0 ) {
  616. // endpoint name has zero length -- try the entity
  617. str = NULL;
  618. MIDIObjectGetStringProperty( entity, kMIDIPropertyName, &str );
  619. if ( str != NULL ) {
  620. CFStringAppend( result, str );
  621. CFRelease( str );
  622. }
  623. }
  624. // now consider the device's name
  625. MIDIDeviceRef device = 0;
  626. MIDIEntityGetDevice( entity, &device );
  627. if ( device == 0 )
  628. return result;
  629. str = NULL;
  630. MIDIObjectGetStringProperty( device, kMIDIPropertyName, &str );
  631. if ( CFStringGetLength( result ) == 0 ) {
  632. CFRelease( result );
  633. return str;
  634. }
  635. if ( str != NULL ) {
  636. // if an external device has only one entity, throw away
  637. // the endpoint name and just use the device name
  638. if ( isExternal && MIDIDeviceGetNumberOfEntities( device ) < 2 ) {
  639. CFRelease( result );
  640. return str;
  641. } else {
  642. if ( CFStringGetLength( str ) == 0 ) {
  643. CFRelease( str );
  644. return result;
  645. }
  646. // does the entity name already start with the device name?
  647. // (some drivers do this though they shouldn't)
  648. // if so, do not prepend
  649. if ( CFStringCompareWithOptions( result, /* endpoint name */
  650. str /* device name */,
  651. CFRangeMake(0, CFStringGetLength( str ) ), 0 ) != kCFCompareEqualTo ) {
  652. // prepend the device name to the entity name
  653. if ( CFStringGetLength( result ) > 0 )
  654. CFStringInsert( result, 0, CFSTR(" ") );
  655. CFStringInsert( result, 0, str );
  656. }
  657. CFRelease( str );
  658. }
  659. }
  660. return result;
  661. }
  662. // This function was submitted by Douglas Casey Tucker and apparently
  663. // derived largely from PortMidi.
  664. static CFStringRef ConnectedEndpointName( MIDIEndpointRef endpoint )
  665. {
  666. CFMutableStringRef result = CFStringCreateMutable( NULL, 0 );
  667. CFStringRef str;
  668. OSStatus err;
  669. int i;
  670. // Does the endpoint have connections?
  671. CFDataRef connections = NULL;
  672. int nConnected = 0;
  673. bool anyStrings = false;
  674. err = MIDIObjectGetDataProperty( endpoint, kMIDIPropertyConnectionUniqueID, &connections );
  675. if ( connections != NULL ) {
  676. // It has connections, follow them
  677. // Concatenate the names of all connected devices
  678. nConnected = CFDataGetLength( connections ) / sizeof(MIDIUniqueID);
  679. if ( nConnected ) {
  680. const SInt32 *pid = (const SInt32 *)(CFDataGetBytePtr(connections));
  681. for ( i=0; i<nConnected; ++i, ++pid ) {
  682. MIDIUniqueID id = EndianS32_BtoN( *pid );
  683. MIDIObjectRef connObject;
  684. MIDIObjectType connObjectType;
  685. err = MIDIObjectFindByUniqueID( id, &connObject, &connObjectType );
  686. if ( err == noErr ) {
  687. if ( connObjectType == kMIDIObjectType_ExternalSource ||
  688. connObjectType == kMIDIObjectType_ExternalDestination ) {
  689. // Connected to an external device's endpoint (10.3 and later).
  690. str = EndpointName( (MIDIEndpointRef)(connObject), true );
  691. } else {
  692. // Connected to an external device (10.2) (or something else, catch-
  693. str = NULL;
  694. MIDIObjectGetStringProperty( connObject, kMIDIPropertyName, &str );
  695. }
  696. if ( str != NULL ) {
  697. if ( anyStrings )
  698. CFStringAppend( result, CFSTR(", ") );
  699. else anyStrings = true;
  700. CFStringAppend( result, str );
  701. CFRelease( str );
  702. }
  703. }
  704. }
  705. }
  706. CFRelease( connections );
  707. }
  708. if ( anyStrings )
  709. return result;
  710. // Here, either the endpoint had no connections, or we failed to obtain names
  711. return EndpointName( endpoint, false );
  712. }
  713. std::string MidiInCore :: getPortName( unsigned int portNumber )
  714. {
  715. CFStringRef nameRef;
  716. MIDIEndpointRef portRef;
  717. char name[128];
  718. std::string stringName;
  719. CFRunLoopRunInMode( kCFRunLoopDefaultMode, 0, false );
  720. if ( portNumber >= MIDIGetNumberOfSources() ) {
  721. std::ostringstream ost;
  722. ost << "MidiInCore::getPortName: the 'portNumber' argument (" << portNumber << ") is invalid.";
  723. errorString_ = ost.str();
  724. error( RtMidiError::WARNING, errorString_ );
  725. return stringName;
  726. }
  727. portRef = MIDIGetSource( portNumber );
  728. nameRef = ConnectedEndpointName(portRef);
  729. CFStringGetCString( nameRef, name, sizeof(name), CFStringGetSystemEncoding());
  730. CFRelease( nameRef );
  731. return stringName = name;
  732. }
  733. //*********************************************************************//
  734. // API: OS-X
  735. // Class Definitions: MidiOutCore
  736. //*********************************************************************//
  737. MidiOutCore :: MidiOutCore( const std::string clientName ) : MidiOutApi()
  738. {
  739. initialize( clientName );
  740. }
  741. MidiOutCore :: ~MidiOutCore( void )
  742. {
  743. // Close a connection if it exists.
  744. closePort();
  745. // Cleanup.
  746. CoreMidiData *data = static_cast<CoreMidiData *> (apiData_);
  747. MIDIClientDispose( data->client );
  748. if ( data->endpoint ) MIDIEndpointDispose( data->endpoint );
  749. delete data;
  750. }
  751. void MidiOutCore :: initialize( const std::string& clientName )
  752. {
  753. // Set up our client.
  754. MIDIClientRef client;
  755. OSStatus result = MIDIClientCreate( CFStringCreateWithCString( NULL, clientName.c_str(), kCFStringEncodingASCII ), NULL, NULL, &client );
  756. if ( result != noErr ) {
  757. errorString_ = "MidiOutCore::initialize: error creating OS-X MIDI client object.";
  758. error( RtMidiError::DRIVER_ERROR, errorString_ );
  759. return;
  760. }
  761. // Save our api-specific connection information.
  762. CoreMidiData *data = (CoreMidiData *) new CoreMidiData;
  763. data->client = client;
  764. data->endpoint = 0;
  765. apiData_ = (void *) data;
  766. }
  767. unsigned int MidiOutCore :: getPortCount()
  768. {
  769. CFRunLoopRunInMode( kCFRunLoopDefaultMode, 0, false );
  770. return MIDIGetNumberOfDestinations();
  771. }
  772. std::string MidiOutCore :: getPortName( unsigned int portNumber )
  773. {
  774. CFStringRef nameRef;
  775. MIDIEndpointRef portRef;
  776. char name[128];
  777. std::string stringName;
  778. CFRunLoopRunInMode( kCFRunLoopDefaultMode, 0, false );
  779. if ( portNumber >= MIDIGetNumberOfDestinations() ) {
  780. std::ostringstream ost;
  781. ost << "MidiOutCore::getPortName: the 'portNumber' argument (" << portNumber << ") is invalid.";
  782. errorString_ = ost.str();
  783. error( RtMidiError::WARNING, errorString_ );
  784. return stringName;
  785. }
  786. portRef = MIDIGetDestination( portNumber );
  787. nameRef = ConnectedEndpointName(portRef);
  788. CFStringGetCString( nameRef, name, sizeof(name), CFStringGetSystemEncoding());
  789. CFRelease( nameRef );
  790. return stringName = name;
  791. }
  792. void MidiOutCore :: openPort( unsigned int portNumber, const std::string portName )
  793. {
  794. if ( connected_ ) {
  795. errorString_ = "MidiOutCore::openPort: a valid connection already exists!";
  796. error( RtMidiError::WARNING, errorString_ );
  797. return;
  798. }
  799. CFRunLoopRunInMode( kCFRunLoopDefaultMode, 0, false );
  800. unsigned int nDest = MIDIGetNumberOfDestinations();
  801. if (nDest < 1) {
  802. errorString_ = "MidiOutCore::openPort: no MIDI output destinations found!";
  803. error( RtMidiError::NO_DEVICES_FOUND, errorString_ );
  804. return;
  805. }
  806. if ( portNumber >= nDest ) {
  807. std::ostringstream ost;
  808. ost << "MidiOutCore::openPort: the 'portNumber' argument (" << portNumber << ") is invalid.";
  809. errorString_ = ost.str();
  810. error( RtMidiError::INVALID_PARAMETER, errorString_ );
  811. return;
  812. }
  813. MIDIPortRef port;
  814. CoreMidiData *data = static_cast<CoreMidiData *> (apiData_);
  815. OSStatus result = MIDIOutputPortCreate( data->client,
  816. CFStringCreateWithCString( NULL, portName.c_str(), kCFStringEncodingASCII ),
  817. &port );
  818. if ( result != noErr ) {
  819. MIDIClientDispose( data->client );
  820. errorString_ = "MidiOutCore::openPort: error creating OS-X MIDI output port.";
  821. error( RtMidiError::DRIVER_ERROR, errorString_ );
  822. return;
  823. }
  824. // Get the desired output port identifier.
  825. MIDIEndpointRef destination = MIDIGetDestination( portNumber );
  826. if ( destination == 0 ) {
  827. MIDIPortDispose( port );
  828. MIDIClientDispose( data->client );
  829. errorString_ = "MidiOutCore::openPort: error getting MIDI output destination reference.";
  830. error( RtMidiError::DRIVER_ERROR, errorString_ );
  831. return;
  832. }
  833. // Save our api-specific connection information.
  834. data->port = port;
  835. data->destinationId = destination;
  836. connected_ = true;
  837. }
  838. void MidiOutCore :: closePort( void )
  839. {
  840. if ( connected_ ) {
  841. CoreMidiData *data = static_cast<CoreMidiData *> (apiData_);
  842. MIDIPortDispose( data->port );
  843. connected_ = false;
  844. }
  845. }
  846. void MidiOutCore :: openVirtualPort( std::string portName )
  847. {
  848. CoreMidiData *data = static_cast<CoreMidiData *> (apiData_);
  849. if ( data->endpoint ) {
  850. errorString_ = "MidiOutCore::openVirtualPort: a virtual output port already exists!";
  851. error( RtMidiError::WARNING, errorString_ );
  852. return;
  853. }
  854. // Create a virtual MIDI output source.
  855. MIDIEndpointRef endpoint;
  856. OSStatus result = MIDISourceCreate( data->client,
  857. CFStringCreateWithCString( NULL, portName.c_str(), kCFStringEncodingASCII ),
  858. &endpoint );
  859. if ( result != noErr ) {
  860. errorString_ = "MidiOutCore::initialize: error creating OS-X virtual MIDI source.";
  861. error( RtMidiError::DRIVER_ERROR, errorString_ );
  862. return;
  863. }
  864. // Save our api-specific connection information.
  865. data->endpoint = endpoint;
  866. }
  867. // Not necessary if we don't treat sysex messages any differently than
  868. // normal messages ... see below.
  869. //static void sysexCompletionProc( MIDISysexSendRequest *sreq )
  870. //{
  871. // free( sreq );
  872. //}
  873. void MidiOutCore :: sendMessage( std::vector<unsigned char> *message )
  874. {
  875. // We use the MIDISendSysex() function to asynchronously send sysex
  876. // messages. Otherwise, we use a single CoreMidi MIDIPacket.
  877. unsigned int nBytes = message->size();
  878. if ( nBytes == 0 ) {
  879. errorString_ = "MidiOutCore::sendMessage: no data in message argument!";
  880. error( RtMidiError::WARNING, errorString_ );
  881. return;
  882. }
  883. // unsigned int packetBytes, bytesLeft = nBytes;
  884. // unsigned int messageIndex = 0;
  885. MIDITimeStamp timeStamp = AudioGetCurrentHostTime();
  886. CoreMidiData *data = static_cast<CoreMidiData *> (apiData_);
  887. OSStatus result;
  888. /*
  889. // I don't think this code is necessary. We can send sysex
  890. // messages through the normal mechanism. In addition, this avoids
  891. // the problem of virtual ports not receiving sysex messages.
  892. if ( message->at(0) == 0xF0 ) {
  893. // Apple's fantastic API requires us to free the allocated data in
  894. // the completion callback but trashes the pointer and size before
  895. // we get a chance to free it!! This is a somewhat ugly hack
  896. // submitted by ptarabbia that puts the sysex buffer data right at
  897. // the end of the MIDISysexSendRequest structure. This solution
  898. // does not require that we wait for a previous sysex buffer to be
  899. // sent before sending a new one, which was the old way we did it.
  900. MIDISysexSendRequest *newRequest = (MIDISysexSendRequest *) malloc(sizeof(struct MIDISysexSendRequest) + nBytes);
  901. char * sysexBuffer = ((char *) newRequest) + sizeof(struct MIDISysexSendRequest);
  902. // Copy data to buffer.
  903. for ( unsigned int i=0; i<nBytes; ++i ) sysexBuffer[i] = message->at(i);
  904. newRequest->destination = data->destinationId;
  905. newRequest->data = (Byte *)sysexBuffer;
  906. newRequest->bytesToSend = nBytes;
  907. newRequest->complete = 0;
  908. newRequest->completionProc = sysexCompletionProc;
  909. newRequest->completionRefCon = newRequest;
  910. result = MIDISendSysex(newRequest);
  911. if ( result != noErr ) {
  912. free( newRequest );
  913. errorString_ = "MidiOutCore::sendMessage: error sending MIDI to virtual destinations.";
  914. error( RtMidiError::WARNING, errorString_ );
  915. return;
  916. }
  917. return;
  918. }
  919. else if ( nBytes > 3 ) {
  920. errorString_ = "MidiOutCore::sendMessage: message format problem ... not sysex but > 3 bytes?";
  921. error( RtMidiError::WARNING, errorString_ );
  922. return;
  923. }
  924. */
  925. MIDIPacketList packetList;
  926. MIDIPacket *packet = MIDIPacketListInit( &packetList );
  927. packet = MIDIPacketListAdd( &packetList, sizeof(packetList), packet, timeStamp, nBytes, (const Byte *) &message->at( 0 ) );
  928. if ( !packet ) {
  929. errorString_ = "MidiOutCore::sendMessage: could not allocate packet list";
  930. error( RtMidiError::DRIVER_ERROR, errorString_ );
  931. return;
  932. }
  933. // Send to any destinations that may have connected to us.
  934. if ( data->endpoint ) {
  935. result = MIDIReceived( data->endpoint, &packetList );
  936. if ( result != noErr ) {
  937. errorString_ = "MidiOutCore::sendMessage: error sending MIDI to virtual destinations.";
  938. error( RtMidiError::WARNING, errorString_ );
  939. }
  940. }
  941. // And send to an explicit destination port if we're connected.
  942. if ( connected_ ) {
  943. result = MIDISend( data->port, data->destinationId, &packetList );
  944. if ( result != noErr ) {
  945. errorString_ = "MidiOutCore::sendMessage: error sending MIDI message to port.";
  946. error( RtMidiError::WARNING, errorString_ );
  947. }
  948. }
  949. }
  950. #endif // __MACOSX_CORE__
  951. //*********************************************************************//
  952. // API: LINUX ALSA SEQUENCER
  953. //*********************************************************************//
  954. // API information found at:
  955. // - http://www.alsa-project.org/documentation.php#Library
  956. #if defined(__LINUX_ALSA__)
  957. // The ALSA Sequencer API is based on the use of a callback function for
  958. // MIDI input.
  959. //
  960. // Thanks to Pedro Lopez-Cabanillas for help with the ALSA sequencer
  961. // time stamps and other assorted fixes!!!
  962. // If you don't need timestamping for incoming MIDI events, define the
  963. // preprocessor definition AVOID_TIMESTAMPING to save resources
  964. // associated with the ALSA sequencer queues.
  965. #include <pthread.h>
  966. #include <sys/time.h>
  967. // ALSA header file.
  968. #include <alsa/asoundlib.h>
  969. // A structure to hold variables related to the ALSA API
  970. // implementation.
  971. struct AlsaMidiData {
  972. snd_seq_t *seq;
  973. unsigned int portNum;
  974. int vport;
  975. snd_seq_port_subscribe_t *subscription;
  976. snd_midi_event_t *coder;
  977. unsigned int bufferSize;
  978. unsigned char *buffer;
  979. pthread_t thread;
  980. pthread_t dummy_thread_id;
  981. unsigned long long lastTime;
  982. int queue_id; // an input queue is needed to get timestamped events
  983. int trigger_fds[2];
  984. };
  985. #define PORT_TYPE( pinfo, bits ) ((snd_seq_port_info_get_capability(pinfo) & (bits)) == (bits))
  986. //*********************************************************************//
  987. // API: LINUX ALSA
  988. // Class Definitions: MidiInAlsa
  989. //*********************************************************************//
  990. static void *alsaMidiHandler( void *ptr )
  991. {
  992. MidiInApi::RtMidiInData *data = static_cast<MidiInApi::RtMidiInData *> (ptr);
  993. AlsaMidiData *apiData = static_cast<AlsaMidiData *> (data->apiData);
  994. long nBytes;
  995. unsigned long long time, lastTime;
  996. bool continueSysex = false;
  997. bool doDecode = false;
  998. MidiInApi::MidiMessage message;
  999. int poll_fd_count;
  1000. struct pollfd *poll_fds;
  1001. snd_seq_event_t *ev;
  1002. int result;
  1003. apiData->bufferSize = 32;
  1004. result = snd_midi_event_new( 0, &apiData->coder );
  1005. if ( result < 0 ) {
  1006. data->doInput = false;
  1007. std::cerr << "\nMidiInAlsa::alsaMidiHandler: error initializing MIDI event parser!\n\n";
  1008. return 0;
  1009. }
  1010. unsigned char *buffer = (unsigned char *) malloc( apiData->bufferSize );
  1011. if ( buffer == NULL ) {
  1012. data->doInput = false;
  1013. snd_midi_event_free( apiData->coder );
  1014. apiData->coder = 0;
  1015. std::cerr << "\nMidiInAlsa::alsaMidiHandler: error initializing buffer memory!\n\n";
  1016. return 0;
  1017. }
  1018. snd_midi_event_init( apiData->coder );
  1019. snd_midi_event_no_status( apiData->coder, 1 ); // suppress running status messages
  1020. poll_fd_count = snd_seq_poll_descriptors_count( apiData->seq, POLLIN ) + 1;
  1021. poll_fds = (struct pollfd*)alloca( poll_fd_count * sizeof( struct pollfd ));
  1022. snd_seq_poll_descriptors( apiData->seq, poll_fds + 1, poll_fd_count - 1, POLLIN );
  1023. poll_fds[0].fd = apiData->trigger_fds[0];
  1024. poll_fds[0].events = POLLIN;
  1025. while ( data->doInput ) {
  1026. if ( snd_seq_event_input_pending( apiData->seq, 1 ) == 0 ) {
  1027. // No data pending
  1028. if ( poll( poll_fds, poll_fd_count, -1) >= 0 ) {
  1029. if ( poll_fds[0].revents & POLLIN ) {
  1030. bool dummy;
  1031. int res = read( poll_fds[0].fd, &dummy, sizeof(dummy) );
  1032. (void) res;
  1033. }
  1034. }
  1035. continue;
  1036. }
  1037. // If here, there should be data.
  1038. result = snd_seq_event_input( apiData->seq, &ev );
  1039. if ( result == -ENOSPC ) {
  1040. std::cerr << "\nMidiInAlsa::alsaMidiHandler: MIDI input buffer overrun!\n\n";
  1041. continue;
  1042. }
  1043. else if ( result <= 0 ) {
  1044. std::cerr << "MidiInAlsa::alsaMidiHandler: unknown MIDI input error!\n";
  1045. continue;
  1046. }
  1047. // This is a bit weird, but we now have to decode an ALSA MIDI
  1048. // event (back) into MIDI bytes. We'll ignore non-MIDI types.
  1049. if ( !continueSysex ) message.bytes.clear();
  1050. doDecode = false;
  1051. switch ( ev->type ) {
  1052. case SND_SEQ_EVENT_PORT_SUBSCRIBED:
  1053. #if defined(__RTMIDI_DEBUG__)
  1054. std::cout << "MidiInAlsa::alsaMidiHandler: port connection made!\n";
  1055. #endif
  1056. break;
  1057. case SND_SEQ_EVENT_PORT_UNSUBSCRIBED:
  1058. #if defined(__RTMIDI_DEBUG__)
  1059. std::cerr << "MidiInAlsa::alsaMidiHandler: port connection has closed!\n";
  1060. std::cout << "sender = " << (int) ev->data.connect.sender.client << ":"
  1061. << (int) ev->data.connect.sender.port
  1062. << ", dest = " << (int) ev->data.connect.dest.client << ":"
  1063. << (int) ev->data.connect.dest.port
  1064. << std::endl;
  1065. #endif
  1066. break;
  1067. case SND_SEQ_EVENT_QFRAME: // MIDI time code
  1068. if ( !( data->ignoreFlags & 0x02 ) ) doDecode = true;
  1069. break;
  1070. case SND_SEQ_EVENT_TICK: // 0xF9 ... MIDI timing tick
  1071. if ( !( data->ignoreFlags & 0x02 ) ) doDecode = true;
  1072. break;
  1073. case SND_SEQ_EVENT_CLOCK: // 0xF8 ... MIDI timing (clock) tick
  1074. if ( !( data->ignoreFlags & 0x02 ) ) doDecode = true;
  1075. break;
  1076. case SND_SEQ_EVENT_SENSING: // Active sensing
  1077. if ( !( data->ignoreFlags & 0x04 ) ) doDecode = true;
  1078. break;
  1079. case SND_SEQ_EVENT_SYSEX:
  1080. if ( (data->ignoreFlags & 0x01) ) break;
  1081. if ( ev->data.ext.len > apiData->bufferSize ) {
  1082. apiData->bufferSize = ev->data.ext.len;
  1083. free( buffer );
  1084. buffer = (unsigned char *) malloc( apiData->bufferSize );
  1085. if ( buffer == NULL ) {
  1086. data->doInput = false;
  1087. std::cerr << "\nMidiInAlsa::alsaMidiHandler: error resizing buffer memory!\n\n";
  1088. break;
  1089. }
  1090. }
  1091. default:
  1092. doDecode = true;
  1093. }
  1094. if ( doDecode ) {
  1095. nBytes = snd_midi_event_decode( apiData->coder, buffer, apiData->bufferSize, ev );
  1096. if ( nBytes > 0 ) {
  1097. // The ALSA sequencer has a maximum buffer size for MIDI sysex
  1098. // events of 256 bytes. If a device sends sysex messages larger
  1099. // than this, they are segmented into 256 byte chunks. So,
  1100. // we'll watch for this and concatenate sysex chunks into a
  1101. // single sysex message if necessary.
  1102. if ( !continueSysex )
  1103. message.bytes.assign( buffer, &buffer[nBytes] );
  1104. else
  1105. message.bytes.insert( message.bytes.end(), buffer, &buffer[nBytes] );
  1106. continueSysex = ( ( ev->type == SND_SEQ_EVENT_SYSEX ) && ( message.bytes.back() != 0xF7 ) );
  1107. if ( !continueSysex ) {
  1108. // Calculate the time stamp:
  1109. message.timeStamp = 0.0;
  1110. // Method 1: Use the system time.
  1111. //(void)gettimeofday(&tv, (struct timezone *)NULL);
  1112. //time = (tv.tv_sec * 1000000) + tv.tv_usec;
  1113. // Method 2: Use the ALSA sequencer event time data.
  1114. // (thanks to Pedro Lopez-Cabanillas!).
  1115. time = ( ev->time.time.tv_sec * 1000000 ) + ( ev->time.time.tv_nsec/1000 );
  1116. lastTime = time;
  1117. time -= apiData->lastTime;
  1118. apiData->lastTime = lastTime;
  1119. if ( data->firstMessage == true )
  1120. data->firstMessage = false;
  1121. else
  1122. message.timeStamp = time * 0.000001;
  1123. }
  1124. else {
  1125. #if defined(__RTMIDI_DEBUG__)
  1126. std::cerr << "\nMidiInAlsa::alsaMidiHandler: event parsing error or not a MIDI event!\n\n";
  1127. #endif
  1128. }
  1129. }
  1130. }
  1131. snd_seq_free_event( ev );
  1132. if ( message.bytes.size() == 0 || continueSysex ) continue;
  1133. if ( data->usingCallback ) {
  1134. RtMidiIn::RtMidiCallback callback = (RtMidiIn::RtMidiCallback) data->userCallback;
  1135. callback( message.timeStamp, &message.bytes, data->userData );
  1136. }
  1137. else {
  1138. // As long as we haven't reached our queue size limit, push the message.
  1139. if ( data->queue.size < data->queue.ringSize ) {
  1140. data->queue.ring[data->queue.back++] = message;
  1141. if ( data->queue.back == data->queue.ringSize )
  1142. data->queue.back = 0;
  1143. data->queue.size++;
  1144. }
  1145. else
  1146. std::cerr << "\nMidiInAlsa: message queue limit reached!!\n\n";
  1147. }
  1148. }
  1149. if ( buffer ) free( buffer );
  1150. snd_midi_event_free( apiData->coder );
  1151. apiData->coder = 0;
  1152. apiData->thread = apiData->dummy_thread_id;
  1153. return 0;
  1154. }
  1155. MidiInAlsa :: MidiInAlsa( const std::string clientName, unsigned int queueSizeLimit ) : MidiInApi( queueSizeLimit )
  1156. {
  1157. initialize( clientName );
  1158. }
  1159. MidiInAlsa :: ~MidiInAlsa()
  1160. {
  1161. // Close a connection if it exists.
  1162. closePort();
  1163. // Shutdown the input thread.
  1164. AlsaMidiData *data = static_cast<AlsaMidiData *> (apiData_);
  1165. if ( inputData_.doInput ) {
  1166. inputData_.doInput = false;
  1167. int res = write( data->trigger_fds[1], &inputData_.doInput, sizeof(inputData_.doInput) );
  1168. (void) res;
  1169. if ( !pthread_equal(data->thread, data->dummy_thread_id) )
  1170. pthread_join( data->thread, NULL );
  1171. }
  1172. // Cleanup.
  1173. close ( data->trigger_fds[0] );
  1174. close ( data->trigger_fds[1] );
  1175. if ( data->vport >= 0 ) snd_seq_delete_port( data->seq, data->vport );
  1176. #ifndef AVOID_TIMESTAMPING
  1177. snd_seq_free_queue( data->seq, data->queue_id );
  1178. #endif
  1179. snd_seq_close( data->seq );
  1180. delete data;
  1181. }
  1182. void MidiInAlsa :: initialize( const std::string& clientName )
  1183. {
  1184. // Set up the ALSA sequencer client.
  1185. snd_seq_t *seq;
  1186. int result = snd_seq_open(&seq, "default", SND_SEQ_OPEN_DUPLEX, SND_SEQ_NONBLOCK);
  1187. if ( result < 0 ) {
  1188. errorString_ = "MidiInAlsa::initialize: error creating ALSA sequencer client object.";
  1189. error( RtMidiError::DRIVER_ERROR, errorString_ );
  1190. return;
  1191. }
  1192. // Set client name.
  1193. snd_seq_set_client_name( seq, clientName.c_str() );
  1194. // Save our api-specific connection information.
  1195. AlsaMidiData *data = (AlsaMidiData *) new AlsaMidiData;
  1196. data->seq = seq;
  1197. data->portNum = -1;
  1198. data->vport = -1;
  1199. data->subscription = 0;
  1200. data->dummy_thread_id = pthread_self();
  1201. data->thread = data->dummy_thread_id;
  1202. data->trigger_fds[0] = -1;
  1203. data->trigger_fds[1] = -1;
  1204. apiData_ = (void *) data;
  1205. inputData_.apiData = (void *) data;
  1206. if ( pipe(data->trigger_fds) == -1 ) {
  1207. errorString_ = "MidiInAlsa::initialize: error creating pipe objects.";
  1208. error( RtMidiError::DRIVER_ERROR, errorString_ );
  1209. return;
  1210. }
  1211. // Create the input queue
  1212. #ifndef AVOID_TIMESTAMPING
  1213. data->queue_id = snd_seq_alloc_named_queue(seq, "RtMidi Queue");
  1214. // Set arbitrary tempo (mm=100) and resolution (240)
  1215. snd_seq_queue_tempo_t *qtempo;
  1216. snd_seq_queue_tempo_alloca(&qtempo);
  1217. snd_seq_queue_tempo_set_tempo(qtempo, 600000);
  1218. snd_seq_queue_tempo_set_ppq(qtempo, 240);
  1219. snd_seq_set_queue_tempo(data->seq, data->queue_id, qtempo);
  1220. snd_seq_drain_output(data->seq);
  1221. #endif
  1222. }
  1223. // This function is used to count or get the pinfo structure for a given port number.
  1224. unsigned int portInfo( snd_seq_t *seq, snd_seq_port_info_t *pinfo, unsigned int type, int portNumber )
  1225. {
  1226. snd_seq_client_info_t *cinfo;
  1227. int client;
  1228. int count = 0;
  1229. snd_seq_client_info_alloca( &cinfo );
  1230. snd_seq_client_info_set_client( cinfo, -1 );
  1231. while ( snd_seq_query_next_client( seq, cinfo ) >= 0 ) {
  1232. client = snd_seq_client_info_get_client( cinfo );
  1233. if ( client == 0 ) continue;
  1234. // Reset query info
  1235. snd_seq_port_info_set_client( pinfo, client );
  1236. snd_seq_port_info_set_port( pinfo, -1 );
  1237. while ( snd_seq_query_next_port( seq, pinfo ) >= 0 ) {
  1238. unsigned int atyp = snd_seq_port_info_get_type( pinfo );
  1239. if ( ( atyp & SND_SEQ_PORT_TYPE_MIDI_GENERIC ) == 0 ) continue;
  1240. unsigned int caps = snd_seq_port_info_get_capability( pinfo );
  1241. if ( ( caps & type ) != type ) continue;
  1242. if ( count == portNumber ) return 1;
  1243. ++count;
  1244. }
  1245. }
  1246. // If a negative portNumber was used, return the port count.
  1247. if ( portNumber < 0 ) return count;
  1248. return 0;
  1249. }
  1250. unsigned int MidiInAlsa :: getPortCount()
  1251. {
  1252. snd_seq_port_info_t *pinfo;
  1253. snd_seq_port_info_alloca( &pinfo );
  1254. AlsaMidiData *data = static_cast<AlsaMidiData *> (apiData_);
  1255. return portInfo( data->seq, pinfo, SND_SEQ_PORT_CAP_READ|SND_SEQ_PORT_CAP_SUBS_READ, -1 );
  1256. }
  1257. std::string MidiInAlsa :: getPortName( unsigned int portNumber )
  1258. {
  1259. snd_seq_client_info_t *cinfo;
  1260. snd_seq_port_info_t *pinfo;
  1261. snd_seq_client_info_alloca( &cinfo );
  1262. snd_seq_port_info_alloca( &pinfo );
  1263. std::string stringName;
  1264. AlsaMidiData *data = static_cast<AlsaMidiData *> (apiData_);
  1265. if ( portInfo( data->seq, pinfo, SND_SEQ_PORT_CAP_READ|SND_SEQ_PORT_CAP_SUBS_READ, (int) portNumber ) ) {
  1266. int cnum = snd_seq_port_info_get_client( pinfo );
  1267. snd_seq_get_any_client_info( data->seq, cnum, cinfo );
  1268. std::ostringstream os;
  1269. os << snd_seq_client_info_get_name( cinfo );
  1270. os << " "; // These lines added to make sure devices are listed
  1271. os << snd_seq_port_info_get_client( pinfo ); // with full portnames added to ensure individual device names
  1272. os << ":";
  1273. os << snd_seq_port_info_get_port( pinfo );
  1274. stringName = os.str();
  1275. return stringName;
  1276. }
  1277. // If we get here, we didn't find a match.
  1278. errorString_ = "MidiInAlsa::getPortName: error looking for port name!";
  1279. error( RtMidiError::WARNING, errorString_ );
  1280. return stringName;
  1281. }
  1282. void MidiInAlsa :: openPort( unsigned int portNumber, const std::string portName )
  1283. {
  1284. if ( connected_ ) {
  1285. errorString_ = "MidiInAlsa::openPort: a valid connection already exists!";
  1286. error( RtMidiError::WARNING, errorString_ );
  1287. return;
  1288. }
  1289. unsigned int nSrc = this->getPortCount();
  1290. if ( nSrc < 1 ) {
  1291. errorString_ = "MidiInAlsa::openPort: no MIDI input sources found!";
  1292. error( RtMidiError::NO_DEVICES_FOUND, errorString_ );
  1293. return;
  1294. }
  1295. snd_seq_port_info_t *pinfo;
  1296. snd_seq_port_info_alloca( &pinfo );
  1297. AlsaMidiData *data = static_cast<AlsaMidiData *> (apiData_);
  1298. if ( portInfo( data->seq, pinfo, SND_SEQ_PORT_CAP_READ|SND_SEQ_PORT_CAP_SUBS_READ, (int) portNumber ) == 0 ) {
  1299. std::ostringstream ost;
  1300. ost << "MidiInAlsa::openPort: the 'portNumber' argument (" << portNumber << ") is invalid.";
  1301. errorString_ = ost.str();
  1302. error( RtMidiError::INVALID_PARAMETER, errorString_ );
  1303. return;
  1304. }
  1305. snd_seq_addr_t sender, receiver;
  1306. sender.client = snd_seq_port_info_get_client( pinfo );
  1307. sender.port = snd_seq_port_info_get_port( pinfo );
  1308. receiver.client = snd_seq_client_id( data->seq );
  1309. if ( data->vport < 0 ) {
  1310. snd_seq_port_info_set_client( pinfo, 0 );
  1311. snd_seq_port_info_set_port( pinfo, 0 );
  1312. snd_seq_port_info_set_capability( pinfo,
  1313. SND_SEQ_PORT_CAP_WRITE |
  1314. SND_SEQ_PORT_CAP_SUBS_WRITE );
  1315. snd_seq_port_info_set_type( pinfo,
  1316. SND_SEQ_PORT_TYPE_MIDI_GENERIC |
  1317. SND_SEQ_PORT_TYPE_APPLICATION );
  1318. snd_seq_port_info_set_midi_channels(pinfo, 16);
  1319. #ifndef AVOID_TIMESTAMPING
  1320. snd_seq_port_info_set_timestamping(pinfo, 1);
  1321. snd_seq_port_info_set_timestamp_real(pinfo, 1);
  1322. snd_seq_port_info_set_timestamp_queue(pinfo, data->queue_id);
  1323. #endif
  1324. snd_seq_port_info_set_name(pinfo, portName.c_str() );
  1325. data->vport = snd_seq_create_port(data->seq, pinfo);
  1326. if ( data->vport < 0 ) {
  1327. errorString_ = "MidiInAlsa::openPort: ALSA error creating input port.";
  1328. error( RtMidiError::DRIVER_ERROR, errorString_ );
  1329. return;
  1330. }
  1331. data->vport = snd_seq_port_info_get_port(pinfo);
  1332. }
  1333. receiver.port = data->vport;
  1334. if ( !data->subscription ) {
  1335. // Make subscription
  1336. if (snd_seq_port_subscribe_malloc( &data->subscription ) < 0) {
  1337. errorString_ = "MidiInAlsa::openPort: ALSA error allocation port subscription.";
  1338. error( RtMidiError::DRIVER_ERROR, errorString_ );
  1339. return;
  1340. }
  1341. snd_seq_port_subscribe_set_sender(data->subscription, &sender);
  1342. snd_seq_port_subscribe_set_dest(data->subscription, &receiver);
  1343. if ( snd_seq_subscribe_port(data->seq, data->subscription) ) {
  1344. snd_seq_port_subscribe_free( data->subscription );
  1345. data->subscription = 0;
  1346. errorString_ = "MidiInAlsa::openPort: ALSA error making port connection.";
  1347. error( RtMidiError::DRIVER_ERROR, errorString_ );
  1348. return;
  1349. }
  1350. }
  1351. if ( inputData_.doInput == false ) {
  1352. // Start the input queue
  1353. #ifndef AVOID_TIMESTAMPING
  1354. snd_seq_start_queue( data->seq, data->queue_id, NULL );
  1355. snd_seq_drain_output( data->seq );
  1356. #endif
  1357. // Start our MIDI input thread.
  1358. pthread_attr_t attr;
  1359. pthread_attr_init(&attr);
  1360. pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
  1361. pthread_attr_setschedpolicy(&attr, SCHED_OTHER);
  1362. inputData_.doInput = true;
  1363. int err = pthread_create(&data->thread, &attr, alsaMidiHandler, &inputData_);
  1364. pthread_attr_destroy(&attr);
  1365. if ( err ) {
  1366. snd_seq_unsubscribe_port( data->seq, data->subscription );
  1367. snd_seq_port_subscribe_free( data->subscription );
  1368. data->subscription = 0;
  1369. inputData_.doInput = false;
  1370. errorString_ = "MidiInAlsa::openPort: error starting MIDI input thread!";
  1371. error( RtMidiError::THREAD_ERROR, errorString_ );
  1372. return;
  1373. }
  1374. }
  1375. connected_ = true;
  1376. }
  1377. void MidiInAlsa :: openVirtualPort( std::string portName )
  1378. {
  1379. AlsaMidiData *data = static_cast<AlsaMidiData *> (apiData_);
  1380. if ( data->vport < 0 ) {
  1381. snd_seq_port_info_t *pinfo;
  1382. snd_seq_port_info_alloca( &pinfo );
  1383. snd_seq_port_info_set_capability( pinfo,
  1384. SND_SEQ_PORT_CAP_WRITE |
  1385. SND_SEQ_PORT_CAP_SUBS_WRITE );
  1386. snd_seq_port_info_set_type( pinfo,
  1387. SND_SEQ_PORT_TYPE_MIDI_GENERIC |
  1388. SND_SEQ_PORT_TYPE_APPLICATION );
  1389. snd_seq_port_info_set_midi_channels(pinfo, 16);
  1390. #ifndef AVOID_TIMESTAMPING
  1391. snd_seq_port_info_set_timestamping(pinfo, 1);
  1392. snd_seq_port_info_set_timestamp_real(pinfo, 1);
  1393. snd_seq_port_info_set_timestamp_queue(pinfo, data->queue_id);
  1394. #endif
  1395. snd_seq_port_info_set_name(pinfo, portName.c_str());
  1396. data->vport = snd_seq_create_port(data->seq, pinfo);
  1397. if ( data->vport < 0 ) {
  1398. errorString_ = "MidiInAlsa::openVirtualPort: ALSA error creating virtual port.";
  1399. error( RtMidiError::DRIVER_ERROR, errorString_ );
  1400. return;
  1401. }
  1402. }
  1403. if ( inputData_.doInput == false ) {
  1404. // Wait for old thread to stop, if still running
  1405. if ( !pthread_equal(data->thread, data->dummy_thread_id) )
  1406. pthread_join( data->thread, NULL );
  1407. // Start the input queue
  1408. #ifndef AVOID_TIMESTAMPING
  1409. snd_seq_start_queue( data->seq, data->queue_id, NULL );
  1410. snd_seq_drain_output( data->seq );
  1411. #endif
  1412. // Start our MIDI input thread.
  1413. pthread_attr_t attr;
  1414. pthread_attr_init(&attr);
  1415. pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
  1416. pthread_attr_setschedpolicy(&attr, SCHED_OTHER);
  1417. inputData_.doInput = true;
  1418. int err = pthread_create(&data->thread, &attr, alsaMidiHandler, &inputData_);
  1419. pthread_attr_destroy(&attr);
  1420. if ( err ) {
  1421. if ( data->subscription ) {
  1422. snd_seq_unsubscribe_port( data->seq, data->subscription );
  1423. snd_seq_port_subscribe_free( data->subscription );
  1424. data->subscription = 0;
  1425. }
  1426. inputData_.doInput = false;
  1427. errorString_ = "MidiInAlsa::openPort: error starting MIDI input thread!";
  1428. error( RtMidiError::THREAD_ERROR, errorString_ );
  1429. return;
  1430. }
  1431. }
  1432. }
  1433. void MidiInAlsa :: closePort( void )
  1434. {
  1435. AlsaMidiData *data = static_cast<AlsaMidiData *> (apiData_);
  1436. if ( connected_ ) {
  1437. if ( data->subscription ) {
  1438. snd_seq_unsubscribe_port( data->seq, data->subscription );
  1439. snd_seq_port_subscribe_free( data->subscription );
  1440. data->subscription = 0;
  1441. }
  1442. // Stop the input queue
  1443. #ifndef AVOID_TIMESTAMPING
  1444. snd_seq_stop_queue( data->seq, data->queue_id, NULL );
  1445. snd_seq_drain_output( data->seq );
  1446. #endif
  1447. connected_ = false;
  1448. }
  1449. // Stop thread to avoid triggering the callback, while the port is intended to be closed
  1450. if ( inputData_.doInput ) {
  1451. inputData_.doInput = false;
  1452. int res = write( data->trigger_fds[1], &inputData_.doInput, sizeof(inputData_.doInput) );
  1453. (void) res;
  1454. if ( !pthread_equal(data->thread, data->dummy_thread_id) )
  1455. pthread_join( data->thread, NULL );
  1456. }
  1457. }
  1458. //*********************************************************************//
  1459. // API: LINUX ALSA
  1460. // Class Definitions: MidiOutAlsa
  1461. //*********************************************************************//
  1462. MidiOutAlsa :: MidiOutAlsa( const std::string clientName ) : MidiOutApi()
  1463. {
  1464. initialize( clientName );
  1465. }
  1466. MidiOutAlsa :: ~MidiOutAlsa()
  1467. {
  1468. // Close a connection if it exists.
  1469. closePort();
  1470. // Cleanup.
  1471. AlsaMidiData *data = static_cast<AlsaMidiData *> (apiData_);
  1472. if ( data->vport >= 0 ) snd_seq_delete_port( data->seq, data->vport );
  1473. if ( data->coder ) snd_midi_event_free( data->coder );
  1474. if ( data->buffer ) free( data->buffer );
  1475. snd_seq_close( data->seq );
  1476. delete data;
  1477. }
  1478. void MidiOutAlsa :: initialize( const std::string& clientName )
  1479. {
  1480. // Set up the ALSA sequencer client.
  1481. snd_seq_t *seq;
  1482. int result1 = snd_seq_open( &seq, "default", SND_SEQ_OPEN_OUTPUT, SND_SEQ_NONBLOCK );
  1483. if ( result1 < 0 ) {
  1484. errorString_ = "MidiOutAlsa::initialize: error creating ALSA sequencer client object.";
  1485. error( RtMidiError::DRIVER_ERROR, errorString_ );
  1486. return;
  1487. }
  1488. // Set client name.
  1489. snd_seq_set_client_name( seq, clientName.c_str() );
  1490. // Save our api-specific connection information.
  1491. AlsaMidiData *data = (AlsaMidiData *) new AlsaMidiData;
  1492. data->seq = seq;
  1493. data->portNum = -1;
  1494. data->vport = -1;
  1495. data->bufferSize = 32;
  1496. data->coder = 0;
  1497. data->buffer = 0;
  1498. int result = snd_midi_event_new( data->bufferSize, &data->coder );
  1499. if ( result < 0 ) {
  1500. delete data;
  1501. errorString_ = "MidiOutAlsa::initialize: error initializing MIDI event parser!\n\n";
  1502. error( RtMidiError::DRIVER_ERROR, errorString_ );
  1503. return;
  1504. }
  1505. data->buffer = (unsigned char *) malloc( data->bufferSize );
  1506. if ( data->buffer == NULL ) {
  1507. delete data;
  1508. errorString_ = "MidiOutAlsa::initialize: error allocating buffer memory!\n\n";
  1509. error( RtMidiError::MEMORY_ERROR, errorString_ );
  1510. return;
  1511. }
  1512. snd_midi_event_init( data->coder );
  1513. apiData_ = (void *) data;
  1514. }
  1515. unsigned int MidiOutAlsa :: getPortCount()
  1516. {
  1517. snd_seq_port_info_t *pinfo;
  1518. snd_seq_port_info_alloca( &pinfo );
  1519. AlsaMidiData *data = static_cast<AlsaMidiData *> (apiData_);
  1520. return portInfo( data->seq, pinfo, SND_SEQ_PORT_CAP_WRITE|SND_SEQ_PORT_CAP_SUBS_WRITE, -1 );
  1521. }
  1522. std::string MidiOutAlsa :: getPortName( unsigned int portNumber )
  1523. {
  1524. snd_seq_client_info_t *cinfo;
  1525. snd_seq_port_info_t *pinfo;
  1526. snd_seq_client_info_alloca( &cinfo );
  1527. snd_seq_port_info_alloca( &pinfo );
  1528. std::string stringName;
  1529. AlsaMidiData *data = static_cast<AlsaMidiData *> (apiData_);
  1530. if ( portInfo( data->seq, pinfo, SND_SEQ_PORT_CAP_WRITE|SND_SEQ_PORT_CAP_SUBS_WRITE, (int) portNumber ) ) {
  1531. int cnum = snd_seq_port_info_get_client(pinfo);
  1532. snd_seq_get_any_client_info( data->seq, cnum, cinfo );
  1533. std::ostringstream os;
  1534. os << snd_seq_client_info_get_name(cinfo);
  1535. os << " "; // These lines added to make sure devices are listed
  1536. os << snd_seq_port_info_get_client( pinfo ); // with full portnames added to ensure individual device names
  1537. os << ":";
  1538. os << snd_seq_port_info_get_port(pinfo);
  1539. stringName = os.str();
  1540. return stringName;
  1541. }
  1542. // If we get here, we didn't find a match.
  1543. errorString_ = "MidiOutAlsa::getPortName: error looking for port name!";
  1544. error( RtMidiError::WARNING, errorString_ );
  1545. return stringName;
  1546. }
  1547. void MidiOutAlsa :: openPort( unsigned int portNumber, const std::string portName )
  1548. {
  1549. if ( connected_ ) {
  1550. errorString_ = "MidiOutAlsa::openPort: a valid connection already exists!";
  1551. error( RtMidiError::WARNING, errorString_ );
  1552. return;
  1553. }
  1554. unsigned int nSrc = this->getPortCount();
  1555. if (nSrc < 1) {
  1556. errorString_ = "MidiOutAlsa::openPort: no MIDI output sources found!";
  1557. error( RtMidiError::NO_DEVICES_FOUND, errorString_ );
  1558. return;
  1559. }
  1560. snd_seq_port_info_t *pinfo;
  1561. snd_seq_port_info_alloca( &pinfo );
  1562. AlsaMidiData *data = static_cast<AlsaMidiData *> (apiData_);
  1563. if ( portInfo( data->seq, pinfo, SND_SEQ_PORT_CAP_WRITE|SND_SEQ_PORT_CAP_SUBS_WRITE, (int) portNumber ) == 0 ) {
  1564. std::ostringstream ost;
  1565. ost << "MidiOutAlsa::openPort: the 'portNumber' argument (" << portNumber << ") is invalid.";
  1566. errorString_ = ost.str();
  1567. error( RtMidiError::INVALID_PARAMETER, errorString_ );
  1568. return;
  1569. }
  1570. snd_seq_addr_t sender, receiver;
  1571. receiver.client = snd_seq_port_info_get_client( pinfo );
  1572. receiver.port = snd_seq_port_info_get_port( pinfo );
  1573. sender.client = snd_seq_client_id( data->seq );
  1574. if ( data->vport < 0 ) {
  1575. data->vport = snd_seq_create_simple_port( data->seq, portName.c_str(),
  1576. SND_SEQ_PORT_CAP_READ|SND_SEQ_PORT_CAP_SUBS_READ,
  1577. SND_SEQ_PORT_TYPE_MIDI_GENERIC|SND_SEQ_PORT_TYPE_APPLICATION );
  1578. if ( data->vport < 0 ) {
  1579. errorString_ = "MidiOutAlsa::openPort: ALSA error creating output port.";
  1580. error( RtMidiError::DRIVER_ERROR, errorString_ );
  1581. return;
  1582. }
  1583. }
  1584. sender.port = data->vport;
  1585. // Make subscription
  1586. if (snd_seq_port_subscribe_malloc( &data->subscription ) < 0) {
  1587. snd_seq_port_subscribe_free( data->subscription );
  1588. errorString_ = "MidiOutAlsa::openPort: error allocating port subscription.";
  1589. error( RtMidiError::DRIVER_ERROR, errorString_ );
  1590. return;
  1591. }
  1592. snd_seq_port_subscribe_set_sender(data->subscription, &sender);
  1593. snd_seq_port_subscribe_set_dest(data->subscription, &receiver);
  1594. snd_seq_port_subscribe_set_time_update(data->subscription, 1);
  1595. snd_seq_port_subscribe_set_time_real(data->subscription, 1);
  1596. if ( snd_seq_subscribe_port(data->seq, data->subscription) ) {
  1597. snd_seq_port_subscribe_free( data->subscription );
  1598. errorString_ = "MidiOutAlsa::openPort: ALSA error making port connection.";
  1599. error( RtMidiError::DRIVER_ERROR, errorString_ );
  1600. return;
  1601. }
  1602. connected_ = true;
  1603. }
  1604. void MidiOutAlsa :: closePort( void )
  1605. {
  1606. if ( connected_ ) {
  1607. AlsaMidiData *data = static_cast<AlsaMidiData *> (apiData_);
  1608. snd_seq_unsubscribe_port( data->seq, data->subscription );
  1609. snd_seq_port_subscribe_free( data->subscription );
  1610. connected_ = false;
  1611. }
  1612. }
  1613. void MidiOutAlsa :: openVirtualPort( std::string portName )
  1614. {
  1615. AlsaMidiData *data = static_cast<AlsaMidiData *> (apiData_);
  1616. if ( data->vport < 0 ) {
  1617. data->vport = snd_seq_create_simple_port( data->seq, portName.c_str(),
  1618. SND_SEQ_PORT_CAP_READ|SND_SEQ_PORT_CAP_SUBS_READ,
  1619. SND_SEQ_PORT_TYPE_MIDI_GENERIC|SND_SEQ_PORT_TYPE_APPLICATION );
  1620. if ( data->vport < 0 ) {
  1621. errorString_ = "MidiOutAlsa::openVirtualPort: ALSA error creating virtual port.";
  1622. error( RtMidiError::DRIVER_ERROR, errorString_ );
  1623. }
  1624. }
  1625. }
  1626. void MidiOutAlsa :: sendMessage( std::vector<unsigned char> *message )
  1627. {
  1628. int result;
  1629. AlsaMidiData *data = static_cast<AlsaMidiData *> (apiData_);
  1630. unsigned int nBytes = message->size();
  1631. if ( nBytes > data->bufferSize ) {
  1632. data->bufferSize = nBytes;
  1633. result = snd_midi_event_resize_buffer ( data->coder, nBytes);
  1634. if ( result != 0 ) {
  1635. errorString_ = "MidiOutAlsa::sendMessage: ALSA error resizing MIDI event buffer.";
  1636. error( RtMidiError::DRIVER_ERROR, errorString_ );
  1637. return;
  1638. }
  1639. free (data->buffer);
  1640. data->buffer = (unsigned char *) malloc( data->bufferSize );
  1641. if ( data->buffer == NULL ) {
  1642. errorString_ = "MidiOutAlsa::initialize: error allocating buffer memory!\n\n";
  1643. error( RtMidiError::MEMORY_ERROR, errorString_ );
  1644. return;
  1645. }
  1646. }
  1647. snd_seq_event_t ev;
  1648. snd_seq_ev_clear(&ev);
  1649. snd_seq_ev_set_source(&ev, data->vport);
  1650. snd_seq_ev_set_subs(&ev);
  1651. snd_seq_ev_set_direct(&ev);
  1652. for ( unsigned int i=0; i<nBytes; ++i ) data->buffer[i] = message->at(i);
  1653. result = snd_midi_event_encode( data->coder, data->buffer, (long)nBytes, &ev );
  1654. if ( result < (int)nBytes ) {
  1655. errorString_ = "MidiOutAlsa::sendMessage: event parsing error!";
  1656. error( RtMidiError::WARNING, errorString_ );
  1657. return;
  1658. }
  1659. // Send the event.
  1660. result = snd_seq_event_output(data->seq, &ev);
  1661. if ( result < 0 ) {
  1662. errorString_ = "MidiOutAlsa::sendMessage: error sending MIDI message to port.";
  1663. error( RtMidiError::WARNING, errorString_ );
  1664. return;
  1665. }
  1666. snd_seq_drain_output(data->seq);
  1667. }
  1668. #endif // __LINUX_ALSA__
  1669. //*********************************************************************//
  1670. // API: Windows Multimedia Library (MM)
  1671. //*********************************************************************//
  1672. // API information deciphered from:
  1673. // - http://msdn.microsoft.com/library/default.asp?url=/library/en-us/multimed/htm/_win32_midi_reference.asp
  1674. // Thanks to Jean-Baptiste Berruchon for the sysex code.
  1675. #if defined(__WINDOWS_MM__)
  1676. // The Windows MM API is based on the use of a callback function for
  1677. // MIDI input. We convert the system specific time stamps to delta
  1678. // time values.
  1679. // Windows MM MIDI header files.
  1680. #include <windows.h>
  1681. #include <mmsystem.h>
  1682. #define RT_SYSEX_BUFFER_SIZE 1024
  1683. #define RT_SYSEX_BUFFER_COUNT 4
  1684. // A structure to hold variables related to the CoreMIDI API
  1685. // implementation.
  1686. struct WinMidiData {
  1687. HMIDIIN inHandle; // Handle to Midi Input Device
  1688. HMIDIOUT outHandle; // Handle to Midi Output Device
  1689. DWORD lastTime;
  1690. MidiInApi::MidiMessage message;
  1691. LPMIDIHDR sysexBuffer[RT_SYSEX_BUFFER_COUNT];
  1692. CRITICAL_SECTION _mutex; // [Patrice] see https://groups.google.com/forum/#!topic/mididev/6OUjHutMpEo
  1693. };
  1694. //*********************************************************************//
  1695. // API: Windows MM
  1696. // Class Definitions: MidiInWinMM
  1697. //*********************************************************************//
  1698. static void CALLBACK midiInputCallback( HMIDIIN /*hmin*/,
  1699. UINT inputStatus,
  1700. DWORD_PTR instancePtr,
  1701. DWORD_PTR midiMessage,
  1702. DWORD timestamp )
  1703. {
  1704. if ( inputStatus != MIM_DATA && inputStatus != MIM_LONGDATA && inputStatus != MIM_LONGERROR ) return;
  1705. //MidiInApi::RtMidiInData *data = static_cast<MidiInApi::RtMidiInData *> (instancePtr);
  1706. MidiInApi::RtMidiInData *data = (MidiInApi::RtMidiInData *)instancePtr;
  1707. WinMidiData *apiData = static_cast<WinMidiData *> (data->apiData);
  1708. // Calculate time stamp.
  1709. if ( data->firstMessage == true ) {
  1710. apiData->message.timeStamp = 0.0;
  1711. data->firstMessage = false;
  1712. }
  1713. else apiData->message.timeStamp = (double) ( timestamp - apiData->lastTime ) * 0.001;
  1714. apiData->lastTime = timestamp;
  1715. if ( inputStatus == MIM_DATA ) { // Channel or system message
  1716. // Make sure the first byte is a status byte.
  1717. unsigned char status = (unsigned char) (midiMessage & 0x000000FF);
  1718. if ( !(status & 0x80) ) return;
  1719. // Determine the number of bytes in the MIDI message.
  1720. unsigned short nBytes = 1;
  1721. if ( status < 0xC0 ) nBytes = 3;
  1722. else if ( status < 0xE0 ) nBytes = 2;
  1723. else if ( status < 0xF0 ) nBytes = 3;
  1724. else if ( status == 0xF1 ) {
  1725. if ( data->ignoreFlags & 0x02 ) return;
  1726. else nBytes = 2;
  1727. }
  1728. else if ( status == 0xF2 ) nBytes = 3;
  1729. else if ( status == 0xF3 ) nBytes = 2;
  1730. else if ( status == 0xF8 && (data->ignoreFlags & 0x02) ) {
  1731. // A MIDI timing tick message and we're ignoring it.
  1732. return;
  1733. }
  1734. else if ( status == 0xFE && (data->ignoreFlags & 0x04) ) {
  1735. // A MIDI active sensing message and we're ignoring it.
  1736. return;
  1737. }
  1738. // Copy bytes to our MIDI message.
  1739. unsigned char *ptr = (unsigned char *) &midiMessage;
  1740. for ( int i=0; i<nBytes; ++i ) apiData->message.bytes.push_back( *ptr++ );
  1741. }
  1742. else { // Sysex message ( MIM_LONGDATA or MIM_LONGERROR )
  1743. MIDIHDR *sysex = ( MIDIHDR *) midiMessage;
  1744. if ( !( data->ignoreFlags & 0x01 ) && inputStatus != MIM_LONGERROR ) {
  1745. // Sysex message and we're not ignoring it
  1746. for ( int i=0; i<(int)sysex->dwBytesRecorded; ++i )
  1747. apiData->message.bytes.push_back( sysex->lpData[i] );
  1748. }
  1749. // The WinMM API requires that the sysex buffer be requeued after
  1750. // input of each sysex message. Even if we are ignoring sysex
  1751. // messages, we still need to requeue the buffer in case the user
  1752. // decides to not ignore sysex messages in the future. However,
  1753. // it seems that WinMM calls this function with an empty sysex
  1754. // buffer when an application closes and in this case, we should
  1755. // avoid requeueing it, else the computer suddenly reboots after
  1756. // one or two minutes.
  1757. if ( apiData->sysexBuffer[sysex->dwUser]->dwBytesRecorded > 0 ) {
  1758. //if ( sysex->dwBytesRecorded > 0 ) {
  1759. EnterCriticalSection( &apiData->_mutex );
  1760. MMRESULT result = midiInAddBuffer( apiData->inHandle, apiData->sysexBuffer[sysex->dwUser], sizeof(MIDIHDR) );
  1761. LeaveCriticalSection( &apiData->_mutex );
  1762. if ( result != MMSYSERR_NOERROR )
  1763. std::cerr << "\nRtMidiIn::midiInputCallback: error sending sysex to Midi device!!\n\n";
  1764. if ( data->ignoreFlags & 0x01 ) return;
  1765. }
  1766. else return;
  1767. }
  1768. if ( data->usingCallback ) {
  1769. RtMidiIn::RtMidiCallback callback = (RtMidiIn::RtMidiCallback) data->userCallback;
  1770. callback( apiData->message.timeStamp, &apiData->message.bytes, data->userData );
  1771. }
  1772. else {
  1773. // As long as we haven't reached our queue size limit, push the message.
  1774. if ( data->queue.size < data->queue.ringSize ) {
  1775. data->queue.ring[data->queue.back++] = apiData->message;
  1776. if ( data->queue.back == data->queue.ringSize )
  1777. data->queue.back = 0;
  1778. data->queue.size++;
  1779. }
  1780. else
  1781. std::cerr << "\nRtMidiIn: message queue limit reached!!\n\n";
  1782. }
  1783. // Clear the vector for the next input message.
  1784. apiData->message.bytes.clear();
  1785. }
  1786. MidiInWinMM :: MidiInWinMM( const std::string clientName, unsigned int queueSizeLimit ) : MidiInApi( queueSizeLimit )
  1787. {
  1788. initialize( clientName );
  1789. }
  1790. MidiInWinMM :: ~MidiInWinMM()
  1791. {
  1792. WinMidiData *data = static_cast<WinMidiData *> (apiData_);
  1793. DeleteCriticalSection( &(data->_mutex) );
  1794. // Close a connection if it exists.
  1795. closePort();
  1796. // Cleanup.
  1797. delete data;
  1798. }
  1799. void MidiInWinMM :: initialize( const std::string& /*clientName*/ )
  1800. {
  1801. // We'll issue a warning here if no devices are available but not
  1802. // throw an error since the user can plugin something later.
  1803. unsigned int nDevices = midiInGetNumDevs();
  1804. if ( nDevices == 0 ) {
  1805. errorString_ = "MidiInWinMM::initialize: no MIDI input devices currently available.";
  1806. error( RtMidiError::WARNING, errorString_ );
  1807. }
  1808. // Save our api-specific connection information.
  1809. WinMidiData *data = (WinMidiData *) new WinMidiData;
  1810. apiData_ = (void *) data;
  1811. inputData_.apiData = (void *) data;
  1812. data->message.bytes.clear(); // needs to be empty for first input message
  1813. if ( !InitializeCriticalSectionAndSpinCount(&(data->_mutex), 0x00000400) ) {
  1814. errorString_ = "MidiInWinMM::initialize: InitializeCriticalSectionAndSpinCount failed.";
  1815. error( RtError::WARNING, errorString_ );
  1816. }
  1817. }
  1818. void MidiInWinMM :: openPort( unsigned int portNumber, const std::string /*portName*/ )
  1819. {
  1820. if ( connected_ ) {
  1821. errorString_ = "MidiInWinMM::openPort: a valid connection already exists!";
  1822. error( RtMidiError::WARNING, errorString_ );
  1823. return;
  1824. }
  1825. unsigned int nDevices = midiInGetNumDevs();
  1826. if (nDevices == 0) {
  1827. errorString_ = "MidiInWinMM::openPort: no MIDI input sources found!";
  1828. error( RtMidiError::NO_DEVICES_FOUND, errorString_ );
  1829. return;
  1830. }
  1831. if ( portNumber >= nDevices ) {
  1832. std::ostringstream ost;
  1833. ost << "MidiInWinMM::openPort: the 'portNumber' argument (" << portNumber << ") is invalid.";
  1834. errorString_ = ost.str();
  1835. error( RtMidiError::INVALID_PARAMETER, errorString_ );
  1836. return;
  1837. }
  1838. WinMidiData *data = static_cast<WinMidiData *> (apiData_);
  1839. MMRESULT result = midiInOpen( &data->inHandle,
  1840. portNumber,
  1841. (DWORD_PTR)&midiInputCallback,
  1842. (DWORD_PTR)&inputData_,
  1843. CALLBACK_FUNCTION );
  1844. if ( result != MMSYSERR_NOERROR ) {
  1845. errorString_ = "MidiInWinMM::openPort: error creating Windows MM MIDI input port.";
  1846. error( RtMidiError::DRIVER_ERROR, errorString_ );
  1847. return;
  1848. }
  1849. // Allocate and init the sysex buffers.
  1850. for ( int i=0; i<RT_SYSEX_BUFFER_COUNT; ++i ) {
  1851. data->sysexBuffer[i] = (MIDIHDR*) new char[ sizeof(MIDIHDR) ];
  1852. data->sysexBuffer[i]->lpData = new char[ RT_SYSEX_BUFFER_SIZE ];
  1853. data->sysexBuffer[i]->dwBufferLength = RT_SYSEX_BUFFER_SIZE;
  1854. data->sysexBuffer[i]->dwUser = i; // We use the dwUser parameter as buffer indicator
  1855. data->sysexBuffer[i]->dwFlags = 0;
  1856. result = midiInPrepareHeader( data->inHandle, data->sysexBuffer[i], sizeof(MIDIHDR) );
  1857. if ( result != MMSYSERR_NOERROR ) {
  1858. midiInClose( data->inHandle );
  1859. errorString_ = "MidiInWinMM::openPort: error starting Windows MM MIDI input port (PrepareHeader).";
  1860. error( RtMidiError::DRIVER_ERROR, errorString_ );
  1861. return;
  1862. }
  1863. // Register the buffer.
  1864. result = midiInAddBuffer( data->inHandle, data->sysexBuffer[i], sizeof(MIDIHDR) );
  1865. if ( result != MMSYSERR_NOERROR ) {
  1866. midiInClose( data->inHandle );
  1867. errorString_ = "MidiInWinMM::openPort: error starting Windows MM MIDI input port (AddBuffer).";
  1868. error( RtMidiError::DRIVER_ERROR, errorString_ );
  1869. return;
  1870. }
  1871. }
  1872. result = midiInStart( data->inHandle );
  1873. if ( result != MMSYSERR_NOERROR ) {
  1874. midiInClose( data->inHandle );
  1875. errorString_ = "MidiInWinMM::openPort: error starting Windows MM MIDI input port.";
  1876. error( RtMidiError::DRIVER_ERROR, errorString_ );
  1877. return;
  1878. }
  1879. connected_ = true;
  1880. }
  1881. void MidiInWinMM :: openVirtualPort( std::string portName )
  1882. {
  1883. // This function cannot be implemented for the Windows MM MIDI API.
  1884. errorString_ = "MidiInWinMM::openVirtualPort: cannot be implemented in Windows MM MIDI API!";
  1885. error( RtMidiError::WARNING, errorString_ );
  1886. }
  1887. void MidiInWinMM :: closePort( void )
  1888. {
  1889. if ( connected_ ) {
  1890. WinMidiData *data = static_cast<WinMidiData *> (apiData_);
  1891. EnterCriticalSection( &data->_mutex );
  1892. midiInReset( data->inHandle );
  1893. midiInStop( data->inHandle );
  1894. for ( int i=0; i<RT_SYSEX_BUFFER_COUNT; ++i ) {
  1895. int result = midiInUnprepareHeader(data->inHandle, data->sysexBuffer[i], sizeof(MIDIHDR));
  1896. delete [] data->sysexBuffer[i]->lpData;
  1897. delete [] data->sysexBuffer[i];
  1898. if ( result != MMSYSERR_NOERROR ) {
  1899. midiInClose( data->inHandle );
  1900. errorString_ = "MidiInWinMM::openPort: error closing Windows MM MIDI input port (midiInUnprepareHeader).";
  1901. error( RtMidiError::DRIVER_ERROR, errorString_ );
  1902. return;
  1903. }
  1904. }
  1905. midiInClose( data->inHandle );
  1906. connected_ = false;
  1907. LeaveCriticalSection( &data->_mutex );
  1908. }
  1909. }
  1910. unsigned int MidiInWinMM :: getPortCount()
  1911. {
  1912. return midiInGetNumDevs();
  1913. }
  1914. std::string MidiInWinMM :: getPortName( unsigned int portNumber )
  1915. {
  1916. std::string stringName;
  1917. unsigned int nDevices = midiInGetNumDevs();
  1918. if ( portNumber >= nDevices ) {
  1919. std::ostringstream ost;
  1920. ost << "MidiInWinMM::getPortName: the 'portNumber' argument (" << portNumber << ") is invalid.";
  1921. errorString_ = ost.str();
  1922. error( RtMidiError::WARNING, errorString_ );
  1923. return stringName;
  1924. }
  1925. MIDIINCAPS deviceCaps;
  1926. midiInGetDevCaps( portNumber, &deviceCaps, sizeof(MIDIINCAPS));
  1927. #if defined( UNICODE ) || defined( _UNICODE )
  1928. int length = WideCharToMultiByte(CP_UTF8, 0, deviceCaps.szPname, -1, NULL, 0, NULL, NULL) - 1;
  1929. stringName.assign( length, 0 );
  1930. length = WideCharToMultiByte(CP_UTF8, 0, deviceCaps.szPname, static_cast<int>(wcslen(deviceCaps.szPname)), &stringName[0], length, NULL, NULL);
  1931. #else
  1932. stringName = std::string( deviceCaps.szPname );
  1933. #endif
  1934. // Next lines added to add the portNumber to the name so that
  1935. // the device's names are sure to be listed with individual names
  1936. // even when they have the same brand name
  1937. std::ostringstream os;
  1938. os << " ";
  1939. os << portNumber;
  1940. stringName += os.str();
  1941. return stringName;
  1942. }
  1943. //*********************************************************************//
  1944. // API: Windows MM
  1945. // Class Definitions: MidiOutWinMM
  1946. //*********************************************************************//
  1947. MidiOutWinMM :: MidiOutWinMM( const std::string clientName ) : MidiOutApi()
  1948. {
  1949. initialize( clientName );
  1950. }
  1951. MidiOutWinMM :: ~MidiOutWinMM()
  1952. {
  1953. // Close a connection if it exists.
  1954. closePort();
  1955. // Cleanup.
  1956. WinMidiData *data = static_cast<WinMidiData *> (apiData_);
  1957. delete data;
  1958. }
  1959. void MidiOutWinMM :: initialize( const std::string& /*clientName*/ )
  1960. {
  1961. // We'll issue a warning here if no devices are available but not
  1962. // throw an error since the user can plug something in later.
  1963. unsigned int nDevices = midiOutGetNumDevs();
  1964. if ( nDevices == 0 ) {
  1965. errorString_ = "MidiOutWinMM::initialize: no MIDI output devices currently available.";
  1966. error( RtMidiError::WARNING, errorString_ );
  1967. }
  1968. // Save our api-specific connection information.
  1969. WinMidiData *data = (WinMidiData *) new WinMidiData;
  1970. apiData_ = (void *) data;
  1971. }
  1972. unsigned int MidiOutWinMM :: getPortCount()
  1973. {
  1974. return midiOutGetNumDevs();
  1975. }
  1976. std::string MidiOutWinMM :: getPortName( unsigned int portNumber )
  1977. {
  1978. std::string stringName;
  1979. unsigned int nDevices = midiOutGetNumDevs();
  1980. if ( portNumber >= nDevices ) {
  1981. std::ostringstream ost;
  1982. ost << "MidiOutWinMM::getPortName: the 'portNumber' argument (" << portNumber << ") is invalid.";
  1983. errorString_ = ost.str();
  1984. error( RtMidiError::WARNING, errorString_ );
  1985. return stringName;
  1986. }
  1987. MIDIOUTCAPS deviceCaps;
  1988. midiOutGetDevCaps( portNumber, &deviceCaps, sizeof(MIDIOUTCAPS));
  1989. #if defined( UNICODE ) || defined( _UNICODE )
  1990. int length = WideCharToMultiByte(CP_UTF8, 0, deviceCaps.szPname, -1, NULL, 0, NULL, NULL) - 1;
  1991. stringName.assign( length, 0 );
  1992. length = WideCharToMultiByte(CP_UTF8, 0, deviceCaps.szPname, static_cast<int>(wcslen(deviceCaps.szPname)), &stringName[0], length, NULL, NULL);
  1993. #else
  1994. stringName = std::string( deviceCaps.szPname );
  1995. #endif
  1996. return stringName;
  1997. }
  1998. void MidiOutWinMM :: openPort( unsigned int portNumber, const std::string /*portName*/ )
  1999. {
  2000. if ( connected_ ) {
  2001. errorString_ = "MidiOutWinMM::openPort: a valid connection already exists!";
  2002. error( RtMidiError::WARNING, errorString_ );
  2003. return;
  2004. }
  2005. unsigned int nDevices = midiOutGetNumDevs();
  2006. if (nDevices < 1) {
  2007. errorString_ = "MidiOutWinMM::openPort: no MIDI output destinations found!";
  2008. error( RtMidiError::NO_DEVICES_FOUND, errorString_ );
  2009. return;
  2010. }
  2011. if ( portNumber >= nDevices ) {
  2012. std::ostringstream ost;
  2013. ost << "MidiOutWinMM::openPort: the 'portNumber' argument (" << portNumber << ") is invalid.";
  2014. errorString_ = ost.str();
  2015. error( RtMidiError::INVALID_PARAMETER, errorString_ );
  2016. return;
  2017. }
  2018. WinMidiData *data = static_cast<WinMidiData *> (apiData_);
  2019. MMRESULT result = midiOutOpen( &data->outHandle,
  2020. portNumber,
  2021. (DWORD)NULL,
  2022. (DWORD)NULL,
  2023. CALLBACK_NULL );
  2024. if ( result != MMSYSERR_NOERROR ) {
  2025. errorString_ = "MidiOutWinMM::openPort: error creating Windows MM MIDI output port.";
  2026. error( RtMidiError::DRIVER_ERROR, errorString_ );
  2027. return;
  2028. }
  2029. connected_ = true;
  2030. }
  2031. void MidiOutWinMM :: closePort( void )
  2032. {
  2033. if ( connected_ ) {
  2034. WinMidiData *data = static_cast<WinMidiData *> (apiData_);
  2035. midiOutReset( data->outHandle );
  2036. midiOutClose( data->outHandle );
  2037. connected_ = false;
  2038. }
  2039. }
  2040. void MidiOutWinMM :: openVirtualPort( std::string portName )
  2041. {
  2042. // This function cannot be implemented for the Windows MM MIDI API.
  2043. errorString_ = "MidiOutWinMM::openVirtualPort: cannot be implemented in Windows MM MIDI API!";
  2044. error( RtMidiError::WARNING, errorString_ );
  2045. }
  2046. void MidiOutWinMM :: sendMessage( std::vector<unsigned char> *message )
  2047. {
  2048. if ( !connected_ ) return;
  2049. unsigned int nBytes = static_cast<unsigned int>(message->size());
  2050. if ( nBytes == 0 ) {
  2051. errorString_ = "MidiOutWinMM::sendMessage: message argument is empty!";
  2052. error( RtMidiError::WARNING, errorString_ );
  2053. return;
  2054. }
  2055. MMRESULT result;
  2056. WinMidiData *data = static_cast<WinMidiData *> (apiData_);
  2057. if ( message->at(0) == 0xF0 ) { // Sysex message
  2058. // Allocate buffer for sysex data.
  2059. char *buffer = (char *) malloc( nBytes );
  2060. if ( buffer == NULL ) {
  2061. errorString_ = "MidiOutWinMM::sendMessage: error allocating sysex message memory!";
  2062. error( RtMidiError::MEMORY_ERROR, errorString_ );
  2063. return;
  2064. }
  2065. // Copy data to buffer.
  2066. for ( unsigned int i=0; i<nBytes; ++i ) buffer[i] = message->at(i);
  2067. // Create and prepare MIDIHDR structure.
  2068. MIDIHDR sysex;
  2069. sysex.lpData = (LPSTR) buffer;
  2070. sysex.dwBufferLength = nBytes;
  2071. sysex.dwFlags = 0;
  2072. result = midiOutPrepareHeader( data->outHandle, &sysex, sizeof(MIDIHDR) );
  2073. if ( result != MMSYSERR_NOERROR ) {
  2074. free( buffer );
  2075. errorString_ = "MidiOutWinMM::sendMessage: error preparing sysex header.";
  2076. error( RtMidiError::DRIVER_ERROR, errorString_ );
  2077. return;
  2078. }
  2079. // Send the message.
  2080. result = midiOutLongMsg( data->outHandle, &sysex, sizeof(MIDIHDR) );
  2081. if ( result != MMSYSERR_NOERROR ) {
  2082. free( buffer );
  2083. errorString_ = "MidiOutWinMM::sendMessage: error sending sysex message.";
  2084. error( RtMidiError::DRIVER_ERROR, errorString_ );
  2085. return;
  2086. }
  2087. // Unprepare the buffer and MIDIHDR.
  2088. while ( MIDIERR_STILLPLAYING == midiOutUnprepareHeader( data->outHandle, &sysex, sizeof (MIDIHDR) ) ) Sleep( 1 );
  2089. free( buffer );
  2090. }
  2091. else { // Channel or system message.
  2092. // Make sure the message size isn't too big.
  2093. if ( nBytes > 3 ) {
  2094. errorString_ = "MidiOutWinMM::sendMessage: message size is greater than 3 bytes (and not sysex)!";
  2095. error( RtMidiError::WARNING, errorString_ );
  2096. return;
  2097. }
  2098. // Pack MIDI bytes into double word.
  2099. DWORD packet;
  2100. unsigned char *ptr = (unsigned char *) &packet;
  2101. for ( unsigned int i=0; i<nBytes; ++i ) {
  2102. *ptr = message->at(i);
  2103. ++ptr;
  2104. }
  2105. // Send the message immediately.
  2106. result = midiOutShortMsg( data->outHandle, packet );
  2107. if ( result != MMSYSERR_NOERROR ) {
  2108. errorString_ = "MidiOutWinMM::sendMessage: error sending MIDI message.";
  2109. error( RtMidiError::DRIVER_ERROR, errorString_ );
  2110. }
  2111. }
  2112. }
  2113. #endif // __WINDOWS_MM__
  2114. // *********************************************************************//
  2115. // API: WINDOWS Kernel Streaming
  2116. //
  2117. // Written by Sebastien Alaiwan, 2012.
  2118. //
  2119. // NOTE BY GARY: much of the KS-specific code below probably should go in a separate file.
  2120. //
  2121. // *********************************************************************//
  2122. #if defined(__WINDOWS_KS__)
  2123. #include <string>
  2124. #include <vector>
  2125. #include <memory>
  2126. #include <stdexcept>
  2127. #include <sstream>
  2128. #include <windows.h>
  2129. #include <setupapi.h>
  2130. #include <mmsystem.h>
  2131. #include "ks.h"
  2132. #include "ksmedia.h"
  2133. #define INSTANTIATE_GUID(a) GUID const a = { STATIC_ ## a }
  2134. INSTANTIATE_GUID(GUID_NULL);
  2135. INSTANTIATE_GUID(KSPROPSETID_Pin);
  2136. INSTANTIATE_GUID(KSPROPSETID_Connection);
  2137. INSTANTIATE_GUID(KSPROPSETID_Topology);
  2138. INSTANTIATE_GUID(KSINTERFACESETID_Standard);
  2139. INSTANTIATE_GUID(KSMEDIUMSETID_Standard);
  2140. INSTANTIATE_GUID(KSDATAFORMAT_TYPE_MUSIC);
  2141. INSTANTIATE_GUID(KSDATAFORMAT_SUBTYPE_MIDI);
  2142. INSTANTIATE_GUID(KSDATAFORMAT_SPECIFIER_NONE);
  2143. #undef INSTANTIATE_GUID
  2144. typedef std::basic_string<TCHAR> tstring;
  2145. inline bool IsValid(HANDLE handle)
  2146. {
  2147. return handle != NULL && handle != INVALID_HANDLE_VALUE;
  2148. }
  2149. class ComException : public std::runtime_error
  2150. {
  2151. private:
  2152. static std::string MakeString(std::string const& s, HRESULT hr)
  2153. {
  2154. std::stringstream ss;
  2155. ss << "(error 0x" << std::hex << hr << ")";
  2156. return s + ss.str();
  2157. }
  2158. public:
  2159. ComException(std::string const& s, HRESULT hr) :
  2160. std::runtime_error(MakeString(s, hr))
  2161. {
  2162. }
  2163. };
  2164. template<typename TFilterType>
  2165. class CKsEnumFilters
  2166. {
  2167. public:
  2168. ~CKsEnumFilters()
  2169. {
  2170. DestroyLists();
  2171. }
  2172. void EnumFilters(GUID const* categories, size_t numCategories)
  2173. {
  2174. DestroyLists();
  2175. if (categories == 0)
  2176. throw std::runtime_error("CKsEnumFilters: invalid argument");
  2177. // Get a handle to the device set specified by the guid
  2178. HDEVINFO hDevInfo = ::SetupDiGetClassDevs(&categories[0], NULL, NULL, DIGCF_PRESENT | DIGCF_DEVICEINTERFACE);
  2179. if (!IsValid(hDevInfo))
  2180. throw std::runtime_error("CKsEnumFilters: no devices found");
  2181. // Loop through members of the set and get details for each
  2182. for ( int iClassMember=0; iClassMember++ ) {
  2183. try {
  2184. SP_DEVICE_INTERFACE_DATA DID;
  2185. DID.cbSize = sizeof(DID);
  2186. DID.Reserved = 0;
  2187. bool fRes = ::SetupDiEnumDeviceInterfaces(hDevInfo, NULL, &categories[0], iClassMember, &DID);
  2188. if (!fRes)
  2189. break;
  2190. // Get filter friendly name
  2191. HKEY hRegKey = ::SetupDiOpenDeviceInterfaceRegKey(hDevInfo, &DID, 0, KEY_READ);
  2192. if (hRegKey == INVALID_HANDLE_VALUE)
  2193. throw std::runtime_error("CKsEnumFilters: interface has no registry");
  2194. char friendlyName[256];
  2195. DWORD dwSize = sizeof friendlyName;
  2196. LONG lval = ::RegQueryValueEx(hRegKey, TEXT("FriendlyName"), NULL, NULL, (LPBYTE)friendlyName, &dwSize);
  2197. ::RegCloseKey(hRegKey);
  2198. if (lval != ERROR_SUCCESS)
  2199. throw std::runtime_error("CKsEnumFilters: interface has no friendly name");
  2200. // Get details for the device registered in this class
  2201. DWORD const cbItfDetails = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA) + MAX_PATH * sizeof(WCHAR);
  2202. std::vector<BYTE> buffer(cbItfDetails);
  2203. SP_DEVICE_INTERFACE_DETAIL_DATA* pDevInterfaceDetails = reinterpret_cast<SP_DEVICE_INTERFACE_DETAIL_DATA*>(&buffer[0]);
  2204. pDevInterfaceDetails->cbSize = sizeof(*pDevInterfaceDetails);
  2205. SP_DEVINFO_DATA DevInfoData;
  2206. DevInfoData.cbSize = sizeof(DevInfoData);
  2207. DevInfoData.Reserved = 0;
  2208. fRes = ::SetupDiGetDeviceInterfaceDetail(hDevInfo, &DID, pDevInterfaceDetails, cbItfDetails, NULL, &DevInfoData);
  2209. if (!fRes)
  2210. throw std::runtime_error("CKsEnumFilters: could not get interface details");
  2211. // check additional category guids which may (or may not) have been supplied
  2212. for (size_t i=1; i < numCategories; ++i) {
  2213. SP_DEVICE_INTERFACE_DATA DIDAlias;
  2214. DIDAlias.cbSize = sizeof(DIDAlias);
  2215. DIDAlias.Reserved = 0;
  2216. fRes = ::SetupDiGetDeviceInterfaceAlias(hDevInfo, &DID, &categories[i], &DIDAlias);
  2217. if (!fRes)
  2218. throw std::runtime_error("CKsEnumFilters: could not get interface alias");
  2219. // Check if the this interface alias is enabled.
  2220. if (!DIDAlias.Flags || (DIDAlias.Flags & SPINT_REMOVED))
  2221. throw std::runtime_error("CKsEnumFilters: interface alias is not enabled");
  2222. }
  2223. std::auto_ptr<TFilterType> pFilter(new TFilterType(pDevInterfaceDetails->DevicePath, friendlyName));
  2224. pFilter->Instantiate();
  2225. pFilter->FindMidiPins();
  2226. pFilter->Validate();
  2227. m_Filters.push_back(pFilter.release());
  2228. }
  2229. catch (std::runtime_error const& e) {
  2230. }
  2231. }
  2232. ::SetupDiDestroyDeviceInfoList(hDevInfo);
  2233. }
  2234. private:
  2235. void DestroyLists()
  2236. {
  2237. for (size_t i=0;i < m_Filters.size();++i)
  2238. delete m_Filters[i];
  2239. m_Filters.clear();
  2240. }
  2241. public:
  2242. // TODO: make this private.
  2243. std::vector<TFilterType*> m_Filters;
  2244. };
  2245. class CKsObject
  2246. {
  2247. public:
  2248. CKsObject(HANDLE handle) : m_handle(handle)
  2249. {
  2250. }
  2251. protected:
  2252. HANDLE m_handle;
  2253. void SetProperty(REFGUID guidPropertySet, ULONG nProperty, void* pvValue, ULONG cbValue)
  2254. {
  2255. KSPROPERTY ksProperty;
  2256. memset(&ksProperty, 0, sizeof ksProperty);
  2257. ksProperty.Set = guidPropertySet;
  2258. ksProperty.Id = nProperty;
  2259. ksProperty.Flags = KSPROPERTY_TYPE_SET;
  2260. HRESULT hr = DeviceIoControlKsProperty(ksProperty, pvValue, cbValue);
  2261. if (FAILED(hr))
  2262. throw ComException("CKsObject::SetProperty: could not set property", hr);
  2263. }
  2264. private:
  2265. HRESULT DeviceIoControlKsProperty(KSPROPERTY& ksProperty, void* pvValue, ULONG cbValue)
  2266. {
  2267. ULONG ulReturned;
  2268. return ::DeviceIoControl(
  2269. m_handle,
  2270. IOCTL_KS_PROPERTY,
  2271. &ksProperty,
  2272. sizeof(ksProperty),
  2273. pvValue,
  2274. cbValue,
  2275. &ulReturned,
  2276. NULL);
  2277. }
  2278. };
  2279. class CKsPin;
  2280. class CKsFilter : public CKsObject
  2281. {
  2282. friend class CKsPin;
  2283. public:
  2284. CKsFilter(tstring const& name, std::string const& sFriendlyName);
  2285. virtual ~CKsFilter();
  2286. virtual void Instantiate();
  2287. template<typename T>
  2288. T GetPinProperty(ULONG nPinId, ULONG nProperty)
  2289. {
  2290. ULONG ulReturned = 0;
  2291. T value;
  2292. KSP_PIN ksPProp;
  2293. ksPProp.Property.Set = KSPROPSETID_Pin;
  2294. ksPProp.Property.Id = nProperty;
  2295. ksPProp.Property.Flags = KSPROPERTY_TYPE_GET;
  2296. ksPProp.PinId = nPinId;
  2297. ksPProp.Reserved = 0;
  2298. HRESULT hr = ::DeviceIoControl(
  2299. m_handle,
  2300. IOCTL_KS_PROPERTY,
  2301. &ksPProp,
  2302. sizeof(KSP_PIN),
  2303. &value,
  2304. sizeof(value),
  2305. &ulReturned,
  2306. NULL);
  2307. if (FAILED(hr))
  2308. throw ComException("CKsFilter::GetPinProperty: failed to retrieve property", hr);
  2309. return value;
  2310. }
  2311. void GetPinPropertyMulti(ULONG nPinId, REFGUID guidPropertySet, ULONG nProperty, PKSMULTIPLE_ITEM* ppKsMultipleItem)
  2312. {
  2313. HRESULT hr;
  2314. KSP_PIN ksPProp;
  2315. ksPProp.Property.Set = guidPropertySet;
  2316. ksPProp.Property.Id = nProperty;
  2317. ksPProp.Property.Flags = KSPROPERTY_TYPE_GET;
  2318. ksPProp.PinId = nPinId;
  2319. ksPProp.Reserved = 0;
  2320. ULONG cbMultipleItem = 0;
  2321. hr = ::DeviceIoControl(m_handle,
  2322. IOCTL_KS_PROPERTY,
  2323. &ksPProp.Property,
  2324. sizeof(KSP_PIN),
  2325. NULL,
  2326. 0,
  2327. &cbMultipleItem,
  2328. NULL);
  2329. if (FAILED(hr))
  2330. throw ComException("CKsFilter::GetPinPropertyMulti: cannot get property", hr);
  2331. *ppKsMultipleItem = (PKSMULTIPLE_ITEM) new BYTE[cbMultipleItem];
  2332. ULONG ulReturned = 0;
  2333. hr = ::DeviceIoControl(
  2334. m_handle,
  2335. IOCTL_KS_PROPERTY,
  2336. &ksPProp,
  2337. sizeof(KSP_PIN),
  2338. (PVOID)*ppKsMultipleItem,
  2339. cbMultipleItem,
  2340. &ulReturned,
  2341. NULL);
  2342. if (FAILED(hr))
  2343. throw ComException("CKsFilter::GetPinPropertyMulti: cannot get property", hr);
  2344. }
  2345. std::string const& GetFriendlyName() const
  2346. {
  2347. return m_sFriendlyName;
  2348. }
  2349. protected:
  2350. std::vector<CKsPin*> m_Pins; // this list owns the pins.
  2351. std::vector<CKsPin*> m_RenderPins;
  2352. std::vector<CKsPin*> m_CapturePins;
  2353. private:
  2354. std::string const m_sFriendlyName; // friendly name eg "Virus TI Synth"
  2355. tstring const m_sName; // Filter path, eg "\\?\usb#vid_133e&pid_0815...\vtimidi02"
  2356. };
  2357. class CKsPin : public CKsObject
  2358. {
  2359. public:
  2360. CKsPin(CKsFilter* pFilter, ULONG nId);
  2361. virtual ~CKsPin();
  2362. virtual void Instantiate();
  2363. void ClosePin();
  2364. void SetState(KSSTATE ksState);
  2365. void WriteData(KSSTREAM_HEADER* pKSSTREAM_HEADER, OVERLAPPED* pOVERLAPPED);
  2366. void ReadData(KSSTREAM_HEADER* pKSSTREAM_HEADER, OVERLAPPED* pOVERLAPPED);
  2367. KSPIN_DATAFLOW GetDataFlow() const
  2368. {
  2369. return m_DataFlow;
  2370. }
  2371. bool IsSink() const
  2372. {
  2373. return m_Communication == KSPIN_COMMUNICATION_SINK
  2374. || m_Communication == KSPIN_COMMUNICATION_BOTH;
  2375. }
  2376. protected:
  2377. PKSPIN_CONNECT m_pKsPinConnect; // creation parameters of pin
  2378. CKsFilter* const m_pFilter;
  2379. ULONG m_cInterfaces;
  2380. PKSIDENTIFIER m_pInterfaces;
  2381. PKSMULTIPLE_ITEM m_pmiInterfaces;
  2382. ULONG m_cMediums;
  2383. PKSIDENTIFIER m_pMediums;
  2384. PKSMULTIPLE_ITEM m_pmiMediums;
  2385. ULONG m_cDataRanges;
  2386. PKSDATARANGE m_pDataRanges;
  2387. PKSMULTIPLE_ITEM m_pmiDataRanges;
  2388. KSPIN_DATAFLOW m_DataFlow;
  2389. KSPIN_COMMUNICATION m_Communication;
  2390. };
  2391. CKsFilter::CKsFilter(tstring const& sName, std::string const& sFriendlyName) :
  2392. CKsObject(INVALID_HANDLE_VALUE),
  2393. m_sFriendlyName(sFriendlyName),
  2394. m_sName(sName)
  2395. {
  2396. if (sName.empty())
  2397. throw std::runtime_error("CKsFilter::CKsFilter: name can't be empty");
  2398. }
  2399. CKsFilter::~CKsFilter()
  2400. {
  2401. for (size_t i=0;i < m_Pins.size();++i)
  2402. delete m_Pins[i];
  2403. if (IsValid(m_handle))
  2404. ::CloseHandle(m_handle);
  2405. }
  2406. void CKsFilter::Instantiate()
  2407. {
  2408. m_handle = CreateFile(
  2409. m_sName.c_str(),
  2410. GENERIC_READ | GENERIC_WRITE,
  2411. 0,
  2412. NULL,
  2413. OPEN_EXISTING,
  2414. FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED,
  2415. NULL);
  2416. if (!IsValid(m_handle))
  2417. {
  2418. DWORD const dwError = GetLastError();
  2419. throw ComException("CKsFilter::Instantiate: can't open driver", HRESULT_FROM_WIN32(dwError));
  2420. }
  2421. }
  2422. CKsPin::CKsPin(CKsFilter* pFilter, ULONG PinId) :
  2423. CKsObject(INVALID_HANDLE_VALUE),
  2424. m_pKsPinConnect(NULL),
  2425. m_pFilter(pFilter)
  2426. {
  2427. m_Communication = m_pFilter->GetPinProperty<KSPIN_COMMUNICATION>(PinId, KSPROPERTY_PIN_COMMUNICATION);
  2428. m_DataFlow = m_pFilter->GetPinProperty<KSPIN_DATAFLOW>(PinId, KSPROPERTY_PIN_DATAFLOW);
  2429. // Interfaces
  2430. m_pFilter->GetPinPropertyMulti(
  2431. PinId,
  2432. KSPROPSETID_Pin,
  2433. KSPROPERTY_PIN_INTERFACES,
  2434. &m_pmiInterfaces);
  2435. m_cInterfaces = m_pmiInterfaces->Count;
  2436. m_pInterfaces = (PKSPIN_INTERFACE)(m_pmiInterfaces + 1);
  2437. // Mediums
  2438. m_pFilter->GetPinPropertyMulti(
  2439. PinId,
  2440. KSPROPSETID_Pin,
  2441. KSPROPERTY_PIN_MEDIUMS,
  2442. &m_pmiMediums);
  2443. m_cMediums = m_pmiMediums->Count;
  2444. m_pMediums = (PKSPIN_MEDIUM)(m_pmiMediums + 1);
  2445. // Data ranges
  2446. m_pFilter->GetPinPropertyMulti(
  2447. PinId,
  2448. KSPROPSETID_Pin,
  2449. KSPROPERTY_PIN_DATARANGES,
  2450. &m_pmiDataRanges);
  2451. m_cDataRanges = m_pmiDataRanges->Count;
  2452. m_pDataRanges = (PKSDATARANGE)(m_pmiDataRanges + 1);
  2453. }
  2454. CKsPin::~CKsPin()
  2455. {
  2456. ClosePin();
  2457. delete[] (BYTE*)m_pKsPinConnect;
  2458. delete[] (BYTE*)m_pmiDataRanges;
  2459. delete[] (BYTE*)m_pmiInterfaces;
  2460. delete[] (BYTE*)m_pmiMediums;
  2461. }
  2462. void CKsPin::ClosePin()
  2463. {
  2464. if (IsValid(m_handle)) {
  2465. SetState(KSSTATE_STOP);
  2466. ::CloseHandle(m_handle);
  2467. }
  2468. m_handle = INVALID_HANDLE_VALUE;
  2469. }
  2470. void CKsPin::SetState(KSSTATE ksState)
  2471. {
  2472. SetProperty(KSPROPSETID_Connection, KSPROPERTY_CONNECTION_STATE, &ksState, sizeof(ksState));
  2473. }
  2474. void CKsPin::Instantiate()
  2475. {
  2476. if (!m_pKsPinConnect)
  2477. throw std::runtime_error("CKsPin::Instanciate: abstract pin");
  2478. DWORD const dwResult = KsCreatePin(m_pFilter->m_handle, m_pKsPinConnect, GENERIC_WRITE | GENERIC_READ, &m_handle);
  2479. if (dwResult != ERROR_SUCCESS)
  2480. throw ComException("CKsMidiCapFilter::CreateRenderPin: Pin instanciation failed", HRESULT_FROM_WIN32(dwResult));
  2481. }
  2482. void CKsPin::WriteData(KSSTREAM_HEADER* pKSSTREAM_HEADER, OVERLAPPED* pOVERLAPPED)
  2483. {
  2484. DWORD cbWritten;
  2485. BOOL fRes = ::DeviceIoControl(
  2486. m_handle,
  2487. IOCTL_KS_WRITE_STREAM,
  2488. NULL,
  2489. 0,
  2490. pKSSTREAM_HEADER,
  2491. pKSSTREAM_HEADER->Size,
  2492. &cbWritten,
  2493. pOVERLAPPED);
  2494. if (!fRes) {
  2495. DWORD const dwError = GetLastError();
  2496. if (dwError != ERROR_IO_PENDING)
  2497. throw ComException("CKsPin::WriteData: DeviceIoControl failed", HRESULT_FROM_WIN32(dwError));
  2498. }
  2499. }
  2500. void CKsPin::ReadData(KSSTREAM_HEADER* pKSSTREAM_HEADER, OVERLAPPED* pOVERLAPPED)
  2501. {
  2502. DWORD cbReturned;
  2503. BOOL fRes = ::DeviceIoControl(
  2504. m_handle,
  2505. IOCTL_KS_READ_STREAM,
  2506. NULL,
  2507. 0,
  2508. pKSSTREAM_HEADER,
  2509. pKSSTREAM_HEADER->Size,
  2510. &cbReturned,
  2511. pOVERLAPPED);
  2512. if (!fRes) {
  2513. DWORD const dwError = GetLastError();
  2514. if (dwError != ERROR_IO_PENDING)
  2515. throw ComException("CKsPin::ReadData: DeviceIoControl failed", HRESULT_FROM_WIN32(dwError));
  2516. }
  2517. }
  2518. class CKsMidiFilter : public CKsFilter
  2519. {
  2520. public:
  2521. void FindMidiPins();
  2522. protected:
  2523. CKsMidiFilter(tstring const& sPath, std::string const& sFriendlyName);
  2524. };
  2525. class CKsMidiPin : public CKsPin
  2526. {
  2527. public:
  2528. CKsMidiPin(CKsFilter* pFilter, ULONG nId);
  2529. };
  2530. class CKsMidiRenFilter : public CKsMidiFilter
  2531. {
  2532. public:
  2533. CKsMidiRenFilter(tstring const& sPath, std::string const& sFriendlyName);
  2534. CKsMidiPin* CreateRenderPin();
  2535. void Validate()
  2536. {
  2537. if (m_RenderPins.empty())
  2538. throw std::runtime_error("Could not find a MIDI render pin");
  2539. }
  2540. };
  2541. class CKsMidiCapFilter : public CKsMidiFilter
  2542. {
  2543. public:
  2544. CKsMidiCapFilter(tstring const& sPath, std::string const& sFriendlyName);
  2545. CKsMidiPin* CreateCapturePin();
  2546. void Validate()
  2547. {
  2548. if (m_CapturePins.empty())
  2549. throw std::runtime_error("Could not find a MIDI capture pin");
  2550. }
  2551. };
  2552. CKsMidiFilter::CKsMidiFilter(tstring const& sPath, std::string const& sFriendlyName) :
  2553. CKsFilter(sPath, sFriendlyName)
  2554. {
  2555. }
  2556. void CKsMidiFilter::FindMidiPins()
  2557. {
  2558. ULONG numPins = GetPinProperty<ULONG>(0, KSPROPERTY_PIN_CTYPES);
  2559. for (ULONG iPin = 0; iPin < numPins; ++iPin) {
  2560. try {
  2561. KSPIN_COMMUNICATION com = GetPinProperty<KSPIN_COMMUNICATION>(iPin, KSPROPERTY_PIN_COMMUNICATION);
  2562. if (com != KSPIN_COMMUNICATION_SINK && com != KSPIN_COMMUNICATION_BOTH)
  2563. throw std::runtime_error("Unknown pin communication value");
  2564. m_Pins.push_back(new CKsMidiPin(this, iPin));
  2565. }
  2566. catch (std::runtime_error const&) {
  2567. // pin instanciation has failed, continue to the next pin.
  2568. }
  2569. }
  2570. m_RenderPins.clear();
  2571. m_CapturePins.clear();
  2572. for (size_t i = 0; i < m_Pins.size(); ++i) {
  2573. CKsPin* const pPin = m_Pins[i];
  2574. if (pPin->IsSink()) {
  2575. if (pPin->GetDataFlow() == KSPIN_DATAFLOW_IN)
  2576. m_RenderPins.push_back(pPin);
  2577. else
  2578. m_CapturePins.push_back(pPin);
  2579. }
  2580. }
  2581. if (m_RenderPins.empty() && m_CapturePins.empty())
  2582. throw std::runtime_error("No valid pins found on the filter.");
  2583. }
  2584. CKsMidiRenFilter::CKsMidiRenFilter(tstring const& sPath, std::string const& sFriendlyName) :
  2585. CKsMidiFilter(sPath, sFriendlyName)
  2586. {
  2587. }
  2588. CKsMidiPin* CKsMidiRenFilter::CreateRenderPin()
  2589. {
  2590. if (m_RenderPins.empty())
  2591. throw std::runtime_error("Could not find a MIDI render pin");
  2592. CKsMidiPin* pPin = (CKsMidiPin*)m_RenderPins[0];
  2593. pPin->Instantiate();
  2594. return pPin;
  2595. }
  2596. CKsMidiCapFilter::CKsMidiCapFilter(tstring const& sPath, std::string const& sFriendlyName) :
  2597. CKsMidiFilter(sPath, sFriendlyName)
  2598. {
  2599. }
  2600. CKsMidiPin* CKsMidiCapFilter::CreateCapturePin()
  2601. {
  2602. if (m_CapturePins.empty())
  2603. throw std::runtime_error("Could not find a MIDI capture pin");
  2604. CKsMidiPin* pPin = (CKsMidiPin*)m_CapturePins[0];
  2605. pPin->Instantiate();
  2606. return pPin;
  2607. }
  2608. CKsMidiPin::CKsMidiPin(CKsFilter* pFilter, ULONG nId) :
  2609. CKsPin(pFilter, nId)
  2610. {
  2611. DWORD const cbPinCreateSize = sizeof(KSPIN_CONNECT) + sizeof(KSDATAFORMAT);
  2612. m_pKsPinConnect = (PKSPIN_CONNECT) new BYTE[cbPinCreateSize];
  2613. m_pKsPinConnect->Interface.Set = KSINTERFACESETID_Standard;
  2614. m_pKsPinConnect->Interface.Id = KSINTERFACE_STANDARD_STREAMING;
  2615. m_pKsPinConnect->Interface.Flags = 0;
  2616. m_pKsPinConnect->Medium.Set = KSMEDIUMSETID_Standard;
  2617. m_pKsPinConnect->Medium.Id = KSMEDIUM_TYPE_ANYINSTANCE;
  2618. m_pKsPinConnect->Medium.Flags = 0;
  2619. m_pKsPinConnect->PinId = nId;
  2620. m_pKsPinConnect->PinToHandle = NULL;
  2621. m_pKsPinConnect->Priority.PriorityClass = KSPRIORITY_NORMAL;
  2622. m_pKsPinConnect->Priority.PrioritySubClass = 1;
  2623. // point m_pDataFormat to just after the pConnect struct
  2624. KSDATAFORMAT* m_pDataFormat = (KSDATAFORMAT*)(m_pKsPinConnect + 1);
  2625. m_pDataFormat->FormatSize = sizeof(KSDATAFORMAT);
  2626. m_pDataFormat->Flags = 0;
  2627. m_pDataFormat->SampleSize = 0;
  2628. m_pDataFormat->Reserved = 0;
  2629. m_pDataFormat->MajorFormat = GUID(KSDATAFORMAT_TYPE_MUSIC);
  2630. m_pDataFormat->SubFormat = GUID(KSDATAFORMAT_SUBTYPE_MIDI);
  2631. m_pDataFormat->Specifier = GUID(KSDATAFORMAT_SPECIFIER_NONE);
  2632. bool hasStdStreamingInterface = false;
  2633. bool hasStdStreamingMedium = false;
  2634. for ( ULONG i = 0; i < m_cInterfaces; i++ ) {
  2635. if (m_pInterfaces[i].Set == KSINTERFACESETID_Standard
  2636. && m_pInterfaces[i].Id == KSINTERFACE_STANDARD_STREAMING)
  2637. hasStdStreamingInterface = true;
  2638. }
  2639. for (ULONG i = 0; i < m_cMediums; i++) {
  2640. if (m_pMediums[i].Set == KSMEDIUMSETID_Standard
  2641. && m_pMediums[i].Id == KSMEDIUM_STANDARD_DEVIO)
  2642. hasStdStreamingMedium = true;
  2643. }
  2644. if (!hasStdStreamingInterface) // No standard streaming interfaces on the pin
  2645. throw std::runtime_error("CKsMidiPin::CKsMidiPin: no standard streaming interface");
  2646. if (!hasStdStreamingMedium) // No standard streaming mediums on the pin
  2647. throw std::runtime_error("CKsMidiPin::CKsMidiPin: no standard streaming medium");
  2648. bool hasMidiDataRange = false;
  2649. BYTE const* pDataRangePtr = reinterpret_cast<BYTE const*>(m_pDataRanges);
  2650. for (ULONG i = 0; i < m_cDataRanges; ++i) {
  2651. KSDATARANGE const* pDataRange = reinterpret_cast<KSDATARANGE const*>(pDataRangePtr);
  2652. if (pDataRange->SubFormat == KSDATAFORMAT_SUBTYPE_MIDI) {
  2653. hasMidiDataRange = true;
  2654. break;
  2655. }
  2656. pDataRangePtr += pDataRange->FormatSize;
  2657. }
  2658. if (!hasMidiDataRange) // No MIDI dataranges on the pin
  2659. throw std::runtime_error("CKsMidiPin::CKsMidiPin: no MIDI datarange");
  2660. }
  2661. struct WindowsKsData
  2662. {
  2663. WindowsKsData() : m_pPin(NULL), m_Buffer(1024), m_hInputThread(NULL)
  2664. {
  2665. memset(&overlapped, 0, sizeof(OVERLAPPED));
  2666. m_hExitEvent = ::CreateEvent(NULL, FALSE, FALSE, NULL);
  2667. overlapped.hEvent = ::CreateEvent(NULL, FALSE, FALSE, NULL);
  2668. m_hInputThread = NULL;
  2669. }
  2670. ~WindowsKsData()
  2671. {
  2672. ::CloseHandle(overlapped.hEvent);
  2673. ::CloseHandle(m_hExitEvent);
  2674. }
  2675. OVERLAPPED overlapped;
  2676. CKsPin* m_pPin;
  2677. std::vector<unsigned char> m_Buffer;
  2678. std::auto_ptr<CKsEnumFilters<CKsMidiCapFilter> > m_pCaptureEnum;
  2679. std::auto_ptr<CKsEnumFilters<CKsMidiRenFilter> > m_pRenderEnum;
  2680. HANDLE m_hInputThread;
  2681. HANDLE m_hExitEvent;
  2682. };
  2683. // *********************************************************************//
  2684. // API: WINDOWS Kernel Streaming
  2685. // Class Definitions: MidiInWinKS
  2686. // *********************************************************************//
  2687. static DWORD WINAPI midiKsInputThread(VOID* pUser)
  2688. {
  2689. MidiInApi::RtMidiInData* data = static_cast<MidiInApi::RtMidiInData*>(pUser);
  2690. WindowsKsData* apiData = static_cast<WindowsKsData*>(data->apiData);
  2691. HANDLE hEvents[] = { apiData->overlapped.hEvent, apiData->m_hExitEvent };
  2692. while ( true ) {
  2693. KSSTREAM_HEADER packet;
  2694. memset(&packet, 0, sizeof packet);
  2695. packet.Size = sizeof(KSSTREAM_HEADER);
  2696. packet.PresentationTime.Time = 0;
  2697. packet.PresentationTime.Numerator = 1;
  2698. packet.PresentationTime.Denominator = 1;
  2699. packet.Data = &apiData->m_Buffer[0];
  2700. packet.DataUsed = 0;
  2701. packet.FrameExtent = apiData->m_Buffer.size();
  2702. apiData->m_pPin->ReadData(&packet, &apiData->overlapped);
  2703. DWORD dwRet = ::WaitForMultipleObjects(2, hEvents, FALSE, INFINITE);
  2704. if ( dwRet == WAIT_OBJECT_0 ) {
  2705. // parse packet
  2706. unsigned char* pData = (unsigned char*)packet.Data;
  2707. unsigned int iOffset = 0;
  2708. while ( iOffset < packet.DataUsed ) {
  2709. KSMUSICFORMAT* pMusic = (KSMUSICFORMAT*)&pData[iOffset];
  2710. iOffset += sizeof(KSMUSICFORMAT);
  2711. MidiInApi::MidiMessage message;
  2712. message.timeStamp = 0;
  2713. for(size_t i=0;i < pMusic->ByteCount;++i)
  2714. message.bytes.push_back(pData[iOffset+i]);
  2715. if ( data->usingCallback ) {
  2716. RtMidiIn::RtMidiCallback callback = (RtMidiIn::RtMidiCallback)data->userCallback;
  2717. callback(message.timeStamp, &message.bytes, data->userData);
  2718. }
  2719. else {
  2720. // As long as we haven't reached our queue size limit, push the message.
  2721. if ( data->queue.size < data->queue.ringSize ) {
  2722. data->queue.ring[data->queue.back++] = message;
  2723. if(data->queue.back == data->queue.ringSize)
  2724. data->queue.back = 0;
  2725. data->queue.size++;
  2726. }
  2727. else
  2728. std::cerr << "\nRtMidiIn: message queue limit reached!!\n\n";
  2729. }
  2730. iOffset += pMusic->ByteCount;
  2731. // re-align on 32 bits
  2732. if ( iOffset % 4 != 0 )
  2733. iOffset += (4 - iOffset % 4);
  2734. }
  2735. }
  2736. else
  2737. break;
  2738. }
  2739. return 0;
  2740. }
  2741. MidiInWinKS :: MidiInWinKS( const std::string clientName, unsigned int queueSizeLimit ) : MidiInApi( queueSizeLimit )
  2742. {
  2743. initialize( clientName );
  2744. }
  2745. void MidiInWinKS :: initialize( const std::string& clientName )
  2746. {
  2747. WindowsKsData* data = new WindowsKsData;
  2748. apiData_ = (void*)data;
  2749. inputData_.apiData = data;
  2750. GUID const aguidEnumCats[] =
  2751. {
  2752. { STATIC_KSCATEGORY_AUDIO }, { STATIC_KSCATEGORY_CAPTURE }
  2753. };
  2754. data->m_pCaptureEnum.reset(new CKsEnumFilters<CKsMidiCapFilter> );
  2755. data->m_pCaptureEnum->EnumFilters(aguidEnumCats, 2);
  2756. }
  2757. MidiInWinKS :: ~MidiInWinKS()
  2758. {
  2759. WindowsKsData* data = static_cast<WindowsKsData*>(apiData_);
  2760. try {
  2761. if ( data->m_pPin )
  2762. closePort();
  2763. }
  2764. catch(...) {
  2765. }
  2766. delete data;
  2767. }
  2768. void MidiInWinKS :: openPort( unsigned int portNumber, const std::string portName )
  2769. {
  2770. WindowsKsData* data = static_cast<WindowsKsData*>(apiData_);
  2771. if ( portNumber < 0 || portNumber >= data->m_pCaptureEnum->m_Filters.size() ) {
  2772. std::stringstream ost;
  2773. ost << "MidiInWinKS::openPort: the 'portNumber' argument (" << portNumber << ") is invalid.";
  2774. errorString_ = ost.str();
  2775. error( RtMidiError::WARNING, errorString_ );
  2776. return;
  2777. }
  2778. CKsMidiCapFilter* pFilter = data->m_pCaptureEnum->m_Filters[portNumber];
  2779. data->m_pPin = pFilter->CreateCapturePin();
  2780. if ( data->m_pPin == NULL ) {
  2781. std::stringstream ost;
  2782. ost << "MidiInWinKS::openPort: KS error opening port (could not create pin)";
  2783. errorString_ = ost.str();
  2784. error( RtMidiError::WARNING, errorString_ );
  2785. return;
  2786. }
  2787. data->m_pPin->SetState(KSSTATE_RUN);
  2788. DWORD threadId;
  2789. data->m_hInputThread = ::CreateThread(NULL, 0, &midiKsInputThread, &inputData_, 0, &threadId);
  2790. if ( data->m_hInputThread == NULL ) {
  2791. std::stringstream ost;
  2792. ost << "MidiInWinKS::openPort: Could not create input thread : Windows error " << GetLastError() << std::endl;;
  2793. errorString_ = ost.str();
  2794. error( RtMidiError::WARNING, errorString_ );
  2795. return;
  2796. }
  2797. connected_ = true;
  2798. }
  2799. void MidiInWinKS :: openVirtualPort( const std::string portName )
  2800. {
  2801. // This function cannot be implemented for the Windows KS MIDI API.
  2802. errorString_ = "MidiInWinKS::openVirtualPort: cannot be implemented in Windows KS MIDI API!";
  2803. error( RtMidiError::WARNING, errorString_ );
  2804. }
  2805. unsigned int MidiInWinKS :: getPortCount()
  2806. {
  2807. WindowsKsData* data = static_cast<WindowsKsData*>(apiData_);
  2808. return (unsigned int)data->m_pCaptureEnum->m_Filters.size();
  2809. }
  2810. std::string MidiInWinKS :: getPortName(unsigned int portNumber)
  2811. {
  2812. WindowsKsData* data = static_cast<WindowsKsData*>(apiData_);
  2813. if (portNumber < 0 || portNumber >= data->m_pCaptureEnum->m_Filters.size()) {
  2814. std::stringstream ost;
  2815. ost << "MidiInWinKS::getPortName: the 'portNumber' argument (" << portNumber << ") is invalid.";
  2816. errorString_ = ost.str();
  2817. error( RtMidiError::WARNING, errorString_ );
  2818. return;
  2819. }
  2820. CKsMidiCapFilter* pFilter = data->m_pCaptureEnum->m_Filters[portNumber];
  2821. return pFilter->GetFriendlyName();
  2822. }
  2823. void MidiInWinKS :: closePort()
  2824. {
  2825. WindowsKsData* data = static_cast<WindowsKsData*>(apiData_);
  2826. connected_ = false;
  2827. if (data->m_hInputThread) {
  2828. ::SignalObjectAndWait(data->m_hExitEvent, data->m_hInputThread, INFINITE, FALSE);
  2829. ::CloseHandle(data->m_hInputThread);
  2830. }
  2831. if (data->m_pPin) {
  2832. data->m_pPin->SetState(KSSTATE_PAUSE);
  2833. data->m_pPin->SetState(KSSTATE_STOP);
  2834. data->m_pPin->ClosePin();
  2835. data->m_pPin = NULL;
  2836. }
  2837. }
  2838. // *********************************************************************//
  2839. // API: WINDOWS Kernel Streaming
  2840. // Class Definitions: MidiOutWinKS
  2841. // *********************************************************************//
  2842. MidiOutWinKS :: MidiOutWinKS( const std::string clientName ) : MidiOutApi()
  2843. {
  2844. initialize( clientName );
  2845. }
  2846. void MidiOutWinKS :: initialize( const std::string& clientName )
  2847. {
  2848. WindowsKsData* data = new WindowsKsData;
  2849. data->m_pPin = NULL;
  2850. data->m_pRenderEnum.reset(new CKsEnumFilters<CKsMidiRenFilter> );
  2851. GUID const aguidEnumCats[] =
  2852. {
  2853. { STATIC_KSCATEGORY_AUDIO }, { STATIC_KSCATEGORY_RENDER }
  2854. };
  2855. data->m_pRenderEnum->EnumFilters(aguidEnumCats, 2);
  2856. apiData_ = (void*)data;
  2857. }
  2858. MidiOutWinKS :: ~MidiOutWinKS()
  2859. {
  2860. // Close a connection if it exists.
  2861. closePort();
  2862. // Cleanup.
  2863. WindowsKsData* data = static_cast<WindowsKsData*>(apiData_);
  2864. delete data;
  2865. }
  2866. void MidiOutWinKS :: openPort( unsigned int portNumber, const std::string portName )
  2867. {
  2868. WindowsKsData* data = static_cast<WindowsKsData*>(apiData_);
  2869. if (portNumber < 0 || portNumber >= data->m_pRenderEnum->m_Filters.size()) {
  2870. std::stringstream ost;
  2871. ost << "MidiOutWinKS::openPort: the 'portNumber' argument (" << portNumber << ") is invalid.";
  2872. errorString_ = ost.str();
  2873. error( RtMidiError::WARNING, errorString_ );
  2874. return;
  2875. }
  2876. CKsMidiRenFilter* pFilter = data->m_pRenderEnum->m_Filters[portNumber];
  2877. data->m_pPin = pFilter->CreateRenderPin();
  2878. if (data->m_pPin == NULL) {
  2879. std::stringstream ost;
  2880. ost << "MidiOutWinKS::openPort: KS error opening port (could not create pin)";
  2881. errorString_ = ost.str();
  2882. error( RtMidiError::WARNING, errorString_ );
  2883. return;
  2884. }
  2885. data->m_pPin->SetState(KSSTATE_RUN);
  2886. connected_ = true;
  2887. }
  2888. void MidiOutWinKS :: openVirtualPort( const std::string portName )
  2889. {
  2890. // This function cannot be implemented for the Windows KS MIDI API.
  2891. errorString_ = "MidiOutWinKS::openVirtualPort: cannot be implemented in Windows KS MIDI API!";
  2892. error( RtMidiError::WARNING, errorString_ );
  2893. }
  2894. unsigned int MidiOutWinKS :: getPortCount()
  2895. {
  2896. WindowsKsData* data = static_cast<WindowsKsData*>(apiData_);
  2897. return (unsigned int)data->m_pRenderEnum->m_Filters.size();
  2898. }
  2899. std::string MidiOutWinKS :: getPortName( unsigned int portNumber )
  2900. {
  2901. WindowsKsData* data = static_cast<WindowsKsData*>(apiData_);
  2902. if ( portNumber < 0 || portNumber >= data->m_pRenderEnum->m_Filters.size() ) {
  2903. std::stringstream ost;
  2904. ost << "MidiOutWinKS::getPortName: the 'portNumber' argument (" << portNumber << ") is invalid.";
  2905. errorString_ = ost.str();
  2906. error( RtMidiError::WARNING, errorString_ );
  2907. return;
  2908. }
  2909. CKsMidiRenFilter* pFilter = data->m_pRenderEnum->m_Filters[portNumber];
  2910. return pFilter->GetFriendlyName();
  2911. }
  2912. void MidiOutWinKS :: closePort()
  2913. {
  2914. WindowsKsData* data = static_cast<WindowsKsData*>(apiData_);
  2915. connected_ = false;
  2916. if ( data->m_pPin ) {
  2917. data->m_pPin->SetState(KSSTATE_PAUSE);
  2918. data->m_pPin->SetState(KSSTATE_STOP);
  2919. data->m_pPin->ClosePin();
  2920. data->m_pPin = NULL;
  2921. }
  2922. }
  2923. void MidiOutWinKS :: sendMessage(std::vector<unsigned char>* pMessage)
  2924. {
  2925. std::vector<unsigned char> const& msg = *pMessage;
  2926. WindowsKsData* data = static_cast<WindowsKsData*>(apiData_);
  2927. size_t iNumMidiBytes = msg.size();
  2928. size_t pos = 0;
  2929. // write header
  2930. KSMUSICFORMAT* pKsMusicFormat = reinterpret_cast<KSMUSICFORMAT*>(&data->m_Buffer[pos]);
  2931. pKsMusicFormat->TimeDeltaMs = 0;
  2932. pKsMusicFormat->ByteCount = iNumMidiBytes;
  2933. pos += sizeof(KSMUSICFORMAT);
  2934. // write MIDI bytes
  2935. if ( pos + iNumMidiBytes > data->m_Buffer.size() ) {
  2936. std::stringstream ost;
  2937. ost << "KsMidiInput::Write: MIDI buffer too small. Required " << pos + iNumMidiBytes << " bytes, only has " << data->m_Buffer.size();
  2938. errorString_ = ost.str();
  2939. error( RtMidiError::WARNING, errorString_ );
  2940. return;
  2941. }
  2942. if ( data->m_pPin == NULL ) {
  2943. std::stringstream ost;
  2944. ost << "MidiOutWinKS::sendMessage: port is not open";
  2945. errorString_ = ost.str();
  2946. error( RtMidiError::WARNING, errorString_ );
  2947. return;
  2948. }
  2949. memcpy(&data->m_Buffer[pos], &msg[0], iNumMidiBytes);
  2950. pos += iNumMidiBytes;
  2951. KSSTREAM_HEADER packet;
  2952. memset(&packet, 0, sizeof packet);
  2953. packet.Size = sizeof(packet);
  2954. packet.PresentationTime.Time = 0;
  2955. packet.PresentationTime.Numerator = 1;
  2956. packet.PresentationTime.Denominator = 1;
  2957. packet.Data = const_cast<unsigned char*>(&data->m_Buffer[0]);
  2958. packet.DataUsed = ((pos+3)/4)*4;
  2959. packet.FrameExtent = data->m_Buffer.size();
  2960. data->m_pPin->WriteData(&packet, NULL);
  2961. }
  2962. #endif // __WINDOWS_KS__
  2963. //*********************************************************************//
  2964. // API: UNIX JACK
  2965. //
  2966. // Written primarily by Alexander Svetalkin, with updates for delta
  2967. // time by Gary Scavone, April 2011.
  2968. //
  2969. // *********************************************************************//
  2970. #if defined(__UNIX_JACK__)
  2971. // JACK header files
  2972. #include <jack/jack.h>
  2973. #include <jack/midiport.h>
  2974. #include <jack/ringbuffer.h>
  2975. #define JACK_RINGBUFFER_SIZE 16384 // Default size for ringbuffer
  2976. struct JackMidiData {
  2977. jack_client_t *client;
  2978. jack_port_t *port;
  2979. jack_ringbuffer_t *buffSize;
  2980. jack_ringbuffer_t *buffMessage;
  2981. jack_time_t lastTime;
  2982. MidiInApi :: RtMidiInData *rtMidiIn;
  2983. };
  2984. //*********************************************************************//
  2985. // API: JACK
  2986. // Class Definitions: MidiInJack
  2987. //*********************************************************************//
  2988. static int jackProcessIn( jack_nframes_t nframes, void *arg )
  2989. {
  2990. JackMidiData *jData = (JackMidiData *) arg;
  2991. MidiInApi :: RtMidiInData *rtData = jData->rtMidiIn;
  2992. jack_midi_event_t event;
  2993. jack_time_t long long time;
  2994. // Is port created?
  2995. if ( jData->port == NULL ) return 0;
  2996. void *buff = jack_port_get_buffer( jData->port, nframes );
  2997. // We have midi events in buffer
  2998. int evCount = jack_midi_get_event_count( buff );
  2999. for (int j = 0; j < evCount; j++) {
  3000. MidiInApi::MidiMessage message;
  3001. message.bytes.clear();
  3002. jack_midi_event_get( &event, buff, j );
  3003. for ( unsigned int i = 0; i < event.size; i++ )
  3004. message.bytes.push_back( event.buffer[i] );
  3005. // Compute the delta time.
  3006. time = jack_get_time();
  3007. if ( rtData->firstMessage == true )
  3008. rtData->firstMessage = false;
  3009. else
  3010. message.timeStamp = ( time - jData->lastTime ) * 0.000001;
  3011. jData->lastTime = time;
  3012. if ( !rtData->continueSysex ) {
  3013. if ( rtData->usingCallback ) {
  3014. RtMidiIn::RtMidiCallback callback = (RtMidiIn::RtMidiCallback) rtData->userCallback;
  3015. callback( message.timeStamp, &message.bytes, rtData->userData );
  3016. }
  3017. else {
  3018. // As long as we haven't reached our queue size limit, push the message.
  3019. if ( rtData->queue.size < rtData->queue.ringSize ) {
  3020. rtData->queue.ring[rtData->queue.back++] = message;
  3021. if ( rtData->queue.back == rtData->queue.ringSize )
  3022. rtData->queue.back = 0;
  3023. rtData->queue.size++;
  3024. }
  3025. else
  3026. std::cerr << "\nMidiInJack: message queue limit reached!!\n\n";
  3027. }
  3028. }
  3029. }
  3030. return 0;
  3031. }
  3032. MidiInJack :: MidiInJack( const std::string clientName, unsigned int queueSizeLimit ) : MidiInApi( queueSizeLimit )
  3033. {
  3034. initialize( clientName );
  3035. }
  3036. void MidiInJack :: initialize( const std::string& clientName )
  3037. {
  3038. JackMidiData *data = new JackMidiData;
  3039. apiData_ = (void *) data;
  3040. data->rtMidiIn = &inputData_;
  3041. data->port = NULL;
  3042. data->client = NULL;
  3043. this->clientName = clientName;
  3044. connect();
  3045. }
  3046. void MidiInJack :: connect()
  3047. {
  3048. JackMidiData *data = static_cast<JackMidiData *> (apiData_);
  3049. if ( data->client )
  3050. return;
  3051. // Initialize JACK client
  3052. if (( data->client = jack_client_open( clientName.c_str(), JackNoStartServer, NULL )) == 0) {
  3053. errorString_ = "MidiInJack::initialize: JACK server not running?";
  3054. error( RtError::WARNING, errorString_ );
  3055. return;
  3056. }
  3057. jack_set_process_callback( data->client, jackProcessIn, data );
  3058. jack_activate( data->client );
  3059. }
  3060. MidiInJack :: ~MidiInJack()
  3061. {
  3062. JackMidiData *data = static_cast<JackMidiData *> (apiData_);
  3063. closePort();
  3064. if ( data->client )
  3065. jack_client_close( data->client );
  3066. delete data;
  3067. }
  3068. void MidiInJack :: openPort( unsigned int portNumber, const std::string portName )
  3069. {
  3070. JackMidiData *data = static_cast<JackMidiData *> (apiData_);
  3071. connect();
  3072. // Creating new port
  3073. if ( data->port == NULL)
  3074. data->port = jack_port_register( data->client, portName.c_str(),
  3075. JACK_DEFAULT_MIDI_TYPE, JackPortIsInput, 0 );
  3076. if ( data->port == NULL) {
  3077. errorString_ = "MidiInJack::openVirtualPort: JACK error creating virtual port";
  3078. error( RtMidiError::DRIVER_ERROR, errorString_ );
  3079. return;
  3080. }
  3081. // Connecting to the output
  3082. std::string name = getPortName( portNumber );
  3083. jack_connect( data->client, name.c_str(), jack_port_name( data->port ) );
  3084. }
  3085. void MidiInJack :: openVirtualPort( const std::string portName )
  3086. {
  3087. JackMidiData *data = static_cast<JackMidiData *> (apiData_);
  3088. connect();
  3089. if ( data->port == NULL )
  3090. data->port = jack_port_register( data->client, portName.c_str(),
  3091. JACK_DEFAULT_MIDI_TYPE, JackPortIsInput, 0 );
  3092. if ( data->port == NULL ) {
  3093. errorString_ = "MidiInJack::openVirtualPort: JACK error creating virtual port";
  3094. error( RtMidiError::DRIVER_ERROR, errorString_ );
  3095. }
  3096. }
  3097. unsigned int MidiInJack :: getPortCount()
  3098. {
  3099. int count = 0;
  3100. JackMidiData *data = static_cast<JackMidiData *> (apiData_);
  3101. connect();
  3102. if ( !data->client )
  3103. return 0;
  3104. // List of available ports
  3105. const char **ports = jack_get_ports( data->client, NULL, JACK_DEFAULT_MIDI_TYPE, JackPortIsOutput );
  3106. if ( ports == NULL ) return 0;
  3107. while ( ports[count] != NULL )
  3108. count++;
  3109. free( ports );
  3110. return count;
  3111. }
  3112. std::string MidiInJack :: getPortName( unsigned int portNumber )
  3113. {
  3114. JackMidiData *data = static_cast<JackMidiData *> (apiData_);
  3115. std::string retStr("");
  3116. connect();
  3117. // List of available ports
  3118. const char **ports = jack_get_ports( data->client, NULL,
  3119. JACK_DEFAULT_MIDI_TYPE, JackPortIsOutput );
  3120. // Check port validity
  3121. if ( ports == NULL ) {
  3122. errorString_ = "MidiInJack::getPortName: no ports available!";
  3123. error( RtMidiError::WARNING, errorString_ );
  3124. return retStr;
  3125. }
  3126. if ( ports[portNumber] == NULL ) {
  3127. std::ostringstream ost;
  3128. ost << "MidiInJack::getPortName: the 'portNumber' argument (" << portNumber << ") is invalid.";
  3129. errorString_ = ost.str();
  3130. error( RtMidiError::WARNING, errorString_ );
  3131. }
  3132. else retStr.assign( ports[portNumber] );
  3133. free( ports );
  3134. return retStr;
  3135. }
  3136. void MidiInJack :: closePort()
  3137. {
  3138. JackMidiData *data = static_cast<JackMidiData *> (apiData_);
  3139. if ( data->port == NULL ) return;
  3140. jack_port_unregister( data->client, data->port );
  3141. data->port = NULL;
  3142. }
  3143. //*********************************************************************//
  3144. // API: JACK
  3145. // Class Definitions: MidiOutJack
  3146. //*********************************************************************//
  3147. // Jack process callback
  3148. static int jackProcessOut( jack_nframes_t nframes, void *arg )
  3149. {
  3150. JackMidiData *data = (JackMidiData *) arg;
  3151. jack_midi_data_t *midiData;
  3152. int space;
  3153. // Is port created?
  3154. if ( data->port == NULL ) return 0;
  3155. void *buff = jack_port_get_buffer( data->port, nframes );
  3156. jack_midi_clear_buffer( buff );
  3157. while ( jack_ringbuffer_read_space( data->buffSize ) > 0 ) {
  3158. jack_ringbuffer_read( data->buffSize, (char *) &space, (size_t) sizeof(space) );
  3159. midiData = jack_midi_event_reserve( buff, 0, space );
  3160. jack_ringbuffer_read( data->buffMessage, (char *) midiData, (size_t) space );
  3161. }
  3162. return 0;
  3163. }
  3164. MidiOutJack :: MidiOutJack( const std::string clientName ) : MidiOutApi()
  3165. {
  3166. initialize( clientName );
  3167. }
  3168. void MidiOutJack :: initialize( const std::string& clientName )
  3169. {
  3170. JackMidiData *data = new JackMidiData;
  3171. apiData_ = (void *) data;
  3172. data->port = NULL;
  3173. data->client = NULL;
  3174. this->clientName = clientName;
  3175. connect();
  3176. }
  3177. void MidiOutJack :: connect()
  3178. {
  3179. JackMidiData *data = static_cast<JackMidiData *> (apiData_);
  3180. if ( data->client )
  3181. return;
  3182. // Initialize JACK client
  3183. if (( data->client = jack_client_open( clientName.c_str(), JackNoStartServer, NULL )) == 0) {
  3184. errorString_ = "MidiOutJack::initialize: JACK server not running?";
  3185. error( RtMidiError::WARNING, errorString_ );
  3186. return;
  3187. }
  3188. jack_set_process_callback( data->client, jackProcessOut, data );
  3189. data->buffSize = jack_ringbuffer_create( JACK_RINGBUFFER_SIZE );
  3190. data->buffMessage = jack_ringbuffer_create( JACK_RINGBUFFER_SIZE );
  3191. jack_activate( data->client );
  3192. }
  3193. MidiOutJack :: ~MidiOutJack()
  3194. {
  3195. JackMidiData *data = static_cast<JackMidiData *> (apiData_);
  3196. closePort();
  3197. if ( data->client ) {
  3198. // Cleanup
  3199. jack_client_close( data->client );
  3200. jack_ringbuffer_free( data->buffSize );
  3201. jack_ringbuffer_free( data->buffMessage );
  3202. }
  3203. delete data;
  3204. }
  3205. void MidiOutJack :: openPort( unsigned int portNumber, const std::string portName )
  3206. {
  3207. JackMidiData *data = static_cast<JackMidiData *> (apiData_);
  3208. connect();
  3209. // Creating new port
  3210. if ( data->port == NULL )
  3211. data->port = jack_port_register( data->client, portName.c_str(),
  3212. JACK_DEFAULT_MIDI_TYPE, JackPortIsOutput, 0 );
  3213. if ( data->port == NULL ) {
  3214. errorString_ = "MidiOutJack::openVirtualPort: JACK error creating virtual port";
  3215. error( RtMidiError::DRIVER_ERROR, errorString_ );
  3216. return;
  3217. }
  3218. // Connecting to the output
  3219. std::string name = getPortName( portNumber );
  3220. jack_connect( data->client, jack_port_name( data->port ), name.c_str() );
  3221. }
  3222. void MidiOutJack :: openVirtualPort( const std::string portName )
  3223. {
  3224. JackMidiData *data = static_cast<JackMidiData *> (apiData_);
  3225. connect();
  3226. if ( data->port == NULL )
  3227. data->port = jack_port_register( data->client, portName.c_str(),
  3228. JACK_DEFAULT_MIDI_TYPE, JackPortIsOutput, 0 );
  3229. if ( data->port == NULL ) {
  3230. errorString_ = "MidiOutJack::openVirtualPort: JACK error creating virtual port";
  3231. error( RtMidiError::DRIVER_ERROR, errorString_ );
  3232. }
  3233. }
  3234. unsigned int MidiOutJack :: getPortCount()
  3235. {
  3236. int count = 0;
  3237. JackMidiData *data = static_cast<JackMidiData *> (apiData_);
  3238. connect();
  3239. if ( !data->client )
  3240. return 0;
  3241. // List of available ports
  3242. const char **ports = jack_get_ports( data->client, NULL,
  3243. JACK_DEFAULT_MIDI_TYPE, JackPortIsInput );
  3244. if ( ports == NULL ) return 0;
  3245. while ( ports[count] != NULL )
  3246. count++;
  3247. free( ports );
  3248. return count;
  3249. }
  3250. std::string MidiOutJack :: getPortName( unsigned int portNumber )
  3251. {
  3252. JackMidiData *data = static_cast<JackMidiData *> (apiData_);
  3253. std::string retStr("");
  3254. connect();
  3255. // List of available ports
  3256. const char **ports = jack_get_ports( data->client, NULL,
  3257. JACK_DEFAULT_MIDI_TYPE, JackPortIsInput );
  3258. // Check port validity
  3259. if ( ports == NULL) {
  3260. errorString_ = "MidiOutJack::getPortName: no ports available!";
  3261. error( RtMidiError::WARNING, errorString_ );
  3262. return retStr;
  3263. }
  3264. if ( ports[portNumber] == NULL) {
  3265. std::ostringstream ost;
  3266. ost << "MidiOutJack::getPortName: the 'portNumber' argument (" << portNumber << ") is invalid.";
  3267. errorString_ = ost.str();
  3268. error( RtMidiError::WARNING, errorString_ );
  3269. }
  3270. else retStr.assign( ports[portNumber] );
  3271. free( ports );
  3272. return retStr;
  3273. }
  3274. void MidiOutJack :: closePort()
  3275. {
  3276. JackMidiData *data = static_cast<JackMidiData *> (apiData_);
  3277. if ( data->port == NULL ) return;
  3278. jack_port_unregister( data->client, data->port );
  3279. data->port = NULL;
  3280. }
  3281. void MidiOutJack :: sendMessage( std::vector<unsigned char> *message )
  3282. {
  3283. int nBytes = message->size();
  3284. JackMidiData *data = static_cast<JackMidiData *> (apiData_);
  3285. // Write full message to buffer
  3286. jack_ringbuffer_write( data->buffMessage, ( const char * ) &( *message )[0],
  3287. message->size() );
  3288. jack_ringbuffer_write( data->buffSize, ( char * ) &nBytes, sizeof( nBytes ) );
  3289. }
  3290. #endif // __UNIX_JACK__