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 92KB

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
6 years ago
10 years ago
10 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
11 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
11 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
11 years ago
11 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613
  1. /*
  2. * Carla Plugin Host
  3. * Copyright (C) 2011-2018 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 __SSE2_MATH__
  27. # include <xmmintrin.h>
  28. #endif
  29. // must be last
  30. #include "jackbridge/JackBridge.hpp"
  31. #define URI_CANVAS_ICON "http://kxstudio.sf.net/ns/canvas/icon"
  32. CARLA_BACKEND_START_NAMESPACE
  33. class CarlaEngineJack;
  34. class CarlaEngineJackClient;
  35. // -----------------------------------------------------------------------
  36. // Fallback data
  37. static const EngineEvent kFallbackJackEngineEvent = { kEngineEventTypeNull, 0, 0, {{ kEngineControlEventTypeNull, 0, 0.0f }} };
  38. // -----------------------------------------------------------------------
  39. // Carla Engine Port removal helper
  40. class CarlaEngineJackAudioPort;
  41. class CarlaEngineJackCVPort;
  42. class CarlaEngineJackEventPort;
  43. struct JackPortDeletionCallback {
  44. virtual ~JackPortDeletionCallback() noexcept {}
  45. virtual void jackAudioPortDeleted(CarlaEngineJackAudioPort* const) noexcept = 0;
  46. virtual void jackCVPortDeleted(CarlaEngineJackCVPort* const) noexcept = 0;
  47. virtual void jackEventPortDeleted(CarlaEngineJackEventPort* const) noexcept = 0;
  48. };
  49. // -----------------------------------------------------------------------
  50. // Carla Engine JACK-Audio port
  51. class CarlaEngineJackAudioPort : public CarlaEngineAudioPort
  52. {
  53. public:
  54. 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
  55. : CarlaEngineAudioPort(client, isInputPort, indexOffset),
  56. fJackClient(jackClient),
  57. fJackPort(jackPort),
  58. kDeletionCallback(delCallback)
  59. {
  60. carla_debug("CarlaEngineJackAudioPort::CarlaEngineJackAudioPort(%s, %p, %p)", bool2str(isInputPort), jackClient, jackPort);
  61. switch (kClient.getEngine().getProccessMode())
  62. {
  63. case ENGINE_PROCESS_MODE_SINGLE_CLIENT:
  64. case ENGINE_PROCESS_MODE_MULTIPLE_CLIENTS:
  65. CARLA_SAFE_ASSERT_RETURN(jackClient != nullptr && jackPort != nullptr,);
  66. #ifndef BUILD_BRIDGE
  67. if (const jack_uuid_t uuid = jackbridge_port_uuid(jackPort))
  68. jackbridge_set_property(jackClient, uuid, JACKEY_SIGNAL_TYPE, "AUDIO", "text/plain");
  69. #endif
  70. break;
  71. default:
  72. CARLA_SAFE_ASSERT(jackClient == nullptr && jackPort == nullptr);
  73. break;
  74. }
  75. }
  76. ~CarlaEngineJackAudioPort() noexcept override
  77. {
  78. carla_debug("CarlaEngineJackAudioPort::~CarlaEngineJackAudioPort()");
  79. if (fJackClient != nullptr && fJackPort != nullptr)
  80. {
  81. #ifndef BUILD_BRIDGE
  82. try {
  83. if (const jack_uuid_t uuid = jackbridge_port_uuid(fJackPort))
  84. jackbridge_remove_property(fJackClient, uuid, JACKEY_SIGNAL_TYPE);
  85. } CARLA_SAFE_EXCEPTION("Audio port remove meta type");
  86. #endif
  87. try {
  88. jackbridge_port_unregister(fJackClient, fJackPort);
  89. } CARLA_SAFE_EXCEPTION("Audio port unregister");
  90. fJackClient = nullptr;
  91. fJackPort = nullptr;
  92. }
  93. if (kDeletionCallback != nullptr)
  94. kDeletionCallback->jackAudioPortDeleted(this);
  95. }
  96. void initBuffer() noexcept override
  97. {
  98. if (fJackPort == nullptr)
  99. return CarlaEngineAudioPort::initBuffer();
  100. const uint32_t bufferSize(kClient.getEngine().getBufferSize());
  101. try {
  102. fBuffer = (float*)jackbridge_port_get_buffer(fJackPort, bufferSize);
  103. }
  104. catch(...) {
  105. fBuffer = nullptr;
  106. return;
  107. }
  108. if (! kIsInput)
  109. carla_zeroFloats(fBuffer, bufferSize);
  110. }
  111. void invalidate() noexcept
  112. {
  113. fJackClient = nullptr;
  114. fJackPort = nullptr;
  115. }
  116. private:
  117. jack_client_t* fJackClient;
  118. jack_port_t* fJackPort;
  119. JackPortDeletionCallback* const kDeletionCallback;
  120. friend class CarlaEngineJackClient;
  121. CARLA_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(CarlaEngineJackAudioPort)
  122. };
  123. // -----------------------------------------------------------------------
  124. // Carla Engine JACK-CV port
  125. class CarlaEngineJackCVPort : public CarlaEngineCVPort
  126. {
  127. public:
  128. 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
  129. : CarlaEngineCVPort(client, isInputPort, indexOffset),
  130. fJackClient(jackClient),
  131. fJackPort(jackPort),
  132. kDeletionCallback(delCallback)
  133. {
  134. carla_debug("CarlaEngineJackCVPort::CarlaEngineJackCVPort(%s, %p, %p)", bool2str(isInputPort), jackClient, jackPort);
  135. switch (kClient.getEngine().getProccessMode())
  136. {
  137. case ENGINE_PROCESS_MODE_SINGLE_CLIENT:
  138. case ENGINE_PROCESS_MODE_MULTIPLE_CLIENTS:
  139. CARLA_SAFE_ASSERT_RETURN(jackClient != nullptr && jackPort != nullptr,);
  140. #ifndef BUILD_BRIDGE
  141. if (const jack_uuid_t uuid = jackbridge_port_uuid(jackPort))
  142. jackbridge_set_property(jackClient, uuid, JACKEY_SIGNAL_TYPE, "CV", "text/plain");
  143. #endif
  144. break;
  145. default:
  146. CARLA_SAFE_ASSERT(jackClient == nullptr && jackPort == nullptr);
  147. break;
  148. }
  149. }
  150. ~CarlaEngineJackCVPort() noexcept override
  151. {
  152. carla_debug("CarlaEngineJackCVPort::~CarlaEngineJackCVPort()");
  153. if (fJackClient != nullptr && fJackPort != nullptr)
  154. {
  155. #ifndef BUILD_BRIDGE
  156. try {
  157. if (const jack_uuid_t uuid = jackbridge_port_uuid(fJackPort))
  158. jackbridge_remove_property(fJackClient, uuid, JACKEY_SIGNAL_TYPE);
  159. } CARLA_SAFE_EXCEPTION("CV port remove meta type");
  160. #endif
  161. try {
  162. jackbridge_port_unregister(fJackClient, fJackPort);
  163. } CARLA_SAFE_EXCEPTION("CV port unregister");
  164. fJackClient = nullptr;
  165. fJackPort = nullptr;
  166. }
  167. if (kDeletionCallback != nullptr)
  168. kDeletionCallback->jackCVPortDeleted(this);
  169. }
  170. void initBuffer() noexcept override
  171. {
  172. if (fJackPort == nullptr)
  173. return CarlaEngineCVPort::initBuffer();
  174. const uint32_t bufferSize(kClient.getEngine().getBufferSize());
  175. try {
  176. fBuffer = (float*)jackbridge_port_get_buffer(fJackPort, bufferSize);
  177. }
  178. catch(...) {
  179. fBuffer = nullptr;
  180. return;
  181. }
  182. if (! kIsInput)
  183. carla_zeroFloats(fBuffer, bufferSize);
  184. }
  185. void invalidate() noexcept
  186. {
  187. fJackClient = nullptr;
  188. fJackPort = nullptr;
  189. }
  190. private:
  191. jack_client_t* fJackClient;
  192. jack_port_t* fJackPort;
  193. JackPortDeletionCallback* const kDeletionCallback;
  194. friend class CarlaEngineJackClient;
  195. CARLA_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(CarlaEngineJackCVPort)
  196. };
  197. // -----------------------------------------------------------------------
  198. // Carla Engine JACK-Event port
  199. class CarlaEngineJackEventPort : public CarlaEngineEventPort
  200. {
  201. public:
  202. 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
  203. : CarlaEngineEventPort(client, isInputPort, indexOffset),
  204. fJackClient(jackClient),
  205. fJackPort(jackPort),
  206. fJackBuffer(nullptr),
  207. fRetEvent(kFallbackJackEngineEvent),
  208. kDeletionCallback(delCallback)
  209. {
  210. carla_debug("CarlaEngineJackEventPort::CarlaEngineJackEventPort(%s, %p, %p)", bool2str(isInputPort), jackClient, jackPort);
  211. switch (kClient.getEngine().getProccessMode())
  212. {
  213. case ENGINE_PROCESS_MODE_SINGLE_CLIENT:
  214. case ENGINE_PROCESS_MODE_MULTIPLE_CLIENTS:
  215. CARLA_SAFE_ASSERT_RETURN(jackClient != nullptr && jackPort != nullptr,);
  216. break;
  217. default:
  218. CARLA_SAFE_ASSERT(jackClient == nullptr && jackPort == nullptr);
  219. break;
  220. }
  221. }
  222. ~CarlaEngineJackEventPort() noexcept override
  223. {
  224. carla_debug("CarlaEngineJackEventPort::~CarlaEngineJackEventPort()");
  225. if (fJackClient != nullptr && fJackPort != nullptr)
  226. {
  227. try {
  228. jackbridge_port_unregister(fJackClient, fJackPort);
  229. } CARLA_SAFE_EXCEPTION("Event port unregister");
  230. fJackClient = nullptr;
  231. fJackPort = nullptr;
  232. }
  233. if (kDeletionCallback != nullptr)
  234. kDeletionCallback->jackEventPortDeleted(this);
  235. }
  236. void initBuffer() noexcept override
  237. {
  238. if (fJackPort == nullptr)
  239. return CarlaEngineEventPort::initBuffer();
  240. try {
  241. fJackBuffer = jackbridge_port_get_buffer(fJackPort, kClient.getEngine().getBufferSize());
  242. }
  243. catch(...) {
  244. fJackBuffer = nullptr;
  245. return;
  246. }
  247. if (! kIsInput)
  248. jackbridge_midi_clear_buffer(fJackBuffer);
  249. }
  250. uint32_t getEventCount() const noexcept override
  251. {
  252. if (fJackPort == nullptr)
  253. return CarlaEngineEventPort::getEventCount();
  254. CARLA_SAFE_ASSERT_RETURN(kIsInput, 0);
  255. CARLA_SAFE_ASSERT_RETURN(fJackBuffer != nullptr, 0);
  256. try {
  257. return jackbridge_midi_get_event_count(fJackBuffer);
  258. } CARLA_SAFE_EXCEPTION_RETURN("jack_midi_get_event_count", 0);
  259. }
  260. const EngineEvent& getEvent(const uint32_t index) const noexcept override
  261. {
  262. if (fJackPort == nullptr)
  263. return CarlaEngineEventPort::getEvent(index);
  264. CARLA_SAFE_ASSERT_RETURN(kIsInput, kFallbackJackEngineEvent);
  265. CARLA_SAFE_ASSERT_RETURN(fJackBuffer != nullptr, kFallbackJackEngineEvent);
  266. return getEventUnchecked(index);
  267. }
  268. const EngineEvent& getEventUnchecked(const uint32_t index) const noexcept override
  269. {
  270. jack_midi_event_t jackEvent;
  271. bool test = false;
  272. try {
  273. test = jackbridge_midi_event_get(&jackEvent, fJackBuffer, index);
  274. } CARLA_SAFE_EXCEPTION_RETURN("jack_midi_event_get", kFallbackJackEngineEvent);
  275. if (! test)
  276. return kFallbackJackEngineEvent;
  277. CARLA_SAFE_ASSERT_RETURN(jackEvent.size < 0xFF /* uint8_t max */, kFallbackJackEngineEvent);
  278. uint8_t port;
  279. if (kIndexOffset < 0xFF /* uint8_t max */)
  280. {
  281. port = static_cast<uint8_t>(kIndexOffset);
  282. }
  283. else
  284. {
  285. port = 0;
  286. carla_safe_assert_uint("kIndexOffset < 0xFF", __FILE__, __LINE__, kIndexOffset);
  287. }
  288. fRetEvent.time = jackEvent.time;
  289. fRetEvent.fillFromMidiData(static_cast<uint8_t>(jackEvent.size), jackEvent.buffer, port);
  290. return fRetEvent;
  291. }
  292. bool writeControlEvent(const uint32_t time, const uint8_t channel, const EngineControlEventType type, const uint16_t param, const float value) noexcept override
  293. {
  294. if (fJackPort == nullptr)
  295. return CarlaEngineEventPort::writeControlEvent(time, channel, type, param, value);
  296. CARLA_SAFE_ASSERT_RETURN(! kIsInput, false);
  297. CARLA_SAFE_ASSERT_RETURN(fJackBuffer != nullptr, false);
  298. CARLA_SAFE_ASSERT_RETURN(type != kEngineControlEventTypeNull, false);
  299. CARLA_SAFE_ASSERT_RETURN(channel < MAX_MIDI_CHANNELS, false);
  300. CARLA_SAFE_ASSERT_RETURN(param < MAX_MIDI_CONTROL, false);
  301. CARLA_SAFE_ASSERT(value >= 0.0f && value <= 1.0f);
  302. if (type == kEngineControlEventTypeParameter) {
  303. CARLA_SAFE_ASSERT(! MIDI_IS_CONTROL_BANK_SELECT(param));
  304. }
  305. uint8_t data[3] = { 0, 0, 0 };
  306. EngineControlEvent ctrlEvent = { type, param, value };
  307. const uint8_t size = ctrlEvent.convertToMidiData(channel, data);
  308. if (size == 0)
  309. return false;
  310. try {
  311. return jackbridge_midi_event_write(fJackBuffer, time, data, size);
  312. } CARLA_SAFE_EXCEPTION_RETURN("jack_midi_event_write", false);
  313. }
  314. bool writeMidiEvent(const uint32_t time, const uint8_t channel, const uint8_t size, const uint8_t* const data) noexcept override
  315. {
  316. if (fJackPort == nullptr)
  317. return CarlaEngineEventPort::writeMidiEvent(time, channel, size, data);
  318. CARLA_SAFE_ASSERT_RETURN(! kIsInput, false);
  319. CARLA_SAFE_ASSERT_RETURN(fJackBuffer != nullptr, false);
  320. CARLA_SAFE_ASSERT_RETURN(channel < MAX_MIDI_CHANNELS, false);
  321. CARLA_SAFE_ASSERT_RETURN(size > 0, false);
  322. CARLA_SAFE_ASSERT_RETURN(data != nullptr, false);
  323. jack_midi_data_t jdata[size];
  324. jdata[0] = static_cast<jack_midi_data_t>(MIDI_GET_STATUS_FROM_DATA(data) + channel);
  325. for (uint8_t i=1; i < size; ++i)
  326. jdata[i] = data[i];
  327. try {
  328. return jackbridge_midi_event_write(fJackBuffer, time, jdata, size);
  329. } CARLA_SAFE_EXCEPTION_RETURN("jack_midi_event_write", false);
  330. }
  331. void invalidate() noexcept
  332. {
  333. fJackClient = nullptr;
  334. fJackPort = nullptr;
  335. }
  336. private:
  337. jack_client_t* fJackClient;
  338. jack_port_t* fJackPort;
  339. void* fJackBuffer;
  340. mutable EngineEvent fRetEvent;
  341. JackPortDeletionCallback* const kDeletionCallback;
  342. friend class CarlaEngineJackClient;
  343. CARLA_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(CarlaEngineJackEventPort)
  344. };
  345. // -----------------------------------------------------------------------
  346. // Jack Engine client
  347. class CarlaEngineJackClient : public CarlaEngineClient,
  348. private JackPortDeletionCallback
  349. {
  350. public:
  351. CarlaEngineJackClient(const CarlaEngine& engine, jack_client_t* const jackClient)
  352. : CarlaEngineClient(engine),
  353. fJackClient(jackClient),
  354. fUseClient(engine.getProccessMode() == ENGINE_PROCESS_MODE_SINGLE_CLIENT || engine.getProccessMode() == ENGINE_PROCESS_MODE_MULTIPLE_CLIENTS),
  355. fAudioPorts(),
  356. fCVPorts(),
  357. fEventPorts(),
  358. fPreRenameMutex(),
  359. fPreRenameConnections()
  360. {
  361. carla_debug("CarlaEngineJackClient::CarlaEngineJackClient(%p)", jackClient);
  362. if (fUseClient)
  363. {
  364. CARLA_SAFE_ASSERT(jackClient != nullptr);
  365. }
  366. else
  367. {
  368. CARLA_SAFE_ASSERT(jackClient == nullptr);
  369. }
  370. }
  371. ~CarlaEngineJackClient() noexcept override
  372. {
  373. carla_debug("CarlaEngineJackClient::~CarlaEngineJackClient()");
  374. if (getProcessMode() == ENGINE_PROCESS_MODE_MULTIPLE_CLIENTS && fJackClient != nullptr) // FIXME
  375. jackbridge_client_close(fJackClient);
  376. // ports must have been deleted by now!
  377. //fAudioPorts.clear();
  378. //fCVPorts.clear();
  379. //fEventPorts.clear();
  380. }
  381. void activate() noexcept override
  382. {
  383. carla_debug("CarlaEngineJackClient::activate()");
  384. if (getProcessMode() == ENGINE_PROCESS_MODE_MULTIPLE_CLIENTS)
  385. {
  386. CARLA_SAFE_ASSERT_RETURN(fJackClient != nullptr && ! isActive(),);
  387. try {
  388. jackbridge_activate(fJackClient);
  389. } catch(...) {}
  390. }
  391. CarlaEngineClient::activate();
  392. const CarlaMutexLocker cml(fPreRenameMutex);
  393. if (fJackClient != nullptr)
  394. {
  395. // restore pre-rename connections
  396. const char* portNameA = nullptr;
  397. const char* portNameB = nullptr;
  398. bool doConnection = false;
  399. for (CarlaStringList::Itenerator it = fPreRenameConnections.begin2(); it.valid(); it.next())
  400. {
  401. const bool connectNow = doConnection;
  402. doConnection = !doConnection;
  403. if (connectNow)
  404. portNameB = it.getValue(nullptr);
  405. else
  406. portNameA = it.getValue(nullptr);
  407. if (! connectNow)
  408. continue;
  409. CARLA_SAFE_ASSERT_CONTINUE(portNameA != nullptr && portNameA[0] != '\0');
  410. CARLA_SAFE_ASSERT_CONTINUE(portNameB != nullptr && portNameB[0] != '\0');
  411. jackbridge_connect(fJackClient, portNameA, portNameB);
  412. }
  413. }
  414. fPreRenameConnections.clear();
  415. }
  416. void deactivate() noexcept override
  417. {
  418. carla_debug("CarlaEngineJackClient::deactivate()");
  419. if (getProcessMode() == ENGINE_PROCESS_MODE_MULTIPLE_CLIENTS)
  420. {
  421. CARLA_SAFE_ASSERT_RETURN(fJackClient != nullptr && isActive(),);
  422. try {
  423. jackbridge_deactivate(fJackClient);
  424. } catch(...) {}
  425. }
  426. CarlaEngineClient::deactivate();
  427. }
  428. bool isOk() const noexcept override
  429. {
  430. if (fUseClient)
  431. return (fJackClient != nullptr);
  432. return CarlaEngineClient::isOk();
  433. }
  434. CarlaEnginePort* addPort(const EnginePortType portType, const char* const name, const bool isInput, const uint32_t indexOffset) override
  435. {
  436. carla_debug("CarlaEngineJackClient::addPort(%i:%s, \"%s\", %s)", portType, EnginePortType2Str(portType), name, bool2str(isInput));
  437. jack_port_t* jackPort = nullptr;
  438. const char* realName = name;
  439. // Create JACK port first, if needed
  440. if (fUseClient)
  441. {
  442. CARLA_SAFE_ASSERT_RETURN(fJackClient != nullptr, nullptr);
  443. realName = _getUniquePortName(name);
  444. switch (portType)
  445. {
  446. case kEnginePortTypeNull:
  447. break;
  448. case kEnginePortTypeAudio:
  449. jackPort = jackbridge_port_register(fJackClient, realName, JACK_DEFAULT_AUDIO_TYPE, isInput ? JackPortIsInput : JackPortIsOutput, 0);
  450. break;
  451. case kEnginePortTypeCV:
  452. jackPort = jackbridge_port_register(fJackClient, realName, JACK_DEFAULT_AUDIO_TYPE, isInput ? JackPortIsInput : JackPortIsOutput, 0);
  453. break;
  454. case kEnginePortTypeEvent:
  455. jackPort = jackbridge_port_register(fJackClient, realName, JACK_DEFAULT_MIDI_TYPE, isInput ? JackPortIsInput : JackPortIsOutput, 0);
  456. break;
  457. }
  458. CARLA_SAFE_ASSERT_RETURN(jackPort != nullptr, nullptr);
  459. }
  460. // Create Engine port
  461. switch (portType)
  462. {
  463. case kEnginePortTypeNull:
  464. break;
  465. case kEnginePortTypeAudio: {
  466. _addAudioPortName(isInput, realName);
  467. if (realName != name) delete[] realName;
  468. CarlaEngineJackAudioPort* const enginePort(new CarlaEngineJackAudioPort(*this, isInput, indexOffset, fJackClient, jackPort, this));
  469. fAudioPorts.append(enginePort);
  470. return enginePort;
  471. }
  472. case kEnginePortTypeCV: {
  473. _addCVPortName(isInput, realName);
  474. if (realName != name) delete[] realName;
  475. CarlaEngineJackCVPort* const enginePort(new CarlaEngineJackCVPort(*this, isInput, indexOffset, fJackClient, jackPort, this));
  476. fCVPorts.append(enginePort);
  477. return enginePort;
  478. }
  479. case kEnginePortTypeEvent: {
  480. _addEventPortName(isInput, realName);
  481. if (realName != name) delete[] realName;
  482. CarlaEngineJackEventPort* const enginePort(new CarlaEngineJackEventPort(*this, isInput, indexOffset, fJackClient, jackPort, this));
  483. fEventPorts.append(enginePort);
  484. return enginePort;
  485. }
  486. }
  487. carla_stderr("CarlaEngineJackClient::addPort(%i, \"%s\", %s) - invalid type", portType, name, bool2str(isInput));
  488. return nullptr;
  489. }
  490. void invalidate() noexcept
  491. {
  492. for (LinkedList<CarlaEngineJackAudioPort*>::Itenerator it = fAudioPorts.begin2(); it.valid(); it.next())
  493. {
  494. CarlaEngineJackAudioPort* const port(it.getValue(nullptr));
  495. CARLA_SAFE_ASSERT_CONTINUE(port != nullptr);
  496. port->invalidate();
  497. }
  498. for (LinkedList<CarlaEngineJackCVPort*>::Itenerator it = fCVPorts.begin2(); it.valid(); it.next())
  499. {
  500. CarlaEngineJackCVPort* const port(it.getValue(nullptr));
  501. CARLA_SAFE_ASSERT_CONTINUE(port != nullptr);
  502. port->invalidate();
  503. }
  504. for (LinkedList<CarlaEngineJackEventPort*>::Itenerator it = fEventPorts.begin2(); it.valid(); it.next())
  505. {
  506. CarlaEngineJackEventPort* const port(it.getValue(nullptr));
  507. CARLA_SAFE_ASSERT_CONTINUE(port != nullptr);
  508. port->invalidate();
  509. }
  510. fJackClient = nullptr;
  511. CarlaEngineClient::deactivate();
  512. }
  513. const char* getJackClientName() const noexcept
  514. {
  515. CARLA_SAFE_ASSERT_RETURN(fJackClient != nullptr, nullptr);
  516. try {
  517. return jackbridge_get_client_name(fJackClient);
  518. } CARLA_SAFE_EXCEPTION_RETURN("jack_get_client_name", nullptr);
  519. }
  520. void jackAudioPortDeleted(CarlaEngineJackAudioPort* const port) noexcept override
  521. {
  522. fAudioPorts.removeAll(port);
  523. }
  524. void jackCVPortDeleted(CarlaEngineJackCVPort* const port) noexcept override
  525. {
  526. fCVPorts.removeAll(port);
  527. }
  528. void jackEventPortDeleted(CarlaEngineJackEventPort* const port) noexcept override
  529. {
  530. fEventPorts.removeAll(port);
  531. }
  532. bool renameInSingleClient(const CarlaString& newClientName)
  533. {
  534. const CarlaString clientNamePrefix(newClientName + ":");
  535. return _renamePorts(fAudioPorts, clientNamePrefix) &&
  536. _renamePorts(fCVPorts, clientNamePrefix) &&
  537. _renamePorts(fEventPorts, clientNamePrefix);
  538. }
  539. void closeForRename(jack_client_t* const newClient, const CarlaString& newClientName) noexcept
  540. {
  541. if (fJackClient != nullptr)
  542. {
  543. if (isActive())
  544. {
  545. {
  546. const CarlaString clientNamePrefix(newClientName + ":");
  547. // store current client connections
  548. const CarlaMutexLocker cml(fPreRenameMutex);
  549. fPreRenameConnections.clear();
  550. _savePortsConnections(fAudioPorts, clientNamePrefix);
  551. _savePortsConnections(fCVPorts, clientNamePrefix);
  552. _savePortsConnections(fEventPorts, clientNamePrefix);
  553. }
  554. try {
  555. jackbridge_deactivate(fJackClient);
  556. } catch(...) {}
  557. }
  558. try {
  559. jackbridge_client_close(fJackClient);
  560. } catch(...) {}
  561. invalidate();
  562. }
  563. fAudioPorts.clear();
  564. fCVPorts.clear();
  565. fEventPorts.clear();
  566. _clearPorts();
  567. fJackClient = newClient;
  568. }
  569. private:
  570. jack_client_t* fJackClient;
  571. const bool fUseClient;
  572. LinkedList<CarlaEngineJackAudioPort*> fAudioPorts;
  573. LinkedList<CarlaEngineJackCVPort*> fCVPorts;
  574. LinkedList<CarlaEngineJackEventPort*> fEventPorts;
  575. CarlaMutex fPreRenameMutex;
  576. CarlaStringList fPreRenameConnections;
  577. template<typename T>
  578. bool _renamePorts(const LinkedList<T*>& t, const CarlaString& clientNamePrefix)
  579. {
  580. for (typename LinkedList<T*>::Itenerator it = t.begin2(); it.valid(); it.next())
  581. {
  582. T* const port(it.getValue(nullptr));
  583. CARLA_SAFE_ASSERT_CONTINUE(port != nullptr);
  584. CARLA_SAFE_ASSERT_CONTINUE(port->fJackPort != nullptr);
  585. const char* shortPortName(jackbridge_port_short_name(port->fJackPort));
  586. CARLA_SAFE_ASSERT_CONTINUE(shortPortName != nullptr && shortPortName[0] != '\0');
  587. const char* const oldClientNameSep(std::strstr(shortPortName, ":"));
  588. CARLA_SAFE_ASSERT_CONTINUE(oldClientNameSep != nullptr && oldClientNameSep[0] != '\0' && oldClientNameSep[1] != '\0');
  589. shortPortName += oldClientNameSep-shortPortName + 1;
  590. const CarlaString newPortName(clientNamePrefix + shortPortName);
  591. if (! jackbridge_port_rename(fJackClient, port->fJackPort, newPortName))
  592. return false;
  593. }
  594. return true;
  595. }
  596. template<typename T>
  597. void _savePortsConnections(const LinkedList<T*>& t, const CarlaString& clientNamePrefix)
  598. {
  599. for (typename LinkedList<T*>::Itenerator it = t.begin2(); it.valid(); it.next())
  600. {
  601. T* const port(it.getValue(nullptr));
  602. CARLA_SAFE_ASSERT_CONTINUE(port != nullptr);
  603. CARLA_SAFE_ASSERT_CONTINUE(port->fJackPort != nullptr);
  604. const char* const shortPortName(jackbridge_port_short_name(port->fJackPort));
  605. CARLA_SAFE_ASSERT_CONTINUE(shortPortName != nullptr && shortPortName[0] != '\0');
  606. const CarlaString portName(clientNamePrefix + shortPortName);
  607. if (const char** const connections = jackbridge_port_get_all_connections(fJackClient, port->fJackPort))
  608. {
  609. for (int i=0; connections[i] != nullptr; ++i)
  610. {
  611. if (port->kIsInput)
  612. {
  613. fPreRenameConnections.append(connections[i]);
  614. fPreRenameConnections.append(portName);
  615. }
  616. else
  617. {
  618. fPreRenameConnections.append(portName);
  619. fPreRenameConnections.append(connections[i]);
  620. }
  621. }
  622. jackbridge_free(connections);
  623. }
  624. }
  625. }
  626. CARLA_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(CarlaEngineJackClient)
  627. };
  628. // -----------------------------------------------------------------------
  629. // Jack Engine
  630. class CarlaEngineJack : public CarlaEngine
  631. #ifndef BUILD_BRIDGE
  632. , private CarlaThread
  633. #endif
  634. {
  635. public:
  636. CarlaEngineJack()
  637. : CarlaEngine(),
  638. #ifndef BUILD_BRIDGE
  639. CarlaThread("CarlaEngineJackCallbacks"),
  640. #endif
  641. fClient(nullptr),
  642. fExternalPatchbay(true),
  643. fFreewheel(false),
  644. #ifdef BUILD_BRIDGE
  645. fIsRunning(false)
  646. #else
  647. fTimebaseMaster(false),
  648. fUsedGroups(),
  649. fUsedPorts(),
  650. fUsedConnections(),
  651. fNewGroups(),
  652. fRetConns(),
  653. fPostPonedEvents(),
  654. fPostPonedEventsMutex()
  655. #endif
  656. {
  657. carla_debug("CarlaEngineJack::CarlaEngineJack()");
  658. #ifdef BUILD_BRIDGE
  659. pData->options.processMode = ENGINE_PROCESS_MODE_MULTIPLE_CLIENTS;
  660. #else
  661. carla_zeroPointers(fRackPorts, kRackPortCount);
  662. #endif
  663. }
  664. ~CarlaEngineJack() noexcept override
  665. {
  666. carla_debug("CarlaEngineJack::~CarlaEngineJack()");
  667. CARLA_SAFE_ASSERT(fClient == nullptr);
  668. #ifndef BUILD_BRIDGE
  669. fUsedGroups.clear();
  670. fUsedPorts.clear();
  671. fUsedConnections.clear();
  672. fNewGroups.clear();
  673. CARLA_SAFE_ASSERT(fPostPonedEvents.count() == 0);
  674. #endif
  675. }
  676. // -------------------------------------------------------------------
  677. // Maximum values
  678. uint getMaxClientNameSize() const noexcept override
  679. {
  680. #ifndef BUILD_BRIDGE
  681. if (pData->options.processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT || pData->options.processMode == ENGINE_PROCESS_MODE_MULTIPLE_CLIENTS)
  682. #endif
  683. {
  684. try {
  685. return static_cast<uint>(jackbridge_client_name_size()-1);
  686. } CARLA_SAFE_EXCEPTION_RETURN("jack_client_name_size", 32);
  687. }
  688. return CarlaEngine::getMaxClientNameSize();
  689. }
  690. uint getMaxPortNameSize() const noexcept override
  691. {
  692. if (pData->options.processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT || pData->options.processMode == ENGINE_PROCESS_MODE_MULTIPLE_CLIENTS)
  693. {
  694. try {
  695. return static_cast<uint>(jackbridge_port_name_size()-1);
  696. } CARLA_SAFE_EXCEPTION_RETURN("jack_port_name_size", 255);
  697. }
  698. return CarlaEngine::getMaxPortNameSize();
  699. }
  700. // -------------------------------------------------------------------
  701. // Virtual, per-engine type calls
  702. bool init(const char* const clientName) override
  703. {
  704. CARLA_SAFE_ASSERT_RETURN(fClient == nullptr, false);
  705. CARLA_SAFE_ASSERT_RETURN(clientName != nullptr && clientName[0] != '\0', false);
  706. CARLA_SAFE_ASSERT_RETURN(jackbridge_is_ok(), false);
  707. carla_debug("CarlaEngineJack::init(\"%s\")", clientName);
  708. fFreewheel = false;
  709. fExternalPatchbay = true;
  710. CarlaString truncatedClientName(clientName);
  711. truncatedClientName.truncate(getMaxClientNameSize());
  712. #ifdef BUILD_BRIDGE
  713. fIsRunning = true;
  714. if (! pData->init(truncatedClientName))
  715. {
  716. close();
  717. setLastError("Failed to init internal data");
  718. return false;
  719. }
  720. if (pData->bufferSize == 0 || carla_isEqual(pData->sampleRate, 0.0))
  721. {
  722. // open temp client to get initial buffer-size and sample-rate values
  723. if (jack_client_t* const tmpClient = jackbridge_client_open(truncatedClientName, JackNoStartServer, nullptr))
  724. {
  725. pData->bufferSize = jackbridge_get_buffer_size(tmpClient);
  726. pData->sampleRate = jackbridge_get_sample_rate(tmpClient);
  727. jackbridge_client_close(tmpClient);
  728. }
  729. else
  730. {
  731. close();
  732. setLastError("Failed to init temporary jack client");
  733. return false;
  734. }
  735. }
  736. return true;
  737. #else
  738. fClient = jackbridge_client_open(truncatedClientName, JackNullOption, nullptr);
  739. if (fClient == nullptr)
  740. {
  741. setLastError("Failed to create new JACK client");
  742. return false;
  743. }
  744. const char* const jackClientName = jackbridge_get_client_name(fClient);
  745. if (! pData->init(jackClientName))
  746. {
  747. jackbridge_client_close(fClient);
  748. fClient = nullptr;
  749. setLastError("Failed to init internal data");
  750. return false;
  751. }
  752. const EngineOptions& opts(pData->options);
  753. pData->bufferSize = jackbridge_get_buffer_size(fClient);
  754. pData->sampleRate = jackbridge_get_sample_rate(fClient);
  755. pData->initTime(opts.transportExtra);
  756. jackbridge_set_thread_init_callback(fClient, carla_jack_thread_init_callback, nullptr);
  757. jackbridge_set_buffer_size_callback(fClient, carla_jack_bufsize_callback, this);
  758. jackbridge_set_sample_rate_callback(fClient, carla_jack_srate_callback, this);
  759. jackbridge_set_freewheel_callback(fClient, carla_jack_freewheel_callback, this);
  760. jackbridge_set_latency_callback(fClient, carla_jack_latency_callback, this);
  761. jackbridge_set_process_callback(fClient, carla_jack_process_callback, this);
  762. jackbridge_on_shutdown(fClient, carla_jack_shutdown_callback, this);
  763. if (opts.transportMode == ENGINE_TRANSPORT_MODE_JACK)
  764. fTimebaseMaster = jackbridge_set_timebase_callback(fClient, true, carla_jack_timebase_callback, this);
  765. if (opts.processMode != ENGINE_PROCESS_MODE_PATCHBAY)
  766. initJackPatchbay(jackClientName);
  767. jackbridge_set_client_registration_callback(fClient, carla_jack_client_registration_callback, this);
  768. jackbridge_set_port_registration_callback(fClient, carla_jack_port_registration_callback, this);
  769. jackbridge_set_port_connect_callback(fClient, carla_jack_port_connect_callback, this);
  770. jackbridge_set_port_rename_callback(fClient, carla_jack_port_rename_callback, this);
  771. if (opts.processMode == ENGINE_PROCESS_MODE_CONTINUOUS_RACK || opts.processMode == ENGINE_PROCESS_MODE_PATCHBAY)
  772. {
  773. fRackPorts[kRackPortAudioIn1] = jackbridge_port_register(fClient, "audio-in1", JACK_DEFAULT_AUDIO_TYPE, JackPortIsInput, 0);
  774. fRackPorts[kRackPortAudioIn2] = jackbridge_port_register(fClient, "audio-in2", JACK_DEFAULT_AUDIO_TYPE, JackPortIsInput, 0);
  775. fRackPorts[kRackPortAudioOut1] = jackbridge_port_register(fClient, "audio-out1", JACK_DEFAULT_AUDIO_TYPE, JackPortIsOutput, 0);
  776. fRackPorts[kRackPortAudioOut2] = jackbridge_port_register(fClient, "audio-out2", JACK_DEFAULT_AUDIO_TYPE, JackPortIsOutput, 0);
  777. fRackPorts[kRackPortEventIn] = jackbridge_port_register(fClient, "events-in", JACK_DEFAULT_MIDI_TYPE, JackPortIsInput, 0);
  778. fRackPorts[kRackPortEventOut] = jackbridge_port_register(fClient, "events-out", JACK_DEFAULT_MIDI_TYPE, JackPortIsOutput, 0);
  779. if (opts.processMode == ENGINE_PROCESS_MODE_CONTINUOUS_RACK)
  780. {
  781. // FIXME?
  782. pData->graph.create(0, 0);
  783. }
  784. else
  785. {
  786. pData->graph.create(2, 2);
  787. patchbayRefresh(false);
  788. }
  789. }
  790. if (jackbridge_activate(fClient))
  791. {
  792. startThread();
  793. callback(ENGINE_CALLBACK_ENGINE_STARTED, 0,
  794. opts.processMode, opts.transportMode,
  795. pData->sampleRate,
  796. getCurrentDriverName());
  797. return true;
  798. }
  799. if (opts.processMode == ENGINE_PROCESS_MODE_CONTINUOUS_RACK || opts.processMode == ENGINE_PROCESS_MODE_PATCHBAY)
  800. {
  801. pData->graph.destroy();
  802. }
  803. pData->close();
  804. jackbridge_client_close(fClient);
  805. fClient = nullptr;
  806. setLastError("Failed to activate the JACK client");
  807. return false;
  808. #endif
  809. }
  810. bool close() override
  811. {
  812. carla_debug("CarlaEngineJack::close()");
  813. #ifdef BUILD_BRIDGE
  814. fClient = nullptr;
  815. fIsRunning = false;
  816. CarlaEngine::close();
  817. return true;
  818. #else
  819. stopThread(-1);
  820. fPostPonedEvents.clear();
  821. CARLA_SAFE_ASSERT_RETURN_ERR(fClient != nullptr, "JACK Client is null");
  822. // deactivate first
  823. const bool deactivated(jackbridge_deactivate(fClient));
  824. // clear engine data
  825. CarlaEngine::close();
  826. fUsedGroups.clear();
  827. fUsedPorts.clear();
  828. fUsedConnections.clear();
  829. fNewGroups.clear();
  830. fPostPonedEvents.clear();
  831. // clear rack/patchbay stuff
  832. if (pData->options.processMode == ENGINE_PROCESS_MODE_CONTINUOUS_RACK ||
  833. pData->options.processMode == ENGINE_PROCESS_MODE_PATCHBAY)
  834. {
  835. if (deactivated)
  836. {
  837. jackbridge_port_unregister(fClient, fRackPorts[kRackPortAudioIn1]);
  838. jackbridge_port_unregister(fClient, fRackPorts[kRackPortAudioIn2]);
  839. jackbridge_port_unregister(fClient, fRackPorts[kRackPortAudioOut1]);
  840. jackbridge_port_unregister(fClient, fRackPorts[kRackPortAudioOut2]);
  841. jackbridge_port_unregister(fClient, fRackPorts[kRackPortEventIn]);
  842. jackbridge_port_unregister(fClient, fRackPorts[kRackPortEventOut]);
  843. }
  844. carla_zeroPointers(fRackPorts, kRackPortCount);
  845. pData->graph.destroy();
  846. }
  847. // close client
  848. if (deactivated)
  849. jackbridge_client_close(fClient);
  850. fClient = nullptr;
  851. return true;
  852. #endif
  853. }
  854. bool isRunning() const noexcept override
  855. {
  856. #ifdef BUILD_BRIDGE
  857. return (fClient != nullptr || fIsRunning);
  858. #else
  859. return (fClient != nullptr);
  860. #endif
  861. }
  862. bool isOffline() const noexcept override
  863. {
  864. return fFreewheel;
  865. }
  866. EngineType getType() const noexcept override
  867. {
  868. return kEngineTypeJack;
  869. }
  870. const char* getCurrentDriverName() const noexcept override
  871. {
  872. return "JACK";
  873. }
  874. #ifndef BUILD_BRIDGE
  875. void setOption(const EngineOption option, const int value, const char* const valueStr) noexcept override
  876. {
  877. if (option == ENGINE_OPTION_TRANSPORT_MODE && fClient != nullptr)
  878. {
  879. CARLA_SAFE_ASSERT_RETURN(value >= ENGINE_TRANSPORT_MODE_DISABLED && value <= ENGINE_TRANSPORT_MODE_JACK,);
  880. if (value == ENGINE_TRANSPORT_MODE_JACK)
  881. {
  882. fTimebaseMaster = jackbridge_set_timebase_callback(fClient, true, carla_jack_timebase_callback, this);
  883. }
  884. else
  885. {
  886. jackbridge_release_timebase(fClient);
  887. fTimebaseMaster = false;
  888. }
  889. }
  890. CarlaEngine::setOption(option, value, valueStr);
  891. }
  892. #endif
  893. CarlaEngineClient* addClient(CarlaPlugin* const plugin) override
  894. {
  895. jack_client_t* client = nullptr;
  896. #ifndef BUILD_BRIDGE
  897. if (pData->options.processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  898. {
  899. client = fClient;
  900. }
  901. else if (pData->options.processMode == ENGINE_PROCESS_MODE_MULTIPLE_CLIENTS)
  902. #endif
  903. {
  904. client = jackbridge_client_open(plugin->getName(), JackNullOption, nullptr);
  905. CARLA_SAFE_ASSERT_RETURN(client != nullptr, nullptr);
  906. jackbridge_set_thread_init_callback(client, carla_jack_thread_init_callback, nullptr);
  907. #ifndef BUILD_BRIDGE
  908. jackbridge_set_latency_callback(client, carla_jack_latency_callback_plugin, plugin);
  909. jackbridge_set_process_callback(client, carla_jack_process_callback_plugin, plugin);
  910. jackbridge_on_shutdown(client, carla_jack_shutdown_callback_plugin, plugin);
  911. #else
  912. fClient = client;
  913. pData->bufferSize = jackbridge_get_buffer_size(client);
  914. pData->sampleRate = jackbridge_get_sample_rate(client);
  915. pData->initTime(nullptr);
  916. jackbridge_set_buffer_size_callback(client, carla_jack_bufsize_callback, this);
  917. jackbridge_set_sample_rate_callback(client, carla_jack_srate_callback, this);
  918. jackbridge_set_freewheel_callback(client, carla_jack_freewheel_callback, this);
  919. jackbridge_set_latency_callback(client, carla_jack_latency_callback, this);
  920. jackbridge_set_process_callback(client, carla_jack_process_callback, this);
  921. jackbridge_on_shutdown(client, carla_jack_shutdown_callback, this);
  922. #endif
  923. }
  924. return new CarlaEngineJackClient(*this, client);
  925. }
  926. #ifndef BUILD_BRIDGE
  927. const char* renamePlugin(const uint id, const char* const newName) override
  928. {
  929. if (pData->options.processMode == ENGINE_PROCESS_MODE_CONTINUOUS_RACK ||
  930. pData->options.processMode == ENGINE_PROCESS_MODE_PATCHBAY)
  931. {
  932. return CarlaEngine::renamePlugin(id, newName);
  933. }
  934. CARLA_SAFE_ASSERT_RETURN(pData->plugins != nullptr, nullptr);
  935. CARLA_SAFE_ASSERT_RETURN(pData->curPluginCount != 0, nullptr);
  936. CARLA_SAFE_ASSERT_RETURN(id < pData->curPluginCount, nullptr);
  937. CARLA_SAFE_ASSERT_RETURN(newName != nullptr && newName[0] != '\0', nullptr);
  938. CarlaPlugin* const plugin(pData->plugins[id].plugin);
  939. CARLA_SAFE_ASSERT_RETURN_ERRN(plugin != nullptr, "Could not find plugin to rename");
  940. CARLA_SAFE_ASSERT_RETURN_ERRN(plugin->getId() == id, "Invalid engine internal data");
  941. // before we stop the engine thread we might need to get the plugin data
  942. const bool needsReinit = (pData->options.processMode == ENGINE_PROCESS_MODE_MULTIPLE_CLIENTS);
  943. const CarlaStateSave* saveStatePtr = nullptr;
  944. if (needsReinit)
  945. {
  946. const CarlaStateSave& saveState(plugin->getStateSave());
  947. saveStatePtr = &saveState;
  948. }
  949. CarlaString uniqueName;
  950. try {
  951. const char* const tmpName = getUniquePluginName(newName);
  952. uniqueName = tmpName;
  953. delete[] tmpName;
  954. } CARLA_SAFE_EXCEPTION("JACK renamePlugin getUniquePluginName");
  955. if (uniqueName.isEmpty())
  956. {
  957. setLastError("Failed to request new unique plugin name");
  958. return nullptr;
  959. }
  960. const ScopedThreadStopper sts(this);
  961. // rename on client client mode, just rename the ports
  962. if (pData->options.processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  963. {
  964. CarlaEngineJackClient* const client((CarlaEngineJackClient*)plugin->getEngineClient());
  965. if (! client->renameInSingleClient(uniqueName))
  966. {
  967. setLastError("Failed to rename some JACK ports, does your JACK version support proper port renaming?");
  968. return nullptr;
  969. }
  970. }
  971. // rename in multiple client mode
  972. else if (pData->options.processMode == ENGINE_PROCESS_MODE_MULTIPLE_CLIENTS)
  973. {
  974. CarlaEngineJackClient* const client((CarlaEngineJackClient*)plugin->getEngineClient());
  975. // we should not be able to do this, jack really needs to allow client rename
  976. if (jack_client_t* const jackClient = jackbridge_client_open(uniqueName, JackNullOption, nullptr))
  977. {
  978. // get new client name
  979. uniqueName = jackbridge_get_client_name(jackClient);
  980. // close client
  981. client->closeForRename(jackClient, uniqueName);
  982. // disable plugin
  983. plugin->setEnabled(false);
  984. // set new client data
  985. jackbridge_set_latency_callback(jackClient, carla_jack_latency_callback_plugin, plugin);
  986. jackbridge_set_process_callback(jackClient, carla_jack_process_callback_plugin, plugin);
  987. jackbridge_on_shutdown(jackClient, carla_jack_shutdown_callback_plugin, plugin);
  988. // NOTE: jack1 locks up here
  989. if (jackbridge_get_version_string() != nullptr)
  990. jackbridge_set_thread_init_callback(jackClient, carla_jack_thread_init_callback, nullptr);
  991. /* The following code is because of a tricky situation.
  992. We cannot lock or do jack operations during jack callbacks on jack1. jack2 events are asynchronous.
  993. When we close the client jack will trigger unregister-port callbacks, which we handle on a separate thread ASAP.
  994. But before that happens we already registered a new client with the same ports (the "renamed" one),
  995. and at this point the port we receive during that callback is actually the new one from the new client..
  996. JACK2 seems to be reusing ports to save space, which is understandable.
  997. Anyway, this means we have to remove all our port-related data before the new client ports are created.
  998. (we also stop the separate jack-events thread to avoid any race conditions while modying our port data) */
  999. stopThread(-1);
  1000. const uint groupId(fUsedGroups.getGroupId(plugin->getName()));
  1001. if (groupId > 0)
  1002. {
  1003. for (LinkedList<PortNameToId>::Itenerator it = fUsedPorts.list.begin2(); it.valid(); it.next())
  1004. {
  1005. for (LinkedList<ConnectionToId>::Itenerator it2 = fUsedConnections.list.begin2(); it2.valid(); it2.next())
  1006. {
  1007. static ConnectionToId connectionFallback = { 0, 0, 0, 0, 0 };
  1008. ConnectionToId& connectionToId = it2.getValue(connectionFallback);
  1009. CARLA_SAFE_ASSERT_CONTINUE(connectionToId.id != 0);
  1010. if (connectionToId.groupA != groupId && connectionToId.groupB != groupId)
  1011. continue;
  1012. callback(ENGINE_CALLBACK_PATCHBAY_CONNECTION_REMOVED, connectionToId.id, 0, 0, 0.0f, nullptr);
  1013. fUsedConnections.list.remove(it2);
  1014. }
  1015. static PortNameToId portNameFallback = { 0, 0, { '\0' }, { '\0' } };
  1016. PortNameToId& portNameToId(it.getValue(portNameFallback));
  1017. CARLA_SAFE_ASSERT_CONTINUE(portNameToId.group != 0);
  1018. if (portNameToId.group != groupId)
  1019. continue;
  1020. callback(ENGINE_CALLBACK_PATCHBAY_PORT_REMOVED, portNameToId.group, static_cast<int>(portNameToId.port), 0, 0.0f, nullptr);
  1021. fUsedPorts.list.remove(it);
  1022. }
  1023. }
  1024. startThread();
  1025. }
  1026. else
  1027. {
  1028. setLastError("Failed to create new JACK client");
  1029. return nullptr;
  1030. }
  1031. }
  1032. // Rename
  1033. plugin->setName(uniqueName);
  1034. if (needsReinit)
  1035. {
  1036. // reload plugin to recreate its ports
  1037. plugin->reload();
  1038. plugin->loadStateSave(*saveStatePtr);
  1039. plugin->setEnabled(true);
  1040. }
  1041. return plugin->getName();
  1042. }
  1043. // -------------------------------------------------------------------
  1044. // Patchbay
  1045. bool patchbayConnect(const uint groupA, const uint portA, const uint groupB, const uint portB) override
  1046. {
  1047. CARLA_SAFE_ASSERT_RETURN(fClient != nullptr, false);
  1048. if (pData->options.processMode == ENGINE_PROCESS_MODE_PATCHBAY && ! fExternalPatchbay)
  1049. return CarlaEngine::patchbayConnect(groupA, portA, groupB, portB);
  1050. const char* const fullPortNameA = fUsedPorts.getFullPortName(groupA, portA);
  1051. CARLA_SAFE_ASSERT_RETURN(fullPortNameA != nullptr && fullPortNameA[0] != '\0', false);
  1052. const char* const fullPortNameB = fUsedPorts.getFullPortName(groupB, portB);
  1053. CARLA_SAFE_ASSERT_RETURN(fullPortNameB != nullptr && fullPortNameB[0] != '\0', false);
  1054. if (! jackbridge_connect(fClient, fullPortNameA, fullPortNameB))
  1055. {
  1056. setLastError("JACK operation failed");
  1057. return false;
  1058. }
  1059. return true;
  1060. }
  1061. bool patchbayDisconnect(const uint connectionId) override
  1062. {
  1063. CARLA_SAFE_ASSERT_RETURN(fClient != nullptr, false);
  1064. if (pData->options.processMode == ENGINE_PROCESS_MODE_PATCHBAY && ! fExternalPatchbay)
  1065. return CarlaEngine::patchbayDisconnect(connectionId);
  1066. ConnectionToId connectionToId = { 0, 0, 0, 0, 0 };
  1067. {
  1068. const CarlaMutexLocker cml(fUsedConnections.mutex);
  1069. for (LinkedList<ConnectionToId>::Itenerator it = fUsedConnections.list.begin2(); it.valid(); it.next())
  1070. {
  1071. connectionToId = it.getValue(connectionToId);
  1072. CARLA_SAFE_ASSERT_CONTINUE(connectionToId.id != 0);
  1073. if (connectionToId.id == connectionId)
  1074. break;
  1075. }
  1076. }
  1077. if (connectionToId.id == 0 || connectionToId.id != connectionId)
  1078. {
  1079. setLastError("Failed to find the requested connection");
  1080. return false;
  1081. }
  1082. const char* const fullPortNameA = fUsedPorts.getFullPortName(connectionToId.groupA, connectionToId.portA);
  1083. CARLA_SAFE_ASSERT_RETURN(fullPortNameA != nullptr && fullPortNameA[0] != '\0', false);
  1084. const char* const fullPortNameB = fUsedPorts.getFullPortName(connectionToId.groupB, connectionToId.portB);
  1085. CARLA_SAFE_ASSERT_RETURN(fullPortNameB != nullptr && fullPortNameB[0] != '\0', false);
  1086. if (! jackbridge_disconnect(fClient, fullPortNameA, fullPortNameB))
  1087. {
  1088. setLastError("JACK operation failed");
  1089. return false;
  1090. }
  1091. return true;
  1092. }
  1093. bool patchbayRefresh(const bool external) override
  1094. {
  1095. CARLA_SAFE_ASSERT_RETURN(fClient != nullptr, false);
  1096. if (pData->options.processMode == ENGINE_PROCESS_MODE_PATCHBAY)
  1097. {
  1098. fExternalPatchbay = external;
  1099. pData->graph.setUsingExternal(external);
  1100. if (! external)
  1101. return CarlaEngine::patchbayRefresh(false);
  1102. }
  1103. fUsedGroups.clear();
  1104. fUsedPorts.clear();
  1105. fUsedConnections.clear();
  1106. fNewGroups.clear();
  1107. initJackPatchbay(jackbridge_get_client_name(fClient));
  1108. return true;
  1109. }
  1110. // -------------------------------------------------------------------
  1111. // Transport
  1112. void transportPlay() noexcept override
  1113. {
  1114. if (pData->options.transportMode == ENGINE_TRANSPORT_MODE_INTERNAL)
  1115. return CarlaEngine::transportPlay();
  1116. if (fClient != nullptr)
  1117. {
  1118. if (! pData->timeInfo.bbt.valid)
  1119. {
  1120. // old timebase master no longer active, make ourselves master again
  1121. pData->time.setNeedsReset();
  1122. fTimebaseMaster = jackbridge_set_timebase_callback(fClient, true, carla_jack_timebase_callback, this);
  1123. }
  1124. try {
  1125. jackbridge_transport_start(fClient);
  1126. } catch(...) {}
  1127. }
  1128. }
  1129. void transportPause() noexcept override
  1130. {
  1131. if (pData->options.transportMode == ENGINE_TRANSPORT_MODE_INTERNAL)
  1132. return CarlaEngine::transportPause();
  1133. if (fClient != nullptr)
  1134. {
  1135. try {
  1136. jackbridge_transport_stop(fClient);
  1137. } catch(...) {}
  1138. }
  1139. }
  1140. void transportBPM(const double bpm) noexcept override
  1141. {
  1142. CarlaEngine::transportBPM(bpm);
  1143. if (fClient == nullptr || fTimebaseMaster)
  1144. return;
  1145. jack_position_t jpos;
  1146. // invalidate
  1147. jpos.unique_1 = 1;
  1148. jpos.unique_2 = 2;
  1149. jackbridge_transport_query(fClient, &jpos);
  1150. if (jpos.unique_1 == jpos.unique_2 && (jpos.valid & JackPositionBBT) != 0)
  1151. {
  1152. carla_stdout("NOTE: Changing BPM without being JACK timebase master");
  1153. jpos.beats_per_minute = bpm;
  1154. try {
  1155. jackbridge_transport_reposition(fClient, &jpos);
  1156. } catch(...) {}
  1157. }
  1158. }
  1159. void transportRelocate(const uint64_t frame) noexcept override
  1160. {
  1161. if (pData->options.transportMode == ENGINE_TRANSPORT_MODE_INTERNAL)
  1162. return CarlaEngine::transportRelocate(frame);
  1163. if (fClient != nullptr)
  1164. {
  1165. try {
  1166. jackbridge_transport_locate(fClient, static_cast<jack_nframes_t>(frame));
  1167. } catch(...) {}
  1168. }
  1169. }
  1170. // -------------------------------------------------------------------
  1171. // Patchbay stuff
  1172. const char* const* getPatchbayConnections(const bool external) const override
  1173. {
  1174. CARLA_SAFE_ASSERT_RETURN(fClient != nullptr, nullptr);
  1175. carla_debug("CarlaEngineJack::getPatchbayConnections(%s)", bool2str(external));
  1176. if (pData->options.processMode == ENGINE_PROCESS_MODE_PATCHBAY && ! external)
  1177. return CarlaEngine::getPatchbayConnections(external);
  1178. CarlaStringList connList;
  1179. if (const char** const ports = jackbridge_get_ports(fClient, nullptr, nullptr, JackPortIsOutput))
  1180. {
  1181. for (int i=0; ports[i] != nullptr; ++i)
  1182. {
  1183. const jack_port_t* const jackPort(jackbridge_port_by_name(fClient, ports[i]));
  1184. const char* const fullPortName(ports[i]);
  1185. CARLA_SAFE_ASSERT_CONTINUE(jackPort != nullptr);
  1186. if (const char** const connections = jackbridge_port_get_all_connections(fClient, jackPort))
  1187. {
  1188. for (int j=0; connections[j] != nullptr; ++j)
  1189. {
  1190. connList.append(fullPortName);
  1191. connList.append(connections[j]);
  1192. }
  1193. jackbridge_free(connections);
  1194. }
  1195. }
  1196. jackbridge_free(ports);
  1197. }
  1198. if (connList.count() == 0)
  1199. return nullptr;
  1200. fRetConns = connList.toCharStringListPtr();
  1201. return fRetConns;
  1202. }
  1203. void restorePatchbayConnection(const bool external, const char* const connSource, const char* const connTarget, const bool sendCallback) override
  1204. {
  1205. CARLA_SAFE_ASSERT_RETURN(fClient != nullptr,);
  1206. CARLA_SAFE_ASSERT_RETURN(connSource != nullptr && connSource[0] != '\0',);
  1207. CARLA_SAFE_ASSERT_RETURN(connTarget != nullptr && connTarget[0] != '\0',);
  1208. carla_debug("CarlaEngineJack::restorePatchbayConnection(\"%s\", \"%s\")", connSource, connTarget);
  1209. if (pData->options.processMode == ENGINE_PROCESS_MODE_PATCHBAY && ! external)
  1210. return CarlaEngine::restorePatchbayConnection(external, connSource, connTarget, sendCallback);
  1211. if (const jack_port_t* const port = jackbridge_port_by_name(fClient, connSource))
  1212. {
  1213. if (jackbridge_port_by_name(fClient, connTarget) == nullptr)
  1214. return;
  1215. if (! jackbridge_port_connected_to(port, connTarget))
  1216. jackbridge_connect(fClient, connSource, connTarget);
  1217. }
  1218. }
  1219. #endif
  1220. // -------------------------------------------------------------------
  1221. protected:
  1222. void handleJackBufferSizeCallback(const uint32_t newBufferSize)
  1223. {
  1224. if (pData->bufferSize == newBufferSize)
  1225. return;
  1226. pData->bufferSize = newBufferSize;
  1227. bufferSizeChanged(newBufferSize);
  1228. }
  1229. void handleJackSampleRateCallback(const double newSampleRate)
  1230. {
  1231. if (carla_isEqual(pData->sampleRate, newSampleRate))
  1232. return;
  1233. pData->sampleRate = newSampleRate;
  1234. sampleRateChanged(newSampleRate);
  1235. }
  1236. void handleJackFreewheelCallback(const bool isFreewheel)
  1237. {
  1238. if (fFreewheel == isFreewheel)
  1239. return;
  1240. fFreewheel = isFreewheel;
  1241. offlineModeChanged(isFreewheel);
  1242. }
  1243. void saveTransportInfo()
  1244. {
  1245. if (pData->options.transportMode != ENGINE_TRANSPORT_MODE_JACK)
  1246. return;
  1247. jack_position_t jpos;
  1248. // invalidate
  1249. jpos.unique_1 = 1;
  1250. jpos.unique_2 = 2;
  1251. pData->timeInfo.playing = (jackbridge_transport_query(fClient, &jpos) == JackTransportRolling);
  1252. if (jpos.unique_1 == jpos.unique_2)
  1253. {
  1254. pData->timeInfo.frame = jpos.frame;
  1255. pData->timeInfo.usecs = jpos.usecs;
  1256. if (jpos.valid & JackPositionBBT)
  1257. {
  1258. pData->timeInfo.bbt.valid = true;
  1259. pData->timeInfo.bbt.bar = jpos.bar;
  1260. pData->timeInfo.bbt.beat = jpos.beat;
  1261. pData->timeInfo.bbt.tick = jpos.tick;
  1262. pData->timeInfo.bbt.barStartTick = jpos.bar_start_tick;
  1263. pData->timeInfo.bbt.beatsPerBar = jpos.beats_per_bar;
  1264. pData->timeInfo.bbt.beatType = jpos.beat_type;
  1265. pData->timeInfo.bbt.ticksPerBeat = jpos.ticks_per_beat;
  1266. pData->timeInfo.bbt.beatsPerMinute = jpos.beats_per_minute;
  1267. }
  1268. else
  1269. {
  1270. pData->timeInfo.bbt.valid = false;
  1271. }
  1272. }
  1273. else
  1274. {
  1275. pData->timeInfo.frame = 0;
  1276. pData->timeInfo.usecs = 0;
  1277. pData->timeInfo.bbt.valid = false;
  1278. }
  1279. }
  1280. void handleJackProcessCallback(const uint32_t nframes)
  1281. {
  1282. const PendingRtEventsRunner prt(this, nframes);
  1283. CARLA_SAFE_ASSERT_RETURN(nframes == pData->bufferSize,);
  1284. saveTransportInfo();
  1285. #ifdef BUILD_BRIDGE
  1286. CarlaPlugin* const plugin(pData->plugins[0].plugin);
  1287. if (plugin != nullptr && plugin->isEnabled() && plugin->tryLock(fFreewheel))
  1288. {
  1289. plugin->initBuffers();
  1290. processPlugin(plugin, nframes);
  1291. plugin->unlock();
  1292. }
  1293. #else
  1294. if (pData->options.processMode == ENGINE_PROCESS_MODE_CONTINUOUS_RACK)
  1295. {
  1296. if (pData->aboutToClose)
  1297. {
  1298. if (float* const audioOut1 = (float*)jackbridge_port_get_buffer(fRackPorts[kRackPortAudioOut1], nframes))
  1299. carla_zeroFloats(audioOut1, nframes);
  1300. if (float* const audioOut2 = (float*)jackbridge_port_get_buffer(fRackPorts[kRackPortAudioOut2], nframes))
  1301. carla_zeroFloats(audioOut2, nframes);
  1302. }
  1303. else if (pData->curPluginCount == 0)
  1304. {
  1305. float* const audioIn1 = (float*)jackbridge_port_get_buffer(fRackPorts[kRackPortAudioIn1], nframes);
  1306. float* const audioIn2 = (float*)jackbridge_port_get_buffer(fRackPorts[kRackPortAudioIn2], nframes);
  1307. float* const audioOut1 = (float*)jackbridge_port_get_buffer(fRackPorts[kRackPortAudioOut1], nframes);
  1308. float* const audioOut2 = (float*)jackbridge_port_get_buffer(fRackPorts[kRackPortAudioOut2], nframes);
  1309. // assert buffers
  1310. CARLA_SAFE_ASSERT_RETURN(audioIn1 != nullptr,);
  1311. CARLA_SAFE_ASSERT_RETURN(audioIn2 != nullptr,);
  1312. CARLA_SAFE_ASSERT_RETURN(audioOut1 != nullptr,);
  1313. CARLA_SAFE_ASSERT_RETURN(audioOut2 != nullptr,);
  1314. // pass-through
  1315. carla_copyFloats(audioOut1, audioIn1, nframes);
  1316. carla_copyFloats(audioOut2, audioIn2, nframes);
  1317. // TODO pass-through MIDI as well
  1318. if (void* const eventOut = jackbridge_port_get_buffer(fRackPorts[kRackPortEventOut], nframes))
  1319. jackbridge_midi_clear_buffer(eventOut);
  1320. return;
  1321. }
  1322. }
  1323. if (pData->options.processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  1324. {
  1325. for (uint i=0; i < pData->curPluginCount; ++i)
  1326. {
  1327. CarlaPlugin* const plugin(pData->plugins[i].plugin);
  1328. if (plugin != nullptr && plugin->isEnabled() && plugin->tryLock(fFreewheel))
  1329. {
  1330. plugin->initBuffers();
  1331. processPlugin(plugin, nframes);
  1332. plugin->unlock();
  1333. }
  1334. }
  1335. }
  1336. else if (pData->options.processMode == ENGINE_PROCESS_MODE_CONTINUOUS_RACK ||
  1337. pData->options.processMode == ENGINE_PROCESS_MODE_PATCHBAY)
  1338. {
  1339. CARLA_SAFE_ASSERT_RETURN(pData->events.in != nullptr,);
  1340. CARLA_SAFE_ASSERT_RETURN(pData->events.out != nullptr,);
  1341. // get buffers from jack
  1342. float* const audioIn1 = (float*)jackbridge_port_get_buffer(fRackPorts[kRackPortAudioIn1], nframes);
  1343. float* const audioIn2 = (float*)jackbridge_port_get_buffer(fRackPorts[kRackPortAudioIn2], nframes);
  1344. float* const audioOut1 = (float*)jackbridge_port_get_buffer(fRackPorts[kRackPortAudioOut1], nframes);
  1345. float* const audioOut2 = (float*)jackbridge_port_get_buffer(fRackPorts[kRackPortAudioOut2], nframes);
  1346. void* const eventIn = jackbridge_port_get_buffer(fRackPorts[kRackPortEventIn], nframes);
  1347. void* const eventOut = jackbridge_port_get_buffer(fRackPorts[kRackPortEventOut], nframes);
  1348. // assert buffers
  1349. CARLA_SAFE_ASSERT_RETURN(audioIn1 != nullptr,);
  1350. CARLA_SAFE_ASSERT_RETURN(audioIn2 != nullptr,);
  1351. CARLA_SAFE_ASSERT_RETURN(audioOut1 != nullptr,);
  1352. CARLA_SAFE_ASSERT_RETURN(audioOut2 != nullptr,);
  1353. // create audio buffers
  1354. const float* inBuf[2] = { audioIn1, audioIn2 };
  1355. /**/ float* outBuf[2] = { audioOut1, audioOut2 };
  1356. // initialize events
  1357. carla_zeroStructs(pData->events.in, kMaxEngineEventInternalCount);
  1358. carla_zeroStructs(pData->events.out, kMaxEngineEventInternalCount);
  1359. if (eventIn != nullptr)
  1360. {
  1361. ushort engineEventIndex = 0;
  1362. jack_midi_event_t jackEvent;
  1363. const uint32_t jackEventCount(jackbridge_midi_get_event_count(eventIn));
  1364. for (uint32_t jackEventIndex=0; jackEventIndex < jackEventCount; ++jackEventIndex)
  1365. {
  1366. if (! jackbridge_midi_event_get(&jackEvent, eventIn, jackEventIndex))
  1367. continue;
  1368. CARLA_SAFE_ASSERT_CONTINUE(jackEvent.size < 0xFF /* uint8_t max */);
  1369. EngineEvent& engineEvent(pData->events.in[engineEventIndex++]);
  1370. engineEvent.time = jackEvent.time;
  1371. engineEvent.fillFromMidiData(static_cast<uint8_t>(jackEvent.size), jackEvent.buffer, 0);
  1372. if (engineEventIndex >= kMaxEngineEventInternalCount)
  1373. break;
  1374. }
  1375. }
  1376. if (pData->options.processMode == ENGINE_PROCESS_MODE_CONTINUOUS_RACK)
  1377. pData->graph.processRack(pData, inBuf, outBuf, nframes);
  1378. else
  1379. pData->graph.process(pData, inBuf, outBuf, nframes);
  1380. // output control
  1381. if (eventOut != nullptr)
  1382. {
  1383. jackbridge_midi_clear_buffer(eventOut);
  1384. uint8_t size = 0;
  1385. uint8_t mdata[3] = { 0, 0, 0 };
  1386. uint8_t mdataTmp[EngineMidiEvent::kDataSize];
  1387. const uint8_t* mdataPtr;
  1388. for (ushort i=0; i < kMaxEngineEventInternalCount; ++i)
  1389. {
  1390. const EngineEvent& engineEvent(pData->events.out[i]);
  1391. /**/ if (engineEvent.type == kEngineEventTypeNull)
  1392. {
  1393. break;
  1394. }
  1395. else if (engineEvent.type == kEngineEventTypeControl)
  1396. {
  1397. const EngineControlEvent& ctrlEvent(engineEvent.ctrl);
  1398. size = ctrlEvent.convertToMidiData(engineEvent.channel, mdata);
  1399. mdataPtr = mdata;
  1400. }
  1401. else if (engineEvent.type == kEngineEventTypeMidi)
  1402. {
  1403. const EngineMidiEvent& midiEvent(engineEvent.midi);
  1404. size = midiEvent.size;
  1405. CARLA_SAFE_ASSERT_CONTINUE(size > 0);
  1406. if (size > EngineMidiEvent::kDataSize)
  1407. {
  1408. CARLA_SAFE_ASSERT_CONTINUE(midiEvent.dataExt != nullptr);
  1409. mdataPtr = midiEvent.dataExt;
  1410. }
  1411. else
  1412. {
  1413. // set first byte
  1414. mdataTmp[0] = static_cast<uint8_t>(midiEvent.data[0] | (engineEvent.channel & MIDI_CHANNEL_BIT));
  1415. // copy rest
  1416. carla_copy<uint8_t>(mdataTmp+1, midiEvent.data+1, size-1);
  1417. // done
  1418. mdataPtr = mdataTmp;
  1419. }
  1420. }
  1421. else
  1422. {
  1423. continue;
  1424. }
  1425. if (size > 0)
  1426. jackbridge_midi_event_write(eventOut, engineEvent.time, mdataPtr, size);
  1427. }
  1428. }
  1429. }
  1430. #endif // ! BUILD_BRIDGE
  1431. }
  1432. void handleJackLatencyCallback(const jack_latency_callback_mode_t /*mode*/)
  1433. {
  1434. // TODO
  1435. }
  1436. #ifndef BUILD_BRIDGE
  1437. void handleJackTimebaseCallback(jack_nframes_t nframes, jack_position_t* const pos, const int new_pos)
  1438. {
  1439. if (new_pos)
  1440. pData->time.setNeedsReset();
  1441. pData->time.fillJackTimeInfo(pos, nframes);
  1442. }
  1443. void handleJackClientRegistrationCallback(const char* const name, const bool reg)
  1444. {
  1445. CARLA_SAFE_ASSERT_RETURN(name != nullptr && name[0] != '\0',);
  1446. // ignore this if on internal patchbay mode
  1447. if (! fExternalPatchbay) return;
  1448. // do nothing on client registration, wait for first port
  1449. if (reg) return;
  1450. const uint groupId(fUsedGroups.getGroupId(name));
  1451. // clients might have been registered without ports
  1452. if (groupId == 0) return;
  1453. GroupNameToId groupNameToId;
  1454. groupNameToId.setData(groupId, name);
  1455. callback(ENGINE_CALLBACK_PATCHBAY_CLIENT_REMOVED, groupNameToId.group, 0, 0, 0.0f, nullptr);
  1456. fUsedGroups.list.removeOne(groupNameToId);
  1457. }
  1458. void handleJackPortRegistrationCallback(const jack_port_id_t port, const bool reg)
  1459. {
  1460. // ignore this if on internal patchbay mode
  1461. if (! fExternalPatchbay) return;
  1462. const jack_port_t* const jackPort(jackbridge_port_by_id(fClient, port));
  1463. CARLA_SAFE_ASSERT_RETURN(jackPort != nullptr,);
  1464. const char* const fullPortName(jackbridge_port_name(jackPort));
  1465. CARLA_SAFE_ASSERT_RETURN(fullPortName != nullptr && fullPortName[0] != '\0',);
  1466. if (reg)
  1467. {
  1468. const char* const shortPortName(jackbridge_port_short_name(jackPort));
  1469. CARLA_SAFE_ASSERT_RETURN(shortPortName != nullptr && shortPortName[0] != '\0',);
  1470. bool found;
  1471. CarlaString groupName(fullPortName);
  1472. groupName.truncate(groupName.rfind(shortPortName, &found)-1);
  1473. CARLA_SAFE_ASSERT_RETURN(found,);
  1474. const int jackPortFlags(jackbridge_port_flags(jackPort));
  1475. uint groupId(fUsedGroups.getGroupId(groupName));
  1476. if (groupId == 0)
  1477. {
  1478. groupId = ++fUsedGroups.lastId;
  1479. PatchbayIcon icon = (jackPortFlags & JackPortIsPhysical) ? PATCHBAY_ICON_HARDWARE : PATCHBAY_ICON_APPLICATION;
  1480. GroupNameToId groupNameToId;
  1481. groupNameToId.setData(groupId, groupName);
  1482. callback(ENGINE_CALLBACK_PATCHBAY_CLIENT_ADDED, groupNameToId.group, icon, -1, 0.0f, groupNameToId.name);
  1483. fNewGroups.append(groupId);
  1484. fUsedGroups.list.append(groupNameToId);
  1485. }
  1486. addPatchbayJackPort(groupId, jackPort, shortPortName, fullPortName, jackPortFlags);
  1487. }
  1488. else
  1489. {
  1490. const PortNameToId& portNameToId(fUsedPorts.getPortNameToId(fullPortName));
  1491. /* NOTE: Due to JACK2 async behaviour the port we get here might be the same of a previous rename-plugin request.
  1492. See the comment on CarlaEngineJack::renamePlugin() for more information. */
  1493. if (portNameToId.group <= 0 || portNameToId.port <= 0) return;
  1494. callback(ENGINE_CALLBACK_PATCHBAY_PORT_REMOVED, portNameToId.group, static_cast<int>(portNameToId.port), 0, 0.0f, nullptr);
  1495. fUsedPorts.list.removeOne(portNameToId);
  1496. }
  1497. }
  1498. void handleJackPortConnectCallback(const jack_port_id_t a, const jack_port_id_t b, const bool connect)
  1499. {
  1500. // ignore this if on internal patchbay mode
  1501. if (! fExternalPatchbay) return;
  1502. const jack_port_t* const jackPortA(jackbridge_port_by_id(fClient, a));
  1503. CARLA_SAFE_ASSERT_RETURN(jackPortA != nullptr,);
  1504. const jack_port_t* const jackPortB(jackbridge_port_by_id(fClient, b));
  1505. CARLA_SAFE_ASSERT_RETURN(jackPortB != nullptr,);
  1506. const char* const fullPortNameA(jackbridge_port_name(jackPortA));
  1507. CARLA_SAFE_ASSERT_RETURN(fullPortNameA != nullptr && fullPortNameA[0] != '\0',);
  1508. const char* const fullPortNameB(jackbridge_port_name(jackPortB));
  1509. CARLA_SAFE_ASSERT_RETURN(fullPortNameB != nullptr && fullPortNameB[0] != '\0',);
  1510. const PortNameToId& portNameToIdA(fUsedPorts.getPortNameToId(fullPortNameA));
  1511. const PortNameToId& portNameToIdB(fUsedPorts.getPortNameToId(fullPortNameB));
  1512. /* NOTE: Due to JACK2 async behaviour the port we get here might be the same of a previous rename-plugin request.
  1513. See the comment on CarlaEngineJack::renamePlugin() for more information. */
  1514. if (portNameToIdA.group <= 0 || portNameToIdA.port <= 0) return;
  1515. if (portNameToIdB.group <= 0 || portNameToIdB.port <= 0) return;
  1516. if (connect)
  1517. {
  1518. char strBuf[STR_MAX+1];
  1519. std::snprintf(strBuf, STR_MAX, "%i:%i:%i:%i", portNameToIdA.group, portNameToIdA.port, portNameToIdB.group, portNameToIdB.port);
  1520. strBuf[STR_MAX] = '\0';
  1521. ConnectionToId connectionToId;
  1522. connectionToId.setData(++fUsedConnections.lastId, portNameToIdA.group, portNameToIdA.port, portNameToIdB.group, portNameToIdB.port);
  1523. callback(ENGINE_CALLBACK_PATCHBAY_CONNECTION_ADDED, connectionToId.id, 0, 0, 0.0f, strBuf);
  1524. fUsedConnections.list.append(connectionToId);
  1525. }
  1526. else
  1527. {
  1528. ConnectionToId connectionToId = { 0, 0, 0, 0, 0 };
  1529. bool found = false;
  1530. {
  1531. const CarlaMutexLocker cml(fUsedConnections.mutex);
  1532. for (LinkedList<ConnectionToId>::Itenerator it = fUsedConnections.list.begin2(); it.valid(); it.next())
  1533. {
  1534. connectionToId = it.getValue(connectionToId);
  1535. CARLA_SAFE_ASSERT_CONTINUE(connectionToId.id != 0);
  1536. if (connectionToId.groupA == portNameToIdA.group && connectionToId.portA == portNameToIdA.port &&
  1537. connectionToId.groupB == portNameToIdB.group && connectionToId.portB == portNameToIdB.port)
  1538. {
  1539. found = true;
  1540. fUsedConnections.list.remove(it);
  1541. break;
  1542. }
  1543. }
  1544. }
  1545. if (found)
  1546. callback(ENGINE_CALLBACK_PATCHBAY_CONNECTION_REMOVED, connectionToId.id, 0, 0, 0.0f, nullptr);
  1547. }
  1548. }
  1549. void handleJackPortRenameCallback(const jack_port_id_t port, const char* const oldFullName, const char* const newFullName)
  1550. {
  1551. // ignore this if on internal patchbay mode
  1552. if (! fExternalPatchbay) return;
  1553. CARLA_SAFE_ASSERT_RETURN(oldFullName != nullptr && oldFullName[0] != '\0',);
  1554. CARLA_SAFE_ASSERT_RETURN(newFullName != nullptr && newFullName[0] != '\0',);
  1555. const jack_port_t* const jackPort(jackbridge_port_by_id(fClient, port));
  1556. CARLA_SAFE_ASSERT_RETURN(jackPort != nullptr,);
  1557. const char* const shortPortName(jackbridge_port_short_name(jackPort));
  1558. CARLA_SAFE_ASSERT_RETURN(shortPortName != nullptr && shortPortName[0] != '\0',);
  1559. bool found;
  1560. CarlaString groupName(newFullName);
  1561. groupName.truncate(groupName.rfind(shortPortName, &found)-1);
  1562. CARLA_SAFE_ASSERT_RETURN(found,);
  1563. const uint groupId(fUsedGroups.getGroupId(groupName));
  1564. CARLA_SAFE_ASSERT_RETURN(groupId > 0,);
  1565. for (LinkedList<PortNameToId>::Itenerator it = fUsedPorts.list.begin2(); it.valid(); it.next())
  1566. {
  1567. static PortNameToId portNameFallback = { 0, 0, { '\0' }, { '\0' } };
  1568. PortNameToId& portNameToId(it.getValue(portNameFallback));
  1569. CARLA_SAFE_ASSERT_CONTINUE(portNameToId.group != 0);
  1570. if (std::strncmp(portNameToId.fullName, oldFullName, STR_MAX) == 0)
  1571. {
  1572. CARLA_SAFE_ASSERT_CONTINUE(portNameToId.group == groupId);
  1573. portNameToId.rename(shortPortName, newFullName);
  1574. callback(ENGINE_CALLBACK_PATCHBAY_PORT_RENAMED, portNameToId.group, static_cast<int>(portNameToId.port), 0, 0.0f, portNameToId.name);
  1575. break;
  1576. }
  1577. }
  1578. }
  1579. #endif
  1580. void handleJackShutdownCallback()
  1581. {
  1582. #ifndef BUILD_BRIDGE
  1583. signalThreadShouldExit();
  1584. #endif
  1585. const PendingRtEventsRunner prt(this, pData->bufferSize);
  1586. for (uint i=0; i < pData->curPluginCount; ++i)
  1587. {
  1588. if (CarlaPlugin* const plugin = pData->plugins[i].plugin)
  1589. {
  1590. plugin->tryLock(true);
  1591. if (CarlaEngineJackClient* const client = (CarlaEngineJackClient*)plugin->getEngineClient())
  1592. client->invalidate();
  1593. plugin->unlock();
  1594. }
  1595. }
  1596. fClient = nullptr;
  1597. #ifndef BUILD_BRIDGE
  1598. carla_zeroPointers(fRackPorts, kRackPortCount);
  1599. #endif
  1600. callback(ENGINE_CALLBACK_QUIT, 0, 0, 0, 0.0f, nullptr);
  1601. }
  1602. // -------------------------------------------------------------------
  1603. void handlePluginJackShutdownCallback(CarlaPlugin* const plugin)
  1604. {
  1605. CarlaEngineJackClient* const engineClient((CarlaEngineJackClient*)plugin->getEngineClient());
  1606. CARLA_SAFE_ASSERT_RETURN(engineClient != nullptr,);
  1607. plugin->tryLock(true);
  1608. engineClient->invalidate();
  1609. plugin->unlock();
  1610. //if (pData->nextAction.pluginId == plugin->getId())
  1611. // pData->nextAction.clearAndReset();
  1612. callback(ENGINE_CALLBACK_PLUGIN_UNAVAILABLE, plugin->getId(), 0, 0, 0.0f, "Killed by JACK");
  1613. }
  1614. // -------------------------------------------------------------------
  1615. private:
  1616. jack_client_t* fClient;
  1617. bool fExternalPatchbay;
  1618. bool fFreewheel;
  1619. // -------------------------------------------------------------------
  1620. #ifdef BUILD_BRIDGE
  1621. bool fIsRunning;
  1622. #else
  1623. enum RackPorts {
  1624. kRackPortAudioIn1 = 0,
  1625. kRackPortAudioIn2 = 1,
  1626. kRackPortAudioOut1 = 2,
  1627. kRackPortAudioOut2 = 3,
  1628. kRackPortEventIn = 4,
  1629. kRackPortEventOut = 5,
  1630. kRackPortCount = 6
  1631. };
  1632. jack_port_t* fRackPorts[kRackPortCount];
  1633. bool fTimebaseMaster;
  1634. PatchbayGroupList fUsedGroups;
  1635. PatchbayPortList fUsedPorts;
  1636. PatchbayConnectionList fUsedConnections;
  1637. LinkedList<uint> fNewGroups;
  1638. mutable CharStringListPtr fRetConns;
  1639. bool findPluginIdAndIcon(const char* const clientName, int& pluginId, PatchbayIcon& icon) noexcept
  1640. {
  1641. carla_debug("CarlaEngineJack::findPluginIdAndIcon(\"%s\", ...)", clientName);
  1642. // TODO - this currently only works in multi-client mode
  1643. if (pData->options.processMode != ENGINE_PROCESS_MODE_MULTIPLE_CLIENTS)
  1644. return false;
  1645. for (uint i=0; i < pData->curPluginCount; ++i)
  1646. {
  1647. CarlaPlugin* const plugin(pData->plugins[i].plugin);
  1648. if (plugin == nullptr || ! plugin->isEnabled())
  1649. continue;
  1650. const CarlaEngineJackClient* const engineClient((const CarlaEngineJackClient*)plugin->getEngineClient());
  1651. CARLA_SAFE_ASSERT_CONTINUE(engineClient != nullptr);
  1652. const char* const engineClientName(engineClient->getJackClientName());
  1653. CARLA_SAFE_ASSERT_CONTINUE(engineClientName != nullptr && engineClientName[0] != '\0');
  1654. if (std::strcmp(clientName, engineClientName) != 0)
  1655. continue;
  1656. pluginId = static_cast<int>(i);
  1657. icon = PATCHBAY_ICON_PLUGIN;
  1658. if (const char* const pluginIcon = plugin->getIconName())
  1659. {
  1660. if (pluginIcon[0] == '\0')
  1661. pass();
  1662. else if (std::strcmp(pluginIcon, "app") == 0 || std::strcmp(pluginIcon, "application") == 0)
  1663. icon = PATCHBAY_ICON_APPLICATION;
  1664. else if (std::strcmp(pluginIcon, "plugin") == 0)
  1665. icon = PATCHBAY_ICON_PLUGIN;
  1666. else if (std::strcmp(pluginIcon, "hardware") == 0)
  1667. icon = PATCHBAY_ICON_HARDWARE;
  1668. else if (std::strcmp(pluginIcon, "carla") == 0)
  1669. icon = PATCHBAY_ICON_CARLA;
  1670. else if (std::strcmp(pluginIcon, "distrho") == 0)
  1671. icon = PATCHBAY_ICON_DISTRHO;
  1672. else if (std::strcmp(pluginIcon, "file") == 0)
  1673. icon = PATCHBAY_ICON_FILE;
  1674. }
  1675. return true;
  1676. }
  1677. return false;
  1678. }
  1679. void initJackPatchbay(const char* const ourName)
  1680. {
  1681. CARLA_SAFE_ASSERT_RETURN(pData->options.processMode != ENGINE_PROCESS_MODE_PATCHBAY || fExternalPatchbay,);
  1682. CARLA_SAFE_ASSERT_RETURN(ourName != nullptr && ourName[0] != '\0',);
  1683. CarlaStringList parsedGroups;
  1684. // add our client first
  1685. {
  1686. parsedGroups.append(ourName);
  1687. GroupNameToId groupNameToId;
  1688. groupNameToId.setData(++fUsedGroups.lastId, ourName);
  1689. callback(ENGINE_CALLBACK_PATCHBAY_CLIENT_ADDED, groupNameToId.group, PATCHBAY_ICON_CARLA, -1, 0.0f, groupNameToId.name);
  1690. fUsedGroups.list.append(groupNameToId);
  1691. }
  1692. // query all jack ports
  1693. if (const char** const ports = jackbridge_get_ports(fClient, nullptr, nullptr, 0))
  1694. {
  1695. for (int i=0; ports[i] != nullptr; ++i)
  1696. {
  1697. const char* const fullPortName(ports[i]);
  1698. CARLA_SAFE_ASSERT_CONTINUE(fullPortName != nullptr && fullPortName[0] != '\0');
  1699. const jack_port_t* const jackPort(jackbridge_port_by_name(fClient, fullPortName));
  1700. CARLA_SAFE_ASSERT_CONTINUE(jackPort != nullptr);
  1701. const char* const shortPortName(jackbridge_port_short_name(jackPort));
  1702. CARLA_SAFE_ASSERT_CONTINUE(shortPortName != nullptr && shortPortName[0] != '\0');
  1703. const int jackPortFlags(jackbridge_port_flags(jackPort));
  1704. uint groupId = 0;
  1705. bool found;
  1706. CarlaString groupName(fullPortName);
  1707. groupName.truncate(groupName.rfind(shortPortName, &found)-1);
  1708. CARLA_SAFE_ASSERT_CONTINUE(found);
  1709. if (parsedGroups.contains(groupName))
  1710. {
  1711. groupId = fUsedGroups.getGroupId(groupName);
  1712. CARLA_SAFE_ASSERT_CONTINUE(groupId > 0);
  1713. }
  1714. else
  1715. {
  1716. groupId = ++fUsedGroups.lastId;
  1717. parsedGroups.append(groupName);
  1718. int pluginId = -1;
  1719. PatchbayIcon icon = (jackPortFlags & JackPortIsPhysical) ? PATCHBAY_ICON_HARDWARE : PATCHBAY_ICON_APPLICATION;
  1720. findPluginIdAndIcon(groupName, pluginId, icon);
  1721. GroupNameToId groupNameToId;
  1722. groupNameToId.setData(groupId, groupName);
  1723. callback(ENGINE_CALLBACK_PATCHBAY_CLIENT_ADDED, groupNameToId.group, icon, pluginId, 0.0f, groupNameToId.name);
  1724. fUsedGroups.list.append(groupNameToId);
  1725. }
  1726. addPatchbayJackPort(groupId, jackPort, shortPortName, fullPortName, jackPortFlags);
  1727. }
  1728. jackbridge_free(ports);
  1729. }
  1730. // query connections, after all ports are in place
  1731. if (const char** const ports = jackbridge_get_ports(fClient, nullptr, nullptr, JackPortIsOutput))
  1732. {
  1733. char strBuf[STR_MAX+1];
  1734. for (int i=0; ports[i] != nullptr; ++i)
  1735. {
  1736. const char* const fullPortName(ports[i]);
  1737. CARLA_SAFE_ASSERT_CONTINUE(fullPortName != nullptr && fullPortName[0] != '\0');
  1738. const jack_port_t* const jackPort(jackbridge_port_by_name(fClient, fullPortName));
  1739. CARLA_SAFE_ASSERT_CONTINUE(jackPort != nullptr);
  1740. const PortNameToId& thisPort(fUsedPorts.getPortNameToId(fullPortName));
  1741. CARLA_SAFE_ASSERT_CONTINUE(thisPort.group > 0);
  1742. CARLA_SAFE_ASSERT_CONTINUE(thisPort.port > 0);
  1743. if (const char** const connections = jackbridge_port_get_all_connections(fClient, jackPort))
  1744. {
  1745. for (int j=0; connections[j] != nullptr; ++j)
  1746. {
  1747. const char* const connection(connections[j]);
  1748. CARLA_SAFE_ASSERT_CONTINUE(connection != nullptr && connection[0] != '\0');
  1749. const PortNameToId& targetPort(fUsedPorts.getPortNameToId(connection));
  1750. CARLA_SAFE_ASSERT_CONTINUE(targetPort.group > 0);
  1751. CARLA_SAFE_ASSERT_CONTINUE(targetPort.port > 0);
  1752. std::snprintf(strBuf, STR_MAX, "%i:%i:%i:%i", thisPort.group, thisPort.port, targetPort.group, targetPort.port);
  1753. strBuf[STR_MAX] = '\0';
  1754. ConnectionToId connectionToId;
  1755. connectionToId.setData(++fUsedConnections.lastId, thisPort.group, thisPort.port, targetPort.group, targetPort.port);
  1756. callback(ENGINE_CALLBACK_PATCHBAY_CONNECTION_ADDED, connectionToId.id, 0, 0, 0.0f, strBuf);
  1757. fUsedConnections.list.append(connectionToId);
  1758. }
  1759. jackbridge_free(connections);
  1760. }
  1761. }
  1762. jackbridge_free(ports);
  1763. }
  1764. }
  1765. void addPatchbayJackPort(const uint groupId, const jack_port_t* const jackPort, const char* const shortPortName, const char* const fullPortName, const int jackPortFlags)
  1766. {
  1767. bool portIsInput = (jackPortFlags & JackPortIsInput);
  1768. bool portIsAudio = (std::strcmp(jackbridge_port_type(jackPort), JACK_DEFAULT_AUDIO_TYPE) == 0);
  1769. bool portIsMIDI = (std::strcmp(jackbridge_port_type(jackPort), JACK_DEFAULT_MIDI_TYPE) == 0);
  1770. bool portIsCV = false;
  1771. bool portIsOSC = false;
  1772. if (const jack_uuid_t uuid = jackbridge_port_uuid(jackPort))
  1773. {
  1774. char* value = nullptr;
  1775. char* type = nullptr;
  1776. if (jackbridge_get_property(uuid, JACKEY_SIGNAL_TYPE, &value, &type)
  1777. && value != nullptr
  1778. && type != nullptr
  1779. && std::strcmp(type, "text/plain") == 0)
  1780. {
  1781. portIsCV = (std::strcmp(value, "CV") == 0);
  1782. portIsOSC = (std::strcmp(value, "OSC") == 0);
  1783. }
  1784. }
  1785. uint canvasPortFlags = 0x0;
  1786. canvasPortFlags |= portIsInput ? PATCHBAY_PORT_IS_INPUT : 0x0;
  1787. /**/ if (portIsCV)
  1788. canvasPortFlags |= PATCHBAY_PORT_TYPE_CV;
  1789. else if (portIsOSC)
  1790. canvasPortFlags |= PATCHBAY_PORT_TYPE_OSC;
  1791. else if (portIsAudio)
  1792. canvasPortFlags |= PATCHBAY_PORT_TYPE_AUDIO;
  1793. else if (portIsMIDI)
  1794. canvasPortFlags |= PATCHBAY_PORT_TYPE_MIDI;
  1795. PortNameToId portNameToId;
  1796. portNameToId.setData(groupId, ++fUsedPorts.lastId, shortPortName, fullPortName);
  1797. callback(ENGINE_CALLBACK_PATCHBAY_PORT_ADDED, portNameToId.group, static_cast<int>(portNameToId.port), static_cast<int>(canvasPortFlags), 0.0f, portNameToId.name);
  1798. fUsedPorts.list.append(portNameToId);
  1799. }
  1800. #endif
  1801. // -------------------------------------------------------------------
  1802. void processPlugin(CarlaPlugin* const plugin, const uint32_t nframes)
  1803. {
  1804. const uint32_t audioInCount(plugin->getAudioInCount());
  1805. const uint32_t audioOutCount(plugin->getAudioOutCount());
  1806. const uint32_t cvInCount(plugin->getCVInCount());
  1807. const uint32_t cvOutCount(plugin->getCVOutCount());
  1808. const float* audioIn[audioInCount];
  1809. /* */ float* audioOut[audioOutCount];
  1810. const float* cvIn[cvInCount];
  1811. /* */ float* cvOut[cvOutCount];
  1812. for (uint32_t i=0; i < audioInCount; ++i)
  1813. {
  1814. CarlaEngineAudioPort* const port(plugin->getAudioInPort(i));
  1815. audioIn[i] = port->getBuffer();
  1816. }
  1817. for (uint32_t i=0; i < audioOutCount; ++i)
  1818. {
  1819. CarlaEngineAudioPort* const port(plugin->getAudioOutPort(i));
  1820. audioOut[i] = port->getBuffer();
  1821. }
  1822. for (uint32_t i=0; i < cvInCount; ++i)
  1823. {
  1824. CarlaEngineCVPort* const port(plugin->getCVInPort(i));
  1825. cvIn[i] = port->getBuffer();
  1826. }
  1827. for (uint32_t i=0; i < cvOutCount; ++i)
  1828. {
  1829. CarlaEngineCVPort* const port(plugin->getCVOutPort(i));
  1830. cvOut[i] = port->getBuffer();
  1831. }
  1832. float inPeaks[2] = { 0.0f };
  1833. float outPeaks[2] = { 0.0f };
  1834. for (uint32_t i=0; i < audioInCount && i < 2; ++i)
  1835. {
  1836. for (uint32_t j=0; j < nframes; ++j)
  1837. {
  1838. const float absV(std::abs(audioIn[i][j]));
  1839. if (absV > inPeaks[i])
  1840. inPeaks[i] = absV;
  1841. }
  1842. }
  1843. plugin->process(audioIn, audioOut, cvIn, cvOut, nframes);
  1844. for (uint32_t i=0; i < audioOutCount && i < 2; ++i)
  1845. {
  1846. for (uint32_t j=0; j < nframes; ++j)
  1847. {
  1848. const float absV(std::abs(audioOut[i][j]));
  1849. if (absV > outPeaks[i])
  1850. outPeaks[i] = absV;
  1851. }
  1852. }
  1853. setPluginPeaks(plugin->getId(), inPeaks, outPeaks);
  1854. }
  1855. #ifndef BUILD_BRIDGE
  1856. // -------------------------------------------------------------------
  1857. struct PostPonedJackEvent {
  1858. enum Type {
  1859. kTypeNull = 0,
  1860. kTypeClientRegister,
  1861. kTypePortRegister,
  1862. kTypePortConnect,
  1863. kTypePortRename
  1864. };
  1865. Type type;
  1866. bool action; // register or connect
  1867. jack_port_id_t port1;
  1868. jack_port_id_t port2;
  1869. char name1[STR_MAX+1];
  1870. char name2[STR_MAX+1];
  1871. };
  1872. LinkedList<PostPonedJackEvent> fPostPonedEvents;
  1873. CarlaMutex fPostPonedEventsMutex;
  1874. void postPoneJackCallback(const PostPonedJackEvent& ev)
  1875. {
  1876. const CarlaMutexLocker cml(fPostPonedEventsMutex);
  1877. fPostPonedEvents.append(ev);
  1878. }
  1879. void run() override
  1880. {
  1881. LinkedList<PostPonedJackEvent> events;
  1882. LinkedList<uint> newPlugins;
  1883. PostPonedJackEvent nullEvent;
  1884. carla_zeroStruct(nullEvent);
  1885. for (; ! shouldThreadExit();)
  1886. {
  1887. {
  1888. const CarlaMutexLocker cml(fPostPonedEventsMutex);
  1889. if (fPostPonedEvents.count() > 0)
  1890. fPostPonedEvents.moveTo(events);
  1891. if (fNewGroups.count() > 0)
  1892. fNewGroups.moveTo(newPlugins);
  1893. }
  1894. if (fClient == nullptr)
  1895. break;
  1896. if (events.count() == 0 && newPlugins.count() == 0)
  1897. {
  1898. carla_msleep(200);
  1899. continue;
  1900. }
  1901. for (LinkedList<PostPonedJackEvent>::Itenerator it = events.begin2(); it.valid(); it.next())
  1902. {
  1903. const PostPonedJackEvent& ev(it.getValue(nullEvent));
  1904. CARLA_SAFE_ASSERT_CONTINUE(ev.type != PostPonedJackEvent::kTypeNull);
  1905. switch (ev.type)
  1906. {
  1907. case PostPonedJackEvent::kTypeNull:
  1908. break;
  1909. case PostPonedJackEvent::kTypeClientRegister:
  1910. handleJackClientRegistrationCallback(ev.name1, ev.action);
  1911. break;
  1912. case PostPonedJackEvent::kTypePortRegister:
  1913. handleJackPortRegistrationCallback(ev.port1, ev.action);
  1914. break;
  1915. case PostPonedJackEvent::kTypePortConnect:
  1916. handleJackPortConnectCallback(ev.port1, ev.port2, ev.action);
  1917. break;
  1918. case PostPonedJackEvent::kTypePortRename:
  1919. handleJackPortRenameCallback(ev.port1, ev.name1, ev.name2);
  1920. break;
  1921. }
  1922. }
  1923. for (LinkedList<uint>::Itenerator it = newPlugins.begin2(); it.valid(); it.next())
  1924. {
  1925. const uint groupId(it.getValue(0));
  1926. CARLA_SAFE_ASSERT_CONTINUE(groupId > 0);
  1927. const char* const groupName(fUsedGroups.getGroupName(groupId));
  1928. CARLA_SAFE_ASSERT_CONTINUE(groupName != nullptr && groupName[0] != '\0');
  1929. int pluginId = -1;
  1930. PatchbayIcon icon = PATCHBAY_ICON_PLUGIN;
  1931. if (findPluginIdAndIcon(groupName, pluginId, icon))
  1932. callback(ENGINE_CALLBACK_PATCHBAY_CLIENT_DATA_CHANGED, groupId, icon, pluginId, 0.0f, nullptr);
  1933. }
  1934. events.clear();
  1935. newPlugins.clear();
  1936. }
  1937. events.clear();
  1938. newPlugins.clear();
  1939. }
  1940. #endif // BUILD_BRIDGE
  1941. // -------------------------------------------------------------------
  1942. // disable -Wattributes warnings
  1943. #if defined(__clang__)
  1944. # pragma clang diagnostic push
  1945. # pragma clang diagnostic ignored "-Wattributes"
  1946. #elif defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6))
  1947. # pragma GCC diagnostic push
  1948. # pragma GCC diagnostic ignored "-Wattributes"
  1949. #endif
  1950. #define handlePtr ((CarlaEngineJack*)arg)
  1951. static void JACKBRIDGE_API carla_jack_thread_init_callback(void*)
  1952. {
  1953. #ifdef __SSE2_MATH__
  1954. // Set FTZ and DAZ flags
  1955. _mm_setcsr(_mm_getcsr() | 0x8040);
  1956. #endif
  1957. }
  1958. static int JACKBRIDGE_API carla_jack_bufsize_callback(jack_nframes_t newBufferSize, void* arg)
  1959. {
  1960. handlePtr->handleJackBufferSizeCallback(newBufferSize);
  1961. return 0;
  1962. }
  1963. static int JACKBRIDGE_API carla_jack_srate_callback(jack_nframes_t newSampleRate, void* arg)
  1964. {
  1965. handlePtr->handleJackSampleRateCallback(newSampleRate);
  1966. return 0;
  1967. }
  1968. static void JACKBRIDGE_API carla_jack_freewheel_callback(int starting, void* arg)
  1969. {
  1970. handlePtr->handleJackFreewheelCallback(bool(starting));
  1971. }
  1972. static int JACKBRIDGE_API carla_jack_process_callback(jack_nframes_t nframes, void* arg) __attribute__((annotate("realtime")))
  1973. {
  1974. handlePtr->handleJackProcessCallback(nframes);
  1975. return 0;
  1976. }
  1977. static void JACKBRIDGE_API carla_jack_latency_callback(jack_latency_callback_mode_t mode, void* arg)
  1978. {
  1979. handlePtr->handleJackLatencyCallback(mode);
  1980. }
  1981. #ifndef BUILD_BRIDGE
  1982. 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")))
  1983. {
  1984. handlePtr->handleJackTimebaseCallback(nframes, pos, new_pos);
  1985. }
  1986. static void JACKBRIDGE_API carla_jack_client_registration_callback(const char* name, int reg, void* arg)
  1987. {
  1988. PostPonedJackEvent ev;
  1989. carla_zeroStruct(ev);
  1990. ev.type = PostPonedJackEvent::kTypeClientRegister;
  1991. ev.action = (reg != 0);
  1992. std::strncpy(ev.name1, name, STR_MAX);
  1993. handlePtr->postPoneJackCallback(ev);
  1994. }
  1995. static void JACKBRIDGE_API carla_jack_port_registration_callback(jack_port_id_t port, int reg, void* arg)
  1996. {
  1997. PostPonedJackEvent ev;
  1998. carla_zeroStruct(ev);
  1999. ev.type = PostPonedJackEvent::kTypePortRegister;
  2000. ev.action = (reg != 0);
  2001. ev.port1 = port;
  2002. handlePtr->postPoneJackCallback(ev);
  2003. }
  2004. static void JACKBRIDGE_API carla_jack_port_connect_callback(jack_port_id_t a, jack_port_id_t b, int connect, void* arg)
  2005. {
  2006. PostPonedJackEvent ev;
  2007. carla_zeroStruct(ev);
  2008. ev.type = PostPonedJackEvent::kTypePortConnect;
  2009. ev.action = (connect != 0);
  2010. ev.port1 = a;
  2011. ev.port2 = b;
  2012. handlePtr->postPoneJackCallback(ev);
  2013. }
  2014. static void JACKBRIDGE_API carla_jack_port_rename_callback(jack_port_id_t port, const char* oldName, const char* newName, void* arg)
  2015. {
  2016. PostPonedJackEvent ev;
  2017. carla_zeroStruct(ev);
  2018. ev.type = PostPonedJackEvent::kTypePortRename;
  2019. ev.port1 = port;
  2020. std::strncpy(ev.name1, oldName, STR_MAX);
  2021. std::strncpy(ev.name2, newName, STR_MAX);
  2022. handlePtr->postPoneJackCallback(ev);
  2023. }
  2024. #endif
  2025. static void JACKBRIDGE_API carla_jack_shutdown_callback(void* arg)
  2026. {
  2027. handlePtr->handleJackShutdownCallback();
  2028. }
  2029. #undef handlePtr
  2030. // -------------------------------------------------------------------
  2031. #ifndef BUILD_BRIDGE
  2032. static int JACKBRIDGE_API carla_jack_process_callback_plugin(jack_nframes_t nframes, void* arg) __attribute__((annotate("realtime")))
  2033. {
  2034. CarlaPlugin* const plugin((CarlaPlugin*)arg);
  2035. CARLA_SAFE_ASSERT_RETURN(plugin != nullptr && plugin->isEnabled(), 0);
  2036. CarlaEngineJack* const engine((CarlaEngineJack*)plugin->getEngine());
  2037. CARLA_SAFE_ASSERT_RETURN(engine != nullptr, 0);
  2038. if (plugin->tryLock(engine->fFreewheel))
  2039. {
  2040. plugin->initBuffers();
  2041. engine->saveTransportInfo();
  2042. engine->processPlugin(plugin, nframes);
  2043. plugin->unlock();
  2044. }
  2045. return 0;
  2046. }
  2047. static void JACKBRIDGE_API carla_jack_latency_callback_plugin(jack_latency_callback_mode_t /*mode*/, void* /*arg*/)
  2048. {
  2049. // TODO
  2050. }
  2051. static void JACKBRIDGE_API carla_jack_shutdown_callback_plugin(void* arg)
  2052. {
  2053. CarlaPlugin* const plugin((CarlaPlugin*)arg);
  2054. CARLA_SAFE_ASSERT_RETURN(plugin != nullptr,);
  2055. CarlaEngineJack* const engine((CarlaEngineJack*)plugin->getEngine());
  2056. CARLA_SAFE_ASSERT_RETURN(engine != nullptr,);
  2057. engine->handlePluginJackShutdownCallback(plugin);
  2058. }
  2059. #endif
  2060. // enable -Wattributes again
  2061. #if defined(__clang__)
  2062. # pragma clang diagnostic pop
  2063. #elif defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6))
  2064. # pragma GCC diagnostic pop
  2065. #endif
  2066. CARLA_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(CarlaEngineJack)
  2067. };
  2068. // -----------------------------------------------------------------------
  2069. CarlaEngine* CarlaEngine::newJack()
  2070. {
  2071. carla_debug("CarlaEngine::newJack()");
  2072. return new CarlaEngineJack();
  2073. }
  2074. // -----------------------------------------------------------------------
  2075. CARLA_BACKEND_END_NAMESPACE