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.

1734 lines
57KB

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