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.

2074 lines
70KB

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