Audio plugin host https://kx.studio/carla
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

CarlaEngineJack.cpp 113KB

11 years ago
9 years ago
11 years ago
10 years ago
11 years ago
10 years ago
11 years ago
10 years ago
10 years ago
11 years ago
11 years ago
10 years ago
11 years ago
11 years ago
10 years ago
11 years ago
11 years ago
11 years ago
11 years ago
10 years ago
11 years ago
10 years ago
11 years ago
11 years ago
10 years ago
11 years ago
11 years ago
11 years ago
10 years ago
11 years ago
10 years ago
11 years ago
11 years ago
11 years ago
10 years ago
11 years ago
11 years ago
11 years ago
10 years ago
11 years ago
11 years ago
10 years ago
10 years ago
10 years ago
11 years ago
10 years ago
11 years ago
10 years ago
10 years ago
11 years ago
10 years ago
11 years ago
11 years ago
11 years ago
10 years ago
11 years ago
11 years ago
10 years ago
10 years ago
11 years ago
11 years ago
11 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
11 years ago
11 years ago
11 years ago
10 years ago
11 years ago
11 years ago
11 years ago
11 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
6 years ago
10 years ago
10 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
10 years ago
10 years ago
5 years ago
11 years ago
6 years ago
11 years ago
10 years ago
10 years ago
10 years ago
10 years ago
6 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
11 years ago
10 years ago
10 years ago
10 years ago
11 years ago
10 years ago
10 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
6 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
11 years ago
11 years ago
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230
  1. /*
  2. * Carla Plugin Host
  3. * Copyright (C) 2011-2019 Filipe Coelho <falktx@falktx.com>
  4. *
  5. * This program is free software; you can redistribute it and/or
  6. * modify it under the terms of the GNU General Public License as
  7. * published by the Free Software Foundation; either version 2 of
  8. * the License, or any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * For a full copy of the GNU General Public License see the doc/GPL.txt file.
  16. */
  17. #include "CarlaEngineInternal.hpp"
  18. #include "CarlaPlugin.hpp"
  19. #include "CarlaBackendUtils.hpp"
  20. #include "CarlaEngineUtils.hpp"
  21. #include "CarlaMathUtils.hpp"
  22. #include "CarlaMIDI.h"
  23. #include "CarlaPatchbayUtils.hpp"
  24. #include "CarlaStringList.hpp"
  25. #include "jackey.h"
  26. #ifdef USING_JUCE
  27. # if defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6))
  28. # pragma GCC diagnostic push
  29. # pragma GCC diagnostic ignored "-Wconversion"
  30. # pragma GCC diagnostic ignored "-Weffc++"
  31. # pragma GCC diagnostic ignored "-Wsign-conversion"
  32. # pragma GCC diagnostic ignored "-Wundef"
  33. # endif
  34. # include "AppConfig.h"
  35. # include "juce_events/juce_events.h"
  36. # if defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6))
  37. # pragma GCC diagnostic pop
  38. # endif
  39. #endif
  40. #ifdef __SSE2_MATH__
  41. # include <xmmintrin.h>
  42. #endif
  43. // must be last
  44. #include "jackbridge/JackBridge.hpp"
  45. #define URI_CANVAS_ICON "http://kxstudio.sf.net/ns/canvas/icon"
  46. CARLA_BACKEND_START_NAMESPACE
  47. class CarlaEngineJack;
  48. class CarlaEngineJackClient;
  49. // -----------------------------------------------------------------------
  50. // Fallback data
  51. static const EngineEvent kFallbackJackEngineEvent = { kEngineEventTypeNull, 0, 0, {{ kEngineControlEventTypeNull, 0, 0.0f }} };
  52. static CarlaEngineEventCV kFallbackEngineEventCV = { nullptr, (uint32_t)-1, 0.0f };
  53. // -----------------------------------------------------------------------
  54. // Carla Engine Port removal helper
  55. class CarlaEngineJackAudioPort;
  56. class CarlaEngineJackCVPort;
  57. class CarlaEngineJackEventPort;
  58. struct JackPortDeletionCallback {
  59. virtual ~JackPortDeletionCallback() noexcept {}
  60. virtual void jackAudioPortDeleted(CarlaEngineJackAudioPort* const) noexcept = 0;
  61. virtual void jackCVPortDeleted(CarlaEngineJackCVPort* const) noexcept = 0;
  62. virtual void jackEventPortDeleted(CarlaEngineJackEventPort* const) noexcept = 0;
  63. };
  64. // -----------------------------------------------------------------------
  65. // Carla Engine JACK-Audio port
  66. class CarlaEngineJackAudioPort : public CarlaEngineAudioPort
  67. {
  68. public:
  69. CarlaEngineJackAudioPort(const CarlaEngineClient& client, const bool isInputPort, const uint32_t indexOffset, jack_client_t* const jackClient, jack_port_t* const jackPort, JackPortDeletionCallback* const delCallback) noexcept
  70. : CarlaEngineAudioPort(client, isInputPort, indexOffset),
  71. fJackClient(jackClient),
  72. fJackPort(jackPort),
  73. kDeletionCallback(delCallback)
  74. {
  75. carla_debug("CarlaEngineJackAudioPort::CarlaEngineJackAudioPort(%s, %p, %p)", bool2str(isInputPort), jackClient, jackPort);
  76. switch (kClient.getEngine().getProccessMode())
  77. {
  78. case ENGINE_PROCESS_MODE_SINGLE_CLIENT:
  79. case ENGINE_PROCESS_MODE_MULTIPLE_CLIENTS:
  80. CARLA_SAFE_ASSERT_RETURN(jackClient != nullptr && jackPort != nullptr,);
  81. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  82. if (const jack_uuid_t uuid = jackbridge_port_uuid(jackPort))
  83. jackbridge_set_property(jackClient, uuid, JACKEY_SIGNAL_TYPE, "AUDIO", "text/plain");
  84. #endif
  85. break;
  86. default:
  87. CARLA_SAFE_ASSERT(jackClient == nullptr && jackPort == nullptr);
  88. break;
  89. }
  90. }
  91. ~CarlaEngineJackAudioPort() noexcept override
  92. {
  93. carla_debug("CarlaEngineJackAudioPort::~CarlaEngineJackAudioPort()");
  94. if (fJackClient != nullptr && fJackPort != nullptr)
  95. {
  96. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  97. try {
  98. if (const jack_uuid_t uuid = jackbridge_port_uuid(fJackPort))
  99. jackbridge_remove_property(fJackClient, uuid, JACKEY_SIGNAL_TYPE);
  100. } CARLA_SAFE_EXCEPTION("Audio port remove meta type");
  101. #endif
  102. try {
  103. jackbridge_port_unregister(fJackClient, fJackPort);
  104. } CARLA_SAFE_EXCEPTION("Audio port unregister");
  105. fJackClient = nullptr;
  106. fJackPort = nullptr;
  107. }
  108. if (kDeletionCallback != nullptr)
  109. kDeletionCallback->jackAudioPortDeleted(this);
  110. }
  111. void initBuffer() noexcept override
  112. {
  113. if (fJackPort == nullptr)
  114. return CarlaEngineAudioPort::initBuffer();
  115. const uint32_t bufferSize(kClient.getEngine().getBufferSize());
  116. try {
  117. fBuffer = (float*)jackbridge_port_get_buffer(fJackPort, bufferSize);
  118. }
  119. catch(...) {
  120. fBuffer = nullptr;
  121. return;
  122. }
  123. if (! kIsInput)
  124. carla_zeroFloats(fBuffer, bufferSize);
  125. }
  126. void invalidate() noexcept
  127. {
  128. fJackClient = nullptr;
  129. fJackPort = nullptr;
  130. }
  131. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  132. void setMetaData(const char* const key, const char* const value, const char* const type) override
  133. {
  134. try {
  135. if (const jack_uuid_t uuid = jackbridge_port_uuid(fJackPort))
  136. jackbridge_set_property(fJackClient, uuid, key, value, type);
  137. } CARLA_SAFE_EXCEPTION("Port setMetaData");
  138. }
  139. #endif
  140. private:
  141. jack_client_t* fJackClient;
  142. jack_port_t* fJackPort;
  143. JackPortDeletionCallback* const kDeletionCallback;
  144. friend class CarlaEngineJackClient;
  145. CARLA_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(CarlaEngineJackAudioPort)
  146. };
  147. // -----------------------------------------------------------------------
  148. // Carla Engine JACK-CV port
  149. class CarlaEngineJackCVPort : public CarlaEngineCVPort
  150. {
  151. public:
  152. CarlaEngineJackCVPort(const CarlaEngineClient& client, const bool isInputPort, const uint32_t indexOffset, jack_client_t* const jackClient, jack_port_t* const jackPort, JackPortDeletionCallback* const delCallback) noexcept
  153. : CarlaEngineCVPort(client, isInputPort, indexOffset),
  154. fJackClient(jackClient),
  155. fJackPort(jackPort),
  156. kDeletionCallback(delCallback)
  157. {
  158. carla_debug("CarlaEngineJackCVPort::CarlaEngineJackCVPort(%s, %p, %p)", bool2str(isInputPort), jackClient, jackPort);
  159. switch (kClient.getEngine().getProccessMode())
  160. {
  161. case ENGINE_PROCESS_MODE_SINGLE_CLIENT:
  162. case ENGINE_PROCESS_MODE_MULTIPLE_CLIENTS:
  163. CARLA_SAFE_ASSERT_RETURN(jackClient != nullptr && jackPort != nullptr,);
  164. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  165. if (const jack_uuid_t uuid = jackbridge_port_uuid(jackPort))
  166. jackbridge_set_property(jackClient, uuid, JACKEY_SIGNAL_TYPE, "CV", "text/plain");
  167. #endif
  168. break;
  169. default:
  170. CARLA_SAFE_ASSERT(jackClient == nullptr && jackPort == nullptr);
  171. break;
  172. }
  173. }
  174. ~CarlaEngineJackCVPort() noexcept override
  175. {
  176. carla_debug("CarlaEngineJackCVPort::~CarlaEngineJackCVPort()");
  177. if (fJackClient != nullptr && fJackPort != nullptr)
  178. {
  179. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  180. try {
  181. if (const jack_uuid_t uuid = jackbridge_port_uuid(fJackPort))
  182. jackbridge_remove_property(fJackClient, uuid, JACKEY_SIGNAL_TYPE);
  183. } CARLA_SAFE_EXCEPTION("CV port remove meta type");
  184. #endif
  185. try {
  186. jackbridge_port_unregister(fJackClient, fJackPort);
  187. } CARLA_SAFE_EXCEPTION("CV port unregister");
  188. fJackClient = nullptr;
  189. fJackPort = nullptr;
  190. }
  191. if (kDeletionCallback != nullptr)
  192. kDeletionCallback->jackCVPortDeleted(this);
  193. }
  194. void initBuffer() noexcept override
  195. {
  196. if (fJackPort == nullptr)
  197. return CarlaEngineCVPort::initBuffer();
  198. const uint32_t bufferSize(kClient.getEngine().getBufferSize());
  199. try {
  200. fBuffer = (float*)jackbridge_port_get_buffer(fJackPort, bufferSize);
  201. }
  202. catch(...) {
  203. fBuffer = nullptr;
  204. return;
  205. }
  206. if (! kIsInput)
  207. carla_zeroFloats(fBuffer, bufferSize);
  208. }
  209. void invalidate() noexcept
  210. {
  211. fJackClient = nullptr;
  212. fJackPort = nullptr;
  213. }
  214. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  215. void setMetaData(const char* const key, const char* const value, const char* const type) override
  216. {
  217. try {
  218. if (const jack_uuid_t uuid = jackbridge_port_uuid(fJackPort))
  219. jackbridge_set_property(fJackClient, uuid, key, value, type);
  220. } CARLA_SAFE_EXCEPTION("Port setMetaData");
  221. }
  222. #endif
  223. private:
  224. jack_client_t* fJackClient;
  225. jack_port_t* fJackPort;
  226. JackPortDeletionCallback* const kDeletionCallback;
  227. friend class CarlaEngineJackClient;
  228. CARLA_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(CarlaEngineJackCVPort)
  229. };
  230. // -----------------------------------------------------------------------
  231. // Carla Engine JACK-Event port
  232. class CarlaEngineJackEventPort : public CarlaEngineEventPort
  233. {
  234. public:
  235. CarlaEngineJackEventPort(const CarlaEngineClient& client, const bool isInputPort, const uint32_t indexOffset, jack_client_t* const jackClient, jack_port_t* const jackPort, JackPortDeletionCallback* const delCallback) noexcept
  236. : CarlaEngineEventPort(client, isInputPort, indexOffset),
  237. fJackClient(jackClient),
  238. fJackPort(jackPort),
  239. fJackBuffer(nullptr),
  240. fBufferMutex(),
  241. fNumCvEvents(0),
  242. fRetEvent(kFallbackJackEngineEvent),
  243. kDeletionCallback(delCallback)
  244. {
  245. carla_debug("CarlaEngineJackEventPort::CarlaEngineJackEventPort(%s, %p, %p)", bool2str(isInputPort), jackClient, jackPort);
  246. switch (kClient.getEngine().getProccessMode())
  247. {
  248. case ENGINE_PROCESS_MODE_SINGLE_CLIENT:
  249. case ENGINE_PROCESS_MODE_MULTIPLE_CLIENTS:
  250. CARLA_SAFE_ASSERT_RETURN(jackClient != nullptr && jackPort != nullptr,);
  251. break;
  252. default:
  253. CARLA_SAFE_ASSERT(jackClient == nullptr && jackPort == nullptr);
  254. break;
  255. }
  256. }
  257. ~CarlaEngineJackEventPort() noexcept override
  258. {
  259. carla_debug("CarlaEngineJackEventPort::~CarlaEngineJackEventPort()");
  260. if (fJackClient != nullptr && fJackPort != nullptr)
  261. {
  262. try {
  263. jackbridge_port_unregister(fJackClient, fJackPort);
  264. } CARLA_SAFE_EXCEPTION("Event port unregister");
  265. fJackClient = nullptr;
  266. fJackPort = nullptr;
  267. }
  268. if (kDeletionCallback != nullptr)
  269. kDeletionCallback->jackEventPortDeleted(this);
  270. }
  271. void initBuffer() noexcept override
  272. {
  273. if (fJackPort == nullptr)
  274. return CarlaEngineEventPort::initBuffer();
  275. fNumCvEvents = 0;
  276. try {
  277. fJackBuffer = jackbridge_port_get_buffer(fJackPort, kClient.getEngine().getBufferSize());
  278. }
  279. catch(...) {
  280. fJackBuffer = nullptr;
  281. return;
  282. }
  283. if (! kIsInput)
  284. jackbridge_midi_clear_buffer(fJackBuffer);
  285. initCvBuffers();
  286. }
  287. bool addCVSource(CarlaEngineCVPort* const port, const uint32_t portIndexOffset) noexcept override
  288. {
  289. if (! CarlaEngineEventPort::addCVSource(port, portIndexOffset))
  290. return false;
  291. if (fJackPort == nullptr)
  292. return true;
  293. if (pData->cvs.count() != 1 || pData->needsBufferDeletion)
  294. return true;
  295. if (pData->processMode != ENGINE_PROCESS_MODE_SINGLE_CLIENT && pData->processMode != ENGINE_PROCESS_MODE_MULTIPLE_CLIENTS)
  296. return true;
  297. CARLA_SAFE_ASSERT_RETURN(pData->buffer == nullptr, true);
  298. EngineEvent* const buffer = new EngineEvent[kMaxEngineEventInternalCount];
  299. carla_zeroStructs(buffer, kMaxEngineEventInternalCount);
  300. {
  301. const CarlaMutexLocker cml(fBufferMutex);
  302. pData->buffer = buffer;
  303. }
  304. pData->needsBufferDeletion = true;
  305. return true;
  306. }
  307. bool removeCVSource(const uint32_t portIndexOffset) noexcept override
  308. {
  309. if (! CarlaEngineEventPort::removeCVSource(portIndexOffset))
  310. return false;
  311. if (fJackPort == nullptr)
  312. return true;
  313. if (pData->cvs.count() != 0 || ! pData->needsBufferDeletion)
  314. return true;
  315. if (pData->processMode != ENGINE_PROCESS_MODE_SINGLE_CLIENT && pData->processMode != ENGINE_PROCESS_MODE_MULTIPLE_CLIENTS)
  316. return true;
  317. EngineEvent* const buffer = pData->buffer;
  318. CARLA_SAFE_ASSERT_RETURN(buffer != nullptr, true);
  319. {
  320. const CarlaMutexLocker cml(fBufferMutex);
  321. pData->buffer = nullptr;
  322. }
  323. delete[] buffer;
  324. pData->needsBufferDeletion = false;
  325. return true;
  326. }
  327. void mixWithCvBuffer(const float* const buffer, const uint32_t frames, const uint32_t indexOffset) noexcept override
  328. {
  329. if (fJackPort == nullptr)
  330. return CarlaEngineEventPort::mixWithCvBuffer(buffer, frames, indexOffset);
  331. CARLA_SAFE_ASSERT_RETURN(fJackBuffer != nullptr,);
  332. CARLA_SAFE_ASSERT_RETURN(buffer != nullptr,);
  333. const CarlaMutexLocker cml(fBufferMutex);
  334. EngineEvent* const eventBuffer = pData->buffer;
  335. CARLA_SAFE_ASSERT_RETURN(eventBuffer != nullptr,);
  336. uint32_t eventIndex = 0;
  337. float v, min, max;
  338. for (LinkedList<CarlaEngineEventCV>::Itenerator it = pData->cvs.begin2(); it.valid(); it.next())
  339. {
  340. CarlaEngineEventCV& ecv(it.getValue(kFallbackEngineEventCV));
  341. if (ecv.indexOffset != indexOffset)
  342. continue;
  343. CARLA_SAFE_ASSERT_RETURN(ecv.cvPort != nullptr,);
  344. float previousValue = ecv.previousValue;
  345. ecv.cvPort->getRange(min, max);
  346. for (uint32_t i=0; i<1/*frames*/; i+=32)
  347. {
  348. v = buffer[i];
  349. if (carla_isNotEqual(v, previousValue))
  350. {
  351. previousValue = v;
  352. EngineEvent& event(eventBuffer[eventIndex++]);
  353. event.type = kEngineEventTypeControl;
  354. event.time = i;
  355. event.channel = kEngineEventNonMidiChannel;
  356. event.ctrl.type = kEngineControlEventTypeParameter;
  357. event.ctrl.param = static_cast<uint16_t>(indexOffset);
  358. event.ctrl.value = carla_fixedValue(0.0f, 1.0f, (v - min) / (max - min));
  359. }
  360. }
  361. ecv.previousValue = previousValue;
  362. break;
  363. }
  364. if (eventIndex != kMaxEngineEventInternalCount)
  365. eventBuffer[eventIndex].type = kEngineEventTypeNull;
  366. fNumCvEvents = eventIndex;
  367. }
  368. uint32_t getEventCount() const noexcept override
  369. {
  370. if (fJackPort == nullptr)
  371. return CarlaEngineEventPort::getEventCount();
  372. CARLA_SAFE_ASSERT_RETURN(kIsInput, 0);
  373. CARLA_SAFE_ASSERT_RETURN(fJackBuffer != nullptr, 0);
  374. try {
  375. return fNumCvEvents + jackbridge_midi_get_event_count(fJackBuffer);
  376. } CARLA_SAFE_EXCEPTION_RETURN("jack_midi_get_event_count", 0);
  377. }
  378. const EngineEvent& getEvent(const uint32_t index) const noexcept override
  379. {
  380. if (fJackPort == nullptr)
  381. return CarlaEngineEventPort::getEvent(index);
  382. CARLA_SAFE_ASSERT_RETURN(kIsInput, kFallbackJackEngineEvent);
  383. CARLA_SAFE_ASSERT_RETURN(fJackBuffer != nullptr, kFallbackJackEngineEvent);
  384. return getEventUnchecked(index);
  385. }
  386. const EngineEvent& getEventUnchecked(uint32_t index) const noexcept override
  387. {
  388. if (EngineEvent* const eventBuffer = pData->buffer)
  389. {
  390. const CarlaMutexLocker cml(fBufferMutex);
  391. if (index < fNumCvEvents)
  392. return pData->buffer[index];
  393. index -= fNumCvEvents;
  394. }
  395. jack_midi_event_t jackEvent;
  396. bool test = false;
  397. try {
  398. test = jackbridge_midi_event_get(&jackEvent, fJackBuffer, index);
  399. } CARLA_SAFE_EXCEPTION_RETURN("jack_midi_event_get", kFallbackJackEngineEvent);
  400. if (! test)
  401. return kFallbackJackEngineEvent;
  402. CARLA_SAFE_ASSERT_RETURN(jackEvent.size < 0xFF /* uint8_t max */, kFallbackJackEngineEvent);
  403. uint8_t port;
  404. if (kIndexOffset < 0xFF /* uint8_t max */)
  405. {
  406. port = static_cast<uint8_t>(kIndexOffset);
  407. }
  408. else
  409. {
  410. port = 0;
  411. carla_safe_assert_uint("kIndexOffset < 0xFF", __FILE__, __LINE__, kIndexOffset);
  412. }
  413. fRetEvent.time = jackEvent.time;
  414. fRetEvent.fillFromMidiData(static_cast<uint8_t>(jackEvent.size), jackEvent.buffer, port);
  415. return fRetEvent;
  416. }
  417. bool writeControlEvent(const uint32_t time, const uint8_t channel, const EngineControlEventType type, const uint16_t param, const float value) noexcept override
  418. {
  419. if (fJackPort == nullptr)
  420. return CarlaEngineEventPort::writeControlEvent(time, channel, type, param, value);
  421. CARLA_SAFE_ASSERT_RETURN(! kIsInput, false);
  422. CARLA_SAFE_ASSERT_RETURN(fJackBuffer != nullptr, false);
  423. CARLA_SAFE_ASSERT_RETURN(type != kEngineControlEventTypeNull, false);
  424. CARLA_SAFE_ASSERT_RETURN(channel < MAX_MIDI_CHANNELS, false);
  425. CARLA_SAFE_ASSERT_RETURN(param < MAX_MIDI_CONTROL, false);
  426. CARLA_SAFE_ASSERT(value >= 0.0f && value <= 1.0f);
  427. if (type == kEngineControlEventTypeParameter) {
  428. CARLA_SAFE_ASSERT(! MIDI_IS_CONTROL_BANK_SELECT(param));
  429. }
  430. uint8_t data[3] = { 0, 0, 0 };
  431. EngineControlEvent ctrlEvent = { type, param, value };
  432. const uint8_t size = ctrlEvent.convertToMidiData(channel, data);
  433. if (size == 0)
  434. return false;
  435. try {
  436. return jackbridge_midi_event_write(fJackBuffer, time, data, size);
  437. } CARLA_SAFE_EXCEPTION_RETURN("jack_midi_event_write", false);
  438. }
  439. bool writeMidiEvent(const uint32_t time, const uint8_t channel, const uint8_t size, const uint8_t* const data) noexcept override
  440. {
  441. if (fJackPort == nullptr)
  442. return CarlaEngineEventPort::writeMidiEvent(time, channel, size, data);
  443. CARLA_SAFE_ASSERT_RETURN(! kIsInput, false);
  444. CARLA_SAFE_ASSERT_RETURN(fJackBuffer != nullptr, false);
  445. CARLA_SAFE_ASSERT_RETURN(channel < MAX_MIDI_CHANNELS, false);
  446. CARLA_SAFE_ASSERT_RETURN(size > 0, false);
  447. CARLA_SAFE_ASSERT_RETURN(data != nullptr, false);
  448. jack_midi_data_t jdata[size];
  449. jdata[0] = static_cast<jack_midi_data_t>(MIDI_GET_STATUS_FROM_DATA(data) + channel);
  450. for (uint8_t i=1; i < size; ++i)
  451. jdata[i] = data[i];
  452. try {
  453. return jackbridge_midi_event_write(fJackBuffer, time, jdata, size);
  454. } CARLA_SAFE_EXCEPTION_RETURN("jack_midi_event_write", false);
  455. }
  456. void invalidate() noexcept
  457. {
  458. fJackClient = nullptr;
  459. fJackPort = nullptr;
  460. }
  461. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  462. void setMetaData(const char* const key, const char* const value, const char* const type) override
  463. {
  464. try {
  465. if (const jack_uuid_t uuid = jackbridge_port_uuid(fJackPort))
  466. jackbridge_set_property(fJackClient, uuid, key, value, type);
  467. } CARLA_SAFE_EXCEPTION("Port setMetaData");
  468. }
  469. #endif
  470. private:
  471. jack_client_t* fJackClient;
  472. jack_port_t* fJackPort;
  473. void* fJackBuffer;
  474. // protect races of pData->buffer usage
  475. CarlaMutex fBufferMutex;
  476. uint32_t fNumCvEvents;
  477. mutable EngineEvent fRetEvent;
  478. JackPortDeletionCallback* const kDeletionCallback;
  479. friend class CarlaEngineJackClient;
  480. CARLA_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(CarlaEngineJackEventPort)
  481. };
  482. // -----------------------------------------------------------------------
  483. // Jack Engine client
  484. class CarlaEngineJackClient : public CarlaEngineClient,
  485. private JackPortDeletionCallback
  486. {
  487. public:
  488. CarlaEngineJackClient(const CarlaEngine& engine, jack_client_t* const jackClient)
  489. : CarlaEngineClient(engine),
  490. fJackClient(jackClient),
  491. fUseClient(engine.getProccessMode() == ENGINE_PROCESS_MODE_SINGLE_CLIENT || engine.getProccessMode() == ENGINE_PROCESS_MODE_MULTIPLE_CLIENTS),
  492. fAudioPorts(),
  493. fCVPorts(),
  494. fEventPorts(),
  495. fPreRenameMutex(),
  496. fPreRenameConnections()
  497. {
  498. carla_debug("CarlaEngineJackClient::CarlaEngineJackClient(%p)", jackClient);
  499. if (fUseClient)
  500. {
  501. CARLA_SAFE_ASSERT(jackClient != nullptr);
  502. }
  503. else
  504. {
  505. CARLA_SAFE_ASSERT(jackClient == nullptr);
  506. }
  507. }
  508. ~CarlaEngineJackClient() noexcept override
  509. {
  510. carla_debug("CarlaEngineJackClient::~CarlaEngineJackClient()");
  511. if (getProcessMode() == ENGINE_PROCESS_MODE_MULTIPLE_CLIENTS && fJackClient != nullptr) // FIXME
  512. jackbridge_client_close(fJackClient);
  513. // ports must have been deleted by now!
  514. //fAudioPorts.clear();
  515. //fCVPorts.clear();
  516. //fEventPorts.clear();
  517. }
  518. void activate() noexcept override
  519. {
  520. carla_debug("CarlaEngineJackClient::activate()");
  521. if (getProcessMode() == ENGINE_PROCESS_MODE_MULTIPLE_CLIENTS)
  522. {
  523. CARLA_SAFE_ASSERT_RETURN(fJackClient != nullptr && ! isActive(),);
  524. try {
  525. jackbridge_activate(fJackClient);
  526. } catch(...) {}
  527. }
  528. CarlaEngineClient::activate();
  529. const CarlaMutexLocker cml(fPreRenameMutex);
  530. if (fJackClient != nullptr)
  531. {
  532. // restore pre-rename connections
  533. const char* portNameA = nullptr;
  534. const char* portNameB = nullptr;
  535. bool doConnection = false;
  536. for (CarlaStringList::Itenerator it = fPreRenameConnections.begin2(); it.valid(); it.next())
  537. {
  538. const bool connectNow = doConnection;
  539. doConnection = !doConnection;
  540. if (connectNow)
  541. portNameB = it.getValue(nullptr);
  542. else
  543. portNameA = it.getValue(nullptr);
  544. if (! connectNow)
  545. continue;
  546. CARLA_SAFE_ASSERT_CONTINUE(portNameA != nullptr && portNameA[0] != '\0');
  547. CARLA_SAFE_ASSERT_CONTINUE(portNameB != nullptr && portNameB[0] != '\0');
  548. jackbridge_connect(fJackClient, portNameA, portNameB);
  549. }
  550. }
  551. fPreRenameConnections.clear();
  552. }
  553. void deactivate() noexcept override
  554. {
  555. carla_debug("CarlaEngineJackClient::deactivate()");
  556. if (getProcessMode() == ENGINE_PROCESS_MODE_MULTIPLE_CLIENTS)
  557. {
  558. CARLA_SAFE_ASSERT_RETURN(fJackClient != nullptr && isActive(),);
  559. try {
  560. jackbridge_deactivate(fJackClient);
  561. } catch(...) {}
  562. }
  563. CarlaEngineClient::deactivate();
  564. }
  565. bool isOk() const noexcept override
  566. {
  567. if (fUseClient)
  568. return (fJackClient != nullptr);
  569. return CarlaEngineClient::isOk();
  570. }
  571. CarlaEnginePort* addPort(const EnginePortType portType, const char* const name, const bool isInput, const uint32_t indexOffset) override
  572. {
  573. carla_debug("CarlaEngineJackClient::addPort(%i:%s, \"%s\", %s)", portType, EnginePortType2Str(portType), name, bool2str(isInput));
  574. jack_port_t* jackPort = nullptr;
  575. const char* realName = name;
  576. // Create JACK port first, if needed
  577. if (fUseClient)
  578. {
  579. CARLA_SAFE_ASSERT_RETURN(fJackClient != nullptr, nullptr);
  580. realName = _getUniquePortName(name);
  581. switch (portType)
  582. {
  583. case kEnginePortTypeNull:
  584. break;
  585. case kEnginePortTypeAudio:
  586. jackPort = jackbridge_port_register(fJackClient, realName, JACK_DEFAULT_AUDIO_TYPE, isInput ? JackPortIsInput : JackPortIsOutput, 0);
  587. break;
  588. case kEnginePortTypeCV:
  589. jackPort = jackbridge_port_register(fJackClient, realName, JACK_DEFAULT_AUDIO_TYPE, isInput ? JackPortIsInput : JackPortIsOutput, 0);
  590. break;
  591. case kEnginePortTypeEvent:
  592. jackPort = jackbridge_port_register(fJackClient, realName, JACK_DEFAULT_MIDI_TYPE, isInput ? JackPortIsInput : JackPortIsOutput, 0);
  593. break;
  594. }
  595. CARLA_SAFE_ASSERT_RETURN(jackPort != nullptr, nullptr);
  596. }
  597. // Create Engine port
  598. switch (portType)
  599. {
  600. case kEnginePortTypeNull:
  601. break;
  602. case kEnginePortTypeAudio: {
  603. _addAudioPortName(isInput, realName);
  604. if (realName != name) delete[] realName;
  605. CarlaEngineJackAudioPort* const enginePort(new CarlaEngineJackAudioPort(*this, isInput, indexOffset, fJackClient, jackPort, this));
  606. fAudioPorts.append(enginePort);
  607. return enginePort;
  608. }
  609. case kEnginePortTypeCV: {
  610. _addCVPortName(isInput, realName);
  611. if (realName != name) delete[] realName;
  612. CarlaEngineJackCVPort* const enginePort(new CarlaEngineJackCVPort(*this, isInput, indexOffset, fJackClient, jackPort, this));
  613. fCVPorts.append(enginePort);
  614. return enginePort;
  615. }
  616. case kEnginePortTypeEvent: {
  617. _addEventPortName(isInput, realName);
  618. if (realName != name) delete[] realName;
  619. CarlaEngineJackEventPort* const enginePort(new CarlaEngineJackEventPort(*this, isInput, indexOffset, fJackClient, jackPort, this));
  620. fEventPorts.append(enginePort);
  621. return enginePort;
  622. }
  623. }
  624. carla_stderr("CarlaEngineJackClient::addPort(%i, \"%s\", %s) - invalid type", portType, name, bool2str(isInput));
  625. return nullptr;
  626. }
  627. void invalidate() noexcept
  628. {
  629. for (LinkedList<CarlaEngineJackAudioPort*>::Itenerator it = fAudioPorts.begin2(); it.valid(); it.next())
  630. {
  631. CarlaEngineJackAudioPort* const port(it.getValue(nullptr));
  632. CARLA_SAFE_ASSERT_CONTINUE(port != nullptr);
  633. port->invalidate();
  634. }
  635. for (LinkedList<CarlaEngineJackCVPort*>::Itenerator it = fCVPorts.begin2(); it.valid(); it.next())
  636. {
  637. CarlaEngineJackCVPort* const port(it.getValue(nullptr));
  638. CARLA_SAFE_ASSERT_CONTINUE(port != nullptr);
  639. port->invalidate();
  640. }
  641. for (LinkedList<CarlaEngineJackEventPort*>::Itenerator it = fEventPorts.begin2(); it.valid(); it.next())
  642. {
  643. CarlaEngineJackEventPort* const port(it.getValue(nullptr));
  644. CARLA_SAFE_ASSERT_CONTINUE(port != nullptr);
  645. port->invalidate();
  646. }
  647. fJackClient = nullptr;
  648. CarlaEngineClient::deactivate();
  649. }
  650. const char* getJackClientName() const noexcept
  651. {
  652. CARLA_SAFE_ASSERT_RETURN(fJackClient != nullptr, nullptr);
  653. try {
  654. return jackbridge_get_client_name(fJackClient);
  655. } CARLA_SAFE_EXCEPTION_RETURN("jack_get_client_name", nullptr);
  656. }
  657. void jackAudioPortDeleted(CarlaEngineJackAudioPort* const port) noexcept override
  658. {
  659. fAudioPorts.removeAll(port);
  660. }
  661. void jackCVPortDeleted(CarlaEngineJackCVPort* const port) noexcept override
  662. {
  663. fCVPorts.removeAll(port);
  664. }
  665. void jackEventPortDeleted(CarlaEngineJackEventPort* const port) noexcept override
  666. {
  667. fEventPorts.removeAll(port);
  668. }
  669. bool renameInSingleClient(const CarlaString& newClientName)
  670. {
  671. const CarlaString clientNamePrefix(newClientName + ":");
  672. return _renamePorts(fAudioPorts, clientNamePrefix) &&
  673. _renamePorts(fCVPorts, clientNamePrefix) &&
  674. _renamePorts(fEventPorts, clientNamePrefix);
  675. }
  676. void closeForRename(jack_client_t* const newClient, const CarlaString& newClientName) noexcept
  677. {
  678. if (fJackClient != nullptr)
  679. {
  680. if (isActive())
  681. {
  682. {
  683. const CarlaString clientNamePrefix(newClientName + ":");
  684. // store current client connections
  685. const CarlaMutexLocker cml(fPreRenameMutex);
  686. fPreRenameConnections.clear();
  687. _savePortsConnections(fAudioPorts, clientNamePrefix);
  688. _savePortsConnections(fCVPorts, clientNamePrefix);
  689. _savePortsConnections(fEventPorts, clientNamePrefix);
  690. }
  691. try {
  692. jackbridge_deactivate(fJackClient);
  693. } catch(...) {}
  694. }
  695. try {
  696. jackbridge_client_close(fJackClient);
  697. } catch(...) {}
  698. invalidate();
  699. }
  700. fAudioPorts.clear();
  701. fCVPorts.clear();
  702. fEventPorts.clear();
  703. _clearPorts();
  704. fJackClient = newClient;
  705. }
  706. private:
  707. jack_client_t* fJackClient;
  708. const bool fUseClient;
  709. LinkedList<CarlaEngineJackAudioPort*> fAudioPorts;
  710. LinkedList<CarlaEngineJackCVPort*> fCVPorts;
  711. LinkedList<CarlaEngineJackEventPort*> fEventPorts;
  712. CarlaMutex fPreRenameMutex;
  713. CarlaStringList fPreRenameConnections;
  714. template<typename T>
  715. bool _renamePorts(const LinkedList<T*>& t, const CarlaString& clientNamePrefix)
  716. {
  717. for (typename LinkedList<T*>::Itenerator it = t.begin2(); it.valid(); it.next())
  718. {
  719. T* const port(it.getValue(nullptr));
  720. CARLA_SAFE_ASSERT_CONTINUE(port != nullptr);
  721. CARLA_SAFE_ASSERT_CONTINUE(port->fJackPort != nullptr);
  722. const char* shortPortName(jackbridge_port_short_name(port->fJackPort));
  723. CARLA_SAFE_ASSERT_CONTINUE(shortPortName != nullptr && shortPortName[0] != '\0');
  724. const char* const oldClientNameSep(std::strstr(shortPortName, ":"));
  725. CARLA_SAFE_ASSERT_CONTINUE(oldClientNameSep != nullptr && oldClientNameSep[0] != '\0' && oldClientNameSep[1] != '\0');
  726. shortPortName += oldClientNameSep-shortPortName + 1;
  727. const CarlaString newPortName(clientNamePrefix + shortPortName);
  728. if (! jackbridge_port_rename(fJackClient, port->fJackPort, newPortName))
  729. return false;
  730. }
  731. return true;
  732. }
  733. template<typename T>
  734. void _savePortsConnections(const LinkedList<T*>& t, const CarlaString& clientNamePrefix)
  735. {
  736. for (typename LinkedList<T*>::Itenerator it = t.begin2(); it.valid(); it.next())
  737. {
  738. T* const port(it.getValue(nullptr));
  739. CARLA_SAFE_ASSERT_CONTINUE(port != nullptr);
  740. CARLA_SAFE_ASSERT_CONTINUE(port->fJackPort != nullptr);
  741. const char* const shortPortName(jackbridge_port_short_name(port->fJackPort));
  742. CARLA_SAFE_ASSERT_CONTINUE(shortPortName != nullptr && shortPortName[0] != '\0');
  743. const CarlaString portName(clientNamePrefix + shortPortName);
  744. if (const char** const connections = jackbridge_port_get_all_connections(fJackClient, port->fJackPort))
  745. {
  746. for (int i=0; connections[i] != nullptr; ++i)
  747. {
  748. if (port->kIsInput)
  749. {
  750. fPreRenameConnections.append(connections[i]);
  751. fPreRenameConnections.append(portName);
  752. }
  753. else
  754. {
  755. fPreRenameConnections.append(portName);
  756. fPreRenameConnections.append(connections[i]);
  757. }
  758. }
  759. jackbridge_free(connections);
  760. }
  761. }
  762. }
  763. CARLA_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(CarlaEngineJackClient)
  764. };
  765. // -----------------------------------------------------------------------
  766. // Jack Engine
  767. class CarlaEngineJack : public CarlaEngine
  768. #ifndef BUILD_BRIDGE
  769. , private CarlaThread
  770. #endif
  771. {
  772. public:
  773. CarlaEngineJack()
  774. : CarlaEngine(),
  775. #ifndef BUILD_BRIDGE
  776. CarlaThread("CarlaEngineJackCallbacks"),
  777. #endif
  778. fClient(nullptr),
  779. fExternalPatchbayHost(true),
  780. fExternalPatchbayOsc(true),
  781. fFreewheel(false),
  782. #ifdef BUILD_BRIDGE
  783. fIsRunning(false)
  784. #else
  785. fTimebaseMaster(false),
  786. fTimebaseRolling(false),
  787. fTimebaseUsecs(0),
  788. fUsedGroups(),
  789. fUsedPorts(),
  790. fUsedConnections(),
  791. fPatchbayProcThreadProtectionMutex(),
  792. fRetConns(),
  793. fPostPonedEvents(),
  794. fPostPonedEventsMutex(),
  795. fIsInternalClient(false)
  796. #endif
  797. {
  798. carla_debug("CarlaEngineJack::CarlaEngineJack()");
  799. #ifdef BUILD_BRIDGE
  800. pData->options.processMode = ENGINE_PROCESS_MODE_MULTIPLE_CLIENTS;
  801. #else
  802. carla_zeroPointers(fRackPorts, kRackPortCount);
  803. #endif
  804. }
  805. ~CarlaEngineJack() noexcept override
  806. {
  807. carla_debug("CarlaEngineJack::~CarlaEngineJack()");
  808. CARLA_SAFE_ASSERT(fClient == nullptr);
  809. #ifndef BUILD_BRIDGE
  810. fUsedGroups.clear();
  811. fUsedPorts.clear();
  812. fUsedConnections.clear();
  813. CARLA_SAFE_ASSERT(fPostPonedEvents.count() == 0);
  814. #endif
  815. }
  816. // -------------------------------------------------------------------
  817. // Maximum values
  818. uint getMaxClientNameSize() const noexcept override
  819. {
  820. #ifndef BUILD_BRIDGE
  821. if (pData->options.processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT || pData->options.processMode == ENGINE_PROCESS_MODE_MULTIPLE_CLIENTS)
  822. #endif
  823. {
  824. try {
  825. return static_cast<uint>(jackbridge_client_name_size()-1);
  826. } CARLA_SAFE_EXCEPTION_RETURN("jack_client_name_size", 32);
  827. }
  828. return CarlaEngine::getMaxClientNameSize();
  829. }
  830. uint getMaxPortNameSize() const noexcept override
  831. {
  832. if (pData->options.processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT || pData->options.processMode == ENGINE_PROCESS_MODE_MULTIPLE_CLIENTS)
  833. {
  834. try {
  835. return static_cast<uint>(jackbridge_port_name_size()-1);
  836. } CARLA_SAFE_EXCEPTION_RETURN("jack_port_name_size", 255);
  837. }
  838. return CarlaEngine::getMaxPortNameSize();
  839. }
  840. // -------------------------------------------------------------------
  841. // Virtual, per-engine type calls
  842. bool init(const char* const clientName) override
  843. {
  844. CARLA_SAFE_ASSERT_RETURN(fClient != nullptr || (clientName != nullptr && clientName[0] != '\0'), false);
  845. CARLA_SAFE_ASSERT_RETURN(jackbridge_is_ok(), false);
  846. carla_debug("CarlaEngineJack::init(\"%s\")", clientName);
  847. fFreewheel = false;
  848. fExternalPatchbayHost = true;
  849. fExternalPatchbayOsc = true;
  850. CarlaString truncatedClientName;
  851. if (fClient == nullptr && clientName != nullptr)
  852. {
  853. truncatedClientName = clientName;
  854. truncatedClientName.truncate(getMaxClientNameSize());
  855. }
  856. #ifdef BUILD_BRIDGE
  857. fIsRunning = true;
  858. if (! pData->init(truncatedClientName))
  859. {
  860. close();
  861. setLastError("Failed to init internal data");
  862. return false;
  863. }
  864. if (pData->bufferSize == 0 || carla_isEqual(pData->sampleRate, 0.0))
  865. {
  866. // open temp client to get initial buffer-size and sample-rate values
  867. if (jack_client_t* const tmpClient = jackbridge_client_open(truncatedClientName, JackNoStartServer, nullptr))
  868. {
  869. pData->bufferSize = jackbridge_get_buffer_size(tmpClient);
  870. pData->sampleRate = jackbridge_get_sample_rate(tmpClient);
  871. jackbridge_client_close(tmpClient);
  872. }
  873. else
  874. {
  875. close();
  876. setLastError("Failed to init temporary jack client");
  877. return false;
  878. }
  879. }
  880. return true;
  881. #else
  882. if (fClient == nullptr && clientName != nullptr)
  883. fClient = jackbridge_client_open(truncatedClientName, JackNoStartServer, nullptr);
  884. if (fClient == nullptr)
  885. {
  886. setLastError("Failed to create new JACK client");
  887. return false;
  888. }
  889. const char* const jackClientName = jackbridge_get_client_name(fClient);
  890. if (! pData->init(jackClientName))
  891. {
  892. jackbridge_client_close(fClient);
  893. fClient = nullptr;
  894. setLastError("Failed to init internal data");
  895. return false;
  896. }
  897. const EngineOptions& opts(pData->options);
  898. pData->bufferSize = jackbridge_get_buffer_size(fClient);
  899. pData->sampleRate = jackbridge_get_sample_rate(fClient);
  900. pData->initTime(opts.transportExtra);
  901. jackbridge_set_thread_init_callback(fClient, carla_jack_thread_init_callback, nullptr);
  902. jackbridge_set_buffer_size_callback(fClient, carla_jack_bufsize_callback, this);
  903. jackbridge_set_sample_rate_callback(fClient, carla_jack_srate_callback, this);
  904. jackbridge_set_freewheel_callback(fClient, carla_jack_freewheel_callback, this);
  905. jackbridge_set_latency_callback(fClient, carla_jack_latency_callback, this);
  906. jackbridge_set_process_callback(fClient, carla_jack_process_callback, this);
  907. jackbridge_on_shutdown(fClient, carla_jack_shutdown_callback, this);
  908. fTimebaseRolling = false;
  909. if (opts.transportMode == ENGINE_TRANSPORT_MODE_JACK)
  910. fTimebaseMaster = jackbridge_set_timebase_callback(fClient, true, carla_jack_timebase_callback, this);
  911. else
  912. fTimebaseMaster = false;
  913. if (opts.processMode != ENGINE_PROCESS_MODE_PATCHBAY)
  914. initJackPatchbay(true, false, jackClientName);
  915. jackbridge_set_client_registration_callback(fClient, carla_jack_client_registration_callback, this);
  916. jackbridge_set_port_registration_callback(fClient, carla_jack_port_registration_callback, this);
  917. jackbridge_set_port_connect_callback(fClient, carla_jack_port_connect_callback, this);
  918. jackbridge_set_port_rename_callback(fClient, carla_jack_port_rename_callback, this);
  919. jackbridge_set_xrun_callback(fClient, carla_jack_xrun_callback, this);
  920. if (opts.processMode == ENGINE_PROCESS_MODE_CONTINUOUS_RACK || opts.processMode == ENGINE_PROCESS_MODE_PATCHBAY)
  921. {
  922. fRackPorts[kRackPortAudioIn1] = jackbridge_port_register(fClient, "audio-in1", JACK_DEFAULT_AUDIO_TYPE, JackPortIsInput, 0);
  923. fRackPorts[kRackPortAudioIn2] = jackbridge_port_register(fClient, "audio-in2", JACK_DEFAULT_AUDIO_TYPE, JackPortIsInput, 0);
  924. fRackPorts[kRackPortAudioOut1] = jackbridge_port_register(fClient, "audio-out1", JACK_DEFAULT_AUDIO_TYPE, JackPortIsOutput, 0);
  925. fRackPorts[kRackPortAudioOut2] = jackbridge_port_register(fClient, "audio-out2", JACK_DEFAULT_AUDIO_TYPE, JackPortIsOutput, 0);
  926. fRackPorts[kRackPortEventIn] = jackbridge_port_register(fClient, "events-in", JACK_DEFAULT_MIDI_TYPE, JackPortIsInput, 0);
  927. fRackPorts[kRackPortEventOut] = jackbridge_port_register(fClient, "events-out", JACK_DEFAULT_MIDI_TYPE, JackPortIsOutput, 0);
  928. if (opts.processMode == ENGINE_PROCESS_MODE_CONTINUOUS_RACK)
  929. {
  930. // FIXME?
  931. pData->graph.create(0, 0, 0, 0);
  932. }
  933. else
  934. {
  935. pData->graph.create(2, 2, 0, 0);
  936. // pData->graph.setUsingExternalHost(true);
  937. // pData->graph.setUsingExternalOSC(true);
  938. patchbayRefresh(true, false, false);
  939. }
  940. }
  941. if (const char* const uuidchar = jackbridge_client_get_uuid(fClient))
  942. {
  943. jack_uuid_t uuid;
  944. if (jackbridge_uuid_parse(uuidchar, &uuid))
  945. {
  946. #if defined(HAVE_LIBLO) && !defined(BUILD_BRIDGE)
  947. const CarlaString& tcp(pData->osc.getServerPathTCP());
  948. const CarlaString& udp(pData->osc.getServerPathUDP());
  949. if (tcp.isNotEmpty())
  950. jackbridge_set_property(fClient, uuid,
  951. "https://kx.studio/ns/carla/osc-tcp", tcp.buffer(), "text/plain");
  952. if (tcp.isNotEmpty())
  953. jackbridge_set_property(fClient, uuid,
  954. "https://kx.studio/ns/carla/osc-udp", udp.buffer(), "text/plain");
  955. #endif
  956. }
  957. }
  958. if (jackbridge_activate(fClient))
  959. {
  960. if (opts.processMode == ENGINE_PROCESS_MODE_CONTINUOUS_RACK ||
  961. opts.processMode == ENGINE_PROCESS_MODE_PATCHBAY)
  962. {
  963. if (pData->options.audioDevice != nullptr &&
  964. std::strcmp(pData->options.audioDevice, "Auto-Connect ON") == 0 &&
  965. std::getenv("LADISH_APP_NAME") == nullptr &&
  966. std::getenv("NSM_URL") == nullptr)
  967. {
  968. char strBuf[STR_MAX];
  969. if (jackbridge_port_by_name(fClient, "system:capture_1") != nullptr)
  970. {
  971. std::snprintf(strBuf, STR_MAX, "%s:audio-in1", jackClientName);
  972. strBuf[STR_MAX-1] = '\0';
  973. jackbridge_connect(fClient, "system:capture_1", strBuf);
  974. std::snprintf(strBuf, STR_MAX, "%s:audio-in2", jackClientName);
  975. strBuf[STR_MAX-1] = '\0';
  976. if (jackbridge_port_by_name(fClient, "system:capture_2") != nullptr)
  977. jackbridge_connect(fClient, "system:capture_2", strBuf);
  978. else
  979. jackbridge_connect(fClient, "system:capture_1", strBuf);
  980. }
  981. if (jackbridge_port_by_name(fClient, "system:playback_1") != nullptr)
  982. {
  983. std::snprintf(strBuf, STR_MAX, "%s:audio-out1", jackClientName);
  984. strBuf[STR_MAX-1] = '\0';
  985. jackbridge_connect(fClient, strBuf, "system:playback_1");
  986. std::snprintf(strBuf, STR_MAX, "%s:audio-out2", jackClientName);
  987. strBuf[STR_MAX-1] = '\0';
  988. if (jackbridge_port_by_name(fClient, "system:playback_2") != nullptr)
  989. jackbridge_connect(fClient, strBuf, "system:playback_2");
  990. else
  991. jackbridge_connect(fClient, strBuf, "system:playback_1");
  992. }
  993. }
  994. }
  995. startThread();
  996. callback(true, true,
  997. ENGINE_CALLBACK_ENGINE_STARTED, 0,
  998. opts.processMode,
  999. opts.transportMode,
  1000. static_cast<int>(pData->bufferSize),
  1001. static_cast<float>(pData->sampleRate),
  1002. getCurrentDriverName());
  1003. return true;
  1004. }
  1005. if (opts.processMode == ENGINE_PROCESS_MODE_CONTINUOUS_RACK ||
  1006. opts.processMode == ENGINE_PROCESS_MODE_PATCHBAY)
  1007. {
  1008. pData->graph.destroy();
  1009. }
  1010. pData->close();
  1011. jackbridge_client_close(fClient);
  1012. fClient = nullptr;
  1013. setLastError("Failed to activate the JACK client");
  1014. return false;
  1015. #endif
  1016. }
  1017. #ifndef BUILD_BRIDGE
  1018. bool initInternal(jack_client_t* const client)
  1019. {
  1020. fClient = client;
  1021. fIsInternalClient = true;
  1022. return init(nullptr);
  1023. }
  1024. #endif
  1025. bool close() override
  1026. {
  1027. carla_debug("CarlaEngineJack::close()");
  1028. #ifdef BUILD_BRIDGE
  1029. fClient = nullptr;
  1030. fIsRunning = false;
  1031. CarlaEngine::close();
  1032. return true;
  1033. #else
  1034. stopThread(-1);
  1035. fPostPonedEvents.clear();
  1036. CARLA_SAFE_ASSERT_RETURN_ERR(fClient != nullptr, "JACK Client is null");
  1037. // deactivate and close client
  1038. jackbridge_deactivate(fClient);
  1039. jackbridge_client_close(fClient);
  1040. // clear engine data
  1041. CarlaEngine::close();
  1042. fUsedGroups.clear();
  1043. fUsedPorts.clear();
  1044. fUsedConnections.clear();
  1045. fPostPonedEvents.clear();
  1046. // clear rack/patchbay stuff
  1047. if (pData->options.processMode == ENGINE_PROCESS_MODE_CONTINUOUS_RACK ||
  1048. pData->options.processMode == ENGINE_PROCESS_MODE_PATCHBAY)
  1049. {
  1050. carla_zeroPointers(fRackPorts, kRackPortCount);
  1051. pData->graph.destroy();
  1052. }
  1053. fClient = nullptr;
  1054. return true;
  1055. #endif
  1056. }
  1057. bool isRunning() const noexcept override
  1058. {
  1059. #ifdef BUILD_BRIDGE
  1060. return (fClient != nullptr || fIsRunning);
  1061. #else
  1062. return (fClient != nullptr);
  1063. #endif
  1064. }
  1065. bool isOffline() const noexcept override
  1066. {
  1067. return fFreewheel;
  1068. }
  1069. EngineType getType() const noexcept override
  1070. {
  1071. return kEngineTypeJack;
  1072. }
  1073. const char* getCurrentDriverName() const noexcept override
  1074. {
  1075. return "JACK";
  1076. }
  1077. #ifndef BUILD_BRIDGE
  1078. float getDSPLoad() const noexcept override
  1079. {
  1080. CARLA_SAFE_ASSERT_RETURN(fClient != nullptr, 0.0f);
  1081. return jackbridge_cpu_load(fClient);
  1082. }
  1083. void callback(const bool sendHost, const bool sendOsc,
  1084. const EngineCallbackOpcode action, const uint pluginId,
  1085. const int value1, const int value2, const int value3,
  1086. const float valuef, const char* const valueStr) noexcept override
  1087. {
  1088. if (action == ENGINE_CALLBACK_PROJECT_LOAD_FINISHED && fTimebaseMaster)
  1089. {
  1090. // project finished loading, need to set bpm here, so we force an update of timebase master
  1091. transportRelocate(pData->timeInfo.frame);
  1092. }
  1093. CarlaEngine::callback(sendHost, sendOsc, action, pluginId, value1, value2, value3, valuef, valueStr);
  1094. }
  1095. #endif
  1096. bool setBufferSizeAndSampleRate(const uint bufferSize, const double sampleRate) override
  1097. {
  1098. CARLA_SAFE_ASSERT_RETURN(carla_isEqual(pData->sampleRate, sampleRate), false);
  1099. CARLA_SAFE_ASSERT_RETURN(fClient != nullptr, false);
  1100. try {
  1101. return jackbridge_set_buffer_size(fClient, bufferSize);
  1102. } CARLA_SAFE_EXCEPTION_RETURN("setBufferSizeAndSampleRate", false);
  1103. }
  1104. EngineTimeInfo getTimeInfo() const noexcept override
  1105. {
  1106. if (pData->options.transportMode != ENGINE_TRANSPORT_MODE_JACK)
  1107. return CarlaEngine::getTimeInfo();
  1108. if (pData->options.processMode != ENGINE_PROCESS_MODE_MULTIPLE_CLIENTS)
  1109. return CarlaEngine::getTimeInfo();
  1110. jack_position_t jpos;
  1111. // invalidate
  1112. jpos.unique_1 = 1;
  1113. jpos.unique_2 = 2;
  1114. EngineTimeInfo timeInfo;
  1115. const bool playing = jackbridge_transport_query(fClient, &jpos) == JackTransportRolling;
  1116. if (jpos.unique_1 != jpos.unique_2)
  1117. {
  1118. timeInfo.playing = false;
  1119. timeInfo.frame = 0;
  1120. timeInfo.usecs = 0;
  1121. timeInfo.bbt.valid = false;
  1122. return timeInfo;
  1123. }
  1124. timeInfo.playing = playing;
  1125. timeInfo.frame = jpos.frame;
  1126. timeInfo.usecs = jpos.usecs;
  1127. if (jpos.valid & JackPositionBBT)
  1128. {
  1129. timeInfo.bbt.valid = true;
  1130. timeInfo.bbt.bar = jpos.bar;
  1131. timeInfo.bbt.beat = jpos.beat;
  1132. timeInfo.bbt.tick = jpos.tick;
  1133. timeInfo.bbt.barStartTick = jpos.bar_start_tick;
  1134. timeInfo.bbt.beatsPerBar = jpos.beats_per_bar;
  1135. timeInfo.bbt.beatType = jpos.beat_type;
  1136. timeInfo.bbt.ticksPerBeat = jpos.ticks_per_beat;
  1137. timeInfo.bbt.beatsPerMinute = jpos.beats_per_minute;
  1138. }
  1139. else
  1140. {
  1141. timeInfo.bbt.valid = false;
  1142. }
  1143. return timeInfo;
  1144. }
  1145. #ifndef BUILD_BRIDGE
  1146. void setOption(const EngineOption option, const int value, const char* const valueStr) noexcept override
  1147. {
  1148. if (option == ENGINE_OPTION_TRANSPORT_MODE && fClient != nullptr)
  1149. {
  1150. CARLA_SAFE_ASSERT_RETURN(value >= ENGINE_TRANSPORT_MODE_DISABLED && value <= ENGINE_TRANSPORT_MODE_JACK,);
  1151. if (value == ENGINE_TRANSPORT_MODE_JACK)
  1152. {
  1153. fTimebaseMaster = jackbridge_set_timebase_callback(fClient, true, carla_jack_timebase_callback, this);
  1154. }
  1155. else
  1156. {
  1157. // jack transport cannot be disabled in multi-client
  1158. callback(true, true,
  1159. ENGINE_CALLBACK_TRANSPORT_MODE_CHANGED, 0,
  1160. ENGINE_TRANSPORT_MODE_JACK,
  1161. 0, 0, 0.0f,
  1162. pData->options.transportExtra);
  1163. CARLA_SAFE_ASSERT_RETURN(pData->options.processMode != ENGINE_PROCESS_MODE_MULTIPLE_CLIENTS,);
  1164. jackbridge_release_timebase(fClient);
  1165. fTimebaseMaster = false;
  1166. }
  1167. }
  1168. CarlaEngine::setOption(option, value, valueStr);
  1169. }
  1170. #endif
  1171. CarlaEngineClient* addClient(CarlaPlugin* const plugin) override
  1172. {
  1173. jack_client_t* client = nullptr;
  1174. #ifndef BUILD_BRIDGE
  1175. if (pData->options.processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  1176. {
  1177. client = fClient;
  1178. }
  1179. else if (pData->options.processMode == ENGINE_PROCESS_MODE_MULTIPLE_CLIENTS)
  1180. #endif
  1181. {
  1182. client = jackbridge_client_open(plugin->getName(), JackNoStartServer, nullptr);
  1183. CARLA_SAFE_ASSERT_RETURN(client != nullptr, nullptr);
  1184. jackbridge_set_thread_init_callback(client, carla_jack_thread_init_callback, nullptr);
  1185. #ifndef BUILD_BRIDGE
  1186. /*
  1187. jackbridge_set_buffer_size_callback(fClient, carla_jack_bufsize_callback_plugin, plugin);
  1188. jackbridge_set_sample_rate_callback(fClient, carla_jack_srate_callback_plugin, plugin);
  1189. */
  1190. jackbridge_set_latency_callback(client, carla_jack_latency_callback_plugin, plugin);
  1191. jackbridge_set_process_callback(client, carla_jack_process_callback_plugin, plugin);
  1192. jackbridge_on_shutdown(client, carla_jack_shutdown_callback_plugin, plugin);
  1193. if (const char* const uuidchar = jackbridge_client_get_uuid(client))
  1194. {
  1195. jack_uuid_t uuid;
  1196. if (jackbridge_uuid_parse(uuidchar, &uuid))
  1197. {
  1198. char strBufId[24];
  1199. std::snprintf(strBufId, 24, "%u", plugin->getId());
  1200. strBufId[23] = '\0';
  1201. jackbridge_set_property(client, uuid,
  1202. "https://kx.studio/ns/carla/plugin-id",
  1203. strBufId,
  1204. "http://www.w3.org/2001/XMLSchema#integer");
  1205. if (const char* const pluginIcon = plugin->getIconName())
  1206. jackbridge_set_property(client, uuid,
  1207. "https://kx.studio/ns/carla/plugin-icon",
  1208. pluginIcon,
  1209. "text/plain");
  1210. }
  1211. }
  1212. #else
  1213. fClient = client;
  1214. pData->bufferSize = jackbridge_get_buffer_size(client);
  1215. pData->sampleRate = jackbridge_get_sample_rate(client);
  1216. pData->initTime(nullptr);
  1217. jackbridge_set_buffer_size_callback(client, carla_jack_bufsize_callback, this);
  1218. jackbridge_set_sample_rate_callback(client, carla_jack_srate_callback, this);
  1219. jackbridge_set_freewheel_callback(client, carla_jack_freewheel_callback, this);
  1220. jackbridge_set_latency_callback(client, carla_jack_latency_callback, this);
  1221. jackbridge_set_process_callback(client, carla_jack_process_callback, this);
  1222. jackbridge_on_shutdown(client, carla_jack_shutdown_callback, this);
  1223. #endif
  1224. }
  1225. return new CarlaEngineJackClient(*this, client);
  1226. }
  1227. #ifndef BUILD_BRIDGE
  1228. bool renamePlugin(const uint id, const char* const newName) override
  1229. {
  1230. if (pData->options.processMode == ENGINE_PROCESS_MODE_CONTINUOUS_RACK ||
  1231. pData->options.processMode == ENGINE_PROCESS_MODE_PATCHBAY)
  1232. {
  1233. return CarlaEngine::renamePlugin(id, newName);
  1234. }
  1235. CARLA_SAFE_ASSERT_RETURN(pData->plugins != nullptr, false);
  1236. CARLA_SAFE_ASSERT_RETURN(pData->curPluginCount != 0, false);
  1237. CARLA_SAFE_ASSERT_RETURN(id < pData->curPluginCount, false);
  1238. CARLA_SAFE_ASSERT_RETURN(newName != nullptr && newName[0] != '\0', false);
  1239. CarlaPlugin* const plugin(pData->plugins[id].plugin);
  1240. CARLA_SAFE_ASSERT_RETURN_ERR(plugin != nullptr, "Could not find plugin to rename");
  1241. CARLA_SAFE_ASSERT_RETURN_ERR(plugin->getId() == id, "Invalid engine internal data");
  1242. // before we stop the engine thread we might need to get the plugin data
  1243. const bool needsReinit = (pData->options.processMode == ENGINE_PROCESS_MODE_MULTIPLE_CLIENTS);
  1244. const CarlaStateSave* saveStatePtr = nullptr;
  1245. if (needsReinit)
  1246. {
  1247. const CarlaStateSave& saveState(plugin->getStateSave());
  1248. saveStatePtr = &saveState;
  1249. }
  1250. CarlaString uniqueName;
  1251. try {
  1252. const char* const tmpName = getUniquePluginName(newName);
  1253. uniqueName = tmpName;
  1254. delete[] tmpName;
  1255. } CARLA_SAFE_EXCEPTION("JACK renamePlugin getUniquePluginName");
  1256. if (uniqueName.isEmpty())
  1257. {
  1258. setLastError("Failed to request new unique plugin name");
  1259. return false;
  1260. }
  1261. const ScopedThreadStopper sts(this);
  1262. // rename on client client mode, just rename the ports
  1263. if (pData->options.processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  1264. {
  1265. CarlaEngineJackClient* const client((CarlaEngineJackClient*)plugin->getEngineClient());
  1266. if (! client->renameInSingleClient(uniqueName))
  1267. {
  1268. setLastError("Failed to rename some JACK ports, does your JACK version support proper port renaming?");
  1269. return false;
  1270. }
  1271. }
  1272. // rename in multiple client mode
  1273. else if (pData->options.processMode == ENGINE_PROCESS_MODE_MULTIPLE_CLIENTS)
  1274. {
  1275. CarlaEngineJackClient* const client((CarlaEngineJackClient*)plugin->getEngineClient());
  1276. // we should not be able to do this, jack really needs to allow client rename
  1277. if (jack_client_t* const jackClient = jackbridge_client_open(uniqueName, JackNoStartServer, nullptr))
  1278. {
  1279. // get new client name
  1280. uniqueName = jackbridge_get_client_name(jackClient);
  1281. // close client
  1282. client->closeForRename(jackClient, uniqueName);
  1283. // disable plugin
  1284. plugin->setEnabled(false);
  1285. // set new client data
  1286. jackbridge_set_latency_callback(jackClient, carla_jack_latency_callback_plugin, plugin);
  1287. jackbridge_set_process_callback(jackClient, carla_jack_process_callback_plugin, plugin);
  1288. jackbridge_on_shutdown(jackClient, carla_jack_shutdown_callback_plugin, plugin);
  1289. // NOTE: jack1 locks up here
  1290. if (jackbridge_get_version_string() != nullptr)
  1291. jackbridge_set_thread_init_callback(jackClient, carla_jack_thread_init_callback, nullptr);
  1292. /* The following code is because of a tricky situation.
  1293. We cannot lock or do jack operations during jack callbacks on jack1. jack2 events are asynchronous.
  1294. When we close the client jack will trigger unregister-port callbacks, which we handle on a separate thread ASAP.
  1295. But before that happens we already registered a new client with the same ports (the "renamed" one),
  1296. and at this point the port we receive during that callback is actually the new one from the new client..
  1297. JACK2 seems to be reusing ports to save space, which is understandable.
  1298. Anyway, this means we have to remove all our port-related data before the new client ports are created.
  1299. (we also stop the separate jack-events thread to avoid any race conditions while modying our port data) */
  1300. stopThread(-1);
  1301. const uint groupId(fUsedGroups.getGroupId(plugin->getName()));
  1302. if (groupId > 0)
  1303. {
  1304. for (LinkedList<PortNameToId>::Itenerator it = fUsedPorts.list.begin2(); it.valid(); it.next())
  1305. {
  1306. for (LinkedList<ConnectionToId>::Itenerator it2 = fUsedConnections.list.begin2(); it2.valid(); it2.next())
  1307. {
  1308. static ConnectionToId connectionFallback = { 0, 0, 0, 0, 0 };
  1309. ConnectionToId& connectionToId = it2.getValue(connectionFallback);
  1310. CARLA_SAFE_ASSERT_CONTINUE(connectionToId.id != 0);
  1311. if (connectionToId.groupA != groupId && connectionToId.groupB != groupId)
  1312. continue;
  1313. callback(fExternalPatchbayHost, fExternalPatchbayOsc,
  1314. ENGINE_CALLBACK_PATCHBAY_CONNECTION_REMOVED,
  1315. connectionToId.id,
  1316. 0, 0, 0, 0.0f, nullptr);
  1317. fUsedConnections.list.remove(it2);
  1318. }
  1319. static PortNameToId portNameFallback = { 0, 0, { '\0' }, { '\0' } };
  1320. PortNameToId& portNameToId(it.getValue(portNameFallback));
  1321. CARLA_SAFE_ASSERT_CONTINUE(portNameToId.group != 0);
  1322. if (portNameToId.group != groupId)
  1323. continue;
  1324. callback(fExternalPatchbayHost, fExternalPatchbayOsc,
  1325. ENGINE_CALLBACK_PATCHBAY_PORT_REMOVED,
  1326. portNameToId.group,
  1327. static_cast<int>(portNameToId.port),
  1328. 0, 0, 0.0f, nullptr);
  1329. fUsedPorts.list.remove(it);
  1330. }
  1331. }
  1332. startThread();
  1333. }
  1334. else
  1335. {
  1336. setLastError("Failed to create new JACK client");
  1337. return false;
  1338. }
  1339. }
  1340. // Rename
  1341. plugin->setName(uniqueName);
  1342. if (needsReinit)
  1343. {
  1344. // reload plugin to recreate its ports
  1345. plugin->reload();
  1346. plugin->loadStateSave(*saveStatePtr);
  1347. plugin->setEnabled(true);
  1348. }
  1349. callback(true, true, ENGINE_CALLBACK_PLUGIN_RENAMED, id, 0, 0, 0, 0.0f, uniqueName);
  1350. return true;
  1351. }
  1352. // -------------------------------------------------------------------
  1353. // Patchbay
  1354. bool patchbayConnect(const bool external,
  1355. const uint groupA, const uint portA, const uint groupB, const uint portB) override
  1356. {
  1357. CARLA_SAFE_ASSERT_RETURN(fClient != nullptr, false);
  1358. if (pData->options.processMode == ENGINE_PROCESS_MODE_PATCHBAY && ! external)
  1359. return CarlaEngine::patchbayConnect(false, groupA, portA, groupB, portB);
  1360. const char* const fullPortNameA = fUsedPorts.getFullPortName(groupA, portA);
  1361. CARLA_SAFE_ASSERT_RETURN(fullPortNameA != nullptr && fullPortNameA[0] != '\0', false);
  1362. const char* const fullPortNameB = fUsedPorts.getFullPortName(groupB, portB);
  1363. CARLA_SAFE_ASSERT_RETURN(fullPortNameB != nullptr && fullPortNameB[0] != '\0', false);
  1364. if (! jackbridge_connect(fClient, fullPortNameA, fullPortNameB))
  1365. {
  1366. setLastError("JACK operation failed");
  1367. return false;
  1368. }
  1369. return true;
  1370. }
  1371. bool patchbayDisconnect(const bool external, const uint connectionId) override
  1372. {
  1373. CARLA_SAFE_ASSERT_RETURN(fClient != nullptr, false);
  1374. if (pData->options.processMode == ENGINE_PROCESS_MODE_PATCHBAY && ! external)
  1375. return CarlaEngine::patchbayDisconnect(false, connectionId);
  1376. ConnectionToId connectionToId = { 0, 0, 0, 0, 0 };
  1377. {
  1378. const CarlaMutexLocker cml(fUsedConnections.mutex);
  1379. for (LinkedList<ConnectionToId>::Itenerator it = fUsedConnections.list.begin2(); it.valid(); it.next())
  1380. {
  1381. connectionToId = it.getValue(connectionToId);
  1382. CARLA_SAFE_ASSERT_CONTINUE(connectionToId.id != 0);
  1383. if (connectionToId.id == connectionId)
  1384. break;
  1385. }
  1386. }
  1387. if (connectionToId.id == 0 || connectionToId.id != connectionId)
  1388. {
  1389. setLastError("Failed to find the requested connection");
  1390. return false;
  1391. }
  1392. const char* const fullPortNameA = fUsedPorts.getFullPortName(connectionToId.groupA, connectionToId.portA);
  1393. CARLA_SAFE_ASSERT_RETURN(fullPortNameA != nullptr && fullPortNameA[0] != '\0', false);
  1394. const char* const fullPortNameB = fUsedPorts.getFullPortName(connectionToId.groupB, connectionToId.portB);
  1395. CARLA_SAFE_ASSERT_RETURN(fullPortNameB != nullptr && fullPortNameB[0] != '\0', false);
  1396. if (! jackbridge_disconnect(fClient, fullPortNameA, fullPortNameB))
  1397. {
  1398. setLastError("JACK operation failed");
  1399. return false;
  1400. }
  1401. return true;
  1402. }
  1403. bool patchbayRefresh(const bool sendHost, const bool sendOSC, const bool external) override
  1404. {
  1405. CARLA_SAFE_ASSERT_RETURN(fClient != nullptr, false);
  1406. carla_debug("patchbayRefresh(%s, %s, %s)", bool2str(sendHost), bool2str(sendOSC), bool2str(external));
  1407. if (pData->options.processMode == ENGINE_PROCESS_MODE_PATCHBAY)
  1408. {
  1409. if (sendHost)
  1410. {
  1411. fExternalPatchbayHost = external;
  1412. pData->graph.setUsingExternalHost(external);
  1413. }
  1414. if (sendOSC)
  1415. {
  1416. fExternalPatchbayOsc = external;
  1417. pData->graph.setUsingExternalOSC(external);
  1418. }
  1419. if (! external)
  1420. return CarlaEngine::patchbayRefresh(sendHost, sendOSC, false);
  1421. }
  1422. fUsedGroups.clear();
  1423. fUsedPorts.clear();
  1424. fUsedConnections.clear();
  1425. initJackPatchbay(sendHost, sendOSC, jackbridge_get_client_name(fClient));
  1426. return true;
  1427. }
  1428. // -------------------------------------------------------------------
  1429. // Transport
  1430. void transportPlay() noexcept override
  1431. {
  1432. if (pData->options.transportMode != ENGINE_TRANSPORT_MODE_JACK)
  1433. return CarlaEngine::transportPlay();
  1434. if (fClient != nullptr)
  1435. {
  1436. if (! pData->timeInfo.bbt.valid)
  1437. {
  1438. // old timebase master no longer active, make ourselves master again
  1439. pData->time.setNeedsReset();
  1440. fTimebaseMaster = jackbridge_set_timebase_callback(fClient, true, carla_jack_timebase_callback, this);
  1441. }
  1442. try {
  1443. jackbridge_transport_start(fClient);
  1444. } catch(...) {}
  1445. }
  1446. }
  1447. void transportPause() noexcept override
  1448. {
  1449. if (pData->options.transportMode != ENGINE_TRANSPORT_MODE_JACK)
  1450. return CarlaEngine::transportPause();
  1451. if (fClient != nullptr)
  1452. {
  1453. try {
  1454. jackbridge_transport_stop(fClient);
  1455. } catch(...) {}
  1456. }
  1457. }
  1458. void transportBPM(const double bpm) noexcept override
  1459. {
  1460. if (pData->options.transportMode != ENGINE_TRANSPORT_MODE_JACK || fTimebaseMaster)
  1461. return CarlaEngine::transportBPM(bpm);
  1462. if (fClient == nullptr)
  1463. return;
  1464. jack_position_t jpos;
  1465. // invalidate
  1466. jpos.unique_1 = 1;
  1467. jpos.unique_2 = 2;
  1468. jackbridge_transport_query(fClient, &jpos);
  1469. if (jpos.unique_1 == jpos.unique_2 && (jpos.valid & JackPositionBBT) != 0)
  1470. {
  1471. carla_stdout("NOTE: Changing BPM without being JACK timebase master");
  1472. jpos.beats_per_minute = bpm;
  1473. try {
  1474. jackbridge_transport_reposition(fClient, &jpos);
  1475. } catch(...) {}
  1476. }
  1477. }
  1478. void transportRelocate(const uint64_t frame) noexcept override
  1479. {
  1480. if (pData->options.transportMode != ENGINE_TRANSPORT_MODE_JACK)
  1481. return CarlaEngine::transportRelocate(frame);
  1482. if (fClient != nullptr)
  1483. {
  1484. try {
  1485. jackbridge_transport_locate(fClient, static_cast<jack_nframes_t>(frame));
  1486. } catch(...) {}
  1487. }
  1488. }
  1489. // -------------------------------------------------------------------
  1490. // Patchbay stuff
  1491. const char* const* getPatchbayConnections(const bool external) const override
  1492. {
  1493. CARLA_SAFE_ASSERT_RETURN(fClient != nullptr, nullptr);
  1494. carla_debug("CarlaEngineJack::getPatchbayConnections(%s)", bool2str(external));
  1495. if (pData->options.processMode == ENGINE_PROCESS_MODE_PATCHBAY && ! external)
  1496. return CarlaEngine::getPatchbayConnections(external);
  1497. CarlaStringList connList;
  1498. if (const char** const ports = jackbridge_get_ports(fClient, nullptr, nullptr, JackPortIsOutput))
  1499. {
  1500. for (int i=0; ports[i] != nullptr; ++i)
  1501. {
  1502. const jack_port_t* const jackPort(jackbridge_port_by_name(fClient, ports[i]));
  1503. const char* const fullPortName(ports[i]);
  1504. CARLA_SAFE_ASSERT_CONTINUE(jackPort != nullptr);
  1505. if (const char** const connections = jackbridge_port_get_all_connections(fClient, jackPort))
  1506. {
  1507. for (int j=0; connections[j] != nullptr; ++j)
  1508. {
  1509. connList.append(fullPortName);
  1510. connList.append(connections[j]);
  1511. }
  1512. jackbridge_free(connections);
  1513. }
  1514. }
  1515. jackbridge_free(ports);
  1516. }
  1517. if (connList.count() == 0)
  1518. return nullptr;
  1519. fRetConns = connList.toCharStringListPtr();
  1520. return fRetConns;
  1521. }
  1522. void restorePatchbayConnection(const bool external, const char* const connSource, const char* const connTarget) override
  1523. {
  1524. CARLA_SAFE_ASSERT_RETURN(fClient != nullptr,);
  1525. CARLA_SAFE_ASSERT_RETURN(connSource != nullptr && connSource[0] != '\0',);
  1526. CARLA_SAFE_ASSERT_RETURN(connTarget != nullptr && connTarget[0] != '\0',);
  1527. carla_debug("CarlaEngineJack::restorePatchbayConnection(%s, \"%s\", \"%s\")",
  1528. bool2str(external), connSource, connTarget);
  1529. if (pData->options.processMode == ENGINE_PROCESS_MODE_PATCHBAY && ! external)
  1530. return CarlaEngine::restorePatchbayConnection(external, connSource, connTarget);
  1531. if (const jack_port_t* const port = jackbridge_port_by_name(fClient, connSource))
  1532. {
  1533. if (jackbridge_port_by_name(fClient, connTarget) == nullptr)
  1534. return;
  1535. if (! jackbridge_port_connected_to(port, connTarget))
  1536. jackbridge_connect(fClient, connSource, connTarget);
  1537. }
  1538. }
  1539. #endif
  1540. // -------------------------------------------------------------------
  1541. protected:
  1542. void handleJackBufferSizeCallback(const uint32_t newBufferSize)
  1543. {
  1544. if (pData->bufferSize == newBufferSize)
  1545. return;
  1546. #ifndef BUILD_BRIDGE
  1547. const CarlaMutexLocker cml(fPatchbayProcThreadProtectionMutex);
  1548. #endif
  1549. pData->bufferSize = newBufferSize;
  1550. bufferSizeChanged(newBufferSize);
  1551. }
  1552. void handleJackSampleRateCallback(const double newSampleRate)
  1553. {
  1554. if (carla_isEqual(pData->sampleRate, newSampleRate))
  1555. return;
  1556. #ifndef BUILD_BRIDGE
  1557. const CarlaMutexLocker cml(fPatchbayProcThreadProtectionMutex);
  1558. #endif
  1559. pData->sampleRate = newSampleRate;
  1560. sampleRateChanged(newSampleRate);
  1561. }
  1562. void handleJackFreewheelCallback(const bool isFreewheel)
  1563. {
  1564. if (fFreewheel == isFreewheel)
  1565. return;
  1566. #ifndef BUILD_BRIDGE
  1567. const CarlaMutexLocker cml(fPatchbayProcThreadProtectionMutex);
  1568. #endif
  1569. fFreewheel = isFreewheel;
  1570. offlineModeChanged(isFreewheel);
  1571. }
  1572. void handleJackProcessCallback(const uint32_t nframes)
  1573. {
  1574. const PendingRtEventsRunner prt(this, nframes);
  1575. CARLA_SAFE_ASSERT_INT2_RETURN(nframes == pData->bufferSize, nframes, pData->bufferSize,);
  1576. #ifdef BUILD_BRIDGE
  1577. CarlaPlugin* const plugin(pData->plugins[0].plugin);
  1578. if (plugin != nullptr && plugin->isEnabled() && plugin->tryLock(fFreewheel))
  1579. {
  1580. plugin->initBuffers();
  1581. processPlugin(plugin, nframes);
  1582. plugin->unlock();
  1583. }
  1584. #else
  1585. if (pData->options.transportMode == ENGINE_TRANSPORT_MODE_JACK && !fTimebaseMaster)
  1586. {
  1587. jack_position_t jpos;
  1588. // invalidate
  1589. jpos.unique_1 = 1;
  1590. jpos.unique_2 = 2;
  1591. EngineTimeInfo timeInfo;
  1592. const bool playing = jackbridge_transport_query(fClient, &jpos) == JackTransportRolling;
  1593. if (jpos.unique_1 != jpos.unique_2)
  1594. {
  1595. timeInfo.playing = false;
  1596. timeInfo.frame = 0;
  1597. timeInfo.usecs = 0;
  1598. timeInfo.bbt.valid = false;
  1599. }
  1600. else
  1601. {
  1602. timeInfo.playing = playing;
  1603. timeInfo.frame = jpos.frame;
  1604. timeInfo.usecs = jpos.usecs;
  1605. if (jpos.valid & JackPositionBBT)
  1606. {
  1607. timeInfo.bbt.valid = true;
  1608. timeInfo.bbt.bar = jpos.bar;
  1609. timeInfo.bbt.beat = jpos.beat;
  1610. timeInfo.bbt.tick = jpos.tick;
  1611. timeInfo.bbt.barStartTick = jpos.bar_start_tick;
  1612. timeInfo.bbt.beatsPerBar = jpos.beats_per_bar;
  1613. timeInfo.bbt.beatType = jpos.beat_type;
  1614. timeInfo.bbt.ticksPerBeat = jpos.ticks_per_beat;
  1615. timeInfo.bbt.beatsPerMinute = jpos.beats_per_minute;
  1616. }
  1617. else
  1618. {
  1619. timeInfo.bbt.valid = false;
  1620. }
  1621. }
  1622. pData->timeInfo = timeInfo;
  1623. }
  1624. if (pData->options.processMode == ENGINE_PROCESS_MODE_CONTINUOUS_RACK)
  1625. {
  1626. if (pData->aboutToClose)
  1627. {
  1628. if (float* const audioOut1 = (float*)jackbridge_port_get_buffer(fRackPorts[kRackPortAudioOut1], nframes))
  1629. carla_zeroFloats(audioOut1, nframes);
  1630. if (float* const audioOut2 = (float*)jackbridge_port_get_buffer(fRackPorts[kRackPortAudioOut2], nframes))
  1631. carla_zeroFloats(audioOut2, nframes);
  1632. }
  1633. else if (pData->curPluginCount == 0)
  1634. {
  1635. float* const audioIn1 = (float*)jackbridge_port_get_buffer(fRackPorts[kRackPortAudioIn1], nframes);
  1636. float* const audioIn2 = (float*)jackbridge_port_get_buffer(fRackPorts[kRackPortAudioIn2], nframes);
  1637. float* const audioOut1 = (float*)jackbridge_port_get_buffer(fRackPorts[kRackPortAudioOut1], nframes);
  1638. float* const audioOut2 = (float*)jackbridge_port_get_buffer(fRackPorts[kRackPortAudioOut2], nframes);
  1639. // assert buffers
  1640. CARLA_SAFE_ASSERT_RETURN(audioIn1 != nullptr,);
  1641. CARLA_SAFE_ASSERT_RETURN(audioIn2 != nullptr,);
  1642. CARLA_SAFE_ASSERT_RETURN(audioOut1 != nullptr,);
  1643. CARLA_SAFE_ASSERT_RETURN(audioOut2 != nullptr,);
  1644. // pass-through
  1645. carla_copyFloats(audioOut1, audioIn1, nframes);
  1646. carla_copyFloats(audioOut2, audioIn2, nframes);
  1647. // TODO pass-through MIDI as well
  1648. if (void* const eventOut = jackbridge_port_get_buffer(fRackPorts[kRackPortEventOut], nframes))
  1649. jackbridge_midi_clear_buffer(eventOut);
  1650. return;
  1651. }
  1652. }
  1653. if (pData->options.processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  1654. {
  1655. for (uint i=0; i < pData->curPluginCount; ++i)
  1656. {
  1657. CarlaPlugin* const plugin(pData->plugins[i].plugin);
  1658. if (plugin != nullptr && plugin->isEnabled() && plugin->tryLock(fFreewheel))
  1659. {
  1660. plugin->initBuffers();
  1661. processPlugin(plugin, nframes);
  1662. plugin->unlock();
  1663. }
  1664. }
  1665. }
  1666. else if (pData->options.processMode == ENGINE_PROCESS_MODE_CONTINUOUS_RACK ||
  1667. pData->options.processMode == ENGINE_PROCESS_MODE_PATCHBAY)
  1668. {
  1669. CARLA_SAFE_ASSERT_RETURN(pData->events.in != nullptr,);
  1670. CARLA_SAFE_ASSERT_RETURN(pData->events.out != nullptr,);
  1671. // get buffers from jack
  1672. float* const audioIn1 = (float*)jackbridge_port_get_buffer(fRackPorts[kRackPortAudioIn1], nframes);
  1673. float* const audioIn2 = (float*)jackbridge_port_get_buffer(fRackPorts[kRackPortAudioIn2], nframes);
  1674. float* const audioOut1 = (float*)jackbridge_port_get_buffer(fRackPorts[kRackPortAudioOut1], nframes);
  1675. float* const audioOut2 = (float*)jackbridge_port_get_buffer(fRackPorts[kRackPortAudioOut2], nframes);
  1676. void* const eventIn = jackbridge_port_get_buffer(fRackPorts[kRackPortEventIn], nframes);
  1677. void* const eventOut = jackbridge_port_get_buffer(fRackPorts[kRackPortEventOut], nframes);
  1678. // assert buffers
  1679. CARLA_SAFE_ASSERT_RETURN(audioIn1 != nullptr,);
  1680. CARLA_SAFE_ASSERT_RETURN(audioIn2 != nullptr,);
  1681. CARLA_SAFE_ASSERT_RETURN(audioOut1 != nullptr,);
  1682. CARLA_SAFE_ASSERT_RETURN(audioOut2 != nullptr,);
  1683. // create audio buffers
  1684. const float* inBuf[2] = { audioIn1, audioIn2 };
  1685. /**/ float* outBuf[2] = { audioOut1, audioOut2 };
  1686. // initialize events
  1687. carla_zeroStructs(pData->events.in, kMaxEngineEventInternalCount);
  1688. carla_zeroStructs(pData->events.out, kMaxEngineEventInternalCount);
  1689. if (eventIn != nullptr)
  1690. {
  1691. ushort engineEventIndex = 0;
  1692. jack_midi_event_t jackEvent;
  1693. const uint32_t jackEventCount(jackbridge_midi_get_event_count(eventIn));
  1694. for (uint32_t jackEventIndex=0; jackEventIndex < jackEventCount; ++jackEventIndex)
  1695. {
  1696. if (! jackbridge_midi_event_get(&jackEvent, eventIn, jackEventIndex))
  1697. continue;
  1698. CARLA_SAFE_ASSERT_CONTINUE(jackEvent.size < 0xFF /* uint8_t max */);
  1699. EngineEvent& engineEvent(pData->events.in[engineEventIndex++]);
  1700. engineEvent.time = jackEvent.time;
  1701. engineEvent.fillFromMidiData(static_cast<uint8_t>(jackEvent.size), jackEvent.buffer, 0);
  1702. if (engineEventIndex >= kMaxEngineEventInternalCount)
  1703. break;
  1704. }
  1705. }
  1706. if (pData->options.processMode == ENGINE_PROCESS_MODE_CONTINUOUS_RACK)
  1707. {
  1708. pData->graph.processRack(pData, inBuf, outBuf, nframes);
  1709. }
  1710. else
  1711. {
  1712. const CarlaMutexLocker cml(fPatchbayProcThreadProtectionMutex);
  1713. pData->graph.process(pData, inBuf, outBuf, nframes);
  1714. }
  1715. // output control
  1716. if (eventOut != nullptr)
  1717. {
  1718. jackbridge_midi_clear_buffer(eventOut);
  1719. uint8_t size = 0;
  1720. uint8_t mdata[3] = { 0, 0, 0 };
  1721. uint8_t mdataTmp[EngineMidiEvent::kDataSize];
  1722. const uint8_t* mdataPtr;
  1723. for (ushort i=0; i < kMaxEngineEventInternalCount; ++i)
  1724. {
  1725. const EngineEvent& engineEvent(pData->events.out[i]);
  1726. /**/ if (engineEvent.type == kEngineEventTypeNull)
  1727. {
  1728. break;
  1729. }
  1730. else if (engineEvent.type == kEngineEventTypeControl)
  1731. {
  1732. const EngineControlEvent& ctrlEvent(engineEvent.ctrl);
  1733. size = ctrlEvent.convertToMidiData(engineEvent.channel, mdata);
  1734. mdataPtr = mdata;
  1735. }
  1736. else if (engineEvent.type == kEngineEventTypeMidi)
  1737. {
  1738. const EngineMidiEvent& midiEvent(engineEvent.midi);
  1739. size = midiEvent.size;
  1740. CARLA_SAFE_ASSERT_CONTINUE(size > 0);
  1741. if (size > EngineMidiEvent::kDataSize)
  1742. {
  1743. CARLA_SAFE_ASSERT_CONTINUE(midiEvent.dataExt != nullptr);
  1744. mdataPtr = midiEvent.dataExt;
  1745. }
  1746. else
  1747. {
  1748. // set first byte
  1749. mdataTmp[0] = static_cast<uint8_t>(midiEvent.data[0] | (engineEvent.channel & MIDI_CHANNEL_BIT));
  1750. // copy rest
  1751. carla_copy<uint8_t>(mdataTmp+1, midiEvent.data+1, size-1U);
  1752. // done
  1753. mdataPtr = mdataTmp;
  1754. }
  1755. }
  1756. else
  1757. {
  1758. continue;
  1759. }
  1760. if (size > 0)
  1761. jackbridge_midi_event_write(eventOut, engineEvent.time, mdataPtr, size);
  1762. }
  1763. }
  1764. }
  1765. if (pData->options.transportMode == ENGINE_TRANSPORT_MODE_JACK)
  1766. {
  1767. if (fTimebaseMaster)
  1768. {
  1769. const bool playing = jackbridge_transport_query(fClient, nullptr) == JackTransportRolling;
  1770. if (fTimebaseRolling != playing)
  1771. {
  1772. fTimebaseRolling = playing;
  1773. pData->timeInfo.playing = playing;
  1774. }
  1775. // Check if we are no longer timebase master
  1776. if (playing && fTimebaseUsecs != 0 && fTimebaseUsecs == pData->timeInfo.usecs)
  1777. {
  1778. carla_debug("No longer timerbase master");
  1779. fTimebaseMaster = false;
  1780. }
  1781. }
  1782. fTimebaseUsecs = pData->timeInfo.usecs;
  1783. }
  1784. #endif // ! BUILD_BRIDGE
  1785. }
  1786. void handleJackLatencyCallback(const jack_latency_callback_mode_t /*mode*/)
  1787. {
  1788. // TODO
  1789. }
  1790. #ifndef BUILD_BRIDGE
  1791. void handleJackTimebaseCallback(jack_nframes_t nframes, jack_position_t* const pos, const int new_pos)
  1792. {
  1793. if (new_pos)
  1794. pData->time.setNeedsReset();
  1795. pData->timeInfo.playing = fTimebaseRolling;
  1796. pData->timeInfo.frame = pos->frame;
  1797. pData->timeInfo.usecs = pos->usecs;
  1798. pData->time.fillJackTimeInfo(pos, nframes);
  1799. }
  1800. void handleJackClientRegistrationCallback(const char* const name, const bool reg)
  1801. {
  1802. CARLA_SAFE_ASSERT_RETURN(name != nullptr && name[0] != '\0',);
  1803. // ignore this if on internal patchbay mode
  1804. #if defined(HAVE_LIBLO) && !defined(BUILD_BRIDGE)
  1805. if (! (fExternalPatchbayHost || (fExternalPatchbayOsc && pData->osc.isControlRegisteredForTCP()))) return;
  1806. #else
  1807. if (! fExternalPatchbayHost) return;
  1808. #endif
  1809. // do nothing on client registration, wait for first port
  1810. if (reg) return;
  1811. const uint groupId(fUsedGroups.getGroupId(name));
  1812. // clients might have been registered without ports
  1813. if (groupId == 0) return;
  1814. GroupNameToId groupNameToId;
  1815. groupNameToId.setData(groupId, name);
  1816. callback(fExternalPatchbayHost, fExternalPatchbayOsc,
  1817. ENGINE_CALLBACK_PATCHBAY_CLIENT_REMOVED, groupNameToId.group, 0, 0, 0, 0.0f, nullptr);
  1818. fUsedGroups.list.removeOne(groupNameToId);
  1819. }
  1820. void handleJackPortRegistrationCallback(const jack_port_id_t port, const bool reg)
  1821. {
  1822. // ignore this if on internal patchbay mode
  1823. #if defined(HAVE_LIBLO) && !defined(BUILD_BRIDGE)
  1824. if (! (fExternalPatchbayHost || (fExternalPatchbayOsc && pData->osc.isControlRegisteredForTCP()))) return;
  1825. #else
  1826. if (! fExternalPatchbayHost) return;
  1827. #endif
  1828. const jack_port_t* const jackPort(jackbridge_port_by_id(fClient, port));
  1829. CARLA_SAFE_ASSERT_RETURN(jackPort != nullptr,);
  1830. const char* const fullPortName(jackbridge_port_name(jackPort));
  1831. CARLA_SAFE_ASSERT_RETURN(fullPortName != nullptr && fullPortName[0] != '\0',);
  1832. if (reg)
  1833. {
  1834. const char* const shortPortName(jackbridge_port_short_name(jackPort));
  1835. CARLA_SAFE_ASSERT_RETURN(shortPortName != nullptr && shortPortName[0] != '\0',);
  1836. bool found;
  1837. CarlaString groupName(fullPortName);
  1838. groupName.truncate(groupName.rfind(shortPortName, &found)-1);
  1839. CARLA_SAFE_ASSERT_RETURN(found,);
  1840. const int jackPortFlags(jackbridge_port_flags(jackPort));
  1841. uint groupId(fUsedGroups.getGroupId(groupName));
  1842. if (groupId == 0)
  1843. {
  1844. groupId = ++fUsedGroups.lastId;
  1845. GroupNameToId groupNameToId;
  1846. groupNameToId.setData(groupId, groupName);
  1847. int pluginId = -1;
  1848. PatchbayIcon icon = (jackPortFlags & JackPortIsPhysical) ? PATCHBAY_ICON_HARDWARE : PATCHBAY_ICON_APPLICATION;
  1849. findPluginIdAndIcon(groupName, pluginId, icon);
  1850. callback(fExternalPatchbayHost, fExternalPatchbayOsc,
  1851. ENGINE_CALLBACK_PATCHBAY_CLIENT_ADDED,
  1852. groupNameToId.group,
  1853. icon,
  1854. pluginId,
  1855. 0, 0.0f,
  1856. groupNameToId.name);
  1857. fUsedGroups.list.append(groupNameToId);
  1858. }
  1859. addPatchbayJackPort(fExternalPatchbayHost, fExternalPatchbayOsc,
  1860. groupId, jackPort, shortPortName, fullPortName, jackPortFlags);
  1861. }
  1862. else
  1863. {
  1864. const PortNameToId& portNameToId(fUsedPorts.getPortNameToId(fullPortName));
  1865. /* NOTE: Due to JACK2 async behaviour the port we get here might be the same of a previous rename-plugin request.
  1866. See the comment on CarlaEngineJack::renamePlugin() for more information. */
  1867. if (portNameToId.group <= 0 || portNameToId.port <= 0) return;
  1868. callback(fExternalPatchbayHost, fExternalPatchbayOsc,
  1869. ENGINE_CALLBACK_PATCHBAY_PORT_REMOVED,
  1870. portNameToId.group,
  1871. static_cast<int>(portNameToId.port),
  1872. 0, 0, 0.0f, nullptr);
  1873. fUsedPorts.list.removeOne(portNameToId);
  1874. }
  1875. }
  1876. void handleJackPortConnectCallback(const jack_port_id_t a, const jack_port_id_t b, const bool connect)
  1877. {
  1878. // ignore this if on internal patchbay mode
  1879. #if defined(HAVE_LIBLO) && !defined(BUILD_BRIDGE)
  1880. if (! (fExternalPatchbayHost || (fExternalPatchbayOsc && pData->osc.isControlRegisteredForTCP()))) return;
  1881. #else
  1882. if (! fExternalPatchbayHost) return;
  1883. #endif
  1884. const jack_port_t* const jackPortA(jackbridge_port_by_id(fClient, a));
  1885. CARLA_SAFE_ASSERT_RETURN(jackPortA != nullptr,);
  1886. const jack_port_t* const jackPortB(jackbridge_port_by_id(fClient, b));
  1887. CARLA_SAFE_ASSERT_RETURN(jackPortB != nullptr,);
  1888. const char* const fullPortNameA(jackbridge_port_name(jackPortA));
  1889. CARLA_SAFE_ASSERT_RETURN(fullPortNameA != nullptr && fullPortNameA[0] != '\0',);
  1890. const char* const fullPortNameB(jackbridge_port_name(jackPortB));
  1891. CARLA_SAFE_ASSERT_RETURN(fullPortNameB != nullptr && fullPortNameB[0] != '\0',);
  1892. const PortNameToId& portNameToIdA(fUsedPorts.getPortNameToId(fullPortNameA));
  1893. const PortNameToId& portNameToIdB(fUsedPorts.getPortNameToId(fullPortNameB));
  1894. /* NOTE: Due to JACK2 async behaviour the port we get here might be the same of a previous rename-plugin request.
  1895. See the comment on CarlaEngineJack::renamePlugin() for more information. */
  1896. if (portNameToIdA.group <= 0 || portNameToIdA.port <= 0) return;
  1897. if (portNameToIdB.group <= 0 || portNameToIdB.port <= 0) return;
  1898. if (connect)
  1899. {
  1900. char strBuf[STR_MAX+1];
  1901. std::snprintf(strBuf, STR_MAX, "%i:%i:%i:%i", portNameToIdA.group, portNameToIdA.port, portNameToIdB.group, portNameToIdB.port);
  1902. strBuf[STR_MAX] = '\0';
  1903. ConnectionToId connectionToId;
  1904. connectionToId.setData(++fUsedConnections.lastId, portNameToIdA.group, portNameToIdA.port, portNameToIdB.group, portNameToIdB.port);
  1905. callback(fExternalPatchbayHost, fExternalPatchbayOsc,
  1906. ENGINE_CALLBACK_PATCHBAY_CONNECTION_ADDED,
  1907. connectionToId.id,
  1908. 0, 0, 0, 0.0f,
  1909. strBuf);
  1910. fUsedConnections.list.append(connectionToId);
  1911. }
  1912. else
  1913. {
  1914. ConnectionToId connectionToId = { 0, 0, 0, 0, 0 };
  1915. bool found = false;
  1916. {
  1917. const CarlaMutexLocker cml(fUsedConnections.mutex);
  1918. for (LinkedList<ConnectionToId>::Itenerator it = fUsedConnections.list.begin2(); it.valid(); it.next())
  1919. {
  1920. connectionToId = it.getValue(connectionToId);
  1921. CARLA_SAFE_ASSERT_CONTINUE(connectionToId.id != 0);
  1922. if (connectionToId.groupA == portNameToIdA.group && connectionToId.portA == portNameToIdA.port &&
  1923. connectionToId.groupB == portNameToIdB.group && connectionToId.portB == portNameToIdB.port)
  1924. {
  1925. found = true;
  1926. fUsedConnections.list.remove(it);
  1927. break;
  1928. }
  1929. }
  1930. }
  1931. if (found) {
  1932. callback(fExternalPatchbayHost, fExternalPatchbayOsc,
  1933. ENGINE_CALLBACK_PATCHBAY_CONNECTION_REMOVED,
  1934. connectionToId.id,
  1935. 0, 0, 0, 0.0f, nullptr);
  1936. }
  1937. }
  1938. }
  1939. void handleJackPortRenameCallback(const jack_port_id_t port, const char* const oldFullName, const char* const newFullName)
  1940. {
  1941. // ignore this if on internal patchbay mode
  1942. #if defined(HAVE_LIBLO) && !defined(BUILD_BRIDGE)
  1943. if (! (fExternalPatchbayHost || (fExternalPatchbayOsc && pData->osc.isControlRegisteredForTCP()))) return;
  1944. #else
  1945. if (! fExternalPatchbayHost) return;
  1946. #endif
  1947. CARLA_SAFE_ASSERT_RETURN(oldFullName != nullptr && oldFullName[0] != '\0',);
  1948. CARLA_SAFE_ASSERT_RETURN(newFullName != nullptr && newFullName[0] != '\0',);
  1949. const jack_port_t* const jackPort(jackbridge_port_by_id(fClient, port));
  1950. CARLA_SAFE_ASSERT_RETURN(jackPort != nullptr,);
  1951. const char* const shortPortName(jackbridge_port_short_name(jackPort));
  1952. CARLA_SAFE_ASSERT_RETURN(shortPortName != nullptr && shortPortName[0] != '\0',);
  1953. bool found;
  1954. CarlaString groupName(newFullName);
  1955. groupName.truncate(groupName.rfind(shortPortName, &found)-1);
  1956. CARLA_SAFE_ASSERT_RETURN(found,);
  1957. const uint groupId(fUsedGroups.getGroupId(groupName));
  1958. CARLA_SAFE_ASSERT_RETURN(groupId > 0,);
  1959. for (LinkedList<PortNameToId>::Itenerator it = fUsedPorts.list.begin2(); it.valid(); it.next())
  1960. {
  1961. static PortNameToId portNameFallback = { 0, 0, { '\0' }, { '\0' } };
  1962. PortNameToId& portNameToId(it.getValue(portNameFallback));
  1963. CARLA_SAFE_ASSERT_CONTINUE(portNameToId.group != 0);
  1964. if (std::strncmp(portNameToId.fullName, oldFullName, STR_MAX) == 0)
  1965. {
  1966. CARLA_SAFE_ASSERT_CONTINUE(portNameToId.group == groupId);
  1967. portNameToId.rename(shortPortName, newFullName);
  1968. callback(fExternalPatchbayHost, fExternalPatchbayOsc,
  1969. ENGINE_CALLBACK_PATCHBAY_PORT_CHANGED,
  1970. portNameToId.group,
  1971. static_cast<int>(portNameToId.port),
  1972. 0, 0, 0.0f,
  1973. portNameToId.name);
  1974. break;
  1975. }
  1976. }
  1977. }
  1978. #endif
  1979. void handleJackShutdownCallback()
  1980. {
  1981. #ifndef BUILD_BRIDGE
  1982. signalThreadShouldExit();
  1983. #endif
  1984. const PendingRtEventsRunner prt(this, pData->bufferSize);
  1985. for (uint i=0; i < pData->curPluginCount; ++i)
  1986. {
  1987. if (CarlaPlugin* const plugin = pData->plugins[i].plugin)
  1988. {
  1989. plugin->tryLock(true);
  1990. if (CarlaEngineJackClient* const client = (CarlaEngineJackClient*)plugin->getEngineClient())
  1991. client->invalidate();
  1992. plugin->unlock();
  1993. }
  1994. }
  1995. fClient = nullptr;
  1996. #ifndef BUILD_BRIDGE
  1997. carla_zeroPointers(fRackPorts, kRackPortCount);
  1998. #endif
  1999. callback(true, true, ENGINE_CALLBACK_QUIT, 0, 0, 0, 0, 0.0f, nullptr);
  2000. }
  2001. // -------------------------------------------------------------------
  2002. void handlePluginJackShutdownCallback(CarlaPlugin* const plugin)
  2003. {
  2004. CarlaEngineJackClient* const engineClient((CarlaEngineJackClient*)plugin->getEngineClient());
  2005. CARLA_SAFE_ASSERT_RETURN(engineClient != nullptr,);
  2006. plugin->tryLock(true);
  2007. engineClient->invalidate();
  2008. plugin->unlock();
  2009. //if (pData->nextAction.pluginId == plugin->getId())
  2010. // pData->nextAction.clearAndReset();
  2011. callback(true, true, ENGINE_CALLBACK_PLUGIN_UNAVAILABLE, plugin->getId(), 0, 0, 0, 0.0f, "Killed by JACK");
  2012. }
  2013. // -------------------------------------------------------------------
  2014. private:
  2015. jack_client_t* fClient;
  2016. bool fExternalPatchbayHost;
  2017. bool fExternalPatchbayOsc;
  2018. bool fFreewheel;
  2019. // -------------------------------------------------------------------
  2020. #ifdef BUILD_BRIDGE
  2021. bool fIsRunning;
  2022. #else
  2023. enum RackPorts {
  2024. kRackPortAudioIn1 = 0,
  2025. kRackPortAudioIn2 = 1,
  2026. kRackPortAudioOut1 = 2,
  2027. kRackPortAudioOut2 = 3,
  2028. kRackPortEventIn = 4,
  2029. kRackPortEventOut = 5,
  2030. kRackPortCount = 6
  2031. };
  2032. jack_port_t* fRackPorts[kRackPortCount];
  2033. bool fTimebaseMaster;
  2034. bool fTimebaseRolling;
  2035. uint64_t fTimebaseUsecs;
  2036. PatchbayGroupList fUsedGroups;
  2037. PatchbayPortList fUsedPorts;
  2038. PatchbayConnectionList fUsedConnections;
  2039. CarlaMutex fPatchbayProcThreadProtectionMutex;
  2040. mutable CharStringListPtr fRetConns;
  2041. void findPluginIdAndIcon(const char* const clientName, int& pluginId, PatchbayIcon& icon) const noexcept
  2042. {
  2043. carla_debug("CarlaEngineJack::findPluginIdAndIcon(\"%s\", ...)", clientName);
  2044. // TODO - this currently only works in multi-client mode
  2045. if (pData->options.processMode != ENGINE_PROCESS_MODE_MULTIPLE_CLIENTS)
  2046. return;
  2047. const char* const uuidstr = jackbridge_get_uuid_for_client_name(fClient, clientName);
  2048. CARLA_SAFE_ASSERT_RETURN(uuidstr != nullptr && uuidstr[0] != '\0',);
  2049. jack_uuid_t uuid;
  2050. CARLA_SAFE_ASSERT_RETURN(jackbridge_uuid_parse(uuidstr, &uuid),);
  2051. {
  2052. char* value = nullptr;
  2053. char* type = nullptr;
  2054. if (! jackbridge_get_property(uuid, "https://kx.studio/ns/carla/plugin-id", &value, &type))
  2055. return;
  2056. CARLA_SAFE_ASSERT_RETURN(type != nullptr && type[0] != '\0',);
  2057. CARLA_SAFE_ASSERT_RETURN(value != nullptr && value[0] != '\0',);
  2058. CARLA_SAFE_ASSERT_RETURN(std::strcmp(type, "http://www.w3.org/2001/XMLSchema#integer") == 0,);
  2059. pluginId = std::atoi(value);
  2060. icon = PATCHBAY_ICON_PLUGIN;
  2061. }
  2062. {
  2063. char* value = nullptr;
  2064. char* type = nullptr;
  2065. if (! jackbridge_get_property(uuid, "https://kx.studio/ns/carla/plugin-icon", &value, &type))
  2066. return;
  2067. CARLA_SAFE_ASSERT_RETURN(type != nullptr && type[0] != '\0',);
  2068. CARLA_SAFE_ASSERT_RETURN(value != nullptr && value[0] != '\0',);
  2069. CARLA_SAFE_ASSERT_RETURN(std::strcmp(type, "text/plain") == 0,);
  2070. /**/ if (std::strcmp(value, "app") == 0)
  2071. icon = PATCHBAY_ICON_APPLICATION;
  2072. else if (std::strcmp(value, "application") == 0)
  2073. icon = PATCHBAY_ICON_APPLICATION;
  2074. else if (std::strcmp(value, "plugin") == 0)
  2075. icon = PATCHBAY_ICON_PLUGIN;
  2076. else if (std::strcmp(value, "hardware") == 0)
  2077. icon = PATCHBAY_ICON_HARDWARE;
  2078. else if (std::strcmp(value, "carla") == 0)
  2079. icon = PATCHBAY_ICON_CARLA;
  2080. else if (std::strcmp(value, "distrho") == 0)
  2081. icon = PATCHBAY_ICON_DISTRHO;
  2082. else if (std::strcmp(value, "file") == 0)
  2083. icon = PATCHBAY_ICON_FILE;
  2084. }
  2085. }
  2086. void initJackPatchbay(const bool sendHost, const bool sendOSC, const char* const ourName)
  2087. {
  2088. CARLA_SAFE_ASSERT_RETURN(pData->options.processMode != ENGINE_PROCESS_MODE_PATCHBAY ||
  2089. (fExternalPatchbayHost && sendHost) || (fExternalPatchbayOsc && sendOSC),);
  2090. CARLA_SAFE_ASSERT_RETURN(ourName != nullptr && ourName[0] != '\0',);
  2091. CarlaStringList parsedGroups;
  2092. // add our client first
  2093. {
  2094. parsedGroups.append(ourName);
  2095. GroupNameToId groupNameToId;
  2096. groupNameToId.setData(++fUsedGroups.lastId, ourName);
  2097. callback(sendHost, sendOSC,
  2098. ENGINE_CALLBACK_PATCHBAY_CLIENT_ADDED,
  2099. groupNameToId.group,
  2100. PATCHBAY_ICON_CARLA,
  2101. MAIN_CARLA_PLUGIN_ID,
  2102. 0, 0.0f,
  2103. groupNameToId.name);
  2104. fUsedGroups.list.append(groupNameToId);
  2105. }
  2106. // query all jack ports
  2107. {
  2108. const char** const ports = jackbridge_get_ports(fClient, nullptr, nullptr, 0);
  2109. CARLA_SAFE_ASSERT_RETURN(ports != nullptr,);
  2110. for (int i=0; ports[i] != nullptr; ++i)
  2111. {
  2112. const char* const fullPortName(ports[i]);
  2113. CARLA_SAFE_ASSERT_CONTINUE(fullPortName != nullptr && fullPortName[0] != '\0');
  2114. const jack_port_t* const jackPort(jackbridge_port_by_name(fClient, fullPortName));
  2115. CARLA_SAFE_ASSERT_CONTINUE(jackPort != nullptr);
  2116. const char* const shortPortName(jackbridge_port_short_name(jackPort));
  2117. CARLA_SAFE_ASSERT_CONTINUE(shortPortName != nullptr && shortPortName[0] != '\0');
  2118. const int jackPortFlags(jackbridge_port_flags(jackPort));
  2119. uint groupId = 0;
  2120. bool found;
  2121. CarlaString groupName(fullPortName);
  2122. groupName.truncate(groupName.rfind(shortPortName, &found)-1);
  2123. CARLA_SAFE_ASSERT_CONTINUE(found);
  2124. if (parsedGroups.contains(groupName))
  2125. {
  2126. groupId = fUsedGroups.getGroupId(groupName);
  2127. CARLA_SAFE_ASSERT_CONTINUE(groupId > 0);
  2128. }
  2129. else
  2130. {
  2131. groupId = ++fUsedGroups.lastId;
  2132. parsedGroups.append(groupName);
  2133. GroupNameToId groupNameToId;
  2134. groupNameToId.setData(groupId, groupName);
  2135. int pluginId = -1;
  2136. PatchbayIcon icon = (jackPortFlags & JackPortIsPhysical) ? PATCHBAY_ICON_HARDWARE : PATCHBAY_ICON_APPLICATION;
  2137. findPluginIdAndIcon(groupName, pluginId, icon);
  2138. callback(sendHost, sendOSC,
  2139. ENGINE_CALLBACK_PATCHBAY_CLIENT_ADDED,
  2140. groupNameToId.group,
  2141. icon,
  2142. pluginId,
  2143. 0, 0.0f,
  2144. groupNameToId.name);
  2145. fUsedGroups.list.append(groupNameToId);
  2146. }
  2147. addPatchbayJackPort(sendHost, sendOSC, groupId, jackPort, shortPortName, fullPortName, jackPortFlags);
  2148. }
  2149. jackbridge_free(ports);
  2150. }
  2151. // query connections, after all ports are in place
  2152. if (const char** const ports = jackbridge_get_ports(fClient, nullptr, nullptr, JackPortIsOutput))
  2153. {
  2154. char strBuf[STR_MAX+1];
  2155. for (int i=0; ports[i] != nullptr; ++i)
  2156. {
  2157. const char* const fullPortName(ports[i]);
  2158. CARLA_SAFE_ASSERT_CONTINUE(fullPortName != nullptr && fullPortName[0] != '\0');
  2159. const jack_port_t* const jackPort(jackbridge_port_by_name(fClient, fullPortName));
  2160. CARLA_SAFE_ASSERT_CONTINUE(jackPort != nullptr);
  2161. const PortNameToId& thisPort(fUsedPorts.getPortNameToId(fullPortName));
  2162. CARLA_SAFE_ASSERT_CONTINUE(thisPort.group > 0);
  2163. CARLA_SAFE_ASSERT_CONTINUE(thisPort.port > 0);
  2164. if (const char** const connections = jackbridge_port_get_all_connections(fClient, jackPort))
  2165. {
  2166. for (int j=0; connections[j] != nullptr; ++j)
  2167. {
  2168. const char* const connection(connections[j]);
  2169. CARLA_SAFE_ASSERT_CONTINUE(connection != nullptr && connection[0] != '\0');
  2170. const PortNameToId& targetPort(fUsedPorts.getPortNameToId(connection));
  2171. CARLA_SAFE_ASSERT_CONTINUE(targetPort.group > 0);
  2172. CARLA_SAFE_ASSERT_CONTINUE(targetPort.port > 0);
  2173. std::snprintf(strBuf, STR_MAX, "%i:%i:%i:%i", thisPort.group, thisPort.port, targetPort.group, targetPort.port);
  2174. strBuf[STR_MAX] = '\0';
  2175. ConnectionToId connectionToId;
  2176. connectionToId.setData(++fUsedConnections.lastId, thisPort.group, thisPort.port, targetPort.group, targetPort.port);
  2177. callback(sendHost, sendOSC,
  2178. ENGINE_CALLBACK_PATCHBAY_CONNECTION_ADDED,
  2179. connectionToId.id,
  2180. 0, 0, 0, 0.0f,
  2181. strBuf);
  2182. fUsedConnections.list.append(connectionToId);
  2183. }
  2184. jackbridge_free(connections);
  2185. }
  2186. }
  2187. jackbridge_free(ports);
  2188. }
  2189. }
  2190. void addPatchbayJackPort(const bool sendHost, const bool sendOSC,
  2191. const uint groupId, const jack_port_t* const jackPort,
  2192. const char* const shortPortName, const char* const fullPortName, const int jackPortFlags)
  2193. {
  2194. bool portIsInput = (jackPortFlags & JackPortIsInput);
  2195. bool portIsAudio = (std::strcmp(jackbridge_port_type(jackPort), JACK_DEFAULT_AUDIO_TYPE) == 0);
  2196. bool portIsMIDI = (std::strcmp(jackbridge_port_type(jackPort), JACK_DEFAULT_MIDI_TYPE) == 0);
  2197. bool portIsCV = false;
  2198. bool portIsOSC = false;
  2199. if (const jack_uuid_t uuid = jackbridge_port_uuid(jackPort))
  2200. {
  2201. char* value = nullptr;
  2202. char* type = nullptr;
  2203. if (jackbridge_get_property(uuid, JACKEY_SIGNAL_TYPE, &value, &type)
  2204. && value != nullptr
  2205. && type != nullptr
  2206. && std::strcmp(type, "text/plain") == 0)
  2207. {
  2208. portIsCV = (std::strcmp(value, "CV") == 0);
  2209. portIsOSC = (std::strcmp(value, "OSC") == 0);
  2210. }
  2211. }
  2212. uint canvasPortFlags = 0x0;
  2213. canvasPortFlags |= portIsInput ? PATCHBAY_PORT_IS_INPUT : 0x0;
  2214. /**/ if (portIsCV)
  2215. canvasPortFlags |= PATCHBAY_PORT_TYPE_CV;
  2216. else if (portIsOSC)
  2217. canvasPortFlags |= PATCHBAY_PORT_TYPE_OSC;
  2218. else if (portIsAudio)
  2219. canvasPortFlags |= PATCHBAY_PORT_TYPE_AUDIO;
  2220. else if (portIsMIDI)
  2221. canvasPortFlags |= PATCHBAY_PORT_TYPE_MIDI;
  2222. PortNameToId portNameToId;
  2223. portNameToId.setData(groupId, ++fUsedPorts.lastId, shortPortName, fullPortName);
  2224. callback(sendHost, sendOSC,
  2225. ENGINE_CALLBACK_PATCHBAY_PORT_ADDED,
  2226. portNameToId.group,
  2227. static_cast<int>(portNameToId.port),
  2228. static_cast<int>(canvasPortFlags),
  2229. 0, 0.0f,
  2230. portNameToId.name);
  2231. fUsedPorts.list.append(portNameToId);
  2232. }
  2233. #endif
  2234. // -------------------------------------------------------------------
  2235. void processPlugin(CarlaPlugin* const plugin, const uint32_t nframes)
  2236. {
  2237. const uint32_t audioInCount(plugin->getAudioInCount());
  2238. const uint32_t audioOutCount(plugin->getAudioOutCount());
  2239. const uint32_t cvInCount(plugin->getCVInCount());
  2240. const uint32_t cvOutCount(plugin->getCVOutCount());
  2241. const float* audioIn[audioInCount];
  2242. /* */ float* audioOut[audioOutCount];
  2243. const float* cvIn[cvInCount];
  2244. /* */ float* cvOut[cvOutCount];
  2245. for (uint32_t i=0; i < audioInCount; ++i)
  2246. {
  2247. CarlaEngineAudioPort* const port(plugin->getAudioInPort(i));
  2248. audioIn[i] = port->getBuffer();
  2249. }
  2250. for (uint32_t i=0; i < audioOutCount; ++i)
  2251. {
  2252. CarlaEngineAudioPort* const port(plugin->getAudioOutPort(i));
  2253. audioOut[i] = port->getBuffer();
  2254. }
  2255. for (uint32_t i=0; i < cvInCount; ++i)
  2256. {
  2257. CarlaEngineCVPort* const port(plugin->getCVInPort(i));
  2258. cvIn[i] = port->getBuffer();
  2259. CARLA_SAFE_ASSERT(cvIn[i] != nullptr);
  2260. }
  2261. for (uint32_t i=0; i < cvOutCount; ++i)
  2262. {
  2263. CarlaEngineCVPort* const port(plugin->getCVOutPort(i));
  2264. cvOut[i] = port->getBuffer();
  2265. }
  2266. float inPeaks[2] = { 0.0f };
  2267. float outPeaks[2] = { 0.0f };
  2268. for (uint32_t i=0; i < audioInCount && i < 2; ++i)
  2269. {
  2270. for (uint32_t j=0; j < nframes; ++j)
  2271. {
  2272. const float absV(std::abs(audioIn[i][j]));
  2273. if (absV > inPeaks[i])
  2274. inPeaks[i] = absV;
  2275. }
  2276. }
  2277. plugin->process(audioIn, audioOut, cvIn, cvOut, nframes);
  2278. for (uint32_t i=0; i < audioOutCount && i < 2; ++i)
  2279. {
  2280. for (uint32_t j=0; j < nframes; ++j)
  2281. {
  2282. const float absV(std::abs(audioOut[i][j]));
  2283. if (absV > outPeaks[i])
  2284. outPeaks[i] = absV;
  2285. }
  2286. }
  2287. setPluginPeaksRT(plugin->getId(), inPeaks, outPeaks);
  2288. }
  2289. #ifndef BUILD_BRIDGE
  2290. // -------------------------------------------------------------------
  2291. struct PostPonedJackEvent {
  2292. enum Type {
  2293. kTypeNull = 0,
  2294. kTypeClientRegister,
  2295. kTypePortRegister,
  2296. kTypePortConnect,
  2297. kTypePortRename
  2298. };
  2299. Type type;
  2300. bool action; // register or connect
  2301. jack_port_id_t port1;
  2302. jack_port_id_t port2;
  2303. char name1[STR_MAX+1];
  2304. char name2[STR_MAX+1];
  2305. };
  2306. LinkedList<PostPonedJackEvent> fPostPonedEvents;
  2307. CarlaMutex fPostPonedEventsMutex;
  2308. bool fIsInternalClient;
  2309. void postPoneJackCallback(const PostPonedJackEvent& ev)
  2310. {
  2311. const CarlaMutexLocker cml(fPostPonedEventsMutex);
  2312. fPostPonedEvents.append(ev);
  2313. }
  2314. void run() override
  2315. {
  2316. LinkedList<PostPonedJackEvent> events;
  2317. PostPonedJackEvent nullEvent;
  2318. carla_zeroStruct(nullEvent);
  2319. for (; ! shouldThreadExit();)
  2320. {
  2321. if (fIsInternalClient)
  2322. idle();
  2323. {
  2324. const CarlaMutexLocker cml(fPostPonedEventsMutex);
  2325. if (fPostPonedEvents.count() > 0)
  2326. fPostPonedEvents.moveTo(events);
  2327. }
  2328. if (fClient == nullptr)
  2329. break;
  2330. if (events.count() == 0)
  2331. {
  2332. carla_msleep(fIsInternalClient ? 50 : 200);
  2333. continue;
  2334. }
  2335. for (LinkedList<PostPonedJackEvent>::Itenerator it = events.begin2(); it.valid(); it.next())
  2336. {
  2337. const PostPonedJackEvent& ev(it.getValue(nullEvent));
  2338. CARLA_SAFE_ASSERT_CONTINUE(ev.type != PostPonedJackEvent::kTypeNull);
  2339. switch (ev.type)
  2340. {
  2341. case PostPonedJackEvent::kTypeNull:
  2342. break;
  2343. case PostPonedJackEvent::kTypeClientRegister:
  2344. handleJackClientRegistrationCallback(ev.name1, ev.action);
  2345. break;
  2346. case PostPonedJackEvent::kTypePortRegister:
  2347. handleJackPortRegistrationCallback(ev.port1, ev.action);
  2348. break;
  2349. case PostPonedJackEvent::kTypePortConnect:
  2350. handleJackPortConnectCallback(ev.port1, ev.port2, ev.action);
  2351. break;
  2352. case PostPonedJackEvent::kTypePortRename:
  2353. handleJackPortRenameCallback(ev.port1, ev.name1, ev.name2);
  2354. break;
  2355. }
  2356. }
  2357. events.clear();
  2358. }
  2359. events.clear();
  2360. }
  2361. #endif // BUILD_BRIDGE
  2362. // -------------------------------------------------------------------
  2363. // disable -Wattributes warnings
  2364. #if defined(__clang__)
  2365. # pragma clang diagnostic push
  2366. # pragma clang diagnostic ignored "-Wattributes"
  2367. #elif defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6))
  2368. # pragma GCC diagnostic push
  2369. # pragma GCC diagnostic ignored "-Wattributes"
  2370. #endif
  2371. #define handlePtr ((CarlaEngineJack*)arg)
  2372. static void JACKBRIDGE_API carla_jack_thread_init_callback(void*)
  2373. {
  2374. #ifdef __SSE2_MATH__
  2375. // Set FTZ and DAZ flags
  2376. _mm_setcsr(_mm_getcsr() | 0x8040);
  2377. #endif
  2378. }
  2379. static int JACKBRIDGE_API carla_jack_bufsize_callback(jack_nframes_t newBufferSize, void* arg)
  2380. {
  2381. handlePtr->handleJackBufferSizeCallback(newBufferSize);
  2382. return 0;
  2383. }
  2384. static int JACKBRIDGE_API carla_jack_srate_callback(jack_nframes_t newSampleRate, void* arg)
  2385. {
  2386. handlePtr->handleJackSampleRateCallback(newSampleRate);
  2387. return 0;
  2388. }
  2389. static void JACKBRIDGE_API carla_jack_freewheel_callback(int starting, void* arg)
  2390. {
  2391. handlePtr->handleJackFreewheelCallback(bool(starting));
  2392. }
  2393. static void JACKBRIDGE_API carla_jack_latency_callback(jack_latency_callback_mode_t mode, void* arg)
  2394. {
  2395. handlePtr->handleJackLatencyCallback(mode);
  2396. }
  2397. static int JACKBRIDGE_API carla_jack_process_callback(jack_nframes_t nframes, void* arg) __attribute__((annotate("realtime")))
  2398. {
  2399. handlePtr->handleJackProcessCallback(nframes);
  2400. return 0;
  2401. }
  2402. #ifndef BUILD_BRIDGE
  2403. static void JACKBRIDGE_API carla_jack_timebase_callback(jack_transport_state_t, jack_nframes_t nframes, jack_position_t* pos, int new_pos, void* arg) __attribute__((annotate("realtime")))
  2404. {
  2405. handlePtr->handleJackTimebaseCallback(nframes, pos, new_pos);
  2406. }
  2407. static void JACKBRIDGE_API carla_jack_client_registration_callback(const char* name, int reg, void* arg)
  2408. {
  2409. PostPonedJackEvent ev;
  2410. carla_zeroStruct(ev);
  2411. ev.type = PostPonedJackEvent::kTypeClientRegister;
  2412. ev.action = (reg != 0);
  2413. std::strncpy(ev.name1, name, STR_MAX);
  2414. handlePtr->postPoneJackCallback(ev);
  2415. }
  2416. static void JACKBRIDGE_API carla_jack_port_registration_callback(jack_port_id_t port, int reg, void* arg)
  2417. {
  2418. PostPonedJackEvent ev;
  2419. carla_zeroStruct(ev);
  2420. ev.type = PostPonedJackEvent::kTypePortRegister;
  2421. ev.action = (reg != 0);
  2422. ev.port1 = port;
  2423. handlePtr->postPoneJackCallback(ev);
  2424. }
  2425. static void JACKBRIDGE_API carla_jack_port_connect_callback(jack_port_id_t a, jack_port_id_t b, int connect, void* arg)
  2426. {
  2427. PostPonedJackEvent ev;
  2428. carla_zeroStruct(ev);
  2429. ev.type = PostPonedJackEvent::kTypePortConnect;
  2430. ev.action = (connect != 0);
  2431. ev.port1 = a;
  2432. ev.port2 = b;
  2433. handlePtr->postPoneJackCallback(ev);
  2434. }
  2435. static void JACKBRIDGE_API carla_jack_port_rename_callback(jack_port_id_t port, const char* oldName, const char* newName, void* arg)
  2436. {
  2437. PostPonedJackEvent ev;
  2438. carla_zeroStruct(ev);
  2439. ev.type = PostPonedJackEvent::kTypePortRename;
  2440. ev.port1 = port;
  2441. std::strncpy(ev.name1, oldName, STR_MAX);
  2442. std::strncpy(ev.name2, newName, STR_MAX);
  2443. handlePtr->postPoneJackCallback(ev);
  2444. }
  2445. static int JACKBRIDGE_API carla_jack_xrun_callback(void* arg)
  2446. {
  2447. ++(handlePtr->pData->xruns);
  2448. return 0;
  2449. }
  2450. #endif
  2451. static void JACKBRIDGE_API carla_jack_shutdown_callback(void* arg)
  2452. {
  2453. handlePtr->handleJackShutdownCallback();
  2454. }
  2455. #undef handlePtr
  2456. // -------------------------------------------------------------------
  2457. #ifndef BUILD_BRIDGE
  2458. static int JACKBRIDGE_API carla_jack_process_callback_plugin(jack_nframes_t nframes, void* arg) __attribute__((annotate("realtime")))
  2459. {
  2460. CarlaPlugin* const plugin((CarlaPlugin*)arg);
  2461. CARLA_SAFE_ASSERT_RETURN(plugin != nullptr && plugin->isEnabled(), 0);
  2462. CarlaEngineJack* const engine((CarlaEngineJack*)plugin->getEngine());
  2463. CARLA_SAFE_ASSERT_RETURN(engine != nullptr, 0);
  2464. if (plugin->tryLock(engine->fFreewheel))
  2465. {
  2466. plugin->initBuffers();
  2467. engine->processPlugin(plugin, nframes);
  2468. plugin->unlock();
  2469. }
  2470. return 0;
  2471. }
  2472. /*
  2473. static int JACKBRIDGE_API carla_jack_bufsize_callback_plugin(jack_nframes_t nframes, void* arg)
  2474. {
  2475. CarlaPlugin* const plugin((CarlaPlugin*)arg);
  2476. CARLA_SAFE_ASSERT_RETURN(plugin != nullptr && plugin->isEnabled(), 0);
  2477. plugin->bufferSizeChanged(nframes);
  2478. return 1;
  2479. }
  2480. static int JACKBRIDGE_API carla_jack_srate_callback_plugin(jack_nframes_t nframes, void* arg)
  2481. {
  2482. CarlaPlugin* const plugin((CarlaPlugin*)arg);
  2483. CARLA_SAFE_ASSERT_RETURN(plugin != nullptr && plugin->isEnabled(), 0);
  2484. plugin->sampleRateChanged(nframes);
  2485. return 1;
  2486. }
  2487. */
  2488. static void JACKBRIDGE_API carla_jack_latency_callback_plugin(jack_latency_callback_mode_t /*mode*/, void* /*arg*/)
  2489. {
  2490. // TODO
  2491. }
  2492. static void JACKBRIDGE_API carla_jack_shutdown_callback_plugin(void* arg)
  2493. {
  2494. CarlaPlugin* const plugin((CarlaPlugin*)arg);
  2495. CARLA_SAFE_ASSERT_RETURN(plugin != nullptr,);
  2496. CarlaEngineJack* const engine((CarlaEngineJack*)plugin->getEngine());
  2497. CARLA_SAFE_ASSERT_RETURN(engine != nullptr,);
  2498. engine->handlePluginJackShutdownCallback(plugin);
  2499. }
  2500. #endif
  2501. // enable -Wattributes again
  2502. #if defined(__clang__)
  2503. # pragma clang diagnostic pop
  2504. #elif defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6))
  2505. # pragma GCC diagnostic pop
  2506. #endif
  2507. CARLA_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(CarlaEngineJack)
  2508. };
  2509. // -----------------------------------------------------------------------
  2510. CarlaEngine* CarlaEngine::newJack()
  2511. {
  2512. carla_debug("CarlaEngine::newJack()");
  2513. return new CarlaEngineJack();
  2514. }
  2515. // -----------------------------------------------------------------------
  2516. CARLA_BACKEND_END_NAMESPACE
  2517. #if defined(JACKBRIDGE_DIRECT) && !defined(BUILD_BRIDGE)
  2518. // -----------------------------------------------------------------------
  2519. // internal jack client
  2520. CARLA_EXPORT
  2521. int jack_initialize (jack_client_t *client, const char *load_init);
  2522. CARLA_EXPORT
  2523. void jack_finish(void *arg);
  2524. #ifdef CARLA_OS_UNIX
  2525. # include "ThreadSafeFFTW.hpp"
  2526. static ThreadSafeFFTW sThreadSafeFFTW;
  2527. #endif
  2528. // -----------------------------------------------------------------------
  2529. CARLA_EXPORT
  2530. int jack_initialize(jack_client_t* const client, const char* const load_init)
  2531. {
  2532. CARLA_BACKEND_USE_NAMESPACE
  2533. EngineProcessMode mode;
  2534. if (load_init != nullptr && std::strcmp(load_init, "rack") == 0)
  2535. mode = ENGINE_PROCESS_MODE_CONTINUOUS_RACK;
  2536. else
  2537. mode = ENGINE_PROCESS_MODE_MULTIPLE_CLIENTS;
  2538. #ifdef USING_JUCE
  2539. juce::initialiseJuce_GUI();
  2540. #endif
  2541. CarlaEngineJack* const engine = new CarlaEngineJack();
  2542. engine->setOption(ENGINE_OPTION_FORCE_STEREO, 1, nullptr);
  2543. engine->setOption(ENGINE_OPTION_AUDIO_DRIVER, 0, "JACK");
  2544. engine->setOption(ENGINE_OPTION_AUDIO_DEVICE, 0, "Auto-Connect ON");
  2545. engine->setOption(ENGINE_OPTION_OSC_ENABLED, 1, nullptr);
  2546. engine->setOption(ENGINE_OPTION_OSC_PORT_TCP, 22752, nullptr);
  2547. engine->setOption(ENGINE_OPTION_OSC_PORT_UDP, 22752, nullptr);
  2548. engine->setOption(ENGINE_OPTION_PROCESS_MODE, mode, nullptr);
  2549. engine->setOption(ENGINE_OPTION_TRANSPORT_MODE, ENGINE_TRANSPORT_MODE_JACK, nullptr);
  2550. // FIXME
  2551. engine->setOption(ENGINE_OPTION_PATH_BINARIES, 0, "/usr/lib/carla");
  2552. engine->setOption(ENGINE_OPTION_PATH_RESOURCES, 0, "/usr/share/resources");
  2553. if (engine->initInternal(client))
  2554. {
  2555. #ifdef CARLA_OS_UNIX
  2556. sThreadSafeFFTW.init();
  2557. #endif
  2558. return 0;
  2559. }
  2560. else
  2561. {
  2562. delete engine;
  2563. #ifdef USING_JUCE
  2564. juce::shutdownJuce_GUI();
  2565. #endif
  2566. return 1;
  2567. }
  2568. }
  2569. CARLA_EXPORT
  2570. void jack_finish(void *arg)
  2571. {
  2572. CARLA_BACKEND_USE_NAMESPACE
  2573. CarlaEngineJack* const engine = (CarlaEngineJack*)arg;;
  2574. CARLA_SAFE_ASSERT_RETURN(engine != nullptr,);
  2575. #ifdef CARLA_OS_UNIX
  2576. const ThreadSafeFFTW::Deinitializer tsfftwde(sThreadSafeFFTW);
  2577. #endif
  2578. engine->setAboutToClose();
  2579. engine->removeAllPlugins();
  2580. engine->close();
  2581. delete engine;
  2582. #ifdef USING_JUCE
  2583. juce::shutdownJuce_GUI();
  2584. #endif
  2585. }
  2586. // -----------------------------------------------------------------------
  2587. #endif // defined(JACKBRIDGE_DIRECT) && !defined(BUILD_BRIDGE)