You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

RtMidi.cpp 109KB

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