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

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