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.

2069 lines
70KB

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