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.

1946 lines
65KB

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