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

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558
  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_ALTERNATIVE_ARCH
  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. bufferSizeChanged(pData->engine->getBufferSize());
  451. reloadPrograms(true);
  452. carla_debug("CarlaPluginJack::reload() - end");
  453. }
  454. // -------------------------------------------------------------------
  455. // Plugin processing
  456. void activate() noexcept override
  457. {
  458. if (! fBridgeThread.isThreadRunning())
  459. {
  460. CARLA_SAFE_ASSERT_RETURN(restartBridgeThread(),);
  461. }
  462. CARLA_SAFE_ASSERT_RETURN(! fTimedError,);
  463. {
  464. const CarlaMutexLocker _cml(fShmNonRtClientControl.mutex);
  465. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientActivate);
  466. fShmNonRtClientControl.commitWrite();
  467. }
  468. fTimedOut = false;
  469. try {
  470. waitForClient("activate", 2000);
  471. } CARLA_SAFE_EXCEPTION("activate - waitForClient");
  472. }
  473. void deactivate() noexcept override
  474. {
  475. if (! fBridgeThread.isThreadRunning())
  476. return;
  477. CARLA_SAFE_ASSERT_RETURN(! fTimedError,);
  478. {
  479. const CarlaMutexLocker _cml(fShmNonRtClientControl.mutex);
  480. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientDeactivate);
  481. fShmNonRtClientControl.commitWrite();
  482. }
  483. fTimedOut = false;
  484. try {
  485. waitForClient("deactivate", 2000);
  486. } CARLA_SAFE_EXCEPTION("deactivate - waitForClient");
  487. }
  488. void process(const float** const audioIn, float** const audioOut, const float**, float**, const uint32_t frames) override
  489. {
  490. // --------------------------------------------------------------------------------------------------------
  491. // Check if active
  492. if (fProcCanceled || fTimedOut || fTimedError || ! pData->active)
  493. {
  494. // disable any output sound
  495. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  496. carla_zeroFloats(audioOut[i], frames);
  497. return;
  498. }
  499. // --------------------------------------------------------------------------------------------------------
  500. // Check if needs reset
  501. if (pData->needsReset)
  502. {
  503. // TODO
  504. pData->needsReset = false;
  505. }
  506. // --------------------------------------------------------------------------------------------------------
  507. // Event Input
  508. if (pData->event.portIn != nullptr)
  509. {
  510. // ----------------------------------------------------------------------------------------------------
  511. // MIDI Input (External)
  512. if (pData->extNotes.mutex.tryLock())
  513. {
  514. for (RtLinkedList<ExternalMidiNote>::Itenerator it = pData->extNotes.data.begin2(); it.valid(); it.next())
  515. {
  516. const ExternalMidiNote& note(it.getValue(kExternalMidiNoteFallback));
  517. CARLA_SAFE_ASSERT_CONTINUE(note.channel >= 0 && note.channel < MAX_MIDI_CHANNELS);
  518. uint8_t data1, data2, data3;
  519. data1 = uint8_t((note.velo > 0 ? MIDI_STATUS_NOTE_ON : MIDI_STATUS_NOTE_OFF) | (note.channel & MIDI_CHANNEL_BIT));
  520. data2 = note.note;
  521. data3 = note.velo;
  522. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientMidiEvent);
  523. fShmRtClientControl.writeUInt(0); // time
  524. fShmRtClientControl.writeByte(0); // port
  525. fShmRtClientControl.writeByte(3); // size
  526. fShmRtClientControl.writeByte(data1);
  527. fShmRtClientControl.writeByte(data2);
  528. fShmRtClientControl.writeByte(data3);
  529. fShmRtClientControl.commitWrite();
  530. }
  531. pData->extNotes.data.clear();
  532. pData->extNotes.mutex.unlock();
  533. } // End of MIDI Input (External)
  534. // ----------------------------------------------------------------------------------------------------
  535. // Event Input (System)
  536. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  537. bool allNotesOffSent = false;
  538. #endif
  539. for (uint32_t i=0, numEvents=pData->event.portIn->getEventCount(); i < numEvents; ++i)
  540. {
  541. const EngineEvent& event(pData->event.portIn->getEvent(i));
  542. // Control change
  543. switch (event.type)
  544. {
  545. case kEngineEventTypeNull:
  546. break;
  547. case kEngineEventTypeControl: {
  548. const EngineControlEvent& ctrlEvent = event.ctrl;
  549. switch (ctrlEvent.type)
  550. {
  551. case kEngineControlEventTypeNull:
  552. break;
  553. case kEngineControlEventTypeParameter:
  554. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  555. // Control backend stuff
  556. if (event.channel == pData->ctrlChannel)
  557. {
  558. float value;
  559. if (MIDI_IS_CONTROL_BREATH_CONTROLLER(ctrlEvent.param) && (pData->hints & PLUGIN_CAN_DRYWET) != 0)
  560. {
  561. value = ctrlEvent.value;
  562. setDryWetRT(value);
  563. }
  564. if (MIDI_IS_CONTROL_CHANNEL_VOLUME(ctrlEvent.param) && (pData->hints & PLUGIN_CAN_VOLUME) != 0)
  565. {
  566. value = ctrlEvent.value*127.0f/100.0f;
  567. setVolumeRT(value);
  568. }
  569. if (MIDI_IS_CONTROL_BALANCE(ctrlEvent.param) && (pData->hints & PLUGIN_CAN_BALANCE) != 0)
  570. {
  571. float left, right;
  572. value = ctrlEvent.value/0.5f - 1.0f;
  573. if (value < 0.0f)
  574. {
  575. left = -1.0f;
  576. right = (value*2.0f)+1.0f;
  577. }
  578. else if (value > 0.0f)
  579. {
  580. left = (value*2.0f)-1.0f;
  581. right = 1.0f;
  582. }
  583. else
  584. {
  585. left = -1.0f;
  586. right = 1.0f;
  587. }
  588. setBalanceLeftRT(left);
  589. setBalanceRightRT(right);
  590. }
  591. }
  592. #endif
  593. break;
  594. case kEngineControlEventTypeMidiBank:
  595. if (pData->options & PLUGIN_OPTION_MAP_PROGRAM_CHANGES)
  596. {
  597. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientControlEventMidiBank);
  598. fShmRtClientControl.writeUInt(event.time);
  599. fShmRtClientControl.writeByte(event.channel);
  600. fShmRtClientControl.writeUShort(event.ctrl.param);
  601. fShmRtClientControl.commitWrite();
  602. }
  603. break;
  604. case kEngineControlEventTypeMidiProgram:
  605. if (pData->options & PLUGIN_OPTION_MAP_PROGRAM_CHANGES)
  606. {
  607. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientControlEventMidiProgram);
  608. fShmRtClientControl.writeUInt(event.time);
  609. fShmRtClientControl.writeByte(event.channel);
  610. fShmRtClientControl.writeUShort(event.ctrl.param);
  611. fShmRtClientControl.commitWrite();
  612. }
  613. break;
  614. case kEngineControlEventTypeAllSoundOff:
  615. if (pData->options & PLUGIN_OPTION_SEND_ALL_SOUND_OFF)
  616. {
  617. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientControlEventAllSoundOff);
  618. fShmRtClientControl.writeUInt(event.time);
  619. fShmRtClientControl.writeByte(event.channel);
  620. fShmRtClientControl.commitWrite();
  621. }
  622. break;
  623. case kEngineControlEventTypeAllNotesOff:
  624. if (pData->options & PLUGIN_OPTION_SEND_ALL_SOUND_OFF)
  625. {
  626. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  627. if (event.channel == pData->ctrlChannel && ! allNotesOffSent)
  628. {
  629. allNotesOffSent = true;
  630. sendMidiAllNotesOffToCallback();
  631. }
  632. #endif
  633. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientControlEventAllNotesOff);
  634. fShmRtClientControl.writeUInt(event.time);
  635. fShmRtClientControl.writeByte(event.channel);
  636. fShmRtClientControl.commitWrite();
  637. }
  638. break;
  639. } // switch (ctrlEvent.type)
  640. break;
  641. } // case kEngineEventTypeControl
  642. case kEngineEventTypeMidi: {
  643. const EngineMidiEvent& midiEvent(event.midi);
  644. if (midiEvent.size == 0 || midiEvent.size >= MAX_MIDI_VALUE)
  645. continue;
  646. const uint8_t* const midiData(midiEvent.size > EngineMidiEvent::kDataSize ? midiEvent.dataExt : midiEvent.data);
  647. uint8_t status = uint8_t(MIDI_GET_STATUS_FROM_DATA(midiData));
  648. if (status == MIDI_STATUS_CHANNEL_PRESSURE && (pData->options & PLUGIN_OPTION_SEND_CHANNEL_PRESSURE) == 0)
  649. continue;
  650. if (status == MIDI_STATUS_CONTROL_CHANGE && (pData->options & PLUGIN_OPTION_SEND_CONTROL_CHANGES) == 0)
  651. continue;
  652. if (status == MIDI_STATUS_POLYPHONIC_AFTERTOUCH && (pData->options & PLUGIN_OPTION_SEND_NOTE_AFTERTOUCH) == 0)
  653. continue;
  654. if (status == MIDI_STATUS_PITCH_WHEEL_CONTROL && (pData->options & PLUGIN_OPTION_SEND_PITCHBEND) == 0)
  655. continue;
  656. // Fix bad note-off
  657. if (status == MIDI_STATUS_NOTE_ON && midiData[2] == 0)
  658. status = MIDI_STATUS_NOTE_OFF;
  659. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientMidiEvent);
  660. fShmRtClientControl.writeUInt(event.time);
  661. fShmRtClientControl.writeByte(midiEvent.port);
  662. fShmRtClientControl.writeByte(midiEvent.size);
  663. fShmRtClientControl.writeByte(uint8_t(midiData[0] | (event.channel & MIDI_CHANNEL_BIT)));
  664. for (uint8_t j=1; j < midiEvent.size; ++j)
  665. fShmRtClientControl.writeByte(midiData[j]);
  666. fShmRtClientControl.commitWrite();
  667. if (status == MIDI_STATUS_NOTE_ON)
  668. pData->postponeRtEvent(kPluginPostRtEventNoteOn, event.channel, midiData[1], midiData[2]);
  669. else if (status == MIDI_STATUS_NOTE_OFF)
  670. pData->postponeRtEvent(kPluginPostRtEventNoteOff, event.channel, midiData[1], 0.0f);
  671. } break;
  672. }
  673. }
  674. pData->postRtEvents.trySplice();
  675. } // End of Event Input
  676. if (! processSingle(audioIn, audioOut, frames))
  677. return;
  678. // --------------------------------------------------------------------------------------------------------
  679. // MIDI Output
  680. if (pData->event.portOut != nullptr)
  681. {
  682. uint32_t time;
  683. uint8_t port, size;
  684. const uint8_t* midiData(fShmRtClientControl.data->midiOut);
  685. for (std::size_t read=0; read<kBridgeRtClientDataMidiOutSize-kBridgeBaseMidiOutHeaderSize;)
  686. {
  687. // get time
  688. time = *(const uint32_t*)midiData;
  689. midiData += 4;
  690. // get port and size
  691. port = *midiData++;
  692. size = *midiData++;
  693. if (size == 0)
  694. break;
  695. // store midi data advancing as needed
  696. uint8_t data[size];
  697. for (uint8_t j=0; j<size; ++j)
  698. data[j] = *midiData++;
  699. pData->event.portOut->writeMidiEvent(time, size, data);
  700. read += kBridgeBaseMidiOutHeaderSize + size;
  701. }
  702. // TODO
  703. (void)port;
  704. } // End of Control and MIDI Output
  705. }
  706. bool processSingle(const float** const audioIn, float** const audioOut, const uint32_t frames)
  707. {
  708. CARLA_SAFE_ASSERT_RETURN(! fTimedError, false);
  709. CARLA_SAFE_ASSERT_RETURN(frames > 0, false);
  710. if (pData->audioIn.count > 0)
  711. {
  712. CARLA_SAFE_ASSERT_RETURN(audioIn != nullptr, false);
  713. }
  714. if (pData->audioOut.count > 0)
  715. {
  716. CARLA_SAFE_ASSERT_RETURN(audioOut != nullptr, false);
  717. }
  718. // --------------------------------------------------------------------------------------------------------
  719. // Try lock, silence otherwise
  720. #ifndef STOAT_TEST_BUILD
  721. if (pData->engine->isOffline())
  722. {
  723. pData->singleMutex.lock();
  724. }
  725. else
  726. #endif
  727. if (! pData->singleMutex.tryLock())
  728. {
  729. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  730. carla_zeroFloats(audioOut[i], frames);
  731. return false;
  732. }
  733. // --------------------------------------------------------------------------------------------------------
  734. // Reset audio buffers
  735. for (uint32_t i=0; i < fInfo.aIns; ++i)
  736. carla_copyFloats(fShmAudioPool.data + (i * frames), audioIn[i], frames);
  737. // --------------------------------------------------------------------------------------------------------
  738. // TimeInfo
  739. const EngineTimeInfo timeInfo(pData->engine->getTimeInfo());
  740. BridgeTimeInfo& bridgeTimeInfo(fShmRtClientControl.data->timeInfo);
  741. bridgeTimeInfo.playing = timeInfo.playing;
  742. bridgeTimeInfo.frame = timeInfo.frame;
  743. bridgeTimeInfo.usecs = timeInfo.usecs;
  744. bridgeTimeInfo.validFlags = timeInfo.bbt.valid ? kPluginBridgeTimeInfoValidBBT : 0x0;
  745. if (timeInfo.bbt.valid)
  746. {
  747. bridgeTimeInfo.bar = timeInfo.bbt.bar;
  748. bridgeTimeInfo.beat = timeInfo.bbt.beat;
  749. bridgeTimeInfo.tick = timeInfo.bbt.tick;
  750. bridgeTimeInfo.beatsPerBar = timeInfo.bbt.beatsPerBar;
  751. bridgeTimeInfo.beatType = timeInfo.bbt.beatType;
  752. bridgeTimeInfo.ticksPerBeat = timeInfo.bbt.ticksPerBeat;
  753. bridgeTimeInfo.beatsPerMinute = timeInfo.bbt.beatsPerMinute;
  754. bridgeTimeInfo.barStartTick = timeInfo.bbt.barStartTick;
  755. }
  756. // --------------------------------------------------------------------------------------------------------
  757. // Run plugin
  758. {
  759. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientProcess);
  760. fShmRtClientControl.writeUInt(frames);
  761. fShmRtClientControl.commitWrite();
  762. }
  763. waitForClient("process", fProcWaitTime);
  764. if (fTimedOut)
  765. {
  766. pData->singleMutex.unlock();
  767. return false;
  768. }
  769. if (fShmRtClientControl.data->procFlags)
  770. {
  771. fInitiated = false;
  772. fProcCanceled = true;
  773. }
  774. for (uint32_t i=0; i < fInfo.aOuts; ++i)
  775. carla_copyFloats(audioOut[i], fShmAudioPool.data + ((i + fInfo.aIns) * frames), frames);
  776. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  777. // --------------------------------------------------------------------------------------------------------
  778. // Post-processing (dry/wet, volume and balance)
  779. {
  780. const bool doVolume = (pData->hints & PLUGIN_CAN_VOLUME) != 0 && carla_isNotEqual(pData->postProc.volume, 1.0f);
  781. const bool doDryWet = (pData->hints & PLUGIN_CAN_DRYWET) != 0 && carla_isNotEqual(pData->postProc.dryWet, 1.0f);
  782. const bool doBalance = (pData->hints & PLUGIN_CAN_BALANCE) != 0 && ! (carla_isEqual(pData->postProc.balanceLeft, -1.0f) && carla_isEqual(pData->postProc.balanceRight, 1.0f));
  783. const bool isMono = (pData->audioIn.count == 1);
  784. bool isPair;
  785. float bufValue, oldBufLeft[doBalance ? frames : 1];
  786. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  787. {
  788. // Dry/Wet
  789. if (doDryWet)
  790. {
  791. const uint32_t c = isMono ? 0 : i;
  792. for (uint32_t k=0; k < frames; ++k)
  793. {
  794. bufValue = audioIn[c][k];
  795. audioOut[i][k] = (audioOut[i][k] * pData->postProc.dryWet) + (bufValue * (1.0f - pData->postProc.dryWet));
  796. }
  797. }
  798. // Balance
  799. if (doBalance)
  800. {
  801. isPair = (i % 2 == 0);
  802. if (isPair)
  803. {
  804. CARLA_ASSERT(i+1 < pData->audioOut.count);
  805. carla_copyFloats(oldBufLeft, audioOut[i], frames);
  806. }
  807. float balRangeL = (pData->postProc.balanceLeft + 1.0f)/2.0f;
  808. float balRangeR = (pData->postProc.balanceRight + 1.0f)/2.0f;
  809. for (uint32_t k=0; k < frames; ++k)
  810. {
  811. if (isPair)
  812. {
  813. // left
  814. audioOut[i][k] = oldBufLeft[k] * (1.0f - balRangeL);
  815. audioOut[i][k] += audioOut[i+1][k] * (1.0f - balRangeR);
  816. }
  817. else
  818. {
  819. // right
  820. audioOut[i][k] = audioOut[i][k] * balRangeR;
  821. audioOut[i][k] += oldBufLeft[k] * balRangeL;
  822. }
  823. }
  824. }
  825. // Volume (and buffer copy)
  826. if (doVolume)
  827. {
  828. for (uint32_t k=0; k < frames; ++k)
  829. audioOut[i][k] *= pData->postProc.volume;
  830. }
  831. }
  832. } // End of Post-processing
  833. #endif
  834. // --------------------------------------------------------------------------------------------------------
  835. pData->singleMutex.unlock();
  836. return true;
  837. }
  838. void bufferSizeChanged(const uint32_t newBufferSize) override
  839. {
  840. resizeAudioPool(newBufferSize);
  841. {
  842. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientSetBufferSize);
  843. fShmRtClientControl.writeUInt(newBufferSize);
  844. fShmRtClientControl.commitWrite();
  845. }
  846. //fProcWaitTime = newBufferSize*1000/pData->engine->getSampleRate();
  847. fProcWaitTime = 1000;
  848. waitForClient("buffersize", 1000);
  849. }
  850. void sampleRateChanged(const double newSampleRate) override
  851. {
  852. {
  853. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientSetSampleRate);
  854. fShmRtClientControl.writeDouble(newSampleRate);
  855. fShmRtClientControl.commitWrite();
  856. }
  857. //fProcWaitTime = pData->engine->getBufferSize()*1000/newSampleRate;
  858. fProcWaitTime = 1000;
  859. waitForClient("samplerate", 1000);
  860. }
  861. void offlineModeChanged(const bool isOffline) override
  862. {
  863. {
  864. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientSetOnline);
  865. fShmRtClientControl.writeBool(isOffline);
  866. fShmRtClientControl.commitWrite();
  867. }
  868. waitForClient("offline", 1000);
  869. }
  870. // -------------------------------------------------------------------
  871. // Post-poned UI Stuff
  872. // -------------------------------------------------------------------
  873. void handleNonRtData()
  874. {
  875. for (; fShmNonRtServerControl.isDataAvailableForReading();)
  876. {
  877. const PluginBridgeNonRtServerOpcode opcode(fShmNonRtServerControl.readOpcode());
  878. //#ifdef DEBUG
  879. if (opcode != kPluginBridgeNonRtServerPong)
  880. {
  881. carla_debug("CarlaPluginJack::handleNonRtData() - got opcode: %s", PluginBridgeNonRtServerOpcode2str(opcode));
  882. }
  883. //#endif
  884. if (opcode != kPluginBridgeNonRtServerNull && fLastPingTime > 0)
  885. fLastPingTime = Time::currentTimeMillis();
  886. switch (opcode)
  887. {
  888. case kPluginBridgeNonRtServerNull:
  889. case kPluginBridgeNonRtServerPong:
  890. case kPluginBridgeNonRtServerPluginInfo1:
  891. case kPluginBridgeNonRtServerPluginInfo2:
  892. case kPluginBridgeNonRtServerAudioCount:
  893. case kPluginBridgeNonRtServerMidiCount:
  894. case kPluginBridgeNonRtServerCvCount:
  895. case kPluginBridgeNonRtServerParameterCount:
  896. case kPluginBridgeNonRtServerProgramCount:
  897. case kPluginBridgeNonRtServerMidiProgramCount:
  898. case kPluginBridgeNonRtServerPortName:
  899. case kPluginBridgeNonRtServerParameterData1:
  900. case kPluginBridgeNonRtServerParameterData2:
  901. case kPluginBridgeNonRtServerParameterRanges:
  902. case kPluginBridgeNonRtServerParameterValue:
  903. case kPluginBridgeNonRtServerParameterValue2:
  904. case kPluginBridgeNonRtServerDefaultValue:
  905. case kPluginBridgeNonRtServerCurrentProgram:
  906. case kPluginBridgeNonRtServerCurrentMidiProgram:
  907. case kPluginBridgeNonRtServerProgramName:
  908. case kPluginBridgeNonRtServerMidiProgramData:
  909. case kPluginBridgeNonRtServerSetCustomData:
  910. break;
  911. case kPluginBridgeNonRtServerSetChunkDataFile:
  912. // uint/size, str[] (filename)
  913. if (const uint32_t chunkFilePathSize = fShmNonRtServerControl.readUInt())
  914. {
  915. char chunkFilePath[chunkFilePathSize];
  916. fShmNonRtServerControl.readCustomData(chunkFilePath, chunkFilePathSize);
  917. }
  918. break;
  919. case kPluginBridgeNonRtServerSetLatency:
  920. case kPluginBridgeNonRtServerSetParameterText:
  921. break;
  922. case kPluginBridgeNonRtServerReady:
  923. fInitiated = true;
  924. break;
  925. case kPluginBridgeNonRtServerSaved:
  926. break;
  927. case kPluginBridgeNonRtServerUiClosed:
  928. carla_stdout("got kPluginBridgeNonRtServerUiClosed, bridge closed cleanly?");
  929. pData->engine->callback(ENGINE_CALLBACK_UI_STATE_CHANGED, pData->id, 0, 0, 0.0f, nullptr);
  930. //fBridgeThread.signalThreadShouldExit();
  931. //handleProcessStopped();
  932. //fBridgeThread.stopThread(5000);
  933. break;
  934. case kPluginBridgeNonRtServerError: {
  935. // error
  936. const uint32_t errorSize(fShmNonRtServerControl.readUInt());
  937. char error[errorSize+1];
  938. carla_zeroChars(error, errorSize+1);
  939. fShmNonRtServerControl.readCustomData(error, errorSize);
  940. if (fInitiated)
  941. {
  942. pData->engine->callback(ENGINE_CALLBACK_ERROR, pData->id, 0, 0, 0.0f, error);
  943. // just in case
  944. pData->engine->setLastError(error);
  945. fInitError = true;
  946. }
  947. else
  948. {
  949. pData->engine->setLastError(error);
  950. fInitError = true;
  951. fInitiated = true;
  952. }
  953. } break;
  954. }
  955. }
  956. }
  957. // -------------------------------------------------------------------
  958. uintptr_t getUiBridgeProcessId() const noexcept override
  959. {
  960. return fBridgeThread.getProcessID();
  961. }
  962. // -------------------------------------------------------------------
  963. bool init(const char* const filename, const char* const name, const char* const label)
  964. {
  965. CARLA_SAFE_ASSERT_RETURN(pData->engine != nullptr, false);
  966. // ---------------------------------------------------------------
  967. // first checks
  968. if (pData->client != nullptr)
  969. {
  970. pData->engine->setLastError("Plugin client is already registered");
  971. return false;
  972. }
  973. if (filename == nullptr || filename[0] == '\0')
  974. {
  975. pData->engine->setLastError("null filename");
  976. return false;
  977. }
  978. if (label == nullptr || label[0] == '\0')
  979. {
  980. pData->engine->setLastError("null label");
  981. return false;
  982. }
  983. // ---------------------------------------------------------------
  984. // check setup
  985. if (std::strlen(label) != 6)
  986. {
  987. pData->engine->setLastError("invalid application setup received");
  988. return false;
  989. }
  990. for (int i=4; --i >= 0;) {
  991. CARLA_SAFE_ASSERT_RETURN(label[i] >= '0' && label[i] <= '0'+64, false);
  992. }
  993. for (int i=6; --i >= 4;) {
  994. CARLA_SAFE_ASSERT_RETURN(label[i] >= '0' && label[i] < '0'+0x4f, false);
  995. }
  996. fInfo.aIns = static_cast<uint8_t>(label[0] - '0');
  997. fInfo.aOuts = static_cast<uint8_t>(label[1] - '0');
  998. fInfo.mIns = static_cast<uint8_t>(carla_minPositive(label[2] - '0', 1));
  999. fInfo.mOuts = static_cast<uint8_t>(carla_minPositive(label[3] - '0', 1));
  1000. fInfo.setupLabel = label;
  1001. const int setupHints = label[5] - '0';
  1002. // ---------------------------------------------------------------
  1003. // set info
  1004. pData->filename = carla_strdup(filename);
  1005. if (name != nullptr && name[0] != '\0')
  1006. pData->name = pData->engine->getUniquePluginName(name);
  1007. else
  1008. pData->name = pData->engine->getUniquePluginName("Jack Application");
  1009. std::srand(static_cast<uint>(std::time(nullptr)));
  1010. // ---------------------------------------------------------------
  1011. // init sem/shm
  1012. if (! fShmAudioPool.initializeServer())
  1013. {
  1014. carla_stderr("Failed to initialize shared memory audio pool");
  1015. return false;
  1016. }
  1017. if (! fShmRtClientControl.initializeServer())
  1018. {
  1019. carla_stderr("Failed to initialize RT client control");
  1020. fShmAudioPool.clear();
  1021. return false;
  1022. }
  1023. if (! fShmNonRtClientControl.initializeServer())
  1024. {
  1025. carla_stderr("Failed to initialize Non-RT client control");
  1026. fShmRtClientControl.clear();
  1027. fShmAudioPool.clear();
  1028. return false;
  1029. }
  1030. if (! fShmNonRtServerControl.initializeServer())
  1031. {
  1032. carla_stderr("Failed to initialize Non-RT server control");
  1033. fShmNonRtClientControl.clear();
  1034. fShmRtClientControl.clear();
  1035. fShmAudioPool.clear();
  1036. return false;
  1037. }
  1038. // ---------------------------------------------------------------
  1039. // setup hints and options
  1040. // FIXME dryWet broken
  1041. pData->hints = PLUGIN_IS_BRIDGE | PLUGIN_OPTION_FIXED_BUFFERS;
  1042. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1043. pData->hints |= /*PLUGIN_CAN_DRYWET |*/ PLUGIN_CAN_VOLUME | PLUGIN_CAN_BALANCE;
  1044. #endif
  1045. //fInfo.optionsAvailable = optionAv;
  1046. if (setupHints & 0x1)
  1047. pData->hints |= PLUGIN_HAS_CUSTOM_UI;
  1048. // ---------------------------------------------------------------
  1049. // init bridge thread
  1050. {
  1051. char shmIdsStr[6*4+1];
  1052. carla_zeroChars(shmIdsStr, 6*4+1);
  1053. std::strncpy(shmIdsStr+6*0, &fShmAudioPool.filename[fShmAudioPool.filename.length()-6], 6);
  1054. std::strncpy(shmIdsStr+6*1, &fShmRtClientControl.filename[fShmRtClientControl.filename.length()-6], 6);
  1055. std::strncpy(shmIdsStr+6*2, &fShmNonRtClientControl.filename[fShmNonRtClientControl.filename.length()-6], 6);
  1056. std::strncpy(shmIdsStr+6*3, &fShmNonRtServerControl.filename[fShmNonRtServerControl.filename.length()-6], 6);
  1057. fBridgeThread.setData(shmIdsStr, label);
  1058. }
  1059. if (! restartBridgeThread())
  1060. return false;
  1061. // ---------------------------------------------------------------
  1062. // register client
  1063. if (pData->name == nullptr)
  1064. pData->name = pData->engine->getUniquePluginName("unknown");
  1065. pData->client = pData->engine->addClient(this);
  1066. if (pData->client == nullptr || ! pData->client->isOk())
  1067. {
  1068. pData->engine->setLastError("Failed to register plugin client");
  1069. return false;
  1070. }
  1071. return true;
  1072. }
  1073. private:
  1074. bool fInitiated;
  1075. bool fInitError;
  1076. bool fTimedOut;
  1077. bool fTimedError;
  1078. bool fProcCanceled;
  1079. uint fProcWaitTime;
  1080. int64_t fLastPingTime;
  1081. CarlaPluginJackThread fBridgeThread;
  1082. BridgeAudioPool fShmAudioPool;
  1083. BridgeRtClientControl fShmRtClientControl;
  1084. BridgeNonRtClientControl fShmNonRtClientControl;
  1085. BridgeNonRtServerControl fShmNonRtServerControl;
  1086. struct Info {
  1087. uint8_t aIns, aOuts;
  1088. uint8_t mIns, mOuts;
  1089. uint optionsAvailable;
  1090. CarlaString setupLabel;
  1091. std::vector<uint8_t> chunk;
  1092. Info()
  1093. : aIns(0),
  1094. aOuts(0),
  1095. mIns(0),
  1096. mOuts(0),
  1097. optionsAvailable(0),
  1098. setupLabel(),
  1099. chunk() {}
  1100. CARLA_DECLARE_NON_COPY_STRUCT(Info)
  1101. } fInfo;
  1102. void handleProcessStopped() noexcept
  1103. {
  1104. const bool wasActive = pData->active;
  1105. pData->active = false;
  1106. if (wasActive)
  1107. {
  1108. #if defined(HAVE_LIBLO) && ! defined(BUILD_BRIDGE)
  1109. if (pData->engine->isOscControlRegistered())
  1110. pData->engine->oscSend_control_set_parameter_value(pData->id, PARAMETER_ACTIVE, 0.0f);
  1111. pData->engine->callback(ENGINE_CALLBACK_PARAMETER_VALUE_CHANGED, pData->id, PARAMETER_ACTIVE, 0, 0.0f, nullptr);
  1112. #endif
  1113. }
  1114. if (pData->hints & PLUGIN_HAS_CUSTOM_UI)
  1115. pData->engine->callback(ENGINE_CALLBACK_UI_STATE_CHANGED, pData->id, 0, 0, 0.0f, nullptr);
  1116. }
  1117. void resizeAudioPool(const uint32_t bufferSize)
  1118. {
  1119. fShmAudioPool.resize(bufferSize, static_cast<uint32_t>(fInfo.aIns+fInfo.aOuts), 0);
  1120. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientSetAudioPool);
  1121. fShmRtClientControl.writeULong(static_cast<uint64_t>(fShmAudioPool.dataSize));
  1122. fShmRtClientControl.commitWrite();
  1123. waitForClient("resize-pool", 5000);
  1124. }
  1125. void waitForClient(const char* const action, const uint msecs)
  1126. {
  1127. CARLA_SAFE_ASSERT_RETURN(! fTimedOut,);
  1128. CARLA_SAFE_ASSERT_RETURN(! fTimedError,);
  1129. if (fShmRtClientControl.waitForClient(msecs))
  1130. return;
  1131. fTimedOut = true;
  1132. carla_stderr2("waitForClient(%s) timed out", action);
  1133. }
  1134. bool restartBridgeThread()
  1135. {
  1136. fInitiated = false;
  1137. fInitError = false;
  1138. fTimedError = false;
  1139. // reset memory
  1140. fProcCanceled = false;
  1141. fShmRtClientControl.data->procFlags = 0;
  1142. carla_zeroStruct(fShmRtClientControl.data->timeInfo);
  1143. carla_zeroBytes(fShmRtClientControl.data->midiOut, kBridgeRtClientDataMidiOutSize);
  1144. fShmRtClientControl.clearData();
  1145. fShmNonRtClientControl.clearData();
  1146. fShmNonRtServerControl.clearData();
  1147. // initial values
  1148. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientVersion);
  1149. fShmNonRtClientControl.writeUInt(CARLA_PLUGIN_BRIDGE_API_VERSION);
  1150. fShmNonRtClientControl.writeUInt(static_cast<uint32_t>(sizeof(BridgeRtClientData)));
  1151. fShmNonRtClientControl.writeUInt(static_cast<uint32_t>(sizeof(BridgeNonRtClientData)));
  1152. fShmNonRtClientControl.writeUInt(static_cast<uint32_t>(sizeof(BridgeNonRtServerData)));
  1153. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientInitialSetup);
  1154. fShmNonRtClientControl.writeUInt(pData->engine->getBufferSize());
  1155. fShmNonRtClientControl.writeDouble(pData->engine->getSampleRate());
  1156. fShmNonRtClientControl.commitWrite();
  1157. if (fShmAudioPool.dataSize != 0)
  1158. {
  1159. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientSetAudioPool);
  1160. fShmRtClientControl.writeULong(static_cast<uint64_t>(fShmAudioPool.dataSize));
  1161. fShmRtClientControl.commitWrite();
  1162. }
  1163. else
  1164. {
  1165. // testing dummy message
  1166. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientNull);
  1167. fShmRtClientControl.commitWrite();
  1168. }
  1169. fBridgeThread.startThread();
  1170. fLastPingTime = Time::currentTimeMillis();
  1171. CARLA_SAFE_ASSERT(fLastPingTime > 0);
  1172. static bool sFirstInit = true;
  1173. int64_t timeoutEnd = 5000;
  1174. if (sFirstInit)
  1175. timeoutEnd *= 2;
  1176. sFirstInit = false;
  1177. const bool needsEngineIdle = pData->engine->getType() != kEngineTypePlugin;
  1178. for (; Time::currentTimeMillis() < fLastPingTime + timeoutEnd && fBridgeThread.isThreadRunning();)
  1179. {
  1180. pData->engine->callback(ENGINE_CALLBACK_IDLE, 0, 0, 0, 0.0f, nullptr);
  1181. if (needsEngineIdle)
  1182. pData->engine->idle();
  1183. idle();
  1184. if (fInitiated)
  1185. break;
  1186. if (pData->engine->isAboutToClose())
  1187. break;
  1188. carla_msleep(20);
  1189. }
  1190. fLastPingTime = -1;
  1191. if (fInitError || ! fInitiated)
  1192. {
  1193. fBridgeThread.stopThread(6000);
  1194. if (! fInitError)
  1195. pData->engine->setLastError("Timeout while waiting for a response from plugin-bridge\n"
  1196. "(or the plugin crashed on initialization?)");
  1197. return false;
  1198. }
  1199. return true;
  1200. }
  1201. CARLA_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(CarlaPluginJack)
  1202. };
  1203. CARLA_BACKEND_END_NAMESPACE
  1204. #endif // CARLA_OS_LINUX
  1205. // -------------------------------------------------------------------------------------------------------------------
  1206. CARLA_BACKEND_START_NAMESPACE
  1207. CarlaPlugin* CarlaPlugin::newJackApp(const Initializer& init)
  1208. {
  1209. carla_debug("CarlaPlugin::newJackApp({%p, \"%s\", \"%s\", \"%s\"})", init.engine, init.filename, init.name, init.label);
  1210. #ifdef CARLA_OS_LINUX
  1211. CarlaPluginJack* const plugin(new CarlaPluginJack(init.engine, init.id));
  1212. if (! plugin->init(init.filename, init.name, init.label))
  1213. {
  1214. delete plugin;
  1215. return nullptr;
  1216. }
  1217. return plugin;
  1218. #else
  1219. init.engine->setLastError("JACK Application support not available");
  1220. return nullptr;
  1221. #endif
  1222. }
  1223. CARLA_BACKEND_END_NAMESPACE
  1224. // -------------------------------------------------------------------------------------------------------------------