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.

2083 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, oldBufLeft[doBalance ? frames : 1];
  1116. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  1117. {
  1118. // Dry/Wet
  1119. if (doDryWet)
  1120. {
  1121. const uint32_t c = isMono ? 0 : i;
  1122. for (uint32_t k=0; k < frames; ++k)
  1123. {
  1124. bufValue = audioIn[c][k];
  1125. audioOut[i][k] = (audioOut[i][k] * pData->postProc.dryWet) + (bufValue * (1.0f - pData->postProc.dryWet));
  1126. }
  1127. }
  1128. // Balance
  1129. if (doBalance)
  1130. {
  1131. isPair = (i % 2 == 0);
  1132. if (isPair)
  1133. {
  1134. CARLA_ASSERT(i+1 < pData->audioOut.count);
  1135. carla_copyFloats(oldBufLeft, audioOut[i], frames);
  1136. }
  1137. float balRangeL = (pData->postProc.balanceLeft + 1.0f)/2.0f;
  1138. float balRangeR = (pData->postProc.balanceRight + 1.0f)/2.0f;
  1139. for (uint32_t k=0; k < frames; ++k)
  1140. {
  1141. if (isPair)
  1142. {
  1143. // left
  1144. audioOut[i][k] = oldBufLeft[k] * (1.0f - balRangeL);
  1145. audioOut[i][k] += audioOut[i+1][k] * (1.0f - balRangeR);
  1146. }
  1147. else
  1148. {
  1149. // right
  1150. audioOut[i][k] = audioOut[i][k] * balRangeR;
  1151. audioOut[i][k] += oldBufLeft[k] * balRangeL;
  1152. }
  1153. }
  1154. }
  1155. // Volume
  1156. if (doVolume)
  1157. {
  1158. for (uint32_t k=0; k < frames; ++k)
  1159. audioOut[i][k] *= pData->postProc.volume;
  1160. }
  1161. }
  1162. } // End of Post-processing
  1163. #endif
  1164. // --------------------------------------------------------------------------------------------------------
  1165. pData->singleMutex.unlock();
  1166. return true;
  1167. }
  1168. void bufferSizeChanged(const uint32_t newBufferSize) override
  1169. {
  1170. fBufferSize = newBufferSize;
  1171. resizeAudioPool(newBufferSize);
  1172. {
  1173. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientSetBufferSize);
  1174. fShmRtClientControl.writeUInt(newBufferSize);
  1175. fShmRtClientControl.commitWrite();
  1176. }
  1177. //fProcWaitTime = newBufferSize*1000/pData->engine->getSampleRate();
  1178. fProcWaitTime = 1000;
  1179. waitForClient("buffersize", 1000);
  1180. }
  1181. void sampleRateChanged(const double newSampleRate) override
  1182. {
  1183. {
  1184. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientSetSampleRate);
  1185. fShmRtClientControl.writeDouble(newSampleRate);
  1186. fShmRtClientControl.commitWrite();
  1187. }
  1188. //fProcWaitTime = pData->engine->getBufferSize()*1000/newSampleRate;
  1189. fProcWaitTime = 1000;
  1190. waitForClient("samplerate", 1000);
  1191. }
  1192. void offlineModeChanged(const bool isOffline) override
  1193. {
  1194. {
  1195. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientSetOnline);
  1196. fShmRtClientControl.writeBool(isOffline);
  1197. fShmRtClientControl.commitWrite();
  1198. }
  1199. waitForClient("offline", 1000);
  1200. }
  1201. // -------------------------------------------------------------------
  1202. // Post-poned UI Stuff
  1203. // -------------------------------------------------------------------
  1204. void handleNonRtData()
  1205. {
  1206. for (; fShmNonRtServerControl.isDataAvailableForReading();)
  1207. {
  1208. const PluginBridgeNonRtServerOpcode opcode(fShmNonRtServerControl.readOpcode());
  1209. //#ifdef DEBUG
  1210. if (opcode != kPluginBridgeNonRtServerPong)
  1211. {
  1212. carla_debug("CarlaPluginJack::handleNonRtData() - got opcode: %s", PluginBridgeNonRtServerOpcode2str(opcode));
  1213. }
  1214. //#endif
  1215. switch (opcode)
  1216. {
  1217. case kPluginBridgeNonRtServerNull:
  1218. case kPluginBridgeNonRtServerPong:
  1219. case kPluginBridgeNonRtServerPluginInfo1:
  1220. case kPluginBridgeNonRtServerPluginInfo2:
  1221. case kPluginBridgeNonRtServerAudioCount:
  1222. case kPluginBridgeNonRtServerMidiCount:
  1223. case kPluginBridgeNonRtServerCvCount:
  1224. case kPluginBridgeNonRtServerParameterCount:
  1225. case kPluginBridgeNonRtServerProgramCount:
  1226. case kPluginBridgeNonRtServerMidiProgramCount:
  1227. case kPluginBridgeNonRtServerPortName:
  1228. case kPluginBridgeNonRtServerParameterData1:
  1229. case kPluginBridgeNonRtServerParameterData2:
  1230. case kPluginBridgeNonRtServerParameterRanges:
  1231. case kPluginBridgeNonRtServerParameterValue:
  1232. case kPluginBridgeNonRtServerParameterValue2:
  1233. case kPluginBridgeNonRtServerParameterTouch:
  1234. case kPluginBridgeNonRtServerDefaultValue:
  1235. case kPluginBridgeNonRtServerCurrentProgram:
  1236. case kPluginBridgeNonRtServerCurrentMidiProgram:
  1237. case kPluginBridgeNonRtServerProgramName:
  1238. case kPluginBridgeNonRtServerMidiProgramData:
  1239. case kPluginBridgeNonRtServerSetCustomData:
  1240. case kPluginBridgeNonRtServerVersion:
  1241. case kPluginBridgeNonRtServerRespEmbedUI:
  1242. case kPluginBridgeNonRtServerResizeEmbedUI:
  1243. break;
  1244. case kPluginBridgeNonRtServerSetChunkDataFile:
  1245. // uint/size, str[] (filename)
  1246. if (const uint32_t chunkFilePathSize = fShmNonRtServerControl.readUInt())
  1247. {
  1248. char chunkFilePath[chunkFilePathSize];
  1249. fShmNonRtServerControl.readCustomData(chunkFilePath, chunkFilePathSize);
  1250. }
  1251. break;
  1252. case kPluginBridgeNonRtServerSetLatency:
  1253. case kPluginBridgeNonRtServerSetParameterText:
  1254. break;
  1255. case kPluginBridgeNonRtServerReady:
  1256. fInitiated = true;
  1257. break;
  1258. case kPluginBridgeNonRtServerSaved:
  1259. break;
  1260. case kPluginBridgeNonRtServerUiClosed:
  1261. pData->engine->callback(true, true,
  1262. ENGINE_CALLBACK_UI_STATE_CHANGED,
  1263. pData->id,
  1264. 0,
  1265. 0, 0, 0.0f, nullptr);
  1266. break;
  1267. case kPluginBridgeNonRtServerError: {
  1268. // error
  1269. const uint32_t errorSize(fShmNonRtServerControl.readUInt());
  1270. char error[errorSize+1];
  1271. carla_zeroChars(error, errorSize+1);
  1272. fShmNonRtServerControl.readCustomData(error, errorSize);
  1273. if (fInitiated)
  1274. {
  1275. pData->engine->callback(true, true, ENGINE_CALLBACK_ERROR, pData->id, 0, 0, 0, 0.0f, error);
  1276. // just in case
  1277. pData->engine->setLastError(error);
  1278. fInitError = true;
  1279. }
  1280. else
  1281. {
  1282. pData->engine->setLastError(error);
  1283. fInitError = true;
  1284. fInitiated = true;
  1285. }
  1286. } break;
  1287. }
  1288. }
  1289. }
  1290. // -------------------------------------------------------------------
  1291. uintptr_t getUiBridgeProcessId() const noexcept override
  1292. {
  1293. return fBridgeThread.getProcessID();
  1294. }
  1295. // -------------------------------------------------------------------
  1296. bool init(const CarlaPluginPtr plugin,
  1297. const char* const filename, const char* const name, const char* const label, const uint options)
  1298. {
  1299. CARLA_SAFE_ASSERT_RETURN(pData->engine != nullptr, false);
  1300. // ---------------------------------------------------------------
  1301. // first checks
  1302. if (pData->client != nullptr)
  1303. {
  1304. pData->engine->setLastError("Plugin client is already registered");
  1305. return false;
  1306. }
  1307. if (filename == nullptr || filename[0] == '\0')
  1308. {
  1309. pData->engine->setLastError("null filename");
  1310. return false;
  1311. }
  1312. if (label == nullptr || label[0] == '\0')
  1313. {
  1314. pData->engine->setLastError("null label");
  1315. return false;
  1316. }
  1317. // ---------------------------------------------------------------
  1318. // check setup
  1319. if (std::strlen(label) < 6)
  1320. {
  1321. pData->engine->setLastError("invalid application setup received");
  1322. return false;
  1323. }
  1324. for (int i=4; --i >= 0;) {
  1325. CARLA_SAFE_ASSERT_INT2_RETURN(label[i] >= '0' && label[i] <= '0'+64, i, label[i], false);
  1326. }
  1327. CARLA_SAFE_ASSERT_INT2_RETURN(label[4] >= '0' && label[4] < '0'+0x4f, 4, label[4], false);
  1328. CARLA_SAFE_ASSERT_UINT2_RETURN(static_cast<uchar>(label[5]) >= '0' &&
  1329. static_cast<uchar>(label[5]) <= '0'+0x73,
  1330. static_cast<uchar>(label[5]),
  1331. static_cast<uchar>('0'+0x73),
  1332. false);
  1333. fInfo.aIns = static_cast<uint8_t>(label[0] - '0');
  1334. fInfo.aOuts = static_cast<uint8_t>(label[1] - '0');
  1335. fInfo.mIns = static_cast<uint8_t>(carla_minPositive(label[2] - '0', 1));
  1336. fInfo.mOuts = static_cast<uint8_t>(carla_minPositive(label[3] - '0', 1));
  1337. fInfo.setupLabel = label;
  1338. // ---------------------------------------------------------------
  1339. // set project unique id
  1340. if (label[6] == '\0')
  1341. setupUniqueProjectID();
  1342. // ---------------------------------------------------------------
  1343. // set icon
  1344. pData->iconName = carla_strdup_safe("application");
  1345. // ---------------------------------------------------------------
  1346. // set info
  1347. pData->filename = carla_strdup(filename);
  1348. if (name != nullptr && name[0] != '\0')
  1349. pData->name = pData->engine->getUniquePluginName(name);
  1350. else
  1351. pData->name = pData->engine->getUniquePluginName("Jack Application");
  1352. std::srand(static_cast<uint>(std::time(nullptr)));
  1353. // ---------------------------------------------------------------
  1354. // init sem/shm
  1355. if (! fShmAudioPool.initializeServer())
  1356. {
  1357. carla_stderr("Failed to initialize shared memory audio pool");
  1358. return false;
  1359. }
  1360. if (! fShmRtClientControl.initializeServer())
  1361. {
  1362. carla_stderr("Failed to initialize RT client control");
  1363. fShmAudioPool.clear();
  1364. return false;
  1365. }
  1366. if (! fShmNonRtClientControl.initializeServer())
  1367. {
  1368. carla_stderr("Failed to initialize Non-RT client control");
  1369. fShmRtClientControl.clear();
  1370. fShmAudioPool.clear();
  1371. return false;
  1372. }
  1373. if (! fShmNonRtServerControl.initializeServer())
  1374. {
  1375. carla_stderr("Failed to initialize Non-RT server control");
  1376. fShmNonRtClientControl.clear();
  1377. fShmRtClientControl.clear();
  1378. fShmAudioPool.clear();
  1379. return false;
  1380. }
  1381. // ---------------------------------------------------------------
  1382. // setup hints and options
  1383. fSetupHints = static_cast<uint>(static_cast<uchar>(label[5]) - '0');
  1384. // FIXME dryWet broken
  1385. pData->hints = PLUGIN_IS_BRIDGE;
  1386. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1387. pData->hints |= /*PLUGIN_CAN_DRYWET |*/ PLUGIN_CAN_VOLUME | PLUGIN_CAN_BALANCE;
  1388. #endif
  1389. if (fSetupHints & LIBJACK_FLAG_CONTROL_WINDOW)
  1390. pData->hints |= PLUGIN_HAS_CUSTOM_UI;
  1391. // ---------------------------------------------------------------
  1392. // init bridge thread
  1393. {
  1394. char shmIdsStr[6*4+1];
  1395. carla_zeroChars(shmIdsStr, 6*4+1);
  1396. std::strncpy(shmIdsStr+6*0, &fShmAudioPool.filename[fShmAudioPool.filename.length()-6], 6);
  1397. std::strncpy(shmIdsStr+6*1, &fShmRtClientControl.filename[fShmRtClientControl.filename.length()-6], 6);
  1398. std::strncpy(shmIdsStr+6*2, &fShmNonRtClientControl.filename[fShmNonRtClientControl.filename.length()-6], 6);
  1399. std::strncpy(shmIdsStr+6*3, &fShmNonRtServerControl.filename[fShmNonRtServerControl.filename.length()-6], 6);
  1400. fBridgeThread.setData(shmIdsStr, fInfo.setupLabel);
  1401. }
  1402. if (! restartBridgeThread())
  1403. return false;
  1404. // ---------------------------------------------------------------
  1405. // register client
  1406. if (pData->name == nullptr)
  1407. pData->name = pData->engine->getUniquePluginName("unknown");
  1408. pData->client = pData->engine->addClient(plugin);
  1409. if (pData->client == nullptr || ! pData->client->isOk())
  1410. {
  1411. pData->engine->setLastError("Failed to register plugin client");
  1412. return false;
  1413. }
  1414. // remove unprintable characters if needed
  1415. if (fSetupHints & LIBJACK_FLAG_EXTERNAL_START)
  1416. fInfo.setupLabel[5U] = static_cast<char>('0' + (fSetupHints ^ LIBJACK_FLAG_EXTERNAL_START));
  1417. // ---------------------------------------------------------------
  1418. // set options
  1419. pData->options = PLUGIN_OPTION_FIXED_BUFFERS;
  1420. if (isPluginOptionEnabled(options, PLUGIN_OPTION_SEND_CONTROL_CHANGES))
  1421. pData->options |= PLUGIN_OPTION_SEND_CONTROL_CHANGES;
  1422. if (isPluginOptionEnabled(options, PLUGIN_OPTION_SEND_CHANNEL_PRESSURE))
  1423. pData->options |= PLUGIN_OPTION_SEND_CHANNEL_PRESSURE;
  1424. if (isPluginOptionEnabled(options, PLUGIN_OPTION_SEND_NOTE_AFTERTOUCH))
  1425. pData->options |= PLUGIN_OPTION_SEND_NOTE_AFTERTOUCH;
  1426. if (isPluginOptionEnabled(options, PLUGIN_OPTION_SEND_PITCHBEND))
  1427. pData->options |= PLUGIN_OPTION_SEND_PITCHBEND;
  1428. if (isPluginOptionEnabled(options, PLUGIN_OPTION_SEND_ALL_SOUND_OFF))
  1429. pData->options |= PLUGIN_OPTION_SEND_ALL_SOUND_OFF;
  1430. if (isPluginOptionEnabled(options, PLUGIN_OPTION_SEND_PROGRAM_CHANGES))
  1431. pData->options |= PLUGIN_OPTION_SEND_PROGRAM_CHANGES;
  1432. if (isPluginOptionInverseEnabled(options, PLUGIN_OPTION_SKIP_SENDING_NOTES))
  1433. pData->options |= PLUGIN_OPTION_SKIP_SENDING_NOTES;
  1434. return true;
  1435. }
  1436. private:
  1437. bool fInitiated;
  1438. bool fInitError;
  1439. bool fTimedOut;
  1440. bool fTimedError;
  1441. bool fProcCanceled;
  1442. uint fBufferSize;
  1443. uint fProcWaitTime;
  1444. uint fSetupHints;
  1445. CarlaPluginJackThread fBridgeThread;
  1446. BridgeAudioPool fShmAudioPool;
  1447. BridgeRtClientControl fShmRtClientControl;
  1448. BridgeNonRtClientControl fShmNonRtClientControl;
  1449. BridgeNonRtServerControl fShmNonRtServerControl;
  1450. struct Info {
  1451. uint8_t aIns, aOuts;
  1452. uint8_t mIns, mOuts;
  1453. CarlaString setupLabel;
  1454. std::vector<uint8_t> chunk;
  1455. Info()
  1456. : aIns(0),
  1457. aOuts(0),
  1458. mIns(0),
  1459. mOuts(0),
  1460. setupLabel(),
  1461. chunk() {}
  1462. CARLA_DECLARE_NON_COPYABLE(Info)
  1463. } fInfo;
  1464. void handleProcessStopped() noexcept
  1465. {
  1466. const bool wasActive = pData->active;
  1467. pData->active = false;
  1468. if (wasActive)
  1469. {
  1470. pData->engine->callback(true, true,
  1471. ENGINE_CALLBACK_PARAMETER_VALUE_CHANGED,
  1472. pData->id,
  1473. PARAMETER_ACTIVE,
  1474. 0, 0,
  1475. 0.0f,
  1476. nullptr);
  1477. }
  1478. if (pData->hints & PLUGIN_HAS_CUSTOM_UI)
  1479. pData->engine->callback(true, true,
  1480. ENGINE_CALLBACK_UI_STATE_CHANGED,
  1481. pData->id,
  1482. 0,
  1483. 0, 0, 0.0f, nullptr);
  1484. }
  1485. void resizeAudioPool(const uint32_t bufferSize)
  1486. {
  1487. fShmAudioPool.resize(bufferSize, static_cast<uint32_t>(fInfo.aIns+fInfo.aOuts), 0);
  1488. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientSetAudioPool);
  1489. fShmRtClientControl.writeULong(static_cast<uint64_t>(fShmAudioPool.dataSize));
  1490. fShmRtClientControl.commitWrite();
  1491. waitForClient("resize-pool", 5000);
  1492. }
  1493. void setupUniqueProjectID()
  1494. {
  1495. const char* const engineProjectFolder = pData->engine->getCurrentProjectFolder();
  1496. carla_stdout("setupUniqueProjectID %s", engineProjectFolder);
  1497. if (engineProjectFolder == nullptr || engineProjectFolder[0] == '\0')
  1498. return;
  1499. const File file(engineProjectFolder);
  1500. CARLA_SAFE_ASSERT_RETURN(file.exists(),);
  1501. char code[6];
  1502. code[5] = '\0';
  1503. String child;
  1504. for (;;)
  1505. {
  1506. static const char* const kValidChars =
  1507. "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  1508. "abcdefghijklmnopqrstuvwxyz"
  1509. "0123456789";
  1510. static const size_t kValidCharsLen(std::strlen(kValidChars)-1U);
  1511. code[0] = kValidChars[safe_rand(kValidCharsLen)];
  1512. code[1] = kValidChars[safe_rand(kValidCharsLen)];
  1513. code[2] = kValidChars[safe_rand(kValidCharsLen)];
  1514. code[3] = kValidChars[safe_rand(kValidCharsLen)];
  1515. code[4] = kValidChars[safe_rand(kValidCharsLen)];
  1516. child = pData->name;
  1517. child += ".";
  1518. child += code;
  1519. const File newFile(file.getChildFile(child));
  1520. if (newFile.existsAsFile())
  1521. continue;
  1522. fInfo.setupLabel += code;
  1523. carla_stdout("new label %s", fInfo.setupLabel.buffer());
  1524. break;
  1525. }
  1526. }
  1527. bool restartBridgeThread()
  1528. {
  1529. fInitiated = false;
  1530. fInitError = false;
  1531. fTimedError = false;
  1532. // reset memory
  1533. fProcCanceled = false;
  1534. fShmRtClientControl.data->procFlags = 0;
  1535. carla_zeroStruct(fShmRtClientControl.data->timeInfo);
  1536. carla_zeroBytes(fShmRtClientControl.data->midiOut, kBridgeRtClientDataMidiOutSize);
  1537. fShmRtClientControl.clearData();
  1538. fShmNonRtClientControl.clearData();
  1539. fShmNonRtServerControl.clearData();
  1540. // initial values
  1541. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientVersion);
  1542. fShmNonRtClientControl.writeUInt(CARLA_PLUGIN_BRIDGE_API_VERSION_CURRENT);
  1543. fShmNonRtClientControl.writeUInt(static_cast<uint32_t>(sizeof(BridgeRtClientData)));
  1544. fShmNonRtClientControl.writeUInt(static_cast<uint32_t>(sizeof(BridgeNonRtClientData)));
  1545. fShmNonRtClientControl.writeUInt(static_cast<uint32_t>(sizeof(BridgeNonRtServerData)));
  1546. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientInitialSetup);
  1547. fShmNonRtClientControl.writeUInt(pData->engine->getBufferSize());
  1548. fShmNonRtClientControl.writeDouble(pData->engine->getSampleRate());
  1549. fShmNonRtClientControl.commitWrite();
  1550. if (fShmAudioPool.dataSize != 0)
  1551. {
  1552. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientSetAudioPool);
  1553. fShmRtClientControl.writeULong(static_cast<uint64_t>(fShmAudioPool.dataSize));
  1554. fShmRtClientControl.commitWrite();
  1555. }
  1556. else
  1557. {
  1558. // testing dummy message
  1559. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientNull);
  1560. fShmRtClientControl.commitWrite();
  1561. }
  1562. fBridgeThread.startThread();
  1563. const bool needsCancelableAction = ! pData->engine->isLoadingProject();
  1564. const bool needsEngineIdle = pData->engine->getType() != kEngineTypePlugin;
  1565. CarlaString actionName;
  1566. if (needsCancelableAction)
  1567. {
  1568. if (fSetupHints & LIBJACK_FLAG_EXTERNAL_START)
  1569. {
  1570. const EngineOptions& options(pData->engine->getOptions());
  1571. CarlaString binaryDir(options.binaryDir);
  1572. char* const hwVars = fBridgeThread.getEnvVarsToExport();
  1573. actionName = "Waiting for external JACK application start, please use the following environment variables:\n";
  1574. actionName += hwVars;
  1575. delete[] hwVars;
  1576. }
  1577. else
  1578. {
  1579. actionName = "Loading JACK application";
  1580. }
  1581. pData->engine->setActionCanceled(false);
  1582. pData->engine->callback(true, true,
  1583. ENGINE_CALLBACK_CANCELABLE_ACTION,
  1584. pData->id,
  1585. 1,
  1586. 0, 0, 0.0f,
  1587. actionName.buffer());
  1588. }
  1589. for (;fBridgeThread.isThreadRunning();)
  1590. {
  1591. pData->engine->callback(true, false, ENGINE_CALLBACK_IDLE, 0, 0, 0, 0, 0.0f, nullptr);
  1592. if (needsEngineIdle)
  1593. pData->engine->idle();
  1594. idle();
  1595. if (fInitiated)
  1596. break;
  1597. if (pData->engine->isAboutToClose() || pData->engine->wasActionCanceled())
  1598. break;
  1599. carla_msleep(5);
  1600. }
  1601. if (needsCancelableAction)
  1602. {
  1603. pData->engine->callback(true, true,
  1604. ENGINE_CALLBACK_CANCELABLE_ACTION,
  1605. pData->id,
  1606. 0,
  1607. 0, 0, 0.0f,
  1608. actionName.buffer());
  1609. }
  1610. if (fInitError || ! fInitiated)
  1611. {
  1612. fBridgeThread.stopThread(6000);
  1613. if (! fInitError)
  1614. pData->engine->setLastError("Timeout while waiting for a response from plugin-bridge\n"
  1615. "(or the plugin crashed on initialization?)");
  1616. return false;
  1617. }
  1618. return true;
  1619. }
  1620. void waitForClient(const char* const action, const uint msecs)
  1621. {
  1622. CARLA_SAFE_ASSERT_RETURN(! fTimedOut,);
  1623. CARLA_SAFE_ASSERT_RETURN(! fTimedError,);
  1624. if (fShmRtClientControl.waitForClient(msecs))
  1625. return;
  1626. fTimedOut = true;
  1627. carla_stderr2("waitForClient(%s) timed out", action);
  1628. }
  1629. CARLA_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(CarlaPluginJack)
  1630. };
  1631. CARLA_BACKEND_END_NAMESPACE
  1632. #endif // CARLA_OS_LINUX
  1633. // -------------------------------------------------------------------------------------------------------------------
  1634. CARLA_BACKEND_START_NAMESPACE
  1635. CarlaPluginPtr CarlaPlugin::newJackApp(const Initializer& init)
  1636. {
  1637. carla_debug("CarlaPlugin::newJackApp({%p, \"%s\", \"%s\", \"%s\"})",
  1638. init.engine, init.filename, init.name, init.label);
  1639. #if defined(CARLA_OS_LINUX) || defined(CARLA_OS_MAC)
  1640. std::shared_ptr<CarlaPluginJack> plugin(new CarlaPluginJack(init.engine, init.id));
  1641. if (! plugin->init(plugin, init.filename, init.name, init.label, init.options))
  1642. return nullptr;
  1643. return plugin;
  1644. #else
  1645. init.engine->setLastError("JACK Application support not available");
  1646. return nullptr;
  1647. #endif
  1648. }
  1649. CARLA_BACKEND_END_NAMESPACE
  1650. // -------------------------------------------------------------------------------------------------------------------