RtMidi.cpp 111 KB

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