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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560
  1. /*
  2. * Carla Plugin JACK
  3. * Copyright (C) 2016-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 "CarlaPluginInternal.hpp"
  18. #include "CarlaEngine.hpp"
  19. #ifdef CARLA_OS_LINUX
  20. #include "CarlaBackendUtils.hpp"
  21. #include "CarlaBridgeUtils.hpp"
  22. #include "CarlaEngineUtils.hpp"
  23. #include "CarlaMathUtils.hpp"
  24. #include "CarlaPipeUtils.hpp"
  25. #include "CarlaShmUtils.hpp"
  26. #include "CarlaThread.hpp"
  27. #include "water/misc/Time.h"
  28. #include "water/text/StringArray.h"
  29. #include "water/threads/ChildProcess.h"
  30. #include "jackbridge/JackBridge.hpp"
  31. #include <ctime>
  32. #include <vector>
  33. // -------------------------------------------------------------------------------------------------------------------
  34. using water::ChildProcess;
  35. using water::File;
  36. using water::String;
  37. using water::StringArray;
  38. using water::Time;
  39. CARLA_BACKEND_START_NAMESPACE
  40. // -------------------------------------------------------------------------------------------------------------------
  41. // Fallback data
  42. static const ExternalMidiNote kExternalMidiNoteFallback = { -1, 0, 0 };
  43. // -------------------------------------------------------------------------------------------------------------------
  44. class CarlaPluginJackThread : public CarlaThread
  45. {
  46. public:
  47. CarlaPluginJackThread(CarlaEngine* const engine, CarlaPlugin* const plugin) noexcept
  48. : CarlaThread("CarlaPluginJackThread"),
  49. kEngine(engine),
  50. kPlugin(plugin),
  51. fShmIds(),
  52. fNumPorts(),
  53. fProcess() {}
  54. void setData(const char* const shmIds, const char* const numPorts) noexcept
  55. {
  56. CARLA_SAFE_ASSERT_RETURN(shmIds != nullptr && shmIds[0] != '\0',);
  57. CARLA_SAFE_ASSERT_RETURN(numPorts != nullptr && numPorts[0] != '\0',);
  58. CARLA_SAFE_ASSERT(! isThreadRunning());
  59. fShmIds = shmIds;
  60. fNumPorts = numPorts;
  61. }
  62. uintptr_t getProcessID() const noexcept
  63. {
  64. CARLA_SAFE_ASSERT_RETURN(fProcess != nullptr, 0);
  65. return (uintptr_t)fProcess->getPID();
  66. }
  67. protected:
  68. void run()
  69. {
  70. if (fProcess == nullptr)
  71. {
  72. fProcess = new ChildProcess();
  73. }
  74. else if (fProcess->isRunning())
  75. {
  76. carla_stderr("CarlaPluginJackThread::run() - already running");
  77. }
  78. String name(kPlugin->getName());
  79. String filename(kPlugin->getFilename());
  80. if (name.isEmpty())
  81. name = "(none)";
  82. CARLA_SAFE_ASSERT_RETURN(filename.isNotEmpty(),);
  83. StringArray arguments;
  84. // binary
  85. arguments.addTokens(filename, true);
  86. bool started;
  87. {
  88. const EngineOptions& options(kEngine->getOptions());
  89. char winIdStr[STR_MAX+1];
  90. std::snprintf(winIdStr, STR_MAX, P_UINTPTR, options.frontendWinId);
  91. winIdStr[STR_MAX] = '\0';
  92. CarlaString libjackdir(options.binaryDir);
  93. libjackdir += "/jack";
  94. CarlaString ldpreload;
  95. #ifdef HAVE_X11
  96. ldpreload = (CarlaString(options.binaryDir)
  97. + "/libcarla_interposer-jack-x11.so");
  98. #endif
  99. const ScopedEngineEnvironmentLocker _seel(kEngine);
  100. const ScopedEnvVar sev2("LD_LIBRARY_PATH", libjackdir.buffer());
  101. const ScopedEnvVar sev1("LD_PRELOAD", ldpreload.isNotEmpty() ? ldpreload.buffer() : nullptr);
  102. if (kPlugin->getHints() & PLUGIN_HAS_CUSTOM_UI)
  103. carla_setenv("CARLA_FRONTEND_WIN_ID", winIdStr);
  104. else
  105. carla_unsetenv("CARLA_FRONTEND_WIN_ID");
  106. carla_setenv("CARLA_LIBJACK_SETUP", fNumPorts.buffer());
  107. carla_setenv("CARLA_SHM_IDS", fShmIds.buffer());
  108. started = fProcess->start(arguments);
  109. }
  110. if (! started)
  111. {
  112. carla_stdout("failed!");
  113. fProcess = nullptr;
  114. return;
  115. }
  116. for (; fProcess->isRunning() && ! shouldThreadExit();)
  117. carla_msleep(50);
  118. // we only get here if bridge crashed or thread asked to exit
  119. if (fProcess->isRunning() && shouldThreadExit())
  120. {
  121. fProcess->waitForProcessToFinish(2000);
  122. if (fProcess->isRunning())
  123. {
  124. carla_stdout("CarlaPluginJackThread::run() - application refused to close, force kill now");
  125. fProcess->kill();
  126. }
  127. }
  128. else
  129. {
  130. // forced quit, may have crashed
  131. if (fProcess->getExitCode() != 0 /*|| fProcess->exitStatus() == QProcess::CrashExit*/)
  132. {
  133. carla_stderr("CarlaPluginJackThread::run() - application crashed");
  134. CarlaString errorString("Plugin '" + CarlaString(kPlugin->getName()) + "' has crashed!\n"
  135. "Saving now will lose its current settings.\n"
  136. "Please remove this plugin, and not rely on it from this point.");
  137. kEngine->callback(CarlaBackend::ENGINE_CALLBACK_ERROR, kPlugin->getId(), 0, 0, 0.0f, errorString);
  138. }
  139. }
  140. fProcess = nullptr;
  141. }
  142. private:
  143. CarlaEngine* const kEngine;
  144. CarlaPlugin* const kPlugin;
  145. CarlaString fShmIds;
  146. CarlaString fNumPorts;
  147. ScopedPointer<ChildProcess> fProcess;
  148. CARLA_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(CarlaPluginJackThread)
  149. };
  150. // -------------------------------------------------------------------------------------------------------------------
  151. class CarlaPluginJack : public CarlaPlugin
  152. {
  153. public:
  154. CarlaPluginJack(CarlaEngine* const engine, const uint id)
  155. : CarlaPlugin(engine, id),
  156. fInitiated(false),
  157. fInitError(false),
  158. fTimedOut(false),
  159. fTimedError(false),
  160. fProcCanceled(false),
  161. fProcWaitTime(0),
  162. fLastPingTime(-1),
  163. fBridgeThread(engine, this),
  164. fShmAudioPool(),
  165. fShmRtClientControl(),
  166. fShmNonRtClientControl(),
  167. fShmNonRtServerControl(),
  168. fInfo()
  169. {
  170. carla_debug("CarlaPluginJack::CarlaPluginJack(%p, %i)", engine, id);
  171. pData->hints |= PLUGIN_IS_BRIDGE;
  172. }
  173. ~CarlaPluginJack() override
  174. {
  175. carla_debug("CarlaPluginJack::~CarlaPluginJack()");
  176. #ifndef BUILD_BRIDGE
  177. // close UI
  178. if (pData->hints & PLUGIN_HAS_CUSTOM_UI)
  179. pData->transientTryCounter = 0;
  180. #endif
  181. pData->singleMutex.lock();
  182. pData->masterMutex.lock();
  183. if (pData->client != nullptr && pData->client->isActive())
  184. pData->client->deactivate();
  185. if (pData->active)
  186. {
  187. deactivate();
  188. pData->active = false;
  189. }
  190. if (fBridgeThread.isThreadRunning())
  191. {
  192. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientQuit);
  193. fShmRtClientControl.commitWrite();
  194. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientQuit);
  195. fShmNonRtClientControl.commitWrite();
  196. if (! fTimedOut)
  197. waitForClient("stopping", 3000);
  198. }
  199. fBridgeThread.stopThread(3000);
  200. fShmNonRtServerControl.clear();
  201. fShmNonRtClientControl.clear();
  202. fShmRtClientControl.clear();
  203. fShmAudioPool.clear();
  204. clearBuffers();
  205. fInfo.chunk.clear();
  206. }
  207. // -------------------------------------------------------------------
  208. // Information (base)
  209. PluginType getType() const noexcept override
  210. {
  211. return PLUGIN_JACK;
  212. }
  213. PluginCategory getCategory() const noexcept override
  214. {
  215. return PLUGIN_CATEGORY_NONE;
  216. }
  217. // -------------------------------------------------------------------
  218. // Information (count)
  219. uint32_t getMidiInCount() const noexcept override
  220. {
  221. return fInfo.mIns;
  222. }
  223. uint32_t getMidiOutCount() const noexcept override
  224. {
  225. return fInfo.mOuts;
  226. }
  227. // -------------------------------------------------------------------
  228. // Information (current data)
  229. // -------------------------------------------------------------------
  230. // Information (per-plugin data)
  231. uint getOptionsAvailable() const noexcept override
  232. {
  233. return fInfo.optionsAvailable;
  234. }
  235. void getLabel(char* const strBuf) const noexcept override
  236. {
  237. std::strncpy(strBuf, fInfo.setupLabel, STR_MAX);
  238. }
  239. void getMaker(char* const strBuf) const noexcept override
  240. {
  241. nullStrBuf(strBuf);
  242. }
  243. void getCopyright(char* const strBuf) const noexcept override
  244. {
  245. nullStrBuf(strBuf);
  246. }
  247. void getRealName(char* const strBuf) const noexcept override
  248. {
  249. // FIXME
  250. std::strncpy(strBuf, "Carla's libjack", STR_MAX);
  251. }
  252. // -------------------------------------------------------------------
  253. // Set data (state)
  254. // -------------------------------------------------------------------
  255. // Set data (internal stuff)
  256. void setOption(const uint option, const bool yesNo, const bool sendCallback) override
  257. {
  258. {
  259. const CarlaMutexLocker _cml(fShmNonRtClientControl.mutex);
  260. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientSetOption);
  261. fShmNonRtClientControl.writeUInt(option);
  262. fShmNonRtClientControl.writeBool(yesNo);
  263. fShmNonRtClientControl.commitWrite();
  264. }
  265. CarlaPlugin::setOption(option, yesNo, sendCallback);
  266. }
  267. void setCtrlChannel(const int8_t channel, const bool sendOsc, const bool sendCallback) noexcept override
  268. {
  269. CARLA_SAFE_ASSERT_RETURN(sendOsc || sendCallback,); // never call this from RT
  270. {
  271. const CarlaMutexLocker _cml(fShmNonRtClientControl.mutex);
  272. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientSetCtrlChannel);
  273. fShmNonRtClientControl.writeShort(channel);
  274. fShmNonRtClientControl.commitWrite();
  275. }
  276. CarlaPlugin::setCtrlChannel(channel, sendOsc, sendCallback);
  277. }
  278. // -------------------------------------------------------------------
  279. // Set data (plugin-specific stuff)
  280. void setCustomData(const char* const type, const char* const key, const char* const value, const bool sendGui) override
  281. {
  282. CARLA_SAFE_ASSERT_RETURN(type != nullptr && type[0] != '\0',);
  283. CARLA_SAFE_ASSERT_RETURN(key != nullptr && key[0] != '\0',);
  284. CARLA_SAFE_ASSERT_RETURN(value != nullptr,);
  285. if (std::strcmp(type, CUSTOM_DATA_TYPE_PROPERTY) == 0)
  286. return CarlaPlugin::setCustomData(type, key, value, sendGui);
  287. if (std::strcmp(type, CUSTOM_DATA_TYPE_STRING) == 0 && std::strcmp(key, "__CarlaPingOnOff__") == 0)
  288. {
  289. #if 0
  290. const CarlaMutexLocker _cml(fShmNonRtClientControl.mutex);
  291. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientPingOnOff);
  292. fShmNonRtClientControl.writeBool(std::strcmp(value, "true") == 0);
  293. fShmNonRtClientControl.commitWrite();
  294. #endif
  295. return;
  296. }
  297. CarlaPlugin::setCustomData(type, key, value, sendGui);
  298. }
  299. // -------------------------------------------------------------------
  300. // Set ui stuff
  301. void showCustomUI(const bool yesNo) override
  302. {
  303. if (yesNo && ! fBridgeThread.isThreadRunning()) {
  304. CARLA_SAFE_ASSERT_RETURN(restartBridgeThread(),);
  305. }
  306. const CarlaMutexLocker _cml(fShmNonRtClientControl.mutex);
  307. fShmNonRtClientControl.writeOpcode(yesNo ? kPluginBridgeNonRtClientShowUI : kPluginBridgeNonRtClientHideUI);
  308. fShmNonRtClientControl.commitWrite();
  309. }
  310. void idle() override
  311. {
  312. if (fBridgeThread.isThreadRunning())
  313. {
  314. if (fInitiated && fTimedOut && pData->active)
  315. setActive(false, true, true);
  316. {
  317. const CarlaMutexLocker _cml(fShmNonRtClientControl.mutex);
  318. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientPing);
  319. fShmNonRtClientControl.commitWrite();
  320. }
  321. try {
  322. handleNonRtData();
  323. } CARLA_SAFE_EXCEPTION("handleNonRtData");
  324. if (fLastPingTime > 0 && Time::currentTimeMillis() > fLastPingTime + 30000)
  325. {
  326. carla_stderr("Did not receive ping message from server for 30 secs, closing...");
  327. // TODO
  328. //threadShouldExit();
  329. //callback(ENGINE_CALLBACK_QUIT, 0, 0, 0, 0.0f, nullptr);
  330. }
  331. }
  332. else if (fInitiated)
  333. {
  334. fTimedOut = true;
  335. fTimedError = true;
  336. fInitiated = false;
  337. handleProcessStopped();
  338. }
  339. else if (fProcCanceled)
  340. {
  341. handleProcessStopped();
  342. fProcCanceled = false;
  343. }
  344. CarlaPlugin::idle();
  345. }
  346. // -------------------------------------------------------------------
  347. // Plugin state
  348. void reload() override
  349. {
  350. CARLA_SAFE_ASSERT_RETURN(pData->engine != nullptr,);
  351. carla_debug("CarlaPluginJack::reload() - start");
  352. const EngineProcessMode processMode(pData->engine->getProccessMode());
  353. // Safely disable plugin for reload
  354. const ScopedDisabler sd(this);
  355. // cleanup of previous data
  356. pData->audioIn.clear();
  357. pData->audioOut.clear();
  358. pData->event.clear();
  359. bool needsCtrlIn, needsCtrlOut;
  360. needsCtrlIn = needsCtrlOut = false;
  361. if (fInfo.aIns > 0)
  362. {
  363. pData->audioIn.createNew(fInfo.aIns);
  364. }
  365. if (fInfo.aOuts > 0)
  366. {
  367. pData->audioOut.createNew(fInfo.aOuts);
  368. needsCtrlIn = true;
  369. }
  370. if (fInfo.mIns > 0)
  371. needsCtrlIn = true;
  372. if (fInfo.mOuts > 0)
  373. needsCtrlOut = true;
  374. const uint portNameSize(pData->engine->getMaxPortNameSize());
  375. CarlaString portName;
  376. // Audio Ins
  377. for (uint8_t j=0; j < fInfo.aIns; ++j)
  378. {
  379. portName.clear();
  380. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  381. {
  382. portName = pData->name;
  383. portName += ":";
  384. }
  385. if (fInfo.aIns > 1)
  386. {
  387. portName += "audio_in_";
  388. portName += CarlaString(j+1);
  389. }
  390. else
  391. {
  392. portName += "audio_in";
  393. }
  394. portName.truncate(portNameSize);
  395. pData->audioIn.ports[j].port = (CarlaEngineAudioPort*)pData->client->addPort(kEnginePortTypeAudio, portName, true, j);
  396. pData->audioIn.ports[j].rindex = j;
  397. }
  398. // Audio Outs
  399. for (uint8_t j=0; j < fInfo.aOuts; ++j)
  400. {
  401. portName.clear();
  402. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  403. {
  404. portName = pData->name;
  405. portName += ":";
  406. }
  407. if (fInfo.aOuts > 1)
  408. {
  409. portName += "audio_out_";
  410. portName += CarlaString(j+1);
  411. }
  412. else
  413. {
  414. portName += "audio_out";
  415. }
  416. portName.truncate(portNameSize);
  417. pData->audioOut.ports[j].port = (CarlaEngineAudioPort*)pData->client->addPort(kEnginePortTypeAudio, portName, false, j);
  418. pData->audioOut.ports[j].rindex = j;
  419. }
  420. if (needsCtrlIn)
  421. {
  422. portName.clear();
  423. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  424. {
  425. portName = pData->name;
  426. portName += ":";
  427. }
  428. portName += "event-in";
  429. portName.truncate(portNameSize);
  430. pData->event.portIn = (CarlaEngineEventPort*)pData->client->addPort(kEnginePortTypeEvent, portName, true, 0);
  431. }
  432. if (needsCtrlOut)
  433. {
  434. portName.clear();
  435. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  436. {
  437. portName = pData->name;
  438. portName += ":";
  439. }
  440. portName += "event-out";
  441. portName.truncate(portNameSize);
  442. pData->event.portOut = (CarlaEngineEventPort*)pData->client->addPort(kEnginePortTypeEvent, portName, false, 0);
  443. }
  444. // extra plugin hints
  445. pData->extraHints = 0x0;
  446. if (fInfo.mIns > 0)
  447. pData->extraHints |= PLUGIN_EXTRA_HINT_HAS_MIDI_IN;
  448. if (fInfo.mOuts > 0)
  449. pData->extraHints |= PLUGIN_EXTRA_HINT_HAS_MIDI_OUT;
  450. if (fInfo.aIns <= 2 && fInfo.aOuts <= 2 && (fInfo.aIns == fInfo.aOuts || fInfo.aIns == 0 || fInfo.aOuts == 0))
  451. pData->extraHints |= PLUGIN_EXTRA_HINT_CAN_RUN_RACK;
  452. bufferSizeChanged(pData->engine->getBufferSize());
  453. reloadPrograms(true);
  454. carla_debug("CarlaPluginJack::reload() - end");
  455. }
  456. // -------------------------------------------------------------------
  457. // Plugin processing
  458. void activate() noexcept override
  459. {
  460. if (! fBridgeThread.isThreadRunning())
  461. {
  462. CARLA_SAFE_ASSERT_RETURN(restartBridgeThread(),);
  463. }
  464. CARLA_SAFE_ASSERT_RETURN(! fTimedError,);
  465. {
  466. const CarlaMutexLocker _cml(fShmNonRtClientControl.mutex);
  467. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientActivate);
  468. fShmNonRtClientControl.commitWrite();
  469. }
  470. fTimedOut = false;
  471. try {
  472. waitForClient("activate", 2000);
  473. } CARLA_SAFE_EXCEPTION("activate - waitForClient");
  474. }
  475. void deactivate() noexcept override
  476. {
  477. if (! fBridgeThread.isThreadRunning())
  478. return;
  479. CARLA_SAFE_ASSERT_RETURN(! fTimedError,);
  480. {
  481. const CarlaMutexLocker _cml(fShmNonRtClientControl.mutex);
  482. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientDeactivate);
  483. fShmNonRtClientControl.commitWrite();
  484. }
  485. fTimedOut = false;
  486. try {
  487. waitForClient("deactivate", 2000);
  488. } CARLA_SAFE_EXCEPTION("deactivate - waitForClient");
  489. }
  490. void process(const float** const audioIn, float** const audioOut, const float**, float**, const uint32_t frames) override
  491. {
  492. // --------------------------------------------------------------------------------------------------------
  493. // Check if active
  494. if (fProcCanceled || fTimedOut || fTimedError || ! pData->active)
  495. {
  496. // disable any output sound
  497. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  498. carla_zeroFloats(audioOut[i], frames);
  499. return;
  500. }
  501. // --------------------------------------------------------------------------------------------------------
  502. // Check if needs reset
  503. if (pData->needsReset)
  504. {
  505. // TODO
  506. pData->needsReset = false;
  507. }
  508. // --------------------------------------------------------------------------------------------------------
  509. // Event Input
  510. if (pData->event.portIn != nullptr)
  511. {
  512. // ----------------------------------------------------------------------------------------------------
  513. // MIDI Input (External)
  514. if (pData->extNotes.mutex.tryLock())
  515. {
  516. for (RtLinkedList<ExternalMidiNote>::Itenerator it = pData->extNotes.data.begin2(); it.valid(); it.next())
  517. {
  518. const ExternalMidiNote& note(it.getValue(kExternalMidiNoteFallback));
  519. CARLA_SAFE_ASSERT_CONTINUE(note.channel >= 0 && note.channel < MAX_MIDI_CHANNELS);
  520. uint8_t data1, data2, data3;
  521. data1 = uint8_t((note.velo > 0 ? MIDI_STATUS_NOTE_ON : MIDI_STATUS_NOTE_OFF) | (note.channel & MIDI_CHANNEL_BIT));
  522. data2 = note.note;
  523. data3 = note.velo;
  524. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientMidiEvent);
  525. fShmRtClientControl.writeUInt(0); // time
  526. fShmRtClientControl.writeByte(0); // port
  527. fShmRtClientControl.writeByte(3); // size
  528. fShmRtClientControl.writeByte(data1);
  529. fShmRtClientControl.writeByte(data2);
  530. fShmRtClientControl.writeByte(data3);
  531. fShmRtClientControl.commitWrite();
  532. }
  533. pData->extNotes.data.clear();
  534. pData->extNotes.mutex.unlock();
  535. } // End of MIDI Input (External)
  536. // ----------------------------------------------------------------------------------------------------
  537. // Event Input (System)
  538. #ifndef BUILD_BRIDGE
  539. bool allNotesOffSent = false;
  540. #endif
  541. for (uint32_t i=0, numEvents=pData->event.portIn->getEventCount(); i < numEvents; ++i)
  542. {
  543. const EngineEvent& event(pData->event.portIn->getEvent(i));
  544. // Control change
  545. switch (event.type)
  546. {
  547. case kEngineEventTypeNull:
  548. break;
  549. case kEngineEventTypeControl: {
  550. const EngineControlEvent& ctrlEvent = event.ctrl;
  551. switch (ctrlEvent.type)
  552. {
  553. case kEngineControlEventTypeNull:
  554. break;
  555. case kEngineControlEventTypeParameter:
  556. #ifndef BUILD_BRIDGE
  557. // Control backend stuff
  558. if (event.channel == pData->ctrlChannel)
  559. {
  560. float value;
  561. if (MIDI_IS_CONTROL_BREATH_CONTROLLER(ctrlEvent.param) && (pData->hints & PLUGIN_CAN_DRYWET) != 0)
  562. {
  563. value = ctrlEvent.value;
  564. setDryWetRT(value);
  565. }
  566. if (MIDI_IS_CONTROL_CHANNEL_VOLUME(ctrlEvent.param) && (pData->hints & PLUGIN_CAN_VOLUME) != 0)
  567. {
  568. value = ctrlEvent.value*127.0f/100.0f;
  569. setVolumeRT(value);
  570. }
  571. if (MIDI_IS_CONTROL_BALANCE(ctrlEvent.param) && (pData->hints & PLUGIN_CAN_BALANCE) != 0)
  572. {
  573. float left, right;
  574. value = ctrlEvent.value/0.5f - 1.0f;
  575. if (value < 0.0f)
  576. {
  577. left = -1.0f;
  578. right = (value*2.0f)+1.0f;
  579. }
  580. else if (value > 0.0f)
  581. {
  582. left = (value*2.0f)-1.0f;
  583. right = 1.0f;
  584. }
  585. else
  586. {
  587. left = -1.0f;
  588. right = 1.0f;
  589. }
  590. setBalanceLeftRT(left);
  591. setBalanceRightRT(right);
  592. }
  593. }
  594. #endif
  595. break;
  596. case kEngineControlEventTypeMidiBank:
  597. if (pData->options & PLUGIN_OPTION_MAP_PROGRAM_CHANGES)
  598. {
  599. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientControlEventMidiBank);
  600. fShmRtClientControl.writeUInt(event.time);
  601. fShmRtClientControl.writeByte(event.channel);
  602. fShmRtClientControl.writeUShort(event.ctrl.param);
  603. fShmRtClientControl.commitWrite();
  604. }
  605. break;
  606. case kEngineControlEventTypeMidiProgram:
  607. if (pData->options & PLUGIN_OPTION_MAP_PROGRAM_CHANGES)
  608. {
  609. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientControlEventMidiProgram);
  610. fShmRtClientControl.writeUInt(event.time);
  611. fShmRtClientControl.writeByte(event.channel);
  612. fShmRtClientControl.writeUShort(event.ctrl.param);
  613. fShmRtClientControl.commitWrite();
  614. }
  615. break;
  616. case kEngineControlEventTypeAllSoundOff:
  617. if (pData->options & PLUGIN_OPTION_SEND_ALL_SOUND_OFF)
  618. {
  619. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientControlEventAllSoundOff);
  620. fShmRtClientControl.writeUInt(event.time);
  621. fShmRtClientControl.writeByte(event.channel);
  622. fShmRtClientControl.commitWrite();
  623. }
  624. break;
  625. case kEngineControlEventTypeAllNotesOff:
  626. if (pData->options & PLUGIN_OPTION_SEND_ALL_SOUND_OFF)
  627. {
  628. #ifndef BUILD_BRIDGE
  629. if (event.channel == pData->ctrlChannel && ! allNotesOffSent)
  630. {
  631. allNotesOffSent = true;
  632. sendMidiAllNotesOffToCallback();
  633. }
  634. #endif
  635. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientControlEventAllNotesOff);
  636. fShmRtClientControl.writeUInt(event.time);
  637. fShmRtClientControl.writeByte(event.channel);
  638. fShmRtClientControl.commitWrite();
  639. }
  640. break;
  641. } // switch (ctrlEvent.type)
  642. break;
  643. } // case kEngineEventTypeControl
  644. case kEngineEventTypeMidi: {
  645. const EngineMidiEvent& midiEvent(event.midi);
  646. if (midiEvent.size == 0 || midiEvent.size >= MAX_MIDI_VALUE)
  647. continue;
  648. const uint8_t* const midiData(midiEvent.size > EngineMidiEvent::kDataSize ? midiEvent.dataExt : midiEvent.data);
  649. uint8_t status = uint8_t(MIDI_GET_STATUS_FROM_DATA(midiData));
  650. if (status == MIDI_STATUS_CHANNEL_PRESSURE && (pData->options & PLUGIN_OPTION_SEND_CHANNEL_PRESSURE) == 0)
  651. continue;
  652. if (status == MIDI_STATUS_CONTROL_CHANGE && (pData->options & PLUGIN_OPTION_SEND_CONTROL_CHANGES) == 0)
  653. continue;
  654. if (status == MIDI_STATUS_POLYPHONIC_AFTERTOUCH && (pData->options & PLUGIN_OPTION_SEND_NOTE_AFTERTOUCH) == 0)
  655. continue;
  656. if (status == MIDI_STATUS_PITCH_WHEEL_CONTROL && (pData->options & PLUGIN_OPTION_SEND_PITCHBEND) == 0)
  657. continue;
  658. // Fix bad note-off
  659. if (status == MIDI_STATUS_NOTE_ON && midiData[2] == 0)
  660. status = MIDI_STATUS_NOTE_OFF;
  661. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientMidiEvent);
  662. fShmRtClientControl.writeUInt(event.time);
  663. fShmRtClientControl.writeByte(midiEvent.port);
  664. fShmRtClientControl.writeByte(midiEvent.size);
  665. fShmRtClientControl.writeByte(uint8_t(midiData[0] | (event.channel & MIDI_CHANNEL_BIT)));
  666. for (uint8_t j=1; j < midiEvent.size; ++j)
  667. fShmRtClientControl.writeByte(midiData[j]);
  668. fShmRtClientControl.commitWrite();
  669. if (status == MIDI_STATUS_NOTE_ON)
  670. pData->postponeRtEvent(kPluginPostRtEventNoteOn, event.channel, midiData[1], midiData[2]);
  671. else if (status == MIDI_STATUS_NOTE_OFF)
  672. pData->postponeRtEvent(kPluginPostRtEventNoteOff, event.channel, midiData[1], 0.0f);
  673. } break;
  674. }
  675. }
  676. pData->postRtEvents.trySplice();
  677. } // End of Event Input
  678. if (! processSingle(audioIn, audioOut, frames))
  679. return;
  680. // --------------------------------------------------------------------------------------------------------
  681. // MIDI Output
  682. if (pData->event.portOut != nullptr)
  683. {
  684. uint32_t time;
  685. uint8_t port, size;
  686. const uint8_t* midiData(fShmRtClientControl.data->midiOut);
  687. for (std::size_t read=0; read<kBridgeRtClientDataMidiOutSize-kBridgeBaseMidiOutHeaderSize;)
  688. {
  689. // get time
  690. time = *(const uint32_t*)midiData;
  691. midiData += 4;
  692. // get port and size
  693. port = *midiData++;
  694. size = *midiData++;
  695. if (size == 0)
  696. break;
  697. // store midi data advancing as needed
  698. uint8_t data[size];
  699. for (uint8_t j=0; j<size; ++j)
  700. data[j] = *midiData++;
  701. pData->event.portOut->writeMidiEvent(time, size, data);
  702. read += kBridgeBaseMidiOutHeaderSize + size;
  703. }
  704. // TODO
  705. (void)port;
  706. } // End of Control and MIDI Output
  707. }
  708. bool processSingle(const float** const audioIn, float** const audioOut, const uint32_t frames)
  709. {
  710. CARLA_SAFE_ASSERT_RETURN(! fTimedError, false);
  711. CARLA_SAFE_ASSERT_RETURN(frames > 0, false);
  712. if (pData->audioIn.count > 0)
  713. {
  714. CARLA_SAFE_ASSERT_RETURN(audioIn != nullptr, false);
  715. }
  716. if (pData->audioOut.count > 0)
  717. {
  718. CARLA_SAFE_ASSERT_RETURN(audioOut != nullptr, false);
  719. }
  720. // --------------------------------------------------------------------------------------------------------
  721. // Try lock, silence otherwise
  722. #ifndef STOAT_TEST_BUILD
  723. if (pData->engine->isOffline())
  724. {
  725. pData->singleMutex.lock();
  726. }
  727. else
  728. #endif
  729. if (! pData->singleMutex.tryLock())
  730. {
  731. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  732. carla_zeroFloats(audioOut[i], frames);
  733. return false;
  734. }
  735. // --------------------------------------------------------------------------------------------------------
  736. // Reset audio buffers
  737. for (uint32_t i=0; i < fInfo.aIns; ++i)
  738. carla_copyFloats(fShmAudioPool.data + (i * frames), audioIn[i], frames);
  739. // --------------------------------------------------------------------------------------------------------
  740. // TimeInfo
  741. const EngineTimeInfo& timeInfo(pData->engine->getTimeInfo());
  742. BridgeTimeInfo& bridgeTimeInfo(fShmRtClientControl.data->timeInfo);
  743. bridgeTimeInfo.playing = timeInfo.playing;
  744. bridgeTimeInfo.frame = timeInfo.frame;
  745. bridgeTimeInfo.usecs = timeInfo.usecs;
  746. bridgeTimeInfo.validFlags = timeInfo.bbt.valid ? kPluginBridgeTimeInfoValidBBT : 0x0;
  747. if (timeInfo.bbt.valid)
  748. {
  749. bridgeTimeInfo.bar = timeInfo.bbt.bar;
  750. bridgeTimeInfo.beat = timeInfo.bbt.beat;
  751. bridgeTimeInfo.tick = timeInfo.bbt.tick;
  752. bridgeTimeInfo.beatsPerBar = timeInfo.bbt.beatsPerBar;
  753. bridgeTimeInfo.beatType = timeInfo.bbt.beatType;
  754. bridgeTimeInfo.ticksPerBeat = timeInfo.bbt.ticksPerBeat;
  755. bridgeTimeInfo.beatsPerMinute = timeInfo.bbt.beatsPerMinute;
  756. bridgeTimeInfo.barStartTick = timeInfo.bbt.barStartTick;
  757. }
  758. // --------------------------------------------------------------------------------------------------------
  759. // Run plugin
  760. {
  761. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientProcess);
  762. fShmRtClientControl.commitWrite();
  763. }
  764. waitForClient("process", fProcWaitTime);
  765. if (fTimedOut)
  766. {
  767. pData->singleMutex.unlock();
  768. return false;
  769. }
  770. if (fShmRtClientControl.data->procFlags)
  771. {
  772. fInitiated = false;
  773. fProcCanceled = true;
  774. }
  775. for (uint32_t i=0; i < fInfo.aOuts; ++i)
  776. carla_copyFloats(audioOut[i], fShmAudioPool.data + ((i + fInfo.aIns) * frames), frames);
  777. #ifndef BUILD_BRIDGE
  778. // --------------------------------------------------------------------------------------------------------
  779. // Post-processing (dry/wet, volume and balance)
  780. {
  781. const bool doVolume = (pData->hints & PLUGIN_CAN_VOLUME) != 0 && carla_isNotEqual(pData->postProc.volume, 1.0f);
  782. const bool doDryWet = (pData->hints & PLUGIN_CAN_DRYWET) != 0 && carla_isNotEqual(pData->postProc.dryWet, 1.0f);
  783. const bool doBalance = (pData->hints & PLUGIN_CAN_BALANCE) != 0 && ! (carla_isEqual(pData->postProc.balanceLeft, -1.0f) && carla_isEqual(pData->postProc.balanceRight, 1.0f));
  784. const bool isMono = (pData->audioIn.count == 1);
  785. bool isPair;
  786. float bufValue, oldBufLeft[doBalance ? frames : 1];
  787. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  788. {
  789. // Dry/Wet
  790. if (doDryWet)
  791. {
  792. const uint32_t c = isMono ? 0 : i;
  793. for (uint32_t k=0; k < frames; ++k)
  794. {
  795. bufValue = audioIn[c][k];
  796. audioOut[i][k] = (audioOut[i][k] * pData->postProc.dryWet) + (bufValue * (1.0f - pData->postProc.dryWet));
  797. }
  798. }
  799. // Balance
  800. if (doBalance)
  801. {
  802. isPair = (i % 2 == 0);
  803. if (isPair)
  804. {
  805. CARLA_ASSERT(i+1 < pData->audioOut.count);
  806. carla_copyFloats(oldBufLeft, audioOut[i], frames);
  807. }
  808. float balRangeL = (pData->postProc.balanceLeft + 1.0f)/2.0f;
  809. float balRangeR = (pData->postProc.balanceRight + 1.0f)/2.0f;
  810. for (uint32_t k=0; k < frames; ++k)
  811. {
  812. if (isPair)
  813. {
  814. // left
  815. audioOut[i][k] = oldBufLeft[k] * (1.0f - balRangeL);
  816. audioOut[i][k] += audioOut[i+1][k] * (1.0f - balRangeR);
  817. }
  818. else
  819. {
  820. // right
  821. audioOut[i][k] = audioOut[i][k] * balRangeR;
  822. audioOut[i][k] += oldBufLeft[k] * balRangeL;
  823. }
  824. }
  825. }
  826. // Volume (and buffer copy)
  827. if (doVolume)
  828. {
  829. for (uint32_t k=0; k < frames; ++k)
  830. audioOut[i][k] *= pData->postProc.volume;
  831. }
  832. }
  833. } // End of Post-processing
  834. #endif
  835. // --------------------------------------------------------------------------------------------------------
  836. pData->singleMutex.unlock();
  837. return true;
  838. }
  839. void bufferSizeChanged(const uint32_t newBufferSize) override
  840. {
  841. resizeAudioPool(newBufferSize);
  842. {
  843. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientSetBufferSize);
  844. fShmRtClientControl.writeUInt(newBufferSize);
  845. fShmRtClientControl.commitWrite();
  846. }
  847. //fProcWaitTime = newBufferSize*1000/pData->engine->getSampleRate();
  848. fProcWaitTime = 1000;
  849. waitForClient("buffersize", 1000);
  850. }
  851. void sampleRateChanged(const double newSampleRate) override
  852. {
  853. {
  854. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientSetSampleRate);
  855. fShmRtClientControl.writeDouble(newSampleRate);
  856. fShmRtClientControl.commitWrite();
  857. }
  858. //fProcWaitTime = pData->engine->getBufferSize()*1000/newSampleRate;
  859. fProcWaitTime = 1000;
  860. waitForClient("samplerate", 1000);
  861. }
  862. void offlineModeChanged(const bool isOffline) override
  863. {
  864. {
  865. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientSetOnline);
  866. fShmRtClientControl.writeBool(isOffline);
  867. fShmRtClientControl.commitWrite();
  868. }
  869. waitForClient("offline", 1000);
  870. }
  871. // -------------------------------------------------------------------
  872. // Post-poned UI Stuff
  873. // -------------------------------------------------------------------
  874. void handleNonRtData()
  875. {
  876. for (; fShmNonRtServerControl.isDataAvailableForReading();)
  877. {
  878. const PluginBridgeNonRtServerOpcode opcode(fShmNonRtServerControl.readOpcode());
  879. //#ifdef DEBUG
  880. if (opcode != kPluginBridgeNonRtServerPong)
  881. {
  882. carla_debug("CarlaPluginJack::handleNonRtData() - got opcode: %s", PluginBridgeNonRtServerOpcode2str(opcode));
  883. }
  884. //#endif
  885. if (opcode != kPluginBridgeNonRtServerNull && fLastPingTime > 0)
  886. fLastPingTime = Time::currentTimeMillis();
  887. switch (opcode)
  888. {
  889. case kPluginBridgeNonRtServerNull:
  890. case kPluginBridgeNonRtServerPong:
  891. case kPluginBridgeNonRtServerPluginInfo1:
  892. case kPluginBridgeNonRtServerPluginInfo2:
  893. case kPluginBridgeNonRtServerAudioCount:
  894. case kPluginBridgeNonRtServerMidiCount:
  895. case kPluginBridgeNonRtServerCvCount:
  896. case kPluginBridgeNonRtServerParameterCount:
  897. case kPluginBridgeNonRtServerProgramCount:
  898. case kPluginBridgeNonRtServerMidiProgramCount:
  899. case kPluginBridgeNonRtServerPortName:
  900. case kPluginBridgeNonRtServerParameterData1:
  901. case kPluginBridgeNonRtServerParameterData2:
  902. case kPluginBridgeNonRtServerParameterRanges:
  903. case kPluginBridgeNonRtServerParameterValue:
  904. case kPluginBridgeNonRtServerParameterValue2:
  905. case kPluginBridgeNonRtServerDefaultValue:
  906. case kPluginBridgeNonRtServerCurrentProgram:
  907. case kPluginBridgeNonRtServerCurrentMidiProgram:
  908. case kPluginBridgeNonRtServerProgramName:
  909. case kPluginBridgeNonRtServerMidiProgramData:
  910. case kPluginBridgeNonRtServerSetCustomData:
  911. break;
  912. case kPluginBridgeNonRtServerSetChunkDataFile:
  913. // uint/size, str[] (filename)
  914. if (const uint32_t chunkFilePathSize = fShmNonRtServerControl.readUInt())
  915. {
  916. char chunkFilePath[chunkFilePathSize];
  917. fShmNonRtServerControl.readCustomData(chunkFilePath, chunkFilePathSize);
  918. }
  919. break;
  920. case kPluginBridgeNonRtServerSetLatency:
  921. case kPluginBridgeNonRtServerSetParameterText:
  922. break;
  923. case kPluginBridgeNonRtServerReady:
  924. fInitiated = true;
  925. break;
  926. case kPluginBridgeNonRtServerSaved:
  927. break;
  928. case kPluginBridgeNonRtServerUiClosed:
  929. carla_stdout("got kPluginBridgeNonRtServerUiClosed, bridge closed cleanly?");
  930. pData->engine->callback(ENGINE_CALLBACK_UI_STATE_CHANGED, pData->id, 0, 0, 0.0f, nullptr);
  931. //fBridgeThread.signalThreadShouldExit();
  932. //handleProcessStopped();
  933. //fBridgeThread.stopThread(5000);
  934. break;
  935. case kPluginBridgeNonRtServerError: {
  936. // error
  937. const uint32_t errorSize(fShmNonRtServerControl.readUInt());
  938. char error[errorSize+1];
  939. carla_zeroChars(error, errorSize+1);
  940. fShmNonRtServerControl.readCustomData(error, errorSize);
  941. if (fInitiated)
  942. {
  943. pData->engine->callback(ENGINE_CALLBACK_ERROR, pData->id, 0, 0, 0.0f, error);
  944. // just in case
  945. pData->engine->setLastError(error);
  946. fInitError = true;
  947. }
  948. else
  949. {
  950. pData->engine->setLastError(error);
  951. fInitError = true;
  952. fInitiated = true;
  953. }
  954. } break;
  955. }
  956. }
  957. }
  958. // -------------------------------------------------------------------
  959. uintptr_t getUiBridgeProcessId() const noexcept override
  960. {
  961. return fBridgeThread.getProcessID();
  962. }
  963. // -------------------------------------------------------------------
  964. bool init(const char* const filename, const char* const name, const char* const label)
  965. {
  966. CARLA_SAFE_ASSERT_RETURN(pData->engine != nullptr, false);
  967. // ---------------------------------------------------------------
  968. // first checks
  969. if (pData->client != nullptr)
  970. {
  971. pData->engine->setLastError("Plugin client is already registered");
  972. return false;
  973. }
  974. if (filename == nullptr || filename[0] == '\0')
  975. {
  976. pData->engine->setLastError("null filename");
  977. return false;
  978. }
  979. if (label == nullptr || label[0] == '\0')
  980. {
  981. pData->engine->setLastError("null label");
  982. return false;
  983. }
  984. // ---------------------------------------------------------------
  985. // check setup
  986. if (std::strlen(label) != 6)
  987. {
  988. pData->engine->setLastError("invalid application setup received");
  989. return false;
  990. }
  991. for (int i=4; --i >= 0;) {
  992. CARLA_SAFE_ASSERT_RETURN(label[i] >= '0' && label[i] <= '0'+64, false);
  993. }
  994. for (int i=6; --i >= 4;) {
  995. CARLA_SAFE_ASSERT_RETURN(label[i] >= '0' && label[i] < '0'+0x4f, false);
  996. }
  997. fInfo.aIns = static_cast<uint8_t>(label[0] - '0');
  998. fInfo.aOuts = static_cast<uint8_t>(label[1] - '0');
  999. fInfo.mIns = static_cast<uint8_t>(carla_minPositive(label[2] - '0', 1));
  1000. fInfo.mOuts = static_cast<uint8_t>(carla_minPositive(label[3] - '0', 1));
  1001. fInfo.setupLabel = label;
  1002. const int setupHints = label[5] - '0';
  1003. // ---------------------------------------------------------------
  1004. // set info
  1005. pData->filename = carla_strdup(filename);
  1006. if (name != nullptr && name[0] != '\0')
  1007. pData->name = pData->engine->getUniquePluginName(name);
  1008. else
  1009. pData->name = pData->engine->getUniquePluginName("Jack Application");
  1010. std::srand(static_cast<uint>(std::time(nullptr)));
  1011. // ---------------------------------------------------------------
  1012. // init sem/shm
  1013. if (! fShmAudioPool.initializeServer())
  1014. {
  1015. carla_stderr("Failed to initialize shared memory audio pool");
  1016. return false;
  1017. }
  1018. if (! fShmRtClientControl.initializeServer())
  1019. {
  1020. carla_stderr("Failed to initialize RT client control");
  1021. fShmAudioPool.clear();
  1022. return false;
  1023. }
  1024. if (! fShmNonRtClientControl.initializeServer())
  1025. {
  1026. carla_stderr("Failed to initialize Non-RT client control");
  1027. fShmRtClientControl.clear();
  1028. fShmAudioPool.clear();
  1029. return false;
  1030. }
  1031. if (! fShmNonRtServerControl.initializeServer())
  1032. {
  1033. carla_stderr("Failed to initialize Non-RT server control");
  1034. fShmNonRtClientControl.clear();
  1035. fShmRtClientControl.clear();
  1036. fShmAudioPool.clear();
  1037. return false;
  1038. }
  1039. // ---------------------------------------------------------------
  1040. // setup hints and options
  1041. // FIXME dryWet broken
  1042. pData->hints = PLUGIN_IS_BRIDGE | PLUGIN_OPTION_FIXED_BUFFERS;
  1043. #ifndef BUILD_BRIDGE
  1044. pData->hints |= /*PLUGIN_CAN_DRYWET |*/ PLUGIN_CAN_VOLUME | PLUGIN_CAN_BALANCE;
  1045. #endif
  1046. //fInfo.optionsAvailable = optionAv;
  1047. if (setupHints & 0x1)
  1048. pData->hints |= PLUGIN_HAS_CUSTOM_UI;
  1049. // ---------------------------------------------------------------
  1050. // init bridge thread
  1051. {
  1052. char shmIdsStr[6*4+1];
  1053. carla_zeroChars(shmIdsStr, 6*4+1);
  1054. std::strncpy(shmIdsStr+6*0, &fShmAudioPool.filename[fShmAudioPool.filename.length()-6], 6);
  1055. std::strncpy(shmIdsStr+6*1, &fShmRtClientControl.filename[fShmRtClientControl.filename.length()-6], 6);
  1056. std::strncpy(shmIdsStr+6*2, &fShmNonRtClientControl.filename[fShmNonRtClientControl.filename.length()-6], 6);
  1057. std::strncpy(shmIdsStr+6*3, &fShmNonRtServerControl.filename[fShmNonRtServerControl.filename.length()-6], 6);
  1058. fBridgeThread.setData(shmIdsStr, label);
  1059. }
  1060. if (! restartBridgeThread())
  1061. return false;
  1062. // ---------------------------------------------------------------
  1063. // register client
  1064. if (pData->name == nullptr)
  1065. pData->name = pData->engine->getUniquePluginName("unknown");
  1066. pData->client = pData->engine->addClient(this);
  1067. if (pData->client == nullptr || ! pData->client->isOk())
  1068. {
  1069. pData->engine->setLastError("Failed to register plugin client");
  1070. return false;
  1071. }
  1072. return true;
  1073. }
  1074. private:
  1075. bool fInitiated;
  1076. bool fInitError;
  1077. bool fTimedOut;
  1078. bool fTimedError;
  1079. bool fProcCanceled;
  1080. uint fProcWaitTime;
  1081. int64_t fLastPingTime;
  1082. CarlaPluginJackThread fBridgeThread;
  1083. BridgeAudioPool fShmAudioPool;
  1084. BridgeRtClientControl fShmRtClientControl;
  1085. BridgeNonRtClientControl fShmNonRtClientControl;
  1086. BridgeNonRtServerControl fShmNonRtServerControl;
  1087. struct Info {
  1088. uint8_t aIns, aOuts;
  1089. uint8_t mIns, mOuts;
  1090. uint optionsAvailable;
  1091. CarlaString setupLabel;
  1092. std::vector<uint8_t> chunk;
  1093. Info()
  1094. : aIns(0),
  1095. aOuts(0),
  1096. mIns(0),
  1097. mOuts(0),
  1098. optionsAvailable(0),
  1099. setupLabel(),
  1100. chunk() {}
  1101. CARLA_DECLARE_NON_COPY_STRUCT(Info)
  1102. } fInfo;
  1103. void handleProcessStopped() noexcept
  1104. {
  1105. const bool wasActive = pData->active;
  1106. pData->active = false;
  1107. if (wasActive)
  1108. {
  1109. #if defined(HAVE_LIBLO) && ! defined(BUILD_BRIDGE)
  1110. if (pData->engine->isOscControlRegistered())
  1111. pData->engine->oscSend_control_set_parameter_value(pData->id, PARAMETER_ACTIVE, 0.0f);
  1112. pData->engine->callback(ENGINE_CALLBACK_PARAMETER_VALUE_CHANGED, pData->id, PARAMETER_ACTIVE, 0, 0.0f, nullptr);
  1113. #endif
  1114. }
  1115. if (pData->hints & PLUGIN_HAS_CUSTOM_UI)
  1116. pData->engine->callback(ENGINE_CALLBACK_UI_STATE_CHANGED, pData->id, 0, 0, 0.0f, nullptr);
  1117. }
  1118. void resizeAudioPool(const uint32_t bufferSize)
  1119. {
  1120. fShmAudioPool.resize(bufferSize, static_cast<uint32_t>(fInfo.aIns+fInfo.aOuts), 0);
  1121. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientSetAudioPool);
  1122. fShmRtClientControl.writeULong(static_cast<uint64_t>(fShmAudioPool.dataSize));
  1123. fShmRtClientControl.commitWrite();
  1124. waitForClient("resize-pool", 5000);
  1125. }
  1126. void waitForClient(const char* const action, const uint msecs)
  1127. {
  1128. CARLA_SAFE_ASSERT_RETURN(! fTimedOut,);
  1129. CARLA_SAFE_ASSERT_RETURN(! fTimedError,);
  1130. if (fShmRtClientControl.waitForClient(msecs))
  1131. return;
  1132. fTimedOut = true;
  1133. carla_stderr2("waitForClient(%s) timed out", action);
  1134. }
  1135. bool restartBridgeThread()
  1136. {
  1137. fInitiated = false;
  1138. fInitError = false;
  1139. fTimedError = false;
  1140. // reset memory
  1141. fProcCanceled = false;
  1142. fShmRtClientControl.data->procFlags = 0;
  1143. carla_zeroStruct(fShmRtClientControl.data->timeInfo);
  1144. carla_zeroBytes(fShmRtClientControl.data->midiOut, kBridgeRtClientDataMidiOutSize);
  1145. fShmRtClientControl.clearData();
  1146. fShmNonRtClientControl.clearData();
  1147. fShmNonRtServerControl.clearData();
  1148. // initial values
  1149. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientVersion);
  1150. fShmNonRtClientControl.writeUInt(CARLA_PLUGIN_BRIDGE_API_VERSION);
  1151. fShmNonRtClientControl.writeUInt(static_cast<uint32_t>(sizeof(BridgeRtClientData)));
  1152. fShmNonRtClientControl.writeUInt(static_cast<uint32_t>(sizeof(BridgeNonRtClientData)));
  1153. fShmNonRtClientControl.writeUInt(static_cast<uint32_t>(sizeof(BridgeNonRtServerData)));
  1154. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientInitialSetup);
  1155. fShmNonRtClientControl.writeUInt(pData->engine->getBufferSize());
  1156. fShmNonRtClientControl.writeDouble(pData->engine->getSampleRate());
  1157. fShmNonRtClientControl.commitWrite();
  1158. if (fShmAudioPool.dataSize != 0)
  1159. {
  1160. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientSetAudioPool);
  1161. fShmRtClientControl.writeULong(static_cast<uint64_t>(fShmAudioPool.dataSize));
  1162. fShmRtClientControl.commitWrite();
  1163. }
  1164. else
  1165. {
  1166. // testing dummy message
  1167. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientNull);
  1168. fShmRtClientControl.commitWrite();
  1169. }
  1170. fBridgeThread.startThread();
  1171. fLastPingTime = Time::currentTimeMillis();
  1172. CARLA_SAFE_ASSERT(fLastPingTime > 0);
  1173. static bool sFirstInit = true;
  1174. int64_t timeoutEnd = 5000;
  1175. if (sFirstInit)
  1176. timeoutEnd *= 2;
  1177. sFirstInit = false;
  1178. const bool needsEngineIdle = pData->engine->getType() != kEngineTypePlugin;
  1179. for (; Time::currentTimeMillis() < fLastPingTime + timeoutEnd && fBridgeThread.isThreadRunning();)
  1180. {
  1181. pData->engine->callback(ENGINE_CALLBACK_IDLE, 0, 0, 0, 0.0f, nullptr);
  1182. if (needsEngineIdle)
  1183. pData->engine->idle();
  1184. idle();
  1185. if (fInitiated)
  1186. break;
  1187. if (pData->engine->isAboutToClose())
  1188. break;
  1189. carla_msleep(20);
  1190. }
  1191. fLastPingTime = -1;
  1192. if (fInitError || ! fInitiated)
  1193. {
  1194. fBridgeThread.stopThread(6000);
  1195. if (! fInitError)
  1196. pData->engine->setLastError("Timeout while waiting for a response from plugin-bridge\n"
  1197. "(or the plugin crashed on initialization?)");
  1198. return false;
  1199. }
  1200. return true;
  1201. }
  1202. CARLA_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(CarlaPluginJack)
  1203. };
  1204. CARLA_BACKEND_END_NAMESPACE
  1205. #endif // CARLA_OS_LINUX
  1206. // -------------------------------------------------------------------------------------------------------------------
  1207. CARLA_BACKEND_START_NAMESPACE
  1208. CarlaPlugin* CarlaPlugin::newJackApp(const Initializer& init)
  1209. {
  1210. carla_debug("CarlaPlugin::newJackApp({%p, \"%s\", \"%s\", \"%s\"})", init.engine, init.filename, init.name, init.label);
  1211. #ifdef CARLA_OS_LINUX
  1212. CarlaPluginJack* const plugin(new CarlaPluginJack(init.engine, init.id));
  1213. if (! plugin->init(init.filename, init.name, init.label))
  1214. {
  1215. delete plugin;
  1216. return nullptr;
  1217. }
  1218. return plugin;
  1219. #else
  1220. init.engine->setLastError("JACK Application support not available");
  1221. return nullptr;
  1222. #endif
  1223. }
  1224. CARLA_BACKEND_END_NAMESPACE
  1225. // -------------------------------------------------------------------------------------------------------------------