RtMidi.cpp 119 KB

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