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. // SPDX-FileCopyrightText: 2011-2025 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. CARLA_BACKEND_START_NAMESPACE
  31. static size_t safe_rand(const size_t limit)
  32. {
  33. const int r = std::rand();
  34. CARLA_SAFE_ASSERT_RETURN(r >= 0, 0);
  35. return static_cast<uint>(r) % limit;
  36. }
  37. // -------------------------------------------------------------------------------------------------------------------
  38. // Fallback data
  39. static const ExternalMidiNote kExternalMidiNoteFallback = { -1, 0, 0 };
  40. // -------------------------------------------------------------------------------------------------------------------
  41. struct Announcer {
  42. virtual ~Announcer() {}
  43. virtual void nsmAnnounced(bool hasGui) = 0;
  44. };
  45. class CarlaPluginJackThread : public CarlaThread
  46. {
  47. public:
  48. CarlaPluginJackThread(Announcer* const ann, CarlaEngine* const engine, CarlaPlugin* const plugin) noexcept
  49. : CarlaThread("CarlaPluginJackThread"),
  50. kAnnouncer(ann),
  51. kEngine(engine),
  52. kPlugin(plugin),
  53. fShmIds(),
  54. fSetupLabel(),
  55. #ifdef HAVE_LIBLO
  56. fOscClientAddress(nullptr),
  57. fOscServer(nullptr),
  58. fHasOptionalGui(false),
  59. fProject(),
  60. #endif
  61. fProcess() {}
  62. void setData(const char* const shmIds, const char* const setupLabel) noexcept
  63. {
  64. CARLA_SAFE_ASSERT_RETURN(shmIds != nullptr && shmIds[0] != '\0',);
  65. CARLA_SAFE_ASSERT_RETURN(setupLabel != nullptr && setupLabel[0] != '\0',);
  66. CARLA_SAFE_ASSERT(! isThreadRunning());
  67. fShmIds = shmIds;
  68. fSetupLabel = setupLabel;
  69. }
  70. uintptr_t getProcessID() const noexcept
  71. {
  72. CARLA_SAFE_ASSERT_RETURN(fProcess != nullptr, 0);
  73. return (uintptr_t)fProcess->getPID();
  74. }
  75. #ifdef HAVE_LIBLO
  76. void nsmSave(const char* const setupLabel)
  77. {
  78. if (fOscClientAddress == nullptr)
  79. return;
  80. if (fSetupLabel != setupLabel)
  81. fSetupLabel = setupLabel;
  82. maybeOpenFirstTime(false);
  83. lo_send_from(fOscClientAddress, fOscServer, LO_TT_IMMEDIATE, "/nsm/client/save", "");
  84. }
  85. bool nsmShowGui(const bool yesNo)
  86. {
  87. if (fOscClientAddress == nullptr || ! fHasOptionalGui)
  88. return false;
  89. lo_send_from(fOscClientAddress, fOscServer, LO_TT_IMMEDIATE,
  90. yesNo ? "/nsm/client/show_optional_gui"
  91. : "/nsm/client/hide_optional_gui", "");
  92. return true;
  93. }
  94. #endif
  95. char* getEnvVarsToExport()
  96. {
  97. const EngineOptions& options(kEngine->getOptions());
  98. CarlaString binaryDir(options.binaryDir);
  99. #ifdef HAVE_LIBLO
  100. const int sessionManager = fSetupLabel[4U] - '0';
  101. #endif
  102. CarlaString ret;
  103. #ifdef CARLA_OS_MAC
  104. ret += "export DYLD_LIBRARY_PATH=" + binaryDir + "/jack\n";
  105. ret += "export DYLD_INSERT_LIBRARIES=" + binaryDir + "/libcarla_interposer-jack-x11.dylib\n";
  106. ret += "export DYLD_FORCE_FLAT_NAMESPACE=1\n";
  107. #else
  108. ret += "export LD_LIBRARY_PATH=" + binaryDir + "/jack\n";
  109. ret += "export LD_PRELOAD=" + binaryDir + "/libcarla_interposer-jack-x11.so\n";
  110. #endif
  111. #ifdef HAVE_LIBLO
  112. if (sessionManager == LIBJACK_SESSION_MANAGER_NSM)
  113. {
  114. for (int i=50; fOscServer == nullptr && --i>=0;)
  115. d_msleep(100);
  116. ret += "export NSM_URL=";
  117. ret += lo_server_get_url(fOscServer);
  118. ret += "\n";
  119. }
  120. #endif
  121. if (kPlugin->getHints() & PLUGIN_HAS_CUSTOM_UI)
  122. ret += "export CARLA_FRONTEND_WIN_ID=" + CarlaString(options.frontendWinId) + "\n";
  123. ret += "export CARLA_LIBJACK_SETUP=" + fSetupLabel + "\n";
  124. ret += "export CARLA_SHM_IDS=" + fShmIds + "\n";
  125. return ret.releaseBufferPointer();
  126. }
  127. protected:
  128. #ifdef HAVE_LIBLO
  129. static void _osc_error_handler(int num, const char* msg, const char* path)
  130. {
  131. carla_stderr2("CarlaPluginJackThread::_osc_error_handler(%i, \"%s\", \"%s\")", num, msg, path);
  132. }
  133. static int _broadcast_handler(const char* path, const char* types, lo_arg** argv, int argc, lo_message msg, void* data)
  134. {
  135. CARLA_SAFE_ASSERT_RETURN(data != nullptr, 0);
  136. carla_stdout("CarlaPluginJackThread::_broadcast_handler(%s, %s, %p, %i)", path, types, argv, argc);
  137. return ((CarlaPluginJackThread*)data)->handleBroadcast(path, types, argv, msg);
  138. }
  139. void maybeOpenFirstTime(const bool announced)
  140. {
  141. if (fSetupLabel.length() <= 6)
  142. return;
  143. if ((announced || fProject.path.isEmpty()) && fProject.init(kPlugin->getName(),
  144. kEngine->getCurrentProjectFolder(),
  145. &fSetupLabel[6U]))
  146. {
  147. carla_stdout("Sending open signal %s %s %s",
  148. fProject.path.buffer(), fProject.display.buffer(), fProject.clientName.buffer());
  149. lo_send_from(fOscClientAddress, fOscServer, LO_TT_IMMEDIATE, "/nsm/client/open", "sss",
  150. fProject.path.buffer(), fProject.display.buffer(), fProject.clientName.buffer());
  151. }
  152. }
  153. int handleBroadcast(const char* path, const char* types, lo_arg** argv, lo_message msg)
  154. {
  155. if (std::strcmp(path, "/nsm/server/announce") == 0)
  156. {
  157. CARLA_SAFE_ASSERT_RETURN(std::strcmp(types, "sssiii") == 0, 0);
  158. const lo_address msgAddress(lo_message_get_source(msg));
  159. CARLA_SAFE_ASSERT_RETURN(msgAddress != nullptr, 0);
  160. char* const msgURL(lo_address_get_url(msgAddress));
  161. CARLA_SAFE_ASSERT_RETURN(msgURL != nullptr, 0);
  162. if (fOscClientAddress != nullptr)
  163. lo_address_free(fOscClientAddress);
  164. fOscClientAddress = lo_address_new_from_url(msgURL);
  165. CARLA_SAFE_ASSERT_RETURN(fOscClientAddress != nullptr, 0);
  166. fProject.appName = &argv[0]->s;
  167. fHasOptionalGui = std::strstr(&argv[1]->s, ":optional-gui:") != nullptr;
  168. kAnnouncer->nsmAnnounced(fHasOptionalGui);
  169. static const char* const featuresG = ":server-control:optional-gui:";
  170. static const char* const featuresN = ":server-control:";
  171. static const char* const method = "/nsm/server/announce";
  172. static const char* const message = "Howdy, what took you so long?";
  173. static const char* const smName = "Carla";
  174. const char* const features = ((fSetupLabel[5U] - '0') & LIBJACK_FLAG_CONTROL_WINDOW)
  175. ? featuresG : featuresN;
  176. lo_send_from(fOscClientAddress, fOscServer, LO_TT_IMMEDIATE, "/reply", "ssss",
  177. method, message, smName, features);
  178. maybeOpenFirstTime(true);
  179. return 0;
  180. }
  181. CARLA_SAFE_ASSERT_RETURN(fOscClientAddress != nullptr, 0);
  182. if (std::strcmp(path, "/reply") == 0)
  183. {
  184. CARLA_SAFE_ASSERT_RETURN(std::strcmp(types, "ss") == 0, 0);
  185. const char* const method = &argv[0]->s;
  186. const char* const message = &argv[1]->s;
  187. carla_stdout("Got reply of '%s' as '%s'", method, message);
  188. if (std::strcmp(method, "/nsm/client/open") == 0)
  189. {
  190. carla_stdout("Sending 'Session is loaded' to %s", fProject.appName.buffer());
  191. lo_send_from(fOscClientAddress, fOscServer, LO_TT_IMMEDIATE, "/nsm/client/session_is_loaded", "");
  192. }
  193. }
  194. else if (std::strcmp(path, "/nsm/client/gui_is_shown") == 0)
  195. {
  196. CARLA_SAFE_ASSERT_RETURN(std::strcmp(types, "") == 0, 0);
  197. kEngine->callback(true, true,
  198. ENGINE_CALLBACK_UI_STATE_CHANGED,
  199. kPlugin->getId(),
  200. 1,
  201. 0, 0, 0.0f, nullptr);
  202. }
  203. else if (std::strcmp(path, "/nsm/client/gui_is_hidden") == 0)
  204. {
  205. CARLA_SAFE_ASSERT_RETURN(std::strcmp(types, "") == 0, 0);
  206. kEngine->callback(true, true,
  207. ENGINE_CALLBACK_UI_STATE_CHANGED,
  208. kPlugin->getId(),
  209. 0,
  210. 0, 0, 0.0f, nullptr);
  211. }
  212. // special messages
  213. else if (std::strcmp(path, "/nsm/gui/client/save") == 0)
  214. {
  215. CARLA_SAFE_ASSERT_RETURN(std::strcmp(types, "s") == 0, 0);
  216. lo_send_from(fOscClientAddress, fOscServer, LO_TT_IMMEDIATE, "/nsm/client/save", "");
  217. }
  218. else if (std::strcmp(path, "/nsm/server/stop") == 0)
  219. {
  220. CARLA_SAFE_ASSERT_RETURN(std::strcmp(types, "s") == 0, 0);
  221. lo_send_from(fOscClientAddress, fOscServer, LO_TT_IMMEDIATE, "/nsm/client/hide_optional_gui", "");
  222. kEngine->callback(true, true,
  223. ENGINE_CALLBACK_UI_STATE_CHANGED,
  224. kPlugin->getId(),
  225. 0,
  226. 0, 0, 0.0f, nullptr);
  227. }
  228. return 0;
  229. }
  230. #endif
  231. void run()
  232. {
  233. #ifdef HAVE_LIBLO
  234. if (fOscClientAddress != nullptr)
  235. {
  236. lo_address_free(fOscClientAddress);
  237. fOscClientAddress = nullptr;
  238. }
  239. const int sessionManager = fSetupLabel[4U] - '0';
  240. if (sessionManager == LIBJACK_SESSION_MANAGER_NSM)
  241. {
  242. // NSM support
  243. fOscServer = lo_server_new_with_proto(nullptr, LO_UDP, _osc_error_handler);
  244. CARLA_SAFE_ASSERT_RETURN(fOscServer != nullptr,);
  245. lo_server_add_method(fOscServer, nullptr, nullptr, _broadcast_handler, this);
  246. }
  247. #endif
  248. const bool externalProcess = ((fSetupLabel[5U] - '0') & LIBJACK_FLAG_EXTERNAL_START)
  249. && ! kEngine->isLoadingProject();
  250. if (! externalProcess)
  251. {
  252. if (fProcess == nullptr)
  253. {
  254. fProcess = new ChildProcess();
  255. }
  256. else if (fProcess->isRunning())
  257. {
  258. carla_stderr("CarlaPluginJackThread::run() - already running");
  259. }
  260. water::String name(kPlugin->getName());
  261. water::String filename(kPlugin->getFilename());
  262. if (name.isEmpty())
  263. name = "(none)";
  264. CARLA_SAFE_ASSERT_RETURN(filename.isNotEmpty(),);
  265. water::StringArray arguments;
  266. // binary
  267. arguments.addTokens(filename, true);
  268. const EngineOptions& options(kEngine->getOptions());
  269. char winIdStr[STR_MAX+1];
  270. std::snprintf(winIdStr, STR_MAX, P_UINTPTR, options.frontendWinId);
  271. winIdStr[STR_MAX] = '\0';
  272. const CarlaString libjackdir(CarlaString(options.binaryDir) + "/jack");
  273. #ifdef CARLA_OS_MAC
  274. const CarlaString ldpreload(CarlaString(options.binaryDir) + "/libcarla_interposer-jack-x11.dylib");
  275. #else
  276. const CarlaString ldpreload(CarlaString(options.binaryDir) + "/libcarla_interposer-jack-x11.so");
  277. #endif
  278. const ScopedEngineEnvironmentLocker _seel(kEngine);
  279. #ifdef CARLA_OS_MAC
  280. const CarlaScopedEnvVar sev2("DYLD_LIBRARY_PATH", libjackdir.buffer());
  281. const CarlaScopedEnvVar sev1("DYLD_INSERT_LIBRARIES", ldpreload.isNotEmpty() ? ldpreload.buffer() : nullptr);
  282. const CarlaScopedEnvVar sev0("DYLD_FORCE_FLAT_NAMESPACE", "1");
  283. #else
  284. const CarlaScopedEnvVar sev2("LD_LIBRARY_PATH", libjackdir.buffer());
  285. const CarlaScopedEnvVar sev1("LD_PRELOAD", ldpreload.isNotEmpty() ? ldpreload.buffer() : nullptr);
  286. #endif
  287. #ifdef HAVE_LIBLO
  288. const CarlaScopedEnvVar sev3("NSM_URL", lo_server_get_url(fOscServer));
  289. #endif
  290. if (kPlugin->getHints() & PLUGIN_HAS_CUSTOM_UI)
  291. carla_setenv("CARLA_FRONTEND_WIN_ID", winIdStr);
  292. else
  293. carla_unsetenv("CARLA_FRONTEND_WIN_ID");
  294. carla_setenv("CARLA_LIBJACK_SETUP", fSetupLabel.buffer());
  295. carla_setenv("CARLA_SHM_IDS", fShmIds.buffer());
  296. if (! fProcess->start(arguments))
  297. {
  298. carla_stdout("failed!");
  299. fProcess = nullptr;
  300. return;
  301. }
  302. }
  303. for (; (externalProcess || fProcess->isRunning()) && ! shouldThreadExit();)
  304. {
  305. #ifdef HAVE_LIBLO
  306. if (sessionManager == LIBJACK_SESSION_MANAGER_NSM)
  307. {
  308. lo_server_recv_noblock(fOscServer, 50);
  309. }
  310. else
  311. #endif
  312. {
  313. d_msleep(50);
  314. }
  315. }
  316. #ifdef HAVE_LIBLO
  317. if (sessionManager == LIBJACK_SESSION_MANAGER_NSM)
  318. {
  319. lo_server_free(fOscServer);
  320. fOscServer = nullptr;
  321. if (fOscClientAddress != nullptr)
  322. {
  323. lo_address_free(fOscClientAddress);
  324. fOscClientAddress = nullptr;
  325. }
  326. }
  327. #endif
  328. if (! externalProcess)
  329. {
  330. // we only get here if bridge crashed or thread asked to exit
  331. if (fProcess->isRunning() && shouldThreadExit())
  332. {
  333. fProcess->waitForProcessToFinish(2000);
  334. if (fProcess->isRunning())
  335. {
  336. carla_stdout("CarlaPluginJackThread::run() - application refused to close, force kill now");
  337. fProcess->kill();
  338. }
  339. }
  340. else
  341. {
  342. // forced quit, may have crashed
  343. if (fProcess->getExitCodeAndClearPID() != 0)
  344. {
  345. carla_stderr("CarlaPluginJackThread::run() - application crashed");
  346. CarlaString errorString("Plugin '" + CarlaString(kPlugin->getName()) + "' has crashed!\n"
  347. "Saving now will lose its current settings.\n"
  348. "Please remove this plugin, and not rely on it from this point.");
  349. kEngine->callback(true, true,
  350. ENGINE_CALLBACK_ERROR,
  351. kPlugin->getId(),
  352. 0, 0, 0, 0.0f,
  353. errorString);
  354. }
  355. }
  356. }
  357. fProcess = nullptr;
  358. }
  359. private:
  360. Announcer* const kAnnouncer;
  361. CarlaEngine* const kEngine;
  362. CarlaPlugin* const kPlugin;
  363. CarlaString fShmIds;
  364. CarlaString fSetupLabel;
  365. #ifdef HAVE_LIBLO
  366. lo_address fOscClientAddress;
  367. lo_server fOscServer;
  368. bool fHasOptionalGui;
  369. struct ProjectData {
  370. CarlaString appName;
  371. CarlaString path;
  372. CarlaString display;
  373. CarlaString clientName;
  374. ProjectData()
  375. : appName(),
  376. path(),
  377. display(),
  378. clientName() {}
  379. bool init(const char* const pluginName,
  380. const char* const engineProjectFolder,
  381. const char* const uniqueCodeID)
  382. {
  383. CARLA_SAFE_ASSERT_RETURN(engineProjectFolder != nullptr && engineProjectFolder[0] != '\0', false);
  384. CARLA_SAFE_ASSERT_RETURN(uniqueCodeID != nullptr && uniqueCodeID[0] != '\0', false);
  385. CARLA_SAFE_ASSERT_RETURN(appName.isNotEmpty(), false);
  386. CarlaString child(pluginName);
  387. child += ".";
  388. child += uniqueCodeID;
  389. const File file(File(engineProjectFolder).getChildFile(child));
  390. clientName = appName + "." + uniqueCodeID;
  391. path = file.getFullPathName().toRawUTF8();
  392. display = file.getFileNameWithoutExtension().toRawUTF8();
  393. return true;
  394. }
  395. CARLA_DECLARE_NON_COPYABLE(ProjectData)
  396. } fProject;
  397. #endif
  398. CarlaScopedPointer<ChildProcess> fProcess;
  399. CARLA_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(CarlaPluginJackThread)
  400. };
  401. // -------------------------------------------------------------------------------------------------------------------
  402. class CarlaPluginJack : public CarlaPlugin,
  403. public Announcer
  404. {
  405. public:
  406. CarlaPluginJack(CarlaEngine* const engine, const uint id)
  407. : CarlaPlugin(engine, id),
  408. fInitiated(false),
  409. fInitError(false),
  410. fTimedOut(false),
  411. fTimedError(false),
  412. fProcCanceled(false),
  413. fBufferSize(engine->getBufferSize()),
  414. fProcWaitTime(0),
  415. fSetupHints(0x0),
  416. fBridgeThread(this, engine, this),
  417. fShmAudioPool(),
  418. fShmRtClientControl(),
  419. fShmNonRtClientControl(),
  420. fShmNonRtServerControl(),
  421. fInfo()
  422. {
  423. carla_debug("CarlaPluginJack::CarlaPluginJack(%p, %i)", engine, id);
  424. pData->hints |= PLUGIN_IS_BRIDGE;
  425. }
  426. ~CarlaPluginJack() override
  427. {
  428. carla_debug("CarlaPluginJack::~CarlaPluginJack()");
  429. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  430. // close UI
  431. if (pData->hints & PLUGIN_HAS_CUSTOM_UI)
  432. pData->transientTryCounter = 0;
  433. #endif
  434. pData->singleMutex.lock();
  435. pData->masterMutex.lock();
  436. if (pData->client != nullptr && pData->client->isActive())
  437. pData->client->deactivate(true);
  438. if (pData->active)
  439. {
  440. deactivate();
  441. pData->active = false;
  442. }
  443. if (fBridgeThread.isThreadRunning())
  444. {
  445. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientQuit);
  446. fShmRtClientControl.commitWrite();
  447. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientQuit);
  448. fShmNonRtClientControl.commitWrite();
  449. if (! fTimedOut)
  450. waitForClient("stopping", 3000);
  451. }
  452. fBridgeThread.stopThread(3000);
  453. fShmNonRtServerControl.clear();
  454. fShmNonRtClientControl.clear();
  455. fShmRtClientControl.clear();
  456. fShmAudioPool.clear();
  457. clearBuffers();
  458. fInfo.chunk.clear();
  459. }
  460. // -------------------------------------------------------------------
  461. void nsmAnnounced(bool hasGui) override
  462. {
  463. if (hasGui || (pData->hints & PLUGIN_HAS_CUSTOM_UI) == 0x0)
  464. return;
  465. {
  466. const CarlaMutexLocker _cml(fShmNonRtClientControl.mutex);
  467. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientShowUI);
  468. fShmNonRtClientControl.commitWrite();
  469. }
  470. pData->engine->callback(true, true,
  471. ENGINE_CALLBACK_UI_STATE_CHANGED,
  472. pData->id,
  473. 1,
  474. 0, 0, 0.0f, nullptr);
  475. }
  476. // -------------------------------------------------------------------
  477. // Information (base)
  478. PluginType getType() const noexcept override
  479. {
  480. return PLUGIN_JACK;
  481. }
  482. PluginCategory getCategory() const noexcept override
  483. {
  484. return PLUGIN_CATEGORY_NONE;
  485. }
  486. // -------------------------------------------------------------------
  487. // Information (count)
  488. uint32_t getMidiInCount() const noexcept override
  489. {
  490. return fInfo.mIns;
  491. }
  492. uint32_t getMidiOutCount() const noexcept override
  493. {
  494. return fInfo.mOuts;
  495. }
  496. // -------------------------------------------------------------------
  497. // Information (current data)
  498. // -------------------------------------------------------------------
  499. // Information (per-plugin data)
  500. uint getOptionsAvailable() const noexcept override
  501. {
  502. uint options = 0x0;
  503. if (fInfo.mIns > 0)
  504. {
  505. options |= PLUGIN_OPTION_SEND_CONTROL_CHANGES;
  506. options |= PLUGIN_OPTION_SEND_CHANNEL_PRESSURE;
  507. options |= PLUGIN_OPTION_SEND_NOTE_AFTERTOUCH;
  508. options |= PLUGIN_OPTION_SEND_PITCHBEND;
  509. options |= PLUGIN_OPTION_SEND_ALL_SOUND_OFF;
  510. options |= PLUGIN_OPTION_SEND_PROGRAM_CHANGES;
  511. options |= PLUGIN_OPTION_SKIP_SENDING_NOTES;
  512. }
  513. return options;
  514. }
  515. bool getLabel(char* const strBuf) const noexcept override
  516. {
  517. std::strncpy(strBuf, fInfo.setupLabel, STR_MAX);
  518. return true;
  519. }
  520. bool getMaker(char* const) const noexcept override
  521. {
  522. return false;
  523. }
  524. bool getCopyright(char* const) const noexcept override
  525. {
  526. return false;
  527. }
  528. bool getRealName(char* const strBuf) const noexcept override
  529. {
  530. // FIXME
  531. std::strncpy(strBuf, "Carla's libjack", STR_MAX);
  532. return true;
  533. }
  534. // -------------------------------------------------------------------
  535. // Set data (state)
  536. void prepareForSave(bool) noexcept override
  537. {
  538. #ifdef HAVE_LIBLO
  539. if (fInfo.setupLabel.length() == 6)
  540. setupUniqueProjectID();
  541. #endif
  542. {
  543. const CarlaMutexLocker _cml(fShmNonRtClientControl.mutex);
  544. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientPrepareForSave);
  545. fShmNonRtClientControl.commitWrite();
  546. }
  547. #ifdef HAVE_LIBLO
  548. fBridgeThread.nsmSave(fInfo.setupLabel);
  549. #endif
  550. }
  551. // -------------------------------------------------------------------
  552. // Set data (internal stuff)
  553. void setOption(const uint option, const bool yesNo, const bool sendCallback) override
  554. {
  555. {
  556. const CarlaMutexLocker _cml(fShmNonRtClientControl.mutex);
  557. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientSetOption);
  558. fShmNonRtClientControl.writeUInt(option);
  559. fShmNonRtClientControl.writeBool(yesNo);
  560. fShmNonRtClientControl.commitWrite();
  561. }
  562. CarlaPlugin::setOption(option, yesNo, sendCallback);
  563. }
  564. void setCtrlChannel(const int8_t channel, const bool sendOsc, const bool sendCallback) noexcept override
  565. {
  566. CARLA_SAFE_ASSERT_RETURN(sendOsc || sendCallback,); // never call this from RT
  567. {
  568. const CarlaMutexLocker _cml(fShmNonRtClientControl.mutex);
  569. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientSetCtrlChannel);
  570. fShmNonRtClientControl.writeShort(channel);
  571. fShmNonRtClientControl.commitWrite();
  572. }
  573. CarlaPlugin::setCtrlChannel(channel, sendOsc, sendCallback);
  574. }
  575. // -------------------------------------------------------------------
  576. // Set data (plugin-specific stuff)
  577. void setCustomData(const char* const type, const char* const key, const char* const value, const bool sendGui) override
  578. {
  579. CARLA_SAFE_ASSERT_RETURN(type != nullptr && type[0] != '\0',);
  580. CARLA_SAFE_ASSERT_RETURN(key != nullptr && key[0] != '\0',);
  581. CARLA_SAFE_ASSERT_RETURN(value != nullptr,);
  582. if (std::strcmp(type, CUSTOM_DATA_TYPE_PROPERTY) == 0)
  583. return CarlaPlugin::setCustomData(type, key, value, sendGui);
  584. if (std::strcmp(type, CUSTOM_DATA_TYPE_STRING) == 0 && std::strcmp(key, "__CarlaPingOnOff__") == 0)
  585. {
  586. #if 0
  587. const CarlaMutexLocker _cml(fShmNonRtClientControl.mutex);
  588. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientPingOnOff);
  589. fShmNonRtClientControl.writeBool(std::strcmp(value, "true") == 0);
  590. fShmNonRtClientControl.commitWrite();
  591. #endif
  592. return;
  593. }
  594. CarlaPlugin::setCustomData(type, key, value, sendGui);
  595. }
  596. // -------------------------------------------------------------------
  597. // Set ui stuff
  598. void showCustomUI(const bool yesNo) override
  599. {
  600. if (yesNo && ! fBridgeThread.isThreadRunning()) {
  601. CARLA_SAFE_ASSERT_RETURN(restartBridgeThread(),);
  602. }
  603. #ifdef HAVE_LIBLO
  604. if (! fBridgeThread.nsmShowGui(yesNo))
  605. #endif
  606. {
  607. const CarlaMutexLocker _cml(fShmNonRtClientControl.mutex);
  608. fShmNonRtClientControl.writeOpcode(yesNo ? kPluginBridgeNonRtClientShowUI : kPluginBridgeNonRtClientHideUI);
  609. fShmNonRtClientControl.commitWrite();
  610. }
  611. }
  612. void idle() override
  613. {
  614. if (fBridgeThread.isThreadRunning())
  615. {
  616. if (fInitiated && fTimedOut && pData->active)
  617. setActive(false, true, true);
  618. {
  619. const CarlaMutexLocker _cml(fShmNonRtClientControl.mutex);
  620. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientPing);
  621. fShmNonRtClientControl.commitWrite();
  622. }
  623. try {
  624. handleNonRtData();
  625. } CARLA_SAFE_EXCEPTION("handleNonRtData");
  626. }
  627. else if (fInitiated)
  628. {
  629. fTimedOut = true;
  630. fTimedError = true;
  631. fInitiated = false;
  632. handleProcessStopped();
  633. }
  634. else if (fProcCanceled)
  635. {
  636. handleProcessStopped();
  637. fProcCanceled = false;
  638. }
  639. CarlaPlugin::idle();
  640. }
  641. // -------------------------------------------------------------------
  642. // Plugin state
  643. void reload() override
  644. {
  645. CARLA_SAFE_ASSERT_RETURN(pData->engine != nullptr,);
  646. carla_debug("CarlaPluginJack::reload() - start");
  647. const EngineProcessMode processMode(pData->engine->getProccessMode());
  648. // Safely disable plugin for reload
  649. const ScopedDisabler sd(this);
  650. // cleanup of previous data
  651. pData->audioIn.clear();
  652. pData->audioOut.clear();
  653. pData->event.clear();
  654. bool needsCtrlIn, needsCtrlOut;
  655. needsCtrlIn = needsCtrlOut = false;
  656. if (fInfo.aIns > 0)
  657. {
  658. pData->audioIn.createNew(fInfo.aIns);
  659. }
  660. if (fInfo.aOuts > 0)
  661. {
  662. pData->audioOut.createNew(fInfo.aOuts);
  663. needsCtrlIn = true;
  664. }
  665. if (fInfo.mIns > 0)
  666. needsCtrlIn = true;
  667. if (fInfo.mOuts > 0)
  668. needsCtrlOut = true;
  669. const uint portNameSize(pData->engine->getMaxPortNameSize());
  670. CarlaString portName;
  671. // Audio Ins
  672. for (uint8_t j=0; j < fInfo.aIns; ++j)
  673. {
  674. portName.clear();
  675. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  676. {
  677. portName = pData->name;
  678. portName += ":";
  679. }
  680. if (fInfo.aIns > 1)
  681. {
  682. portName += "audio_in_";
  683. portName += CarlaString(j+1);
  684. }
  685. else
  686. {
  687. portName += "audio_in";
  688. }
  689. portName.truncate(portNameSize);
  690. pData->audioIn.ports[j].port = (CarlaEngineAudioPort*)pData->client->addPort(kEnginePortTypeAudio, portName, true, j);
  691. pData->audioIn.ports[j].rindex = j;
  692. }
  693. // Audio Outs
  694. for (uint8_t j=0; j < fInfo.aOuts; ++j)
  695. {
  696. portName.clear();
  697. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  698. {
  699. portName = pData->name;
  700. portName += ":";
  701. }
  702. if (fInfo.aOuts > 1)
  703. {
  704. portName += "audio_out_";
  705. portName += CarlaString(j+1);
  706. }
  707. else
  708. {
  709. portName += "audio_out";
  710. }
  711. portName.truncate(portNameSize);
  712. pData->audioOut.ports[j].port = (CarlaEngineAudioPort*)pData->client->addPort(kEnginePortTypeAudio, portName, false, j);
  713. pData->audioOut.ports[j].rindex = j;
  714. }
  715. if (needsCtrlIn)
  716. {
  717. portName.clear();
  718. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  719. {
  720. portName = pData->name;
  721. portName += ":";
  722. }
  723. portName += "event-in";
  724. portName.truncate(portNameSize);
  725. pData->event.portIn = (CarlaEngineEventPort*)pData->client->addPort(kEnginePortTypeEvent, portName, true, 0);
  726. }
  727. if (needsCtrlOut)
  728. {
  729. portName.clear();
  730. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  731. {
  732. portName = pData->name;
  733. portName += ":";
  734. }
  735. portName += "event-out";
  736. portName.truncate(portNameSize);
  737. pData->event.portOut = (CarlaEngineEventPort*)pData->client->addPort(kEnginePortTypeEvent, portName, false, 0);
  738. }
  739. // extra plugin hints
  740. pData->extraHints = 0x0;
  741. if (fInfo.mIns > 0)
  742. pData->extraHints |= PLUGIN_EXTRA_HINT_HAS_MIDI_IN;
  743. if (fInfo.mOuts > 0)
  744. pData->extraHints |= PLUGIN_EXTRA_HINT_HAS_MIDI_OUT;
  745. bufferSizeChanged(pData->engine->getBufferSize());
  746. reloadPrograms(true);
  747. carla_debug("CarlaPluginJack::reload() - end");
  748. }
  749. // -------------------------------------------------------------------
  750. // Plugin processing
  751. void activate() noexcept override
  752. {
  753. if (! fBridgeThread.isThreadRunning())
  754. {
  755. CARLA_SAFE_ASSERT_RETURN(restartBridgeThread(),);
  756. }
  757. CARLA_SAFE_ASSERT_RETURN(! fTimedError,);
  758. {
  759. const CarlaMutexLocker _cml(fShmNonRtClientControl.mutex);
  760. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientActivate);
  761. fShmNonRtClientControl.commitWrite();
  762. }
  763. fTimedOut = false;
  764. try {
  765. waitForClient("activate", 2000);
  766. } CARLA_SAFE_EXCEPTION("activate - waitForClient");
  767. }
  768. void deactivate() noexcept override
  769. {
  770. if (! fBridgeThread.isThreadRunning())
  771. return;
  772. CARLA_SAFE_ASSERT_RETURN(! fTimedError,);
  773. {
  774. const CarlaMutexLocker _cml(fShmNonRtClientControl.mutex);
  775. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientDeactivate);
  776. fShmNonRtClientControl.commitWrite();
  777. }
  778. fTimedOut = false;
  779. try {
  780. waitForClient("deactivate", 2000);
  781. } CARLA_SAFE_EXCEPTION("deactivate - waitForClient");
  782. }
  783. void process(const float* const* const audioIn, float** const audioOut,
  784. const float* const*, float**, const uint32_t frames) override
  785. {
  786. // --------------------------------------------------------------------------------------------------------
  787. // Check if active
  788. if (fProcCanceled || fTimedOut || fTimedError || ! pData->active)
  789. {
  790. // disable any output sound
  791. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  792. carla_zeroFloats(audioOut[i], frames);
  793. return;
  794. }
  795. // --------------------------------------------------------------------------------------------------------
  796. // Check if needs reset
  797. if (pData->needsReset)
  798. {
  799. // TODO
  800. pData->needsReset = false;
  801. }
  802. // --------------------------------------------------------------------------------------------------------
  803. // Event Input
  804. if (pData->event.portIn != nullptr)
  805. {
  806. // ----------------------------------------------------------------------------------------------------
  807. // MIDI Input (External)
  808. if (pData->extNotes.mutex.tryLock())
  809. {
  810. for (RtLinkedList<ExternalMidiNote>::Itenerator it = pData->extNotes.data.begin2(); it.valid(); it.next())
  811. {
  812. const ExternalMidiNote& note(it.getValue(kExternalMidiNoteFallback));
  813. CARLA_SAFE_ASSERT_CONTINUE(note.channel >= 0 && note.channel < MAX_MIDI_CHANNELS);
  814. uint8_t data1, data2, data3;
  815. data1 = uint8_t((note.velo > 0 ? MIDI_STATUS_NOTE_ON : MIDI_STATUS_NOTE_OFF) | (note.channel & MIDI_CHANNEL_BIT));
  816. data2 = note.note;
  817. data3 = note.velo;
  818. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientMidiEvent);
  819. fShmRtClientControl.writeUInt(0); // time
  820. fShmRtClientControl.writeByte(0); // port
  821. fShmRtClientControl.writeByte(3); // size
  822. fShmRtClientControl.writeByte(data1);
  823. fShmRtClientControl.writeByte(data2);
  824. fShmRtClientControl.writeByte(data3);
  825. fShmRtClientControl.commitWrite();
  826. }
  827. pData->extNotes.data.clear();
  828. pData->extNotes.mutex.unlock();
  829. } // End of MIDI Input (External)
  830. // ----------------------------------------------------------------------------------------------------
  831. // Event Input (System)
  832. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  833. bool allNotesOffSent = false;
  834. #endif
  835. for (uint32_t i=0, numEvents=pData->event.portIn->getEventCount(); i < numEvents; ++i)
  836. {
  837. const EngineEvent& event(pData->event.portIn->getEvent(i));
  838. // Control change
  839. switch (event.type)
  840. {
  841. case kEngineEventTypeNull:
  842. break;
  843. case kEngineEventTypeControl: {
  844. const EngineControlEvent& ctrlEvent = event.ctrl;
  845. switch (ctrlEvent.type)
  846. {
  847. case kEngineControlEventTypeNull:
  848. break;
  849. case kEngineControlEventTypeParameter:
  850. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  851. // Control backend stuff
  852. if (event.channel == pData->ctrlChannel)
  853. {
  854. float value;
  855. if (MIDI_IS_CONTROL_BREATH_CONTROLLER(ctrlEvent.param) && (pData->hints & PLUGIN_CAN_DRYWET) != 0)
  856. {
  857. value = ctrlEvent.normalizedValue;
  858. setDryWetRT(value, true);
  859. }
  860. if (MIDI_IS_CONTROL_CHANNEL_VOLUME(ctrlEvent.param) && (pData->hints & PLUGIN_CAN_VOLUME) != 0)
  861. {
  862. value = ctrlEvent.normalizedValue*127.0f/100.0f;
  863. setVolumeRT(value, true);
  864. }
  865. if (MIDI_IS_CONTROL_BALANCE(ctrlEvent.param) && (pData->hints & PLUGIN_CAN_BALANCE) != 0)
  866. {
  867. float left, right;
  868. value = ctrlEvent.normalizedValue/0.5f - 1.0f;
  869. if (value < 0.0f)
  870. {
  871. left = -1.0f;
  872. right = (value*2.0f)+1.0f;
  873. }
  874. else if (value > 0.0f)
  875. {
  876. left = (value*2.0f)-1.0f;
  877. right = 1.0f;
  878. }
  879. else
  880. {
  881. left = -1.0f;
  882. right = 1.0f;
  883. }
  884. setBalanceLeftRT(left, true);
  885. setBalanceRightRT(right, true);
  886. }
  887. }
  888. #endif
  889. if ((pData->options & PLUGIN_OPTION_SEND_CONTROL_CHANGES) != 0 && ctrlEvent.param < MAX_MIDI_VALUE)
  890. {
  891. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientMidiEvent);
  892. fShmRtClientControl.writeUInt(event.time);
  893. fShmRtClientControl.writeByte(0); // port
  894. fShmRtClientControl.writeByte(3); // size
  895. fShmRtClientControl.writeByte(uint8_t(MIDI_STATUS_CONTROL_CHANGE | (event.channel & MIDI_CHANNEL_BIT)));
  896. fShmRtClientControl.writeByte(uint8_t(ctrlEvent.param));
  897. fShmRtClientControl.writeByte(uint8_t(ctrlEvent.normalizedValue*127.0f + 0.5f));
  898. }
  899. break;
  900. case kEngineControlEventTypeMidiBank:
  901. if (pData->options & PLUGIN_OPTION_MAP_PROGRAM_CHANGES)
  902. {
  903. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientControlEventMidiBank);
  904. fShmRtClientControl.writeUInt(event.time);
  905. fShmRtClientControl.writeByte(event.channel);
  906. fShmRtClientControl.writeUShort(event.ctrl.param);
  907. fShmRtClientControl.commitWrite();
  908. }
  909. break;
  910. case kEngineControlEventTypeMidiProgram:
  911. if (pData->options & PLUGIN_OPTION_MAP_PROGRAM_CHANGES)
  912. {
  913. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientControlEventMidiProgram);
  914. fShmRtClientControl.writeUInt(event.time);
  915. fShmRtClientControl.writeByte(event.channel);
  916. fShmRtClientControl.writeUShort(event.ctrl.param);
  917. fShmRtClientControl.commitWrite();
  918. }
  919. break;
  920. case kEngineControlEventTypeAllSoundOff:
  921. if (pData->options & PLUGIN_OPTION_SEND_ALL_SOUND_OFF)
  922. {
  923. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientControlEventAllSoundOff);
  924. fShmRtClientControl.writeUInt(event.time);
  925. fShmRtClientControl.writeByte(event.channel);
  926. fShmRtClientControl.commitWrite();
  927. }
  928. break;
  929. case kEngineControlEventTypeAllNotesOff:
  930. if (pData->options & PLUGIN_OPTION_SEND_ALL_SOUND_OFF)
  931. {
  932. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  933. if (event.channel == pData->ctrlChannel && ! allNotesOffSent)
  934. {
  935. allNotesOffSent = true;
  936. postponeRtAllNotesOff();
  937. }
  938. #endif
  939. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientControlEventAllNotesOff);
  940. fShmRtClientControl.writeUInt(event.time);
  941. fShmRtClientControl.writeByte(event.channel);
  942. fShmRtClientControl.commitWrite();
  943. }
  944. break;
  945. } // switch (ctrlEvent.type)
  946. break;
  947. } // case kEngineEventTypeControl
  948. case kEngineEventTypeMidi: {
  949. const EngineMidiEvent& midiEvent(event.midi);
  950. if (midiEvent.size == 0 || midiEvent.size >= MAX_MIDI_VALUE)
  951. continue;
  952. const uint8_t* const midiData(midiEvent.size > EngineMidiEvent::kDataSize ? midiEvent.dataExt : midiEvent.data);
  953. uint8_t status = uint8_t(MIDI_GET_STATUS_FROM_DATA(midiData));
  954. if ((status == MIDI_STATUS_NOTE_OFF || status == MIDI_STATUS_NOTE_ON) && (pData->options & PLUGIN_OPTION_SKIP_SENDING_NOTES))
  955. continue;
  956. if (status == MIDI_STATUS_CHANNEL_PRESSURE && (pData->options & PLUGIN_OPTION_SEND_CHANNEL_PRESSURE) == 0)
  957. continue;
  958. if (status == MIDI_STATUS_CONTROL_CHANGE && (pData->options & PLUGIN_OPTION_SEND_CONTROL_CHANGES) == 0)
  959. continue;
  960. if (status == MIDI_STATUS_POLYPHONIC_AFTERTOUCH && (pData->options & PLUGIN_OPTION_SEND_NOTE_AFTERTOUCH) == 0)
  961. continue;
  962. if (status == MIDI_STATUS_PITCH_WHEEL_CONTROL && (pData->options & PLUGIN_OPTION_SEND_PITCHBEND) == 0)
  963. continue;
  964. // Fix bad note-off
  965. if (status == MIDI_STATUS_NOTE_ON && midiData[2] == 0)
  966. status = MIDI_STATUS_NOTE_OFF;
  967. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientMidiEvent);
  968. fShmRtClientControl.writeUInt(event.time);
  969. fShmRtClientControl.writeByte(midiEvent.port);
  970. fShmRtClientControl.writeByte(midiEvent.size);
  971. fShmRtClientControl.writeByte(uint8_t(midiData[0] | (event.channel & MIDI_CHANNEL_BIT)));
  972. for (uint8_t j=1; j < midiEvent.size; ++j)
  973. fShmRtClientControl.writeByte(midiData[j]);
  974. fShmRtClientControl.commitWrite();
  975. if (status == MIDI_STATUS_NOTE_ON)
  976. {
  977. pData->postponeNoteOnRtEvent(true, event.channel, midiData[1], midiData[2]);
  978. }
  979. else if (status == MIDI_STATUS_NOTE_OFF)
  980. {
  981. pData->postponeNoteOffRtEvent(true, event.channel, midiData[1]);
  982. }
  983. } break;
  984. }
  985. }
  986. pData->postRtEvents.trySplice();
  987. } // End of Event Input
  988. if (! processSingle(audioIn, audioOut, frames))
  989. return;
  990. // --------------------------------------------------------------------------------------------------------
  991. // MIDI Output
  992. if (pData->event.portOut != nullptr)
  993. {
  994. uint32_t time;
  995. uint8_t port, size;
  996. const uint8_t* midiData(fShmRtClientControl.data->midiOut);
  997. for (std::size_t read=0; read<kBridgeRtClientDataMidiOutSize-kBridgeBaseMidiOutHeaderSize;)
  998. {
  999. // get time
  1000. time = *(const uint32_t*)midiData;
  1001. midiData += 4;
  1002. // get port and size
  1003. port = *midiData++;
  1004. size = *midiData++;
  1005. if (size == 0)
  1006. break;
  1007. // store midi data advancing as needed
  1008. uint8_t data[size];
  1009. for (uint8_t j=0; j<size; ++j)
  1010. data[j] = *midiData++;
  1011. pData->event.portOut->writeMidiEvent(time, size, data);
  1012. read += kBridgeBaseMidiOutHeaderSize + size;
  1013. }
  1014. // TODO
  1015. (void)port;
  1016. } // End of Control and MIDI Output
  1017. }
  1018. bool processSingle(const float* const* const audioIn, float** const audioOut, const uint32_t frames)
  1019. {
  1020. CARLA_SAFE_ASSERT_RETURN(! fTimedError, false);
  1021. CARLA_SAFE_ASSERT_RETURN(frames > 0, false);
  1022. CARLA_SAFE_ASSERT_RETURN(frames <= fBufferSize, false);
  1023. if (pData->audioIn.count > 0)
  1024. {
  1025. CARLA_SAFE_ASSERT_RETURN(audioIn != nullptr, false);
  1026. }
  1027. if (pData->audioOut.count > 0)
  1028. {
  1029. CARLA_SAFE_ASSERT_RETURN(audioOut != nullptr, false);
  1030. }
  1031. // --------------------------------------------------------------------------------------------------------
  1032. // Try lock, silence otherwise
  1033. #ifndef STOAT_TEST_BUILD
  1034. if (pData->engine->isOffline())
  1035. {
  1036. pData->singleMutex.lock();
  1037. }
  1038. else
  1039. #endif
  1040. if (! pData->singleMutex.tryLock())
  1041. {
  1042. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  1043. carla_zeroFloats(audioOut[i], frames);
  1044. return false;
  1045. }
  1046. // --------------------------------------------------------------------------------------------------------
  1047. // Reset audio buffers
  1048. for (uint32_t i=0; i < fInfo.aIns; ++i)
  1049. carla_copyFloats(fShmAudioPool.data + (i * fBufferSize), audioIn[i], frames);
  1050. // --------------------------------------------------------------------------------------------------------
  1051. // TimeInfo
  1052. const EngineTimeInfo timeInfo(pData->engine->getTimeInfo());
  1053. BridgeTimeInfo& bridgeTimeInfo(fShmRtClientControl.data->timeInfo);
  1054. bridgeTimeInfo.playing = timeInfo.playing;
  1055. bridgeTimeInfo.frame = timeInfo.frame;
  1056. bridgeTimeInfo.usecs = timeInfo.usecs;
  1057. bridgeTimeInfo.validFlags = timeInfo.bbt.valid ? kPluginBridgeTimeInfoValidBBT : 0x0;
  1058. if (timeInfo.bbt.valid)
  1059. {
  1060. bridgeTimeInfo.bar = timeInfo.bbt.bar;
  1061. bridgeTimeInfo.beat = timeInfo.bbt.beat;
  1062. bridgeTimeInfo.tick = timeInfo.bbt.tick;
  1063. bridgeTimeInfo.beatsPerBar = timeInfo.bbt.beatsPerBar;
  1064. bridgeTimeInfo.beatType = timeInfo.bbt.beatType;
  1065. bridgeTimeInfo.ticksPerBeat = timeInfo.bbt.ticksPerBeat;
  1066. bridgeTimeInfo.beatsPerMinute = timeInfo.bbt.beatsPerMinute;
  1067. bridgeTimeInfo.barStartTick = timeInfo.bbt.barStartTick;
  1068. }
  1069. // --------------------------------------------------------------------------------------------------------
  1070. // Run plugin
  1071. {
  1072. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientProcess);
  1073. fShmRtClientControl.writeUInt(frames);
  1074. fShmRtClientControl.commitWrite();
  1075. }
  1076. waitForClient("process", fProcWaitTime);
  1077. if (fTimedOut)
  1078. {
  1079. pData->singleMutex.unlock();
  1080. return false;
  1081. }
  1082. if (fShmRtClientControl.data->procFlags)
  1083. {
  1084. fInitiated = false;
  1085. fProcCanceled = true;
  1086. }
  1087. for (uint32_t i=0; i < fInfo.aOuts; ++i)
  1088. carla_copyFloats(audioOut[i], fShmAudioPool.data + ((i + fInfo.aIns) * fBufferSize), frames);
  1089. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1090. // --------------------------------------------------------------------------------------------------------
  1091. // Post-processing (dry/wet, volume and balance)
  1092. {
  1093. const bool doVolume = (pData->hints & PLUGIN_CAN_VOLUME) != 0 && carla_isNotEqual(pData->postProc.volume, 1.0f);
  1094. const bool doDryWet = (pData->hints & PLUGIN_CAN_DRYWET) != 0 && carla_isNotEqual(pData->postProc.dryWet, 1.0f);
  1095. const bool doBalance = (pData->hints & PLUGIN_CAN_BALANCE) != 0 && ! (carla_isEqual(pData->postProc.balanceLeft, -1.0f) && carla_isEqual(pData->postProc.balanceRight, 1.0f));
  1096. const bool isMono = (pData->audioIn.count == 1);
  1097. bool isPair;
  1098. float bufValue;
  1099. float* const oldBufLeft = pData->postProc.extraBuffer;
  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. CarlaString 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. d_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. #if defined(CARLA_OS_LINUX) || defined(CARLA_OS_MAC)
  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. // -------------------------------------------------------------------------------------------------------------------