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

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