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.

2067 lines
70KB

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