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.

2084 lines
71KB

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