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.

CarlaPluginJack.cpp 70KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067
  1. /*
  2. * Carla Plugin JACK
  3. * Copyright (C) 2016-2020 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 "CarlaPluginInternal.hpp"
  18. #include "CarlaEngine.hpp"
  19. #ifdef CARLA_OS_LINUX
  20. #include "CarlaLibJackHints.h"
  21. #include "CarlaBackendUtils.hpp"
  22. #include "CarlaBridgeUtils.hpp"
  23. #include "CarlaEngineUtils.hpp"
  24. #include "CarlaMathUtils.hpp"
  25. #include "CarlaPipeUtils.hpp"
  26. #include "CarlaScopeUtils.hpp"
  27. #include "CarlaShmUtils.hpp"
  28. #include "CarlaThread.hpp"
  29. #ifdef HAVE_LIBLO
  30. # include "CarlaOscUtils.hpp"
  31. #else
  32. # warning No liblo support, NSM (session state) will not be available
  33. #endif
  34. #include "water/files/File.h"
  35. #include "water/misc/Time.h"
  36. #include "water/text/StringArray.h"
  37. #include "water/threads/ChildProcess.h"
  38. #include "jackbridge/JackBridge.hpp"
  39. #include <ctime>
  40. #include <vector>
  41. // -------------------------------------------------------------------------------------------------------------------
  42. using water::ChildProcess;
  43. using water::File;
  44. using water::String;
  45. using water::StringArray;
  46. using water::Time;
  47. CARLA_BACKEND_START_NAMESPACE
  48. static size_t safe_rand(const size_t limit)
  49. {
  50. const int r = std::rand();
  51. CARLA_SAFE_ASSERT_RETURN(r >= 0, 0);
  52. return static_cast<uint>(r) % limit;
  53. }
  54. // -------------------------------------------------------------------------------------------------------------------
  55. // Fallback data
  56. static const ExternalMidiNote kExternalMidiNoteFallback = { -1, 0, 0 };
  57. // -------------------------------------------------------------------------------------------------------------------
  58. struct Announcer {
  59. virtual ~Announcer() {}
  60. virtual void nsmAnnounced(bool hasGui) = 0;
  61. };
  62. class CarlaPluginJackThread : public CarlaThread
  63. {
  64. public:
  65. CarlaPluginJackThread(Announcer* const ann, CarlaEngine* const engine, CarlaPlugin* const plugin) noexcept
  66. : CarlaThread("CarlaPluginJackThread"),
  67. kAnnouncer(ann),
  68. kEngine(engine),
  69. kPlugin(plugin),
  70. fShmIds(),
  71. fSetupLabel(),
  72. #ifdef HAVE_LIBLO
  73. fOscClientAddress(nullptr),
  74. fOscServer(nullptr),
  75. fHasOptionalGui(false),
  76. fProject(),
  77. #endif
  78. fProcess() {}
  79. void setData(const char* const shmIds, const char* const setupLabel) noexcept
  80. {
  81. CARLA_SAFE_ASSERT_RETURN(shmIds != nullptr && shmIds[0] != '\0',);
  82. CARLA_SAFE_ASSERT_RETURN(setupLabel != nullptr && setupLabel[0] != '\0',);
  83. CARLA_SAFE_ASSERT(! isThreadRunning());
  84. fShmIds = shmIds;
  85. fSetupLabel = setupLabel;
  86. }
  87. uintptr_t getProcessID() const noexcept
  88. {
  89. CARLA_SAFE_ASSERT_RETURN(fProcess != nullptr, 0);
  90. return (uintptr_t)fProcess->getPID();
  91. }
  92. #ifdef HAVE_LIBLO
  93. void nsmSave(const char* const setupLabel)
  94. {
  95. if (fOscClientAddress == nullptr)
  96. return;
  97. if (fSetupLabel != setupLabel)
  98. fSetupLabel = setupLabel;
  99. maybeOpenFirstTime(false);
  100. lo_send_from(fOscClientAddress, fOscServer, LO_TT_IMMEDIATE, "/nsm/client/save", "");
  101. }
  102. bool nsmShowGui(const bool yesNo)
  103. {
  104. if (fOscClientAddress == nullptr || ! fHasOptionalGui)
  105. return false;
  106. lo_send_from(fOscClientAddress, fOscServer, LO_TT_IMMEDIATE,
  107. yesNo ? "/nsm/client/show_optional_gui"
  108. : "/nsm/client/hide_optional_gui", "");
  109. return true;
  110. }
  111. #endif
  112. char* getEnvVarsToExport()
  113. {
  114. const EngineOptions& options(kEngine->getOptions());
  115. CarlaString binaryDir(options.binaryDir);
  116. #ifdef HAVE_LIBLO
  117. const int sessionManager = fSetupLabel[4] - '0';
  118. #endif
  119. CarlaString ret;
  120. ret += "export LD_LIBRARY_PATH=" + binaryDir + "/jack\n";
  121. ret += "export LD_PRELOAD=" + binaryDir + "/libcarla_interposer-jack-x11.so\n";
  122. #ifdef HAVE_LIBLO
  123. if (sessionManager == LIBJACK_SESSION_MANAGER_NSM)
  124. {
  125. for (int i=50; fOscServer == nullptr && --i>=0;)
  126. carla_msleep(100);
  127. ret += "export NSM_URL=";
  128. ret += lo_server_get_url(fOscServer);
  129. ret += "\n";
  130. }
  131. #endif
  132. if (kPlugin->getHints() & PLUGIN_HAS_CUSTOM_UI)
  133. ret += "export CARLA_FRONTEND_WIN_ID=" + CarlaString(options.frontendWinId) + "\n";
  134. ret += "export CARLA_LIBJACK_SETUP=" + fSetupLabel + "\n";
  135. ret += "export CARLA_SHM_IDS=" + fShmIds + "\n";
  136. return ret.releaseBufferPointer();
  137. }
  138. protected:
  139. #ifdef HAVE_LIBLO
  140. static void _osc_error_handler(int num, const char* msg, const char* path)
  141. {
  142. carla_stderr2("CarlaPluginJackThread::_osc_error_handler(%i, \"%s\", \"%s\")", num, msg, path);
  143. }
  144. static int _broadcast_handler(const char* path, const char* types, lo_arg** argv, int argc, lo_message msg, void* data)
  145. {
  146. CARLA_SAFE_ASSERT_RETURN(data != nullptr, 0);
  147. carla_stdout("CarlaPluginJackThread::_broadcast_handler(%s, %s, %p, %i)", path, types, argv, argc);
  148. return ((CarlaPluginJackThread*)data)->handleBroadcast(path, types, argv, msg);
  149. }
  150. void maybeOpenFirstTime(const bool announced)
  151. {
  152. if (fSetupLabel.length() <= 6)
  153. return;
  154. if ((announced || fProject.path.isEmpty()) && fProject.init(kPlugin->getName(),
  155. kEngine->getCurrentProjectFolder(),
  156. &fSetupLabel[6]))
  157. {
  158. carla_stdout("Sending open signal %s %s %s",
  159. fProject.path.buffer(), fProject.display.buffer(), fProject.clientName.buffer());
  160. lo_send_from(fOscClientAddress, fOscServer, LO_TT_IMMEDIATE, "/nsm/client/open", "sss",
  161. fProject.path.buffer(), fProject.display.buffer(), fProject.clientName.buffer());
  162. }
  163. }
  164. int handleBroadcast(const char* path, const char* types, lo_arg** argv, lo_message msg)
  165. {
  166. if (std::strcmp(path, "/nsm/server/announce") == 0)
  167. {
  168. CARLA_SAFE_ASSERT_RETURN(std::strcmp(types, "sssiii") == 0, 0);
  169. const lo_address msgAddress(lo_message_get_source(msg));
  170. CARLA_SAFE_ASSERT_RETURN(msgAddress != nullptr, 0);
  171. char* const msgURL(lo_address_get_url(msgAddress));
  172. CARLA_SAFE_ASSERT_RETURN(msgURL != nullptr, 0);
  173. if (fOscClientAddress != nullptr)
  174. lo_address_free(fOscClientAddress);
  175. fOscClientAddress = lo_address_new_from_url(msgURL);
  176. CARLA_SAFE_ASSERT_RETURN(fOscClientAddress != nullptr, 0);
  177. fProject.appName = &argv[0]->s;
  178. fHasOptionalGui = std::strstr(&argv[1]->s, ":optional-gui:") != nullptr;
  179. kAnnouncer->nsmAnnounced(fHasOptionalGui);
  180. static const char* const featuresG = ":server-control:optional-gui:";
  181. static const char* const featuresN = ":server-control:";
  182. static const char* const method = "/nsm/server/announce";
  183. static const char* const message = "Howdy, what took you so long?";
  184. static const char* const smName = "Carla";
  185. const char* const features = ((fSetupLabel[5] - '0') & LIBJACK_FLAG_CONTROL_WINDOW)
  186. ? featuresG : featuresN;
  187. lo_send_from(fOscClientAddress, fOscServer, LO_TT_IMMEDIATE, "/reply", "ssss",
  188. method, message, smName, features);
  189. maybeOpenFirstTime(true);
  190. return 0;
  191. }
  192. CARLA_SAFE_ASSERT_RETURN(fOscClientAddress != nullptr, 0);
  193. if (std::strcmp(path, "/reply") == 0)
  194. {
  195. CARLA_SAFE_ASSERT_RETURN(std::strcmp(types, "ss") == 0, 0);
  196. const char* const method = &argv[0]->s;
  197. const char* const message = &argv[1]->s;
  198. carla_stdout("Got reply of '%s' as '%s'", method, message);
  199. if (std::strcmp(method, "/nsm/client/open") == 0)
  200. {
  201. carla_stdout("Sending 'Session is loaded' to %s", fProject.appName.buffer());
  202. lo_send_from(fOscClientAddress, fOscServer, LO_TT_IMMEDIATE, "/nsm/client/session_is_loaded", "");
  203. }
  204. }
  205. else if (std::strcmp(path, "/nsm/client/gui_is_shown") == 0)
  206. {
  207. CARLA_SAFE_ASSERT_RETURN(std::strcmp(types, "") == 0, 0);
  208. kEngine->callback(true, true,
  209. ENGINE_CALLBACK_UI_STATE_CHANGED,
  210. kPlugin->getId(),
  211. 1,
  212. 0, 0, 0.0f, nullptr);
  213. }
  214. else if (std::strcmp(path, "/nsm/client/gui_is_hidden") == 0)
  215. {
  216. CARLA_SAFE_ASSERT_RETURN(std::strcmp(types, "") == 0, 0);
  217. kEngine->callback(true, true,
  218. ENGINE_CALLBACK_UI_STATE_CHANGED,
  219. kPlugin->getId(),
  220. 0,
  221. 0, 0, 0.0f, nullptr);
  222. }
  223. // special messages
  224. else if (std::strcmp(path, "/nsm/gui/client/save") == 0)
  225. {
  226. CARLA_SAFE_ASSERT_RETURN(std::strcmp(types, "s") == 0, 0);
  227. lo_send_from(fOscClientAddress, fOscServer, LO_TT_IMMEDIATE, "/nsm/client/save", "");
  228. }
  229. else if (std::strcmp(path, "/nsm/server/stop") == 0)
  230. {
  231. CARLA_SAFE_ASSERT_RETURN(std::strcmp(types, "s") == 0, 0);
  232. lo_send_from(fOscClientAddress, fOscServer, LO_TT_IMMEDIATE, "/nsm/client/hide_optional_gui", "");
  233. kEngine->callback(true, true,
  234. ENGINE_CALLBACK_UI_STATE_CHANGED,
  235. kPlugin->getId(),
  236. 0,
  237. 0, 0, 0.0f, nullptr);
  238. }
  239. return 0;
  240. }
  241. #endif
  242. void run()
  243. {
  244. #ifdef HAVE_LIBLO
  245. if (fOscClientAddress != nullptr)
  246. {
  247. lo_address_free(fOscClientAddress);
  248. fOscClientAddress = nullptr;
  249. }
  250. const int sessionManager = fSetupLabel[4] - '0';
  251. if (sessionManager == LIBJACK_SESSION_MANAGER_NSM)
  252. {
  253. // NSM support
  254. fOscServer = lo_server_new_with_proto(nullptr, LO_UDP, _osc_error_handler);
  255. CARLA_SAFE_ASSERT_RETURN(fOscServer != nullptr,);
  256. lo_server_add_method(fOscServer, nullptr, nullptr, _broadcast_handler, this);
  257. }
  258. #endif
  259. const bool externalProcess = ((fSetupLabel[5] - '0') & LIBJACK_FLAG_EXTERNAL_START)
  260. && ! kEngine->isLoadingProject();
  261. if (! externalProcess)
  262. {
  263. if (fProcess == nullptr)
  264. {
  265. fProcess = new ChildProcess();
  266. }
  267. else if (fProcess->isRunning())
  268. {
  269. carla_stderr("CarlaPluginJackThread::run() - already running");
  270. }
  271. String name(kPlugin->getName());
  272. String filename(kPlugin->getFilename());
  273. if (name.isEmpty())
  274. name = "(none)";
  275. CARLA_SAFE_ASSERT_RETURN(filename.isNotEmpty(),);
  276. StringArray arguments;
  277. // binary
  278. arguments.addTokens(filename, true);
  279. const EngineOptions& options(kEngine->getOptions());
  280. char winIdStr[STR_MAX+1];
  281. std::snprintf(winIdStr, STR_MAX, P_UINTPTR, options.frontendWinId);
  282. winIdStr[STR_MAX] = '\0';
  283. const CarlaString libjackdir(CarlaString(options.binaryDir) + "/jack");
  284. const CarlaString ldpreload(CarlaString(options.binaryDir) + "/libcarla_interposer-jack-x11.so");
  285. const ScopedEngineEnvironmentLocker _seel(kEngine);
  286. const CarlaScopedEnvVar sev2("LD_LIBRARY_PATH", libjackdir.buffer());
  287. const CarlaScopedEnvVar sev1("LD_PRELOAD", ldpreload.isNotEmpty() ? ldpreload.buffer() : nullptr);
  288. #ifdef HAVE_LIBLO
  289. const CarlaScopedEnvVar sev3("NSM_URL", lo_server_get_url(fOscServer));
  290. #endif
  291. if (kPlugin->getHints() & PLUGIN_HAS_CUSTOM_UI)
  292. carla_setenv("CARLA_FRONTEND_WIN_ID", winIdStr);
  293. else
  294. carla_unsetenv("CARLA_FRONTEND_WIN_ID");
  295. carla_setenv("CARLA_LIBJACK_SETUP", fSetupLabel.buffer());
  296. carla_setenv("CARLA_SHM_IDS", fShmIds.buffer());
  297. if (! fProcess->start(arguments))
  298. {
  299. carla_stdout("failed!");
  300. fProcess = nullptr;
  301. return;
  302. }
  303. }
  304. for (; (externalProcess || fProcess->isRunning()) && ! shouldThreadExit();)
  305. {
  306. #ifdef HAVE_LIBLO
  307. if (sessionManager == LIBJACK_SESSION_MANAGER_NSM)
  308. {
  309. lo_server_recv_noblock(fOscServer, 50);
  310. }
  311. else
  312. #endif
  313. {
  314. carla_msleep(50);
  315. }
  316. }
  317. #ifdef HAVE_LIBLO
  318. if (sessionManager == LIBJACK_SESSION_MANAGER_NSM)
  319. {
  320. lo_server_free(fOscServer);
  321. fOscServer = nullptr;
  322. if (fOscClientAddress != nullptr)
  323. {
  324. lo_address_free(fOscClientAddress);
  325. fOscClientAddress = nullptr;
  326. }
  327. }
  328. #endif
  329. if (! externalProcess)
  330. {
  331. // we only get here if bridge crashed or thread asked to exit
  332. if (fProcess->isRunning() && shouldThreadExit())
  333. {
  334. fProcess->waitForProcessToFinish(2000);
  335. if (fProcess->isRunning())
  336. {
  337. carla_stdout("CarlaPluginJackThread::run() - application refused to close, force kill now");
  338. fProcess->kill();
  339. }
  340. }
  341. else
  342. {
  343. // forced quit, may have crashed
  344. if (fProcess->getExitCode() != 0 /*|| fProcess->exitStatus() == QProcess::CrashExit*/)
  345. {
  346. carla_stderr("CarlaPluginJackThread::run() - application crashed");
  347. CarlaString errorString("Plugin '" + CarlaString(kPlugin->getName()) + "' has crashed!\n"
  348. "Saving now will lose its current settings.\n"
  349. "Please remove this plugin, and not rely on it from this point.");
  350. kEngine->callback(true, true,
  351. ENGINE_CALLBACK_ERROR,
  352. kPlugin->getId(),
  353. 0, 0, 0, 0.0f,
  354. errorString);
  355. }
  356. }
  357. }
  358. fProcess = nullptr;
  359. }
  360. private:
  361. Announcer* const kAnnouncer;
  362. CarlaEngine* const kEngine;
  363. CarlaPlugin* const kPlugin;
  364. CarlaString fShmIds;
  365. CarlaString fSetupLabel;
  366. #ifdef HAVE_LIBLO
  367. lo_address fOscClientAddress;
  368. lo_server fOscServer;
  369. bool fHasOptionalGui;
  370. struct ProjectData {
  371. CarlaString appName;
  372. CarlaString path;
  373. CarlaString display;
  374. CarlaString clientName;
  375. ProjectData()
  376. : appName(),
  377. path(),
  378. display(),
  379. clientName() {}
  380. bool init(const char* const pluginName,
  381. const char* const engineProjectFolder,
  382. const char* const uniqueCodeID)
  383. {
  384. CARLA_SAFE_ASSERT_RETURN(engineProjectFolder != nullptr && engineProjectFolder[0] != '\0', false);
  385. CARLA_SAFE_ASSERT_RETURN(uniqueCodeID != nullptr && uniqueCodeID[0] != '\0', false);
  386. CARLA_SAFE_ASSERT_RETURN(appName.isNotEmpty(), false);
  387. String child(pluginName);
  388. child += ".";
  389. child += uniqueCodeID;
  390. const File file(File(engineProjectFolder).getChildFile(child));
  391. clientName = appName + "." + uniqueCodeID;
  392. path = file.getFullPathName().toRawUTF8();
  393. display = file.getFileNameWithoutExtension().toRawUTF8();
  394. return true;
  395. }
  396. CARLA_DECLARE_NON_COPY_STRUCT(ProjectData)
  397. } fProject;
  398. #endif
  399. CarlaScopedPointer<ChildProcess> fProcess;
  400. CARLA_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(CarlaPluginJackThread)
  401. };
  402. // -------------------------------------------------------------------------------------------------------------------
  403. class CarlaPluginJack : public CarlaPlugin,
  404. public Announcer
  405. {
  406. public:
  407. CarlaPluginJack(CarlaEngine* const engine, const uint id)
  408. : CarlaPlugin(engine, id),
  409. fInitiated(false),
  410. fInitError(false),
  411. fTimedOut(false),
  412. fTimedError(false),
  413. fProcCanceled(false),
  414. fBufferSize(engine->getBufferSize()),
  415. fProcWaitTime(0),
  416. fSetupHints(0x0),
  417. fBridgeThread(this, engine, this),
  418. fShmAudioPool(),
  419. fShmRtClientControl(),
  420. fShmNonRtClientControl(),
  421. fShmNonRtServerControl(),
  422. fInfo()
  423. {
  424. carla_debug("CarlaPluginJack::CarlaPluginJack(%p, %i)", engine, id);
  425. pData->hints |= PLUGIN_IS_BRIDGE;
  426. }
  427. ~CarlaPluginJack() override
  428. {
  429. carla_debug("CarlaPluginJack::~CarlaPluginJack()");
  430. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  431. // close UI
  432. if (pData->hints & PLUGIN_HAS_CUSTOM_UI)
  433. pData->transientTryCounter = 0;
  434. #endif
  435. pData->singleMutex.lock();
  436. pData->masterMutex.lock();
  437. if (pData->client != nullptr && pData->client->isActive())
  438. pData->client->deactivate(true);
  439. if (pData->active)
  440. {
  441. deactivate();
  442. pData->active = false;
  443. }
  444. if (fBridgeThread.isThreadRunning())
  445. {
  446. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientQuit);
  447. fShmRtClientControl.commitWrite();
  448. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientQuit);
  449. fShmNonRtClientControl.commitWrite();
  450. if (! fTimedOut)
  451. waitForClient("stopping", 3000);
  452. }
  453. fBridgeThread.stopThread(3000);
  454. fShmNonRtServerControl.clear();
  455. fShmNonRtClientControl.clear();
  456. fShmRtClientControl.clear();
  457. fShmAudioPool.clear();
  458. clearBuffers();
  459. fInfo.chunk.clear();
  460. }
  461. // -------------------------------------------------------------------
  462. void nsmAnnounced(bool hasGui) override
  463. {
  464. if (hasGui || (pData->hints & PLUGIN_HAS_CUSTOM_UI) == 0x0)
  465. return;
  466. {
  467. const CarlaMutexLocker _cml(fShmNonRtClientControl.mutex);
  468. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientShowUI);
  469. fShmNonRtClientControl.commitWrite();
  470. }
  471. pData->engine->callback(true, true,
  472. ENGINE_CALLBACK_UI_STATE_CHANGED,
  473. pData->id,
  474. 1,
  475. 0, 0, 0.0f, nullptr);
  476. }
  477. // -------------------------------------------------------------------
  478. // Information (base)
  479. PluginType getType() const noexcept override
  480. {
  481. return PLUGIN_JACK;
  482. }
  483. PluginCategory getCategory() const noexcept override
  484. {
  485. return PLUGIN_CATEGORY_NONE;
  486. }
  487. // -------------------------------------------------------------------
  488. // Information (count)
  489. uint32_t getMidiInCount() const noexcept override
  490. {
  491. return fInfo.mIns;
  492. }
  493. uint32_t getMidiOutCount() const noexcept override
  494. {
  495. return fInfo.mOuts;
  496. }
  497. // -------------------------------------------------------------------
  498. // Information (current data)
  499. // -------------------------------------------------------------------
  500. // Information (per-plugin data)
  501. uint getOptionsAvailable() const noexcept override
  502. {
  503. uint options = 0x0;
  504. if (fInfo.mIns > 0)
  505. {
  506. options |= PLUGIN_OPTION_SEND_CONTROL_CHANGES;
  507. options |= PLUGIN_OPTION_SEND_CHANNEL_PRESSURE;
  508. options |= PLUGIN_OPTION_SEND_NOTE_AFTERTOUCH;
  509. options |= PLUGIN_OPTION_SEND_PITCHBEND;
  510. options |= PLUGIN_OPTION_SEND_ALL_SOUND_OFF;
  511. options |= PLUGIN_OPTION_SEND_PROGRAM_CHANGES;
  512. }
  513. return options;
  514. }
  515. bool getLabel(char* const strBuf) const noexcept override
  516. {
  517. std::strncpy(strBuf, fInfo.setupLabel, STR_MAX);
  518. return true;
  519. }
  520. bool getMaker(char* const) const noexcept override
  521. {
  522. return false;
  523. }
  524. bool getCopyright(char* const) const noexcept override
  525. {
  526. return false;
  527. }
  528. bool getRealName(char* const strBuf) const noexcept override
  529. {
  530. // FIXME
  531. std::strncpy(strBuf, "Carla's libjack", STR_MAX);
  532. return true;
  533. }
  534. // -------------------------------------------------------------------
  535. // Set data (state)
  536. void prepareForSave() noexcept override
  537. {
  538. #ifdef HAVE_LIBLO
  539. if (fInfo.setupLabel.length() == 6)
  540. setupUniqueProjectID();
  541. #endif
  542. {
  543. const CarlaMutexLocker _cml(fShmNonRtClientControl.mutex);
  544. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientPrepareForSave);
  545. fShmNonRtClientControl.commitWrite();
  546. }
  547. #ifdef HAVE_LIBLO
  548. fBridgeThread.nsmSave(fInfo.setupLabel);
  549. #endif
  550. }
  551. // -------------------------------------------------------------------
  552. // Set data (internal stuff)
  553. void setOption(const uint option, const bool yesNo, const bool sendCallback) override
  554. {
  555. {
  556. const CarlaMutexLocker _cml(fShmNonRtClientControl.mutex);
  557. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientSetOption);
  558. fShmNonRtClientControl.writeUInt(option);
  559. fShmNonRtClientControl.writeBool(yesNo);
  560. fShmNonRtClientControl.commitWrite();
  561. }
  562. CarlaPlugin::setOption(option, yesNo, sendCallback);
  563. }
  564. void setCtrlChannel(const int8_t channel, const bool sendOsc, const bool sendCallback) noexcept override
  565. {
  566. CARLA_SAFE_ASSERT_RETURN(sendOsc || sendCallback,); // never call this from RT
  567. {
  568. const CarlaMutexLocker _cml(fShmNonRtClientControl.mutex);
  569. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientSetCtrlChannel);
  570. fShmNonRtClientControl.writeShort(channel);
  571. fShmNonRtClientControl.commitWrite();
  572. }
  573. CarlaPlugin::setCtrlChannel(channel, sendOsc, sendCallback);
  574. }
  575. // -------------------------------------------------------------------
  576. // Set data (plugin-specific stuff)
  577. void setCustomData(const char* const type, const char* const key, const char* const value, const bool sendGui) override
  578. {
  579. CARLA_SAFE_ASSERT_RETURN(type != nullptr && type[0] != '\0',);
  580. CARLA_SAFE_ASSERT_RETURN(key != nullptr && key[0] != '\0',);
  581. CARLA_SAFE_ASSERT_RETURN(value != nullptr,);
  582. if (std::strcmp(type, CUSTOM_DATA_TYPE_PROPERTY) == 0)
  583. return CarlaPlugin::setCustomData(type, key, value, sendGui);
  584. if (std::strcmp(type, CUSTOM_DATA_TYPE_STRING) == 0 && std::strcmp(key, "__CarlaPingOnOff__") == 0)
  585. {
  586. #if 0
  587. const CarlaMutexLocker _cml(fShmNonRtClientControl.mutex);
  588. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientPingOnOff);
  589. fShmNonRtClientControl.writeBool(std::strcmp(value, "true") == 0);
  590. fShmNonRtClientControl.commitWrite();
  591. #endif
  592. return;
  593. }
  594. CarlaPlugin::setCustomData(type, key, value, sendGui);
  595. }
  596. // -------------------------------------------------------------------
  597. // Set ui stuff
  598. void showCustomUI(const bool yesNo) override
  599. {
  600. if (yesNo && ! fBridgeThread.isThreadRunning()) {
  601. CARLA_SAFE_ASSERT_RETURN(restartBridgeThread(),);
  602. }
  603. #ifdef HAVE_LIBLO
  604. if (! fBridgeThread.nsmShowGui(yesNo))
  605. #endif
  606. {
  607. const CarlaMutexLocker _cml(fShmNonRtClientControl.mutex);
  608. fShmNonRtClientControl.writeOpcode(yesNo ? kPluginBridgeNonRtClientShowUI : kPluginBridgeNonRtClientHideUI);
  609. fShmNonRtClientControl.commitWrite();
  610. }
  611. }
  612. void idle() override
  613. {
  614. if (fBridgeThread.isThreadRunning())
  615. {
  616. if (fInitiated && fTimedOut && pData->active)
  617. setActive(false, true, true);
  618. {
  619. const CarlaMutexLocker _cml(fShmNonRtClientControl.mutex);
  620. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientPing);
  621. fShmNonRtClientControl.commitWrite();
  622. }
  623. try {
  624. handleNonRtData();
  625. } CARLA_SAFE_EXCEPTION("handleNonRtData");
  626. }
  627. else if (fInitiated)
  628. {
  629. fTimedOut = true;
  630. fTimedError = true;
  631. fInitiated = false;
  632. handleProcessStopped();
  633. }
  634. else if (fProcCanceled)
  635. {
  636. handleProcessStopped();
  637. fProcCanceled = false;
  638. }
  639. CarlaPlugin::idle();
  640. }
  641. // -------------------------------------------------------------------
  642. // Plugin state
  643. void reload() override
  644. {
  645. CARLA_SAFE_ASSERT_RETURN(pData->engine != nullptr,);
  646. carla_debug("CarlaPluginJack::reload() - start");
  647. const EngineProcessMode processMode(pData->engine->getProccessMode());
  648. // Safely disable plugin for reload
  649. const ScopedDisabler sd(this);
  650. // cleanup of previous data
  651. pData->audioIn.clear();
  652. pData->audioOut.clear();
  653. pData->event.clear();
  654. bool needsCtrlIn, needsCtrlOut;
  655. needsCtrlIn = needsCtrlOut = false;
  656. if (fInfo.aIns > 0)
  657. {
  658. pData->audioIn.createNew(fInfo.aIns);
  659. }
  660. if (fInfo.aOuts > 0)
  661. {
  662. pData->audioOut.createNew(fInfo.aOuts);
  663. needsCtrlIn = true;
  664. }
  665. if (fInfo.mIns > 0)
  666. needsCtrlIn = true;
  667. if (fInfo.mOuts > 0)
  668. needsCtrlOut = true;
  669. const uint portNameSize(pData->engine->getMaxPortNameSize());
  670. CarlaString portName;
  671. // Audio Ins
  672. for (uint8_t j=0; j < fInfo.aIns; ++j)
  673. {
  674. portName.clear();
  675. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  676. {
  677. portName = pData->name;
  678. portName += ":";
  679. }
  680. if (fInfo.aIns > 1)
  681. {
  682. portName += "audio_in_";
  683. portName += CarlaString(j+1);
  684. }
  685. else
  686. {
  687. portName += "audio_in";
  688. }
  689. portName.truncate(portNameSize);
  690. pData->audioIn.ports[j].port = (CarlaEngineAudioPort*)pData->client->addPort(kEnginePortTypeAudio, portName, true, j);
  691. pData->audioIn.ports[j].rindex = j;
  692. }
  693. // Audio Outs
  694. for (uint8_t j=0; j < fInfo.aOuts; ++j)
  695. {
  696. portName.clear();
  697. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  698. {
  699. portName = pData->name;
  700. portName += ":";
  701. }
  702. if (fInfo.aOuts > 1)
  703. {
  704. portName += "audio_out_";
  705. portName += CarlaString(j+1);
  706. }
  707. else
  708. {
  709. portName += "audio_out";
  710. }
  711. portName.truncate(portNameSize);
  712. pData->audioOut.ports[j].port = (CarlaEngineAudioPort*)pData->client->addPort(kEnginePortTypeAudio, portName, false, j);
  713. pData->audioOut.ports[j].rindex = j;
  714. }
  715. if (needsCtrlIn)
  716. {
  717. portName.clear();
  718. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  719. {
  720. portName = pData->name;
  721. portName += ":";
  722. }
  723. portName += "event-in";
  724. portName.truncate(portNameSize);
  725. pData->event.portIn = (CarlaEngineEventPort*)pData->client->addPort(kEnginePortTypeEvent, portName, true, 0);
  726. }
  727. if (needsCtrlOut)
  728. {
  729. portName.clear();
  730. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  731. {
  732. portName = pData->name;
  733. portName += ":";
  734. }
  735. portName += "event-out";
  736. portName.truncate(portNameSize);
  737. pData->event.portOut = (CarlaEngineEventPort*)pData->client->addPort(kEnginePortTypeEvent, portName, false, 0);
  738. }
  739. // extra plugin hints
  740. pData->extraHints = 0x0;
  741. if (fInfo.mIns > 0)
  742. pData->extraHints |= PLUGIN_EXTRA_HINT_HAS_MIDI_IN;
  743. if (fInfo.mOuts > 0)
  744. pData->extraHints |= PLUGIN_EXTRA_HINT_HAS_MIDI_OUT;
  745. bufferSizeChanged(pData->engine->getBufferSize());
  746. reloadPrograms(true);
  747. carla_debug("CarlaPluginJack::reload() - end");
  748. }
  749. // -------------------------------------------------------------------
  750. // Plugin processing
  751. void activate() noexcept override
  752. {
  753. if (! fBridgeThread.isThreadRunning())
  754. {
  755. CARLA_SAFE_ASSERT_RETURN(restartBridgeThread(),);
  756. }
  757. CARLA_SAFE_ASSERT_RETURN(! fTimedError,);
  758. {
  759. const CarlaMutexLocker _cml(fShmNonRtClientControl.mutex);
  760. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientActivate);
  761. fShmNonRtClientControl.commitWrite();
  762. }
  763. fTimedOut = false;
  764. try {
  765. waitForClient("activate", 2000);
  766. } CARLA_SAFE_EXCEPTION("activate - waitForClient");
  767. }
  768. void deactivate() noexcept override
  769. {
  770. if (! fBridgeThread.isThreadRunning())
  771. return;
  772. CARLA_SAFE_ASSERT_RETURN(! fTimedError,);
  773. {
  774. const CarlaMutexLocker _cml(fShmNonRtClientControl.mutex);
  775. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientDeactivate);
  776. fShmNonRtClientControl.commitWrite();
  777. }
  778. fTimedOut = false;
  779. try {
  780. waitForClient("deactivate", 2000);
  781. } CARLA_SAFE_EXCEPTION("deactivate - waitForClient");
  782. }
  783. void process(const float* const* const audioIn, float** const audioOut,
  784. const float* const*, float**, const uint32_t frames) override
  785. {
  786. // --------------------------------------------------------------------------------------------------------
  787. // Check if active
  788. if (fProcCanceled || fTimedOut || fTimedError || ! pData->active)
  789. {
  790. // disable any output sound
  791. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  792. carla_zeroFloats(audioOut[i], frames);
  793. return;
  794. }
  795. // --------------------------------------------------------------------------------------------------------
  796. // Check if needs reset
  797. if (pData->needsReset)
  798. {
  799. // TODO
  800. pData->needsReset = false;
  801. }
  802. // --------------------------------------------------------------------------------------------------------
  803. // Event Input
  804. if (pData->event.portIn != nullptr)
  805. {
  806. // ----------------------------------------------------------------------------------------------------
  807. // MIDI Input (External)
  808. if (pData->extNotes.mutex.tryLock())
  809. {
  810. for (RtLinkedList<ExternalMidiNote>::Itenerator it = pData->extNotes.data.begin2(); it.valid(); it.next())
  811. {
  812. const ExternalMidiNote& note(it.getValue(kExternalMidiNoteFallback));
  813. CARLA_SAFE_ASSERT_CONTINUE(note.channel >= 0 && note.channel < MAX_MIDI_CHANNELS);
  814. uint8_t data1, data2, data3;
  815. data1 = uint8_t((note.velo > 0 ? MIDI_STATUS_NOTE_ON : MIDI_STATUS_NOTE_OFF) | (note.channel & MIDI_CHANNEL_BIT));
  816. data2 = note.note;
  817. data3 = note.velo;
  818. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientMidiEvent);
  819. fShmRtClientControl.writeUInt(0); // time
  820. fShmRtClientControl.writeByte(0); // port
  821. fShmRtClientControl.writeByte(3); // size
  822. fShmRtClientControl.writeByte(data1);
  823. fShmRtClientControl.writeByte(data2);
  824. fShmRtClientControl.writeByte(data3);
  825. fShmRtClientControl.commitWrite();
  826. }
  827. pData->extNotes.data.clear();
  828. pData->extNotes.mutex.unlock();
  829. } // End of MIDI Input (External)
  830. // ----------------------------------------------------------------------------------------------------
  831. // Event Input (System)
  832. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  833. bool allNotesOffSent = false;
  834. #endif
  835. for (uint32_t i=0, numEvents=pData->event.portIn->getEventCount(); i < numEvents; ++i)
  836. {
  837. const EngineEvent& event(pData->event.portIn->getEvent(i));
  838. // Control change
  839. switch (event.type)
  840. {
  841. case kEngineEventTypeNull:
  842. break;
  843. case kEngineEventTypeControl: {
  844. const EngineControlEvent& ctrlEvent = event.ctrl;
  845. switch (ctrlEvent.type)
  846. {
  847. case kEngineControlEventTypeNull:
  848. break;
  849. case kEngineControlEventTypeParameter:
  850. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  851. // Control backend stuff
  852. if (event.channel == pData->ctrlChannel)
  853. {
  854. float value;
  855. if (MIDI_IS_CONTROL_BREATH_CONTROLLER(ctrlEvent.param) && (pData->hints & PLUGIN_CAN_DRYWET) != 0)
  856. {
  857. value = ctrlEvent.value;
  858. setDryWetRT(value, true);
  859. }
  860. if (MIDI_IS_CONTROL_CHANNEL_VOLUME(ctrlEvent.param) && (pData->hints & PLUGIN_CAN_VOLUME) != 0)
  861. {
  862. value = ctrlEvent.value*127.0f/100.0f;
  863. setVolumeRT(value, true);
  864. }
  865. if (MIDI_IS_CONTROL_BALANCE(ctrlEvent.param) && (pData->hints & PLUGIN_CAN_BALANCE) != 0)
  866. {
  867. float left, right;
  868. value = ctrlEvent.value/0.5f - 1.0f;
  869. if (value < 0.0f)
  870. {
  871. left = -1.0f;
  872. right = (value*2.0f)+1.0f;
  873. }
  874. else if (value > 0.0f)
  875. {
  876. left = (value*2.0f)-1.0f;
  877. right = 1.0f;
  878. }
  879. else
  880. {
  881. left = -1.0f;
  882. right = 1.0f;
  883. }
  884. setBalanceLeftRT(left, true);
  885. setBalanceRightRT(right, true);
  886. }
  887. }
  888. #endif
  889. if ((pData->options & PLUGIN_OPTION_SEND_CONTROL_CHANGES) != 0 && ctrlEvent.param < MAX_MIDI_VALUE)
  890. {
  891. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientMidiEvent);
  892. fShmRtClientControl.writeUInt(event.time);
  893. fShmRtClientControl.writeByte(0); // port
  894. fShmRtClientControl.writeByte(3); // size
  895. fShmRtClientControl.writeByte(uint8_t(MIDI_STATUS_CONTROL_CHANGE | (event.channel & MIDI_CHANNEL_BIT)));
  896. fShmRtClientControl.writeByte(uint8_t(ctrlEvent.param));
  897. fShmRtClientControl.writeByte(uint8_t(ctrlEvent.value*127.0f));
  898. }
  899. break;
  900. case kEngineControlEventTypeMidiBank:
  901. if (pData->options & PLUGIN_OPTION_MAP_PROGRAM_CHANGES)
  902. {
  903. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientControlEventMidiBank);
  904. fShmRtClientControl.writeUInt(event.time);
  905. fShmRtClientControl.writeByte(event.channel);
  906. fShmRtClientControl.writeUShort(event.ctrl.param);
  907. fShmRtClientControl.commitWrite();
  908. }
  909. break;
  910. case kEngineControlEventTypeMidiProgram:
  911. if (pData->options & PLUGIN_OPTION_MAP_PROGRAM_CHANGES)
  912. {
  913. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientControlEventMidiProgram);
  914. fShmRtClientControl.writeUInt(event.time);
  915. fShmRtClientControl.writeByte(event.channel);
  916. fShmRtClientControl.writeUShort(event.ctrl.param);
  917. fShmRtClientControl.commitWrite();
  918. }
  919. break;
  920. case kEngineControlEventTypeAllSoundOff:
  921. if (pData->options & PLUGIN_OPTION_SEND_ALL_SOUND_OFF)
  922. {
  923. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientControlEventAllSoundOff);
  924. fShmRtClientControl.writeUInt(event.time);
  925. fShmRtClientControl.writeByte(event.channel);
  926. fShmRtClientControl.commitWrite();
  927. }
  928. break;
  929. case kEngineControlEventTypeAllNotesOff:
  930. if (pData->options & PLUGIN_OPTION_SEND_ALL_SOUND_OFF)
  931. {
  932. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  933. if (event.channel == pData->ctrlChannel && ! allNotesOffSent)
  934. {
  935. allNotesOffSent = true;
  936. postponeRtAllNotesOff();
  937. }
  938. #endif
  939. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientControlEventAllNotesOff);
  940. fShmRtClientControl.writeUInt(event.time);
  941. fShmRtClientControl.writeByte(event.channel);
  942. fShmRtClientControl.commitWrite();
  943. }
  944. break;
  945. } // switch (ctrlEvent.type)
  946. break;
  947. } // case kEngineEventTypeControl
  948. case kEngineEventTypeMidi: {
  949. const EngineMidiEvent& midiEvent(event.midi);
  950. if (midiEvent.size == 0 || midiEvent.size >= MAX_MIDI_VALUE)
  951. continue;
  952. const uint8_t* const midiData(midiEvent.size > EngineMidiEvent::kDataSize ? midiEvent.dataExt : midiEvent.data);
  953. uint8_t status = uint8_t(MIDI_GET_STATUS_FROM_DATA(midiData));
  954. if (status == MIDI_STATUS_CHANNEL_PRESSURE && (pData->options & PLUGIN_OPTION_SEND_CHANNEL_PRESSURE) == 0)
  955. continue;
  956. if (status == MIDI_STATUS_CONTROL_CHANGE && (pData->options & PLUGIN_OPTION_SEND_CONTROL_CHANGES) == 0)
  957. continue;
  958. if (status == MIDI_STATUS_POLYPHONIC_AFTERTOUCH && (pData->options & PLUGIN_OPTION_SEND_NOTE_AFTERTOUCH) == 0)
  959. continue;
  960. if (status == MIDI_STATUS_PITCH_WHEEL_CONTROL && (pData->options & PLUGIN_OPTION_SEND_PITCHBEND) == 0)
  961. continue;
  962. // Fix bad note-off
  963. if (status == MIDI_STATUS_NOTE_ON && midiData[2] == 0)
  964. status = MIDI_STATUS_NOTE_OFF;
  965. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientMidiEvent);
  966. fShmRtClientControl.writeUInt(event.time);
  967. fShmRtClientControl.writeByte(midiEvent.port);
  968. fShmRtClientControl.writeByte(midiEvent.size);
  969. fShmRtClientControl.writeByte(uint8_t(midiData[0] | (event.channel & MIDI_CHANNEL_BIT)));
  970. for (uint8_t j=1; j < midiEvent.size; ++j)
  971. fShmRtClientControl.writeByte(midiData[j]);
  972. fShmRtClientControl.commitWrite();
  973. if (status == MIDI_STATUS_NOTE_ON)
  974. {
  975. pData->postponeRtEvent(kPluginPostRtEventNoteOn,
  976. true,
  977. event.channel,
  978. midiData[1],
  979. midiData[2],
  980. 0.0f);
  981. }
  982. else if (status == MIDI_STATUS_NOTE_OFF)
  983. {
  984. pData->postponeRtEvent(kPluginPostRtEventNoteOff,
  985. true,
  986. event.channel,
  987. midiData[1],
  988. 0, 0.0f);
  989. }
  990. } break;
  991. }
  992. }
  993. pData->postRtEvents.trySplice();
  994. } // End of Event Input
  995. if (! processSingle(audioIn, audioOut, frames))
  996. return;
  997. // --------------------------------------------------------------------------------------------------------
  998. // MIDI Output
  999. if (pData->event.portOut != nullptr)
  1000. {
  1001. uint32_t time;
  1002. uint8_t port, size;
  1003. const uint8_t* midiData(fShmRtClientControl.data->midiOut);
  1004. for (std::size_t read=0; read<kBridgeRtClientDataMidiOutSize-kBridgeBaseMidiOutHeaderSize;)
  1005. {
  1006. // get time
  1007. time = *(const uint32_t*)midiData;
  1008. midiData += 4;
  1009. // get port and size
  1010. port = *midiData++;
  1011. size = *midiData++;
  1012. if (size == 0)
  1013. break;
  1014. // store midi data advancing as needed
  1015. uint8_t data[size];
  1016. for (uint8_t j=0; j<size; ++j)
  1017. data[j] = *midiData++;
  1018. pData->event.portOut->writeMidiEvent(time, size, data);
  1019. read += kBridgeBaseMidiOutHeaderSize + size;
  1020. }
  1021. // TODO
  1022. (void)port;
  1023. } // End of Control and MIDI Output
  1024. }
  1025. bool processSingle(const float* const* const audioIn, float** const audioOut, const uint32_t frames)
  1026. {
  1027. CARLA_SAFE_ASSERT_RETURN(! fTimedError, false);
  1028. CARLA_SAFE_ASSERT_RETURN(frames > 0, false);
  1029. CARLA_SAFE_ASSERT_RETURN(frames <= fBufferSize, false);
  1030. if (pData->audioIn.count > 0)
  1031. {
  1032. CARLA_SAFE_ASSERT_RETURN(audioIn != nullptr, false);
  1033. }
  1034. if (pData->audioOut.count > 0)
  1035. {
  1036. CARLA_SAFE_ASSERT_RETURN(audioOut != nullptr, false);
  1037. }
  1038. // --------------------------------------------------------------------------------------------------------
  1039. // Try lock, silence otherwise
  1040. #ifndef STOAT_TEST_BUILD
  1041. if (pData->engine->isOffline())
  1042. {
  1043. pData->singleMutex.lock();
  1044. }
  1045. else
  1046. #endif
  1047. if (! pData->singleMutex.tryLock())
  1048. {
  1049. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  1050. carla_zeroFloats(audioOut[i], frames);
  1051. return false;
  1052. }
  1053. // --------------------------------------------------------------------------------------------------------
  1054. // Reset audio buffers
  1055. for (uint32_t i=0; i < fInfo.aIns; ++i)
  1056. carla_copyFloats(fShmAudioPool.data + (i * fBufferSize), audioIn[i], frames);
  1057. // --------------------------------------------------------------------------------------------------------
  1058. // TimeInfo
  1059. const EngineTimeInfo timeInfo(pData->engine->getTimeInfo());
  1060. BridgeTimeInfo& bridgeTimeInfo(fShmRtClientControl.data->timeInfo);
  1061. bridgeTimeInfo.playing = timeInfo.playing;
  1062. bridgeTimeInfo.frame = timeInfo.frame;
  1063. bridgeTimeInfo.usecs = timeInfo.usecs;
  1064. bridgeTimeInfo.validFlags = timeInfo.bbt.valid ? kPluginBridgeTimeInfoValidBBT : 0x0;
  1065. if (timeInfo.bbt.valid)
  1066. {
  1067. bridgeTimeInfo.bar = timeInfo.bbt.bar;
  1068. bridgeTimeInfo.beat = timeInfo.bbt.beat;
  1069. bridgeTimeInfo.tick = timeInfo.bbt.tick;
  1070. bridgeTimeInfo.beatsPerBar = timeInfo.bbt.beatsPerBar;
  1071. bridgeTimeInfo.beatType = timeInfo.bbt.beatType;
  1072. bridgeTimeInfo.ticksPerBeat = timeInfo.bbt.ticksPerBeat;
  1073. bridgeTimeInfo.beatsPerMinute = timeInfo.bbt.beatsPerMinute;
  1074. bridgeTimeInfo.barStartTick = timeInfo.bbt.barStartTick;
  1075. }
  1076. // --------------------------------------------------------------------------------------------------------
  1077. // Run plugin
  1078. {
  1079. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientProcess);
  1080. fShmRtClientControl.writeUInt(frames);
  1081. fShmRtClientControl.commitWrite();
  1082. }
  1083. waitForClient("process", fProcWaitTime);
  1084. if (fTimedOut)
  1085. {
  1086. pData->singleMutex.unlock();
  1087. return false;
  1088. }
  1089. if (fShmRtClientControl.data->procFlags)
  1090. {
  1091. fInitiated = false;
  1092. fProcCanceled = true;
  1093. }
  1094. for (uint32_t i=0; i < fInfo.aOuts; ++i)
  1095. carla_copyFloats(audioOut[i], fShmAudioPool.data + ((i + fInfo.aIns) * fBufferSize), frames);
  1096. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1097. // --------------------------------------------------------------------------------------------------------
  1098. // Post-processing (dry/wet, volume and balance)
  1099. {
  1100. const bool doVolume = (pData->hints & PLUGIN_CAN_VOLUME) != 0 && carla_isNotEqual(pData->postProc.volume, 1.0f);
  1101. const bool doDryWet = (pData->hints & PLUGIN_CAN_DRYWET) != 0 && carla_isNotEqual(pData->postProc.dryWet, 1.0f);
  1102. const bool doBalance = (pData->hints & PLUGIN_CAN_BALANCE) != 0 && ! (carla_isEqual(pData->postProc.balanceLeft, -1.0f) && carla_isEqual(pData->postProc.balanceRight, 1.0f));
  1103. const bool isMono = (pData->audioIn.count == 1);
  1104. bool isPair;
  1105. float bufValue, oldBufLeft[doBalance ? frames : 1];
  1106. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  1107. {
  1108. // Dry/Wet
  1109. if (doDryWet)
  1110. {
  1111. const uint32_t c = isMono ? 0 : i;
  1112. for (uint32_t k=0; k < frames; ++k)
  1113. {
  1114. bufValue = audioIn[c][k];
  1115. audioOut[i][k] = (audioOut[i][k] * pData->postProc.dryWet) + (bufValue * (1.0f - pData->postProc.dryWet));
  1116. }
  1117. }
  1118. // Balance
  1119. if (doBalance)
  1120. {
  1121. isPair = (i % 2 == 0);
  1122. if (isPair)
  1123. {
  1124. CARLA_ASSERT(i+1 < pData->audioOut.count);
  1125. carla_copyFloats(oldBufLeft, audioOut[i], frames);
  1126. }
  1127. float balRangeL = (pData->postProc.balanceLeft + 1.0f)/2.0f;
  1128. float balRangeR = (pData->postProc.balanceRight + 1.0f)/2.0f;
  1129. for (uint32_t k=0; k < frames; ++k)
  1130. {
  1131. if (isPair)
  1132. {
  1133. // left
  1134. audioOut[i][k] = oldBufLeft[k] * (1.0f - balRangeL);
  1135. audioOut[i][k] += audioOut[i+1][k] * (1.0f - balRangeR);
  1136. }
  1137. else
  1138. {
  1139. // right
  1140. audioOut[i][k] = audioOut[i][k] * balRangeR;
  1141. audioOut[i][k] += oldBufLeft[k] * balRangeL;
  1142. }
  1143. }
  1144. }
  1145. // Volume (and buffer copy)
  1146. if (doVolume)
  1147. {
  1148. for (uint32_t k=0; k < frames; ++k)
  1149. audioOut[i][k] *= pData->postProc.volume;
  1150. }
  1151. }
  1152. } // End of Post-processing
  1153. #endif
  1154. // --------------------------------------------------------------------------------------------------------
  1155. pData->singleMutex.unlock();
  1156. return true;
  1157. }
  1158. void bufferSizeChanged(const uint32_t newBufferSize) override
  1159. {
  1160. fBufferSize = newBufferSize;
  1161. resizeAudioPool(newBufferSize);
  1162. {
  1163. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientSetBufferSize);
  1164. fShmRtClientControl.writeUInt(newBufferSize);
  1165. fShmRtClientControl.commitWrite();
  1166. }
  1167. //fProcWaitTime = newBufferSize*1000/pData->engine->getSampleRate();
  1168. fProcWaitTime = 1000;
  1169. waitForClient("buffersize", 1000);
  1170. }
  1171. void sampleRateChanged(const double newSampleRate) override
  1172. {
  1173. {
  1174. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientSetSampleRate);
  1175. fShmRtClientControl.writeDouble(newSampleRate);
  1176. fShmRtClientControl.commitWrite();
  1177. }
  1178. //fProcWaitTime = pData->engine->getBufferSize()*1000/newSampleRate;
  1179. fProcWaitTime = 1000;
  1180. waitForClient("samplerate", 1000);
  1181. }
  1182. void offlineModeChanged(const bool isOffline) override
  1183. {
  1184. {
  1185. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientSetOnline);
  1186. fShmRtClientControl.writeBool(isOffline);
  1187. fShmRtClientControl.commitWrite();
  1188. }
  1189. waitForClient("offline", 1000);
  1190. }
  1191. // -------------------------------------------------------------------
  1192. // Post-poned UI Stuff
  1193. // -------------------------------------------------------------------
  1194. void handleNonRtData()
  1195. {
  1196. for (; fShmNonRtServerControl.isDataAvailableForReading();)
  1197. {
  1198. const PluginBridgeNonRtServerOpcode opcode(fShmNonRtServerControl.readOpcode());
  1199. //#ifdef DEBUG
  1200. if (opcode != kPluginBridgeNonRtServerPong)
  1201. {
  1202. carla_debug("CarlaPluginJack::handleNonRtData() - got opcode: %s", PluginBridgeNonRtServerOpcode2str(opcode));
  1203. }
  1204. //#endif
  1205. switch (opcode)
  1206. {
  1207. case kPluginBridgeNonRtServerNull:
  1208. case kPluginBridgeNonRtServerPong:
  1209. case kPluginBridgeNonRtServerPluginInfo1:
  1210. case kPluginBridgeNonRtServerPluginInfo2:
  1211. case kPluginBridgeNonRtServerAudioCount:
  1212. case kPluginBridgeNonRtServerMidiCount:
  1213. case kPluginBridgeNonRtServerCvCount:
  1214. case kPluginBridgeNonRtServerParameterCount:
  1215. case kPluginBridgeNonRtServerProgramCount:
  1216. case kPluginBridgeNonRtServerMidiProgramCount:
  1217. case kPluginBridgeNonRtServerPortName:
  1218. case kPluginBridgeNonRtServerParameterData1:
  1219. case kPluginBridgeNonRtServerParameterData2:
  1220. case kPluginBridgeNonRtServerParameterRanges:
  1221. case kPluginBridgeNonRtServerParameterValue:
  1222. case kPluginBridgeNonRtServerParameterValue2:
  1223. case kPluginBridgeNonRtServerParameterTouch:
  1224. case kPluginBridgeNonRtServerDefaultValue:
  1225. case kPluginBridgeNonRtServerCurrentProgram:
  1226. case kPluginBridgeNonRtServerCurrentMidiProgram:
  1227. case kPluginBridgeNonRtServerProgramName:
  1228. case kPluginBridgeNonRtServerMidiProgramData:
  1229. case kPluginBridgeNonRtServerSetCustomData:
  1230. case kPluginBridgeNonRtServerVersion:
  1231. break;
  1232. case kPluginBridgeNonRtServerSetChunkDataFile:
  1233. // uint/size, str[] (filename)
  1234. if (const uint32_t chunkFilePathSize = fShmNonRtServerControl.readUInt())
  1235. {
  1236. char chunkFilePath[chunkFilePathSize];
  1237. fShmNonRtServerControl.readCustomData(chunkFilePath, chunkFilePathSize);
  1238. }
  1239. break;
  1240. case kPluginBridgeNonRtServerSetLatency:
  1241. case kPluginBridgeNonRtServerSetParameterText:
  1242. break;
  1243. case kPluginBridgeNonRtServerReady:
  1244. fInitiated = true;
  1245. break;
  1246. case kPluginBridgeNonRtServerSaved:
  1247. break;
  1248. case kPluginBridgeNonRtServerUiClosed:
  1249. pData->engine->callback(true, true,
  1250. ENGINE_CALLBACK_UI_STATE_CHANGED,
  1251. pData->id,
  1252. 0,
  1253. 0, 0, 0.0f, nullptr);
  1254. break;
  1255. case kPluginBridgeNonRtServerError: {
  1256. // error
  1257. const uint32_t errorSize(fShmNonRtServerControl.readUInt());
  1258. char error[errorSize+1];
  1259. carla_zeroChars(error, errorSize+1);
  1260. fShmNonRtServerControl.readCustomData(error, errorSize);
  1261. if (fInitiated)
  1262. {
  1263. pData->engine->callback(true, true, ENGINE_CALLBACK_ERROR, pData->id, 0, 0, 0, 0.0f, error);
  1264. // just in case
  1265. pData->engine->setLastError(error);
  1266. fInitError = true;
  1267. }
  1268. else
  1269. {
  1270. pData->engine->setLastError(error);
  1271. fInitError = true;
  1272. fInitiated = true;
  1273. }
  1274. } break;
  1275. }
  1276. }
  1277. }
  1278. // -------------------------------------------------------------------
  1279. uintptr_t getUiBridgeProcessId() const noexcept override
  1280. {
  1281. return fBridgeThread.getProcessID();
  1282. }
  1283. // -------------------------------------------------------------------
  1284. bool init(const CarlaPluginPtr plugin,
  1285. const char* const filename, const char* const name, const char* const label, const uint options)
  1286. {
  1287. CARLA_SAFE_ASSERT_RETURN(pData->engine != nullptr, false);
  1288. // ---------------------------------------------------------------
  1289. // first checks
  1290. if (pData->client != nullptr)
  1291. {
  1292. pData->engine->setLastError("Plugin client is already registered");
  1293. return false;
  1294. }
  1295. if (filename == nullptr || filename[0] == '\0')
  1296. {
  1297. pData->engine->setLastError("null filename");
  1298. return false;
  1299. }
  1300. if (label == nullptr || label[0] == '\0')
  1301. {
  1302. pData->engine->setLastError("null label");
  1303. return false;
  1304. }
  1305. // ---------------------------------------------------------------
  1306. // check setup
  1307. if (std::strlen(label) < 6)
  1308. {
  1309. pData->engine->setLastError("invalid application setup received");
  1310. return false;
  1311. }
  1312. for (int i=4; --i >= 0;) {
  1313. CARLA_SAFE_ASSERT_INT2_RETURN(label[i] >= '0' && label[i] <= '0'+64, i, label[i], false);
  1314. }
  1315. CARLA_SAFE_ASSERT_INT2_RETURN(label[4] >= '0' && label[4] < '0'+0x4f, 4, label[4], false);
  1316. CARLA_SAFE_ASSERT_UINT2_RETURN(static_cast<uchar>(label[5]) >= '0' &&
  1317. static_cast<uchar>(label[5]) <= '0'+0x73,
  1318. static_cast<uchar>(label[5]),
  1319. static_cast<uchar>('0'+0x73),
  1320. false);
  1321. fInfo.aIns = static_cast<uint8_t>(label[0] - '0');
  1322. fInfo.aOuts = static_cast<uint8_t>(label[1] - '0');
  1323. fInfo.mIns = static_cast<uint8_t>(carla_minPositive(label[2] - '0', 1));
  1324. fInfo.mOuts = static_cast<uint8_t>(carla_minPositive(label[3] - '0', 1));
  1325. fInfo.setupLabel = label;
  1326. // ---------------------------------------------------------------
  1327. // set project unique id
  1328. if (label[6] == '\0')
  1329. setupUniqueProjectID();
  1330. // ---------------------------------------------------------------
  1331. // set icon
  1332. pData->iconName = carla_strdup_safe("application");
  1333. // ---------------------------------------------------------------
  1334. // set info
  1335. pData->filename = carla_strdup(filename);
  1336. if (name != nullptr && name[0] != '\0')
  1337. pData->name = pData->engine->getUniquePluginName(name);
  1338. else
  1339. pData->name = pData->engine->getUniquePluginName("Jack Application");
  1340. std::srand(static_cast<uint>(std::time(nullptr)));
  1341. // ---------------------------------------------------------------
  1342. // init sem/shm
  1343. if (! fShmAudioPool.initializeServer())
  1344. {
  1345. carla_stderr("Failed to initialize shared memory audio pool");
  1346. return false;
  1347. }
  1348. if (! fShmRtClientControl.initializeServer())
  1349. {
  1350. carla_stderr("Failed to initialize RT client control");
  1351. fShmAudioPool.clear();
  1352. return false;
  1353. }
  1354. if (! fShmNonRtClientControl.initializeServer())
  1355. {
  1356. carla_stderr("Failed to initialize Non-RT client control");
  1357. fShmRtClientControl.clear();
  1358. fShmAudioPool.clear();
  1359. return false;
  1360. }
  1361. if (! fShmNonRtServerControl.initializeServer())
  1362. {
  1363. carla_stderr("Failed to initialize Non-RT server control");
  1364. fShmNonRtClientControl.clear();
  1365. fShmRtClientControl.clear();
  1366. fShmAudioPool.clear();
  1367. return false;
  1368. }
  1369. // ---------------------------------------------------------------
  1370. // setup hints and options
  1371. fSetupHints = static_cast<uint>(static_cast<uchar>(label[5]) - '0');
  1372. // FIXME dryWet broken
  1373. pData->hints = PLUGIN_IS_BRIDGE;
  1374. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1375. pData->hints |= /*PLUGIN_CAN_DRYWET |*/ PLUGIN_CAN_VOLUME | PLUGIN_CAN_BALANCE;
  1376. #endif
  1377. if (fSetupHints & LIBJACK_FLAG_CONTROL_WINDOW)
  1378. pData->hints |= PLUGIN_HAS_CUSTOM_UI;
  1379. // ---------------------------------------------------------------
  1380. // init bridge thread
  1381. {
  1382. char shmIdsStr[6*4+1];
  1383. carla_zeroChars(shmIdsStr, 6*4+1);
  1384. std::strncpy(shmIdsStr+6*0, &fShmAudioPool.filename[fShmAudioPool.filename.length()-6], 6);
  1385. std::strncpy(shmIdsStr+6*1, &fShmRtClientControl.filename[fShmRtClientControl.filename.length()-6], 6);
  1386. std::strncpy(shmIdsStr+6*2, &fShmNonRtClientControl.filename[fShmNonRtClientControl.filename.length()-6], 6);
  1387. std::strncpy(shmIdsStr+6*3, &fShmNonRtServerControl.filename[fShmNonRtServerControl.filename.length()-6], 6);
  1388. fBridgeThread.setData(shmIdsStr, fInfo.setupLabel);
  1389. }
  1390. if (! restartBridgeThread())
  1391. return false;
  1392. // ---------------------------------------------------------------
  1393. // register client
  1394. if (pData->name == nullptr)
  1395. pData->name = pData->engine->getUniquePluginName("unknown");
  1396. pData->client = pData->engine->addClient(plugin);
  1397. if (pData->client == nullptr || ! pData->client->isOk())
  1398. {
  1399. pData->engine->setLastError("Failed to register plugin client");
  1400. return false;
  1401. }
  1402. // remove unprintable characters if needed
  1403. if (fSetupHints & LIBJACK_FLAG_EXTERNAL_START)
  1404. fInfo.setupLabel[5] = static_cast<char>('0' + (fSetupHints ^ LIBJACK_FLAG_EXTERNAL_START));
  1405. // ---------------------------------------------------------------
  1406. // set options
  1407. pData->options = PLUGIN_OPTION_FIXED_BUFFERS;
  1408. if (isPluginOptionEnabled(options, PLUGIN_OPTION_SEND_CONTROL_CHANGES))
  1409. pData->options |= PLUGIN_OPTION_SEND_CONTROL_CHANGES;
  1410. if (isPluginOptionEnabled(options, PLUGIN_OPTION_SEND_CHANNEL_PRESSURE))
  1411. pData->options |= PLUGIN_OPTION_SEND_CHANNEL_PRESSURE;
  1412. if (isPluginOptionEnabled(options, PLUGIN_OPTION_SEND_NOTE_AFTERTOUCH))
  1413. pData->options |= PLUGIN_OPTION_SEND_NOTE_AFTERTOUCH;
  1414. if (isPluginOptionEnabled(options, PLUGIN_OPTION_SEND_PITCHBEND))
  1415. pData->options |= PLUGIN_OPTION_SEND_PITCHBEND;
  1416. if (isPluginOptionEnabled(options, PLUGIN_OPTION_SEND_ALL_SOUND_OFF))
  1417. pData->options |= PLUGIN_OPTION_SEND_ALL_SOUND_OFF;
  1418. if (isPluginOptionEnabled(options, PLUGIN_OPTION_SEND_PROGRAM_CHANGES))
  1419. pData->options |= PLUGIN_OPTION_SEND_PROGRAM_CHANGES;
  1420. return true;
  1421. }
  1422. private:
  1423. bool fInitiated;
  1424. bool fInitError;
  1425. bool fTimedOut;
  1426. bool fTimedError;
  1427. bool fProcCanceled;
  1428. uint fBufferSize;
  1429. uint fProcWaitTime;
  1430. uint fSetupHints;
  1431. CarlaPluginJackThread fBridgeThread;
  1432. BridgeAudioPool fShmAudioPool;
  1433. BridgeRtClientControl fShmRtClientControl;
  1434. BridgeNonRtClientControl fShmNonRtClientControl;
  1435. BridgeNonRtServerControl fShmNonRtServerControl;
  1436. struct Info {
  1437. uint8_t aIns, aOuts;
  1438. uint8_t mIns, mOuts;
  1439. CarlaString setupLabel;
  1440. std::vector<uint8_t> chunk;
  1441. Info()
  1442. : aIns(0),
  1443. aOuts(0),
  1444. mIns(0),
  1445. mOuts(0),
  1446. setupLabel(),
  1447. chunk() {}
  1448. CARLA_DECLARE_NON_COPY_STRUCT(Info)
  1449. } fInfo;
  1450. void handleProcessStopped() noexcept
  1451. {
  1452. const bool wasActive = pData->active;
  1453. pData->active = false;
  1454. if (wasActive)
  1455. {
  1456. pData->engine->callback(true, true,
  1457. ENGINE_CALLBACK_PARAMETER_VALUE_CHANGED,
  1458. pData->id,
  1459. PARAMETER_ACTIVE,
  1460. 0, 0,
  1461. 0.0f,
  1462. nullptr);
  1463. }
  1464. if (pData->hints & PLUGIN_HAS_CUSTOM_UI)
  1465. pData->engine->callback(true, true,
  1466. ENGINE_CALLBACK_UI_STATE_CHANGED,
  1467. pData->id,
  1468. 0,
  1469. 0, 0, 0.0f, nullptr);
  1470. }
  1471. void resizeAudioPool(const uint32_t bufferSize)
  1472. {
  1473. fShmAudioPool.resize(bufferSize, static_cast<uint32_t>(fInfo.aIns+fInfo.aOuts), 0);
  1474. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientSetAudioPool);
  1475. fShmRtClientControl.writeULong(static_cast<uint64_t>(fShmAudioPool.dataSize));
  1476. fShmRtClientControl.commitWrite();
  1477. waitForClient("resize-pool", 5000);
  1478. }
  1479. void setupUniqueProjectID()
  1480. {
  1481. const char* const engineProjectFolder = pData->engine->getCurrentProjectFolder();
  1482. carla_stdout("setupUniqueProjectID %s", engineProjectFolder);
  1483. if (engineProjectFolder == nullptr || engineProjectFolder[0] == '\0')
  1484. return;
  1485. const File file(engineProjectFolder);
  1486. CARLA_SAFE_ASSERT_RETURN(file.exists(),);
  1487. char code[6];
  1488. code[5] = '\0';
  1489. String child;
  1490. for (;;)
  1491. {
  1492. static const char* const kValidChars =
  1493. "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  1494. "abcdefghijklmnopqrstuvwxyz"
  1495. "0123456789";
  1496. static const size_t kValidCharsLen(std::strlen(kValidChars)-1U);
  1497. code[0] = kValidChars[safe_rand(kValidCharsLen)];
  1498. code[1] = kValidChars[safe_rand(kValidCharsLen)];
  1499. code[2] = kValidChars[safe_rand(kValidCharsLen)];
  1500. code[3] = kValidChars[safe_rand(kValidCharsLen)];
  1501. code[4] = kValidChars[safe_rand(kValidCharsLen)];
  1502. child = pData->name;
  1503. child += ".";
  1504. child += code;
  1505. const File newFile(file.getChildFile(child));
  1506. if (newFile.existsAsFile())
  1507. continue;
  1508. fInfo.setupLabel += code;
  1509. carla_stdout("new label %s", fInfo.setupLabel.buffer());
  1510. break;
  1511. }
  1512. }
  1513. bool restartBridgeThread()
  1514. {
  1515. fInitiated = false;
  1516. fInitError = false;
  1517. fTimedError = false;
  1518. // reset memory
  1519. fProcCanceled = false;
  1520. fShmRtClientControl.data->procFlags = 0;
  1521. carla_zeroStruct(fShmRtClientControl.data->timeInfo);
  1522. carla_zeroBytes(fShmRtClientControl.data->midiOut, kBridgeRtClientDataMidiOutSize);
  1523. fShmRtClientControl.clearData();
  1524. fShmNonRtClientControl.clearData();
  1525. fShmNonRtServerControl.clearData();
  1526. // initial values
  1527. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientVersion);
  1528. fShmNonRtClientControl.writeUInt(CARLA_PLUGIN_BRIDGE_API_VERSION_CURRENT);
  1529. fShmNonRtClientControl.writeUInt(static_cast<uint32_t>(sizeof(BridgeRtClientData)));
  1530. fShmNonRtClientControl.writeUInt(static_cast<uint32_t>(sizeof(BridgeNonRtClientData)));
  1531. fShmNonRtClientControl.writeUInt(static_cast<uint32_t>(sizeof(BridgeNonRtServerData)));
  1532. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientInitialSetup);
  1533. fShmNonRtClientControl.writeUInt(pData->engine->getBufferSize());
  1534. fShmNonRtClientControl.writeDouble(pData->engine->getSampleRate());
  1535. fShmNonRtClientControl.commitWrite();
  1536. if (fShmAudioPool.dataSize != 0)
  1537. {
  1538. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientSetAudioPool);
  1539. fShmRtClientControl.writeULong(static_cast<uint64_t>(fShmAudioPool.dataSize));
  1540. fShmRtClientControl.commitWrite();
  1541. }
  1542. else
  1543. {
  1544. // testing dummy message
  1545. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientNull);
  1546. fShmRtClientControl.commitWrite();
  1547. }
  1548. fBridgeThread.startThread();
  1549. const bool needsCancelableAction = ! pData->engine->isLoadingProject();
  1550. const bool needsEngineIdle = pData->engine->getType() != kEngineTypePlugin;
  1551. CarlaString actionName;
  1552. if (needsCancelableAction)
  1553. {
  1554. if (fSetupHints & LIBJACK_FLAG_EXTERNAL_START)
  1555. {
  1556. const EngineOptions& options(pData->engine->getOptions());
  1557. CarlaString binaryDir(options.binaryDir);
  1558. char* const hwVars = fBridgeThread.getEnvVarsToExport();
  1559. actionName = "Waiting for external JACK application start, please use the following environment variables:\n";
  1560. actionName += hwVars;
  1561. delete[] hwVars;
  1562. }
  1563. else
  1564. {
  1565. actionName = "Loading JACK application";
  1566. }
  1567. pData->engine->setActionCanceled(false);
  1568. pData->engine->callback(true, true,
  1569. ENGINE_CALLBACK_CANCELABLE_ACTION,
  1570. pData->id,
  1571. 1,
  1572. 0, 0, 0.0f,
  1573. actionName.buffer());
  1574. }
  1575. for (;fBridgeThread.isThreadRunning();)
  1576. {
  1577. pData->engine->callback(true, false, ENGINE_CALLBACK_IDLE, 0, 0, 0, 0, 0.0f, nullptr);
  1578. if (needsEngineIdle)
  1579. pData->engine->idle();
  1580. idle();
  1581. if (fInitiated)
  1582. break;
  1583. if (pData->engine->isAboutToClose() || pData->engine->wasActionCanceled())
  1584. break;
  1585. carla_msleep(5);
  1586. }
  1587. if (needsCancelableAction)
  1588. {
  1589. pData->engine->callback(true, true,
  1590. ENGINE_CALLBACK_CANCELABLE_ACTION,
  1591. pData->id,
  1592. 0,
  1593. 0, 0, 0.0f,
  1594. actionName.buffer());
  1595. }
  1596. if (fInitError || ! fInitiated)
  1597. {
  1598. fBridgeThread.stopThread(6000);
  1599. if (! fInitError)
  1600. pData->engine->setLastError("Timeout while waiting for a response from plugin-bridge\n"
  1601. "(or the plugin crashed on initialization?)");
  1602. return false;
  1603. }
  1604. return true;
  1605. }
  1606. void waitForClient(const char* const action, const uint msecs)
  1607. {
  1608. CARLA_SAFE_ASSERT_RETURN(! fTimedOut,);
  1609. CARLA_SAFE_ASSERT_RETURN(! fTimedError,);
  1610. if (fShmRtClientControl.waitForClient(msecs))
  1611. return;
  1612. fTimedOut = true;
  1613. carla_stderr2("waitForClient(%s) timed out", action);
  1614. }
  1615. CARLA_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(CarlaPluginJack)
  1616. };
  1617. CARLA_BACKEND_END_NAMESPACE
  1618. #endif // CARLA_OS_LINUX
  1619. // -------------------------------------------------------------------------------------------------------------------
  1620. CARLA_BACKEND_START_NAMESPACE
  1621. CarlaPluginPtr CarlaPlugin::newJackApp(const Initializer& init)
  1622. {
  1623. carla_debug("CarlaPlugin::newJackApp({%p, \"%s\", \"%s\", \"%s\"})",
  1624. init.engine, init.filename, init.name, init.label);
  1625. #ifdef CARLA_OS_LINUX
  1626. std::shared_ptr<CarlaPluginJack> plugin(new CarlaPluginJack(init.engine, init.id));
  1627. if (! plugin->init(plugin, init.filename, init.name, init.label, init.options))
  1628. return nullptr;
  1629. return plugin;
  1630. #else
  1631. init.engine->setLastError("JACK Application support not available");
  1632. return nullptr;
  1633. #endif
  1634. }
  1635. CARLA_BACKEND_END_NAMESPACE
  1636. // -------------------------------------------------------------------------------------------------------------------