RtMidi.cpp 124 KB

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