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.

1948 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* const audioIn, float** const audioOut,
  721. const float* const*, float**, const uint32_t frames) override
  722. {
  723. // --------------------------------------------------------------------------------------------------------
  724. // Check if active
  725. if (fProcCanceled || fTimedOut || fTimedError || ! pData->active)
  726. {
  727. // disable any output sound
  728. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  729. carla_zeroFloats(audioOut[i], frames);
  730. return;
  731. }
  732. // --------------------------------------------------------------------------------------------------------
  733. // Check if needs reset
  734. if (pData->needsReset)
  735. {
  736. // TODO
  737. pData->needsReset = false;
  738. }
  739. // --------------------------------------------------------------------------------------------------------
  740. // Event Input
  741. if (pData->event.portIn != nullptr)
  742. {
  743. // ----------------------------------------------------------------------------------------------------
  744. // MIDI Input (External)
  745. if (pData->extNotes.mutex.tryLock())
  746. {
  747. for (RtLinkedList<ExternalMidiNote>::Itenerator it = pData->extNotes.data.begin2(); it.valid(); it.next())
  748. {
  749. const ExternalMidiNote& note(it.getValue(kExternalMidiNoteFallback));
  750. CARLA_SAFE_ASSERT_CONTINUE(note.channel >= 0 && note.channel < MAX_MIDI_CHANNELS);
  751. uint8_t data1, data2, data3;
  752. data1 = uint8_t((note.velo > 0 ? MIDI_STATUS_NOTE_ON : MIDI_STATUS_NOTE_OFF) | (note.channel & MIDI_CHANNEL_BIT));
  753. data2 = note.note;
  754. data3 = note.velo;
  755. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientMidiEvent);
  756. fShmRtClientControl.writeUInt(0); // time
  757. fShmRtClientControl.writeByte(0); // port
  758. fShmRtClientControl.writeByte(3); // size
  759. fShmRtClientControl.writeByte(data1);
  760. fShmRtClientControl.writeByte(data2);
  761. fShmRtClientControl.writeByte(data3);
  762. fShmRtClientControl.commitWrite();
  763. }
  764. pData->extNotes.data.clear();
  765. pData->extNotes.mutex.unlock();
  766. } // End of MIDI Input (External)
  767. // ----------------------------------------------------------------------------------------------------
  768. // Event Input (System)
  769. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  770. bool allNotesOffSent = false;
  771. #endif
  772. for (uint32_t i=0, numEvents=pData->event.portIn->getEventCount(); i < numEvents; ++i)
  773. {
  774. const EngineEvent& event(pData->event.portIn->getEvent(i));
  775. // Control change
  776. switch (event.type)
  777. {
  778. case kEngineEventTypeNull:
  779. break;
  780. case kEngineEventTypeControl: {
  781. const EngineControlEvent& ctrlEvent = event.ctrl;
  782. switch (ctrlEvent.type)
  783. {
  784. case kEngineControlEventTypeNull:
  785. break;
  786. case kEngineControlEventTypeParameter:
  787. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  788. // Control backend stuff
  789. if (event.channel == pData->ctrlChannel)
  790. {
  791. float value;
  792. if (MIDI_IS_CONTROL_BREATH_CONTROLLER(ctrlEvent.param) && (pData->hints & PLUGIN_CAN_DRYWET) != 0)
  793. {
  794. value = ctrlEvent.value;
  795. setDryWetRT(value, true);
  796. }
  797. if (MIDI_IS_CONTROL_CHANNEL_VOLUME(ctrlEvent.param) && (pData->hints & PLUGIN_CAN_VOLUME) != 0)
  798. {
  799. value = ctrlEvent.value*127.0f/100.0f;
  800. setVolumeRT(value, true);
  801. }
  802. if (MIDI_IS_CONTROL_BALANCE(ctrlEvent.param) && (pData->hints & PLUGIN_CAN_BALANCE) != 0)
  803. {
  804. float left, right;
  805. value = ctrlEvent.value/0.5f - 1.0f;
  806. if (value < 0.0f)
  807. {
  808. left = -1.0f;
  809. right = (value*2.0f)+1.0f;
  810. }
  811. else if (value > 0.0f)
  812. {
  813. left = (value*2.0f)-1.0f;
  814. right = 1.0f;
  815. }
  816. else
  817. {
  818. left = -1.0f;
  819. right = 1.0f;
  820. }
  821. setBalanceLeftRT(left, true);
  822. setBalanceRightRT(right, true);
  823. }
  824. }
  825. #endif
  826. break;
  827. case kEngineControlEventTypeMidiBank:
  828. if (pData->options & PLUGIN_OPTION_MAP_PROGRAM_CHANGES)
  829. {
  830. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientControlEventMidiBank);
  831. fShmRtClientControl.writeUInt(event.time);
  832. fShmRtClientControl.writeByte(event.channel);
  833. fShmRtClientControl.writeUShort(event.ctrl.param);
  834. fShmRtClientControl.commitWrite();
  835. }
  836. break;
  837. case kEngineControlEventTypeMidiProgram:
  838. if (pData->options & PLUGIN_OPTION_MAP_PROGRAM_CHANGES)
  839. {
  840. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientControlEventMidiProgram);
  841. fShmRtClientControl.writeUInt(event.time);
  842. fShmRtClientControl.writeByte(event.channel);
  843. fShmRtClientControl.writeUShort(event.ctrl.param);
  844. fShmRtClientControl.commitWrite();
  845. }
  846. break;
  847. case kEngineControlEventTypeAllSoundOff:
  848. if (pData->options & PLUGIN_OPTION_SEND_ALL_SOUND_OFF)
  849. {
  850. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientControlEventAllSoundOff);
  851. fShmRtClientControl.writeUInt(event.time);
  852. fShmRtClientControl.writeByte(event.channel);
  853. fShmRtClientControl.commitWrite();
  854. }
  855. break;
  856. case kEngineControlEventTypeAllNotesOff:
  857. if (pData->options & PLUGIN_OPTION_SEND_ALL_SOUND_OFF)
  858. {
  859. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  860. if (event.channel == pData->ctrlChannel && ! allNotesOffSent)
  861. {
  862. allNotesOffSent = true;
  863. postponeRtAllNotesOff();
  864. }
  865. #endif
  866. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientControlEventAllNotesOff);
  867. fShmRtClientControl.writeUInt(event.time);
  868. fShmRtClientControl.writeByte(event.channel);
  869. fShmRtClientControl.commitWrite();
  870. }
  871. break;
  872. } // switch (ctrlEvent.type)
  873. break;
  874. } // case kEngineEventTypeControl
  875. case kEngineEventTypeMidi: {
  876. const EngineMidiEvent& midiEvent(event.midi);
  877. if (midiEvent.size == 0 || midiEvent.size >= MAX_MIDI_VALUE)
  878. continue;
  879. const uint8_t* const midiData(midiEvent.size > EngineMidiEvent::kDataSize ? midiEvent.dataExt : midiEvent.data);
  880. uint8_t status = uint8_t(MIDI_GET_STATUS_FROM_DATA(midiData));
  881. if (status == MIDI_STATUS_CHANNEL_PRESSURE && (pData->options & PLUGIN_OPTION_SEND_CHANNEL_PRESSURE) == 0)
  882. continue;
  883. if (status == MIDI_STATUS_CONTROL_CHANGE && (pData->options & PLUGIN_OPTION_SEND_CONTROL_CHANGES) == 0)
  884. continue;
  885. if (status == MIDI_STATUS_POLYPHONIC_AFTERTOUCH && (pData->options & PLUGIN_OPTION_SEND_NOTE_AFTERTOUCH) == 0)
  886. continue;
  887. if (status == MIDI_STATUS_PITCH_WHEEL_CONTROL && (pData->options & PLUGIN_OPTION_SEND_PITCHBEND) == 0)
  888. continue;
  889. // Fix bad note-off
  890. if (status == MIDI_STATUS_NOTE_ON && midiData[2] == 0)
  891. status = MIDI_STATUS_NOTE_OFF;
  892. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientMidiEvent);
  893. fShmRtClientControl.writeUInt(event.time);
  894. fShmRtClientControl.writeByte(midiEvent.port);
  895. fShmRtClientControl.writeByte(midiEvent.size);
  896. fShmRtClientControl.writeByte(uint8_t(midiData[0] | (event.channel & MIDI_CHANNEL_BIT)));
  897. for (uint8_t j=1; j < midiEvent.size; ++j)
  898. fShmRtClientControl.writeByte(midiData[j]);
  899. fShmRtClientControl.commitWrite();
  900. if (status == MIDI_STATUS_NOTE_ON)
  901. {
  902. pData->postponeRtEvent(kPluginPostRtEventNoteOn,
  903. true,
  904. event.channel,
  905. midiData[1],
  906. midiData[2],
  907. 0.0f);
  908. }
  909. else if (status == MIDI_STATUS_NOTE_OFF)
  910. {
  911. pData->postponeRtEvent(kPluginPostRtEventNoteOff,
  912. true,
  913. event.channel,
  914. midiData[1],
  915. 0, 0.0f);
  916. }
  917. } break;
  918. }
  919. }
  920. pData->postRtEvents.trySplice();
  921. } // End of Event Input
  922. if (! processSingle(audioIn, audioOut, frames))
  923. return;
  924. // --------------------------------------------------------------------------------------------------------
  925. // MIDI Output
  926. if (pData->event.portOut != nullptr)
  927. {
  928. uint32_t time;
  929. uint8_t port, size;
  930. const uint8_t* midiData(fShmRtClientControl.data->midiOut);
  931. for (std::size_t read=0; read<kBridgeRtClientDataMidiOutSize-kBridgeBaseMidiOutHeaderSize;)
  932. {
  933. // get time
  934. time = *(const uint32_t*)midiData;
  935. midiData += 4;
  936. // get port and size
  937. port = *midiData++;
  938. size = *midiData++;
  939. if (size == 0)
  940. break;
  941. // store midi data advancing as needed
  942. uint8_t data[size];
  943. for (uint8_t j=0; j<size; ++j)
  944. data[j] = *midiData++;
  945. pData->event.portOut->writeMidiEvent(time, size, data);
  946. read += kBridgeBaseMidiOutHeaderSize + size;
  947. }
  948. // TODO
  949. (void)port;
  950. } // End of Control and MIDI Output
  951. }
  952. bool processSingle(const float* const* const audioIn, float** const audioOut, const uint32_t frames)
  953. {
  954. CARLA_SAFE_ASSERT_RETURN(! fTimedError, false);
  955. CARLA_SAFE_ASSERT_RETURN(frames > 0, false);
  956. CARLA_SAFE_ASSERT_RETURN(frames <= fBufferSize, false);
  957. if (pData->audioIn.count > 0)
  958. {
  959. CARLA_SAFE_ASSERT_RETURN(audioIn != nullptr, false);
  960. }
  961. if (pData->audioOut.count > 0)
  962. {
  963. CARLA_SAFE_ASSERT_RETURN(audioOut != nullptr, false);
  964. }
  965. // --------------------------------------------------------------------------------------------------------
  966. // Try lock, silence otherwise
  967. #ifndef STOAT_TEST_BUILD
  968. if (pData->engine->isOffline())
  969. {
  970. pData->singleMutex.lock();
  971. }
  972. else
  973. #endif
  974. if (! pData->singleMutex.tryLock())
  975. {
  976. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  977. carla_zeroFloats(audioOut[i], frames);
  978. return false;
  979. }
  980. // --------------------------------------------------------------------------------------------------------
  981. // Reset audio buffers
  982. for (uint32_t i=0; i < fInfo.aIns; ++i)
  983. carla_copyFloats(fShmAudioPool.data + (i * fBufferSize), audioIn[i], frames);
  984. // --------------------------------------------------------------------------------------------------------
  985. // TimeInfo
  986. const EngineTimeInfo timeInfo(pData->engine->getTimeInfo());
  987. BridgeTimeInfo& bridgeTimeInfo(fShmRtClientControl.data->timeInfo);
  988. bridgeTimeInfo.playing = timeInfo.playing;
  989. bridgeTimeInfo.frame = timeInfo.frame;
  990. bridgeTimeInfo.usecs = timeInfo.usecs;
  991. bridgeTimeInfo.validFlags = timeInfo.bbt.valid ? kPluginBridgeTimeInfoValidBBT : 0x0;
  992. if (timeInfo.bbt.valid)
  993. {
  994. bridgeTimeInfo.bar = timeInfo.bbt.bar;
  995. bridgeTimeInfo.beat = timeInfo.bbt.beat;
  996. bridgeTimeInfo.tick = timeInfo.bbt.tick;
  997. bridgeTimeInfo.beatsPerBar = timeInfo.bbt.beatsPerBar;
  998. bridgeTimeInfo.beatType = timeInfo.bbt.beatType;
  999. bridgeTimeInfo.ticksPerBeat = timeInfo.bbt.ticksPerBeat;
  1000. bridgeTimeInfo.beatsPerMinute = timeInfo.bbt.beatsPerMinute;
  1001. bridgeTimeInfo.barStartTick = timeInfo.bbt.barStartTick;
  1002. }
  1003. // --------------------------------------------------------------------------------------------------------
  1004. // Run plugin
  1005. {
  1006. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientProcess);
  1007. fShmRtClientControl.writeUInt(frames);
  1008. fShmRtClientControl.commitWrite();
  1009. }
  1010. waitForClient("process", fProcWaitTime);
  1011. if (fTimedOut)
  1012. {
  1013. pData->singleMutex.unlock();
  1014. return false;
  1015. }
  1016. if (fShmRtClientControl.data->procFlags)
  1017. {
  1018. fInitiated = false;
  1019. fProcCanceled = true;
  1020. }
  1021. for (uint32_t i=0; i < fInfo.aOuts; ++i)
  1022. carla_copyFloats(audioOut[i], fShmAudioPool.data + ((i + fInfo.aIns) * fBufferSize), frames);
  1023. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1024. // --------------------------------------------------------------------------------------------------------
  1025. // Post-processing (dry/wet, volume and balance)
  1026. {
  1027. const bool doVolume = (pData->hints & PLUGIN_CAN_VOLUME) != 0 && carla_isNotEqual(pData->postProc.volume, 1.0f);
  1028. const bool doDryWet = (pData->hints & PLUGIN_CAN_DRYWET) != 0 && carla_isNotEqual(pData->postProc.dryWet, 1.0f);
  1029. const bool doBalance = (pData->hints & PLUGIN_CAN_BALANCE) != 0 && ! (carla_isEqual(pData->postProc.balanceLeft, -1.0f) && carla_isEqual(pData->postProc.balanceRight, 1.0f));
  1030. const bool isMono = (pData->audioIn.count == 1);
  1031. bool isPair;
  1032. float bufValue, oldBufLeft[doBalance ? frames : 1];
  1033. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  1034. {
  1035. // Dry/Wet
  1036. if (doDryWet)
  1037. {
  1038. const uint32_t c = isMono ? 0 : i;
  1039. for (uint32_t k=0; k < frames; ++k)
  1040. {
  1041. bufValue = audioIn[c][k];
  1042. audioOut[i][k] = (audioOut[i][k] * pData->postProc.dryWet) + (bufValue * (1.0f - pData->postProc.dryWet));
  1043. }
  1044. }
  1045. // Balance
  1046. if (doBalance)
  1047. {
  1048. isPair = (i % 2 == 0);
  1049. if (isPair)
  1050. {
  1051. CARLA_ASSERT(i+1 < pData->audioOut.count);
  1052. carla_copyFloats(oldBufLeft, audioOut[i], frames);
  1053. }
  1054. float balRangeL = (pData->postProc.balanceLeft + 1.0f)/2.0f;
  1055. float balRangeR = (pData->postProc.balanceRight + 1.0f)/2.0f;
  1056. for (uint32_t k=0; k < frames; ++k)
  1057. {
  1058. if (isPair)
  1059. {
  1060. // left
  1061. audioOut[i][k] = oldBufLeft[k] * (1.0f - balRangeL);
  1062. audioOut[i][k] += audioOut[i+1][k] * (1.0f - balRangeR);
  1063. }
  1064. else
  1065. {
  1066. // right
  1067. audioOut[i][k] = audioOut[i][k] * balRangeR;
  1068. audioOut[i][k] += oldBufLeft[k] * balRangeL;
  1069. }
  1070. }
  1071. }
  1072. // Volume (and buffer copy)
  1073. if (doVolume)
  1074. {
  1075. for (uint32_t k=0; k < frames; ++k)
  1076. audioOut[i][k] *= pData->postProc.volume;
  1077. }
  1078. }
  1079. } // End of Post-processing
  1080. #endif
  1081. // --------------------------------------------------------------------------------------------------------
  1082. pData->singleMutex.unlock();
  1083. return true;
  1084. }
  1085. void bufferSizeChanged(const uint32_t newBufferSize) override
  1086. {
  1087. fBufferSize = newBufferSize;
  1088. resizeAudioPool(newBufferSize);
  1089. {
  1090. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientSetBufferSize);
  1091. fShmRtClientControl.writeUInt(newBufferSize);
  1092. fShmRtClientControl.commitWrite();
  1093. }
  1094. //fProcWaitTime = newBufferSize*1000/pData->engine->getSampleRate();
  1095. fProcWaitTime = 1000;
  1096. waitForClient("buffersize", 1000);
  1097. }
  1098. void sampleRateChanged(const double newSampleRate) override
  1099. {
  1100. {
  1101. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientSetSampleRate);
  1102. fShmRtClientControl.writeDouble(newSampleRate);
  1103. fShmRtClientControl.commitWrite();
  1104. }
  1105. //fProcWaitTime = pData->engine->getBufferSize()*1000/newSampleRate;
  1106. fProcWaitTime = 1000;
  1107. waitForClient("samplerate", 1000);
  1108. }
  1109. void offlineModeChanged(const bool isOffline) override
  1110. {
  1111. {
  1112. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientSetOnline);
  1113. fShmRtClientControl.writeBool(isOffline);
  1114. fShmRtClientControl.commitWrite();
  1115. }
  1116. waitForClient("offline", 1000);
  1117. }
  1118. // -------------------------------------------------------------------
  1119. // Post-poned UI Stuff
  1120. // -------------------------------------------------------------------
  1121. void handleNonRtData()
  1122. {
  1123. for (; fShmNonRtServerControl.isDataAvailableForReading();)
  1124. {
  1125. const PluginBridgeNonRtServerOpcode opcode(fShmNonRtServerControl.readOpcode());
  1126. //#ifdef DEBUG
  1127. if (opcode != kPluginBridgeNonRtServerPong)
  1128. {
  1129. carla_debug("CarlaPluginJack::handleNonRtData() - got opcode: %s", PluginBridgeNonRtServerOpcode2str(opcode));
  1130. }
  1131. //#endif
  1132. switch (opcode)
  1133. {
  1134. case kPluginBridgeNonRtServerNull:
  1135. case kPluginBridgeNonRtServerPong:
  1136. case kPluginBridgeNonRtServerPluginInfo1:
  1137. case kPluginBridgeNonRtServerPluginInfo2:
  1138. case kPluginBridgeNonRtServerAudioCount:
  1139. case kPluginBridgeNonRtServerMidiCount:
  1140. case kPluginBridgeNonRtServerCvCount:
  1141. case kPluginBridgeNonRtServerParameterCount:
  1142. case kPluginBridgeNonRtServerProgramCount:
  1143. case kPluginBridgeNonRtServerMidiProgramCount:
  1144. case kPluginBridgeNonRtServerPortName:
  1145. case kPluginBridgeNonRtServerParameterData1:
  1146. case kPluginBridgeNonRtServerParameterData2:
  1147. case kPluginBridgeNonRtServerParameterRanges:
  1148. case kPluginBridgeNonRtServerParameterValue:
  1149. case kPluginBridgeNonRtServerParameterValue2:
  1150. case kPluginBridgeNonRtServerParameterTouch:
  1151. case kPluginBridgeNonRtServerDefaultValue:
  1152. case kPluginBridgeNonRtServerCurrentProgram:
  1153. case kPluginBridgeNonRtServerCurrentMidiProgram:
  1154. case kPluginBridgeNonRtServerProgramName:
  1155. case kPluginBridgeNonRtServerMidiProgramData:
  1156. case kPluginBridgeNonRtServerSetCustomData:
  1157. case kPluginBridgeNonRtServerVersion:
  1158. break;
  1159. case kPluginBridgeNonRtServerSetChunkDataFile:
  1160. // uint/size, str[] (filename)
  1161. if (const uint32_t chunkFilePathSize = fShmNonRtServerControl.readUInt())
  1162. {
  1163. char chunkFilePath[chunkFilePathSize];
  1164. fShmNonRtServerControl.readCustomData(chunkFilePath, chunkFilePathSize);
  1165. }
  1166. break;
  1167. case kPluginBridgeNonRtServerSetLatency:
  1168. case kPluginBridgeNonRtServerSetParameterText:
  1169. break;
  1170. case kPluginBridgeNonRtServerReady:
  1171. fInitiated = true;
  1172. break;
  1173. case kPluginBridgeNonRtServerSaved:
  1174. break;
  1175. case kPluginBridgeNonRtServerUiClosed:
  1176. pData->engine->callback(true, true,
  1177. ENGINE_CALLBACK_UI_STATE_CHANGED,
  1178. pData->id,
  1179. 0,
  1180. 0, 0, 0.0f, nullptr);
  1181. break;
  1182. case kPluginBridgeNonRtServerError: {
  1183. // error
  1184. const uint32_t errorSize(fShmNonRtServerControl.readUInt());
  1185. char error[errorSize+1];
  1186. carla_zeroChars(error, errorSize+1);
  1187. fShmNonRtServerControl.readCustomData(error, errorSize);
  1188. if (fInitiated)
  1189. {
  1190. pData->engine->callback(true, true, ENGINE_CALLBACK_ERROR, pData->id, 0, 0, 0, 0.0f, error);
  1191. // just in case
  1192. pData->engine->setLastError(error);
  1193. fInitError = true;
  1194. }
  1195. else
  1196. {
  1197. pData->engine->setLastError(error);
  1198. fInitError = true;
  1199. fInitiated = true;
  1200. }
  1201. } break;
  1202. }
  1203. }
  1204. }
  1205. // -------------------------------------------------------------------
  1206. uintptr_t getUiBridgeProcessId() const noexcept override
  1207. {
  1208. return fBridgeThread.getProcessID();
  1209. }
  1210. // -------------------------------------------------------------------
  1211. bool init(const char* const filename, const char* const name, const char* const label)
  1212. {
  1213. CARLA_SAFE_ASSERT_RETURN(pData->engine != nullptr, false);
  1214. // ---------------------------------------------------------------
  1215. // first checks
  1216. if (pData->client != nullptr)
  1217. {
  1218. pData->engine->setLastError("Plugin client is already registered");
  1219. return false;
  1220. }
  1221. if (filename == nullptr || filename[0] == '\0')
  1222. {
  1223. pData->engine->setLastError("null filename");
  1224. return false;
  1225. }
  1226. if (label == nullptr || label[0] == '\0')
  1227. {
  1228. pData->engine->setLastError("null label");
  1229. return false;
  1230. }
  1231. // ---------------------------------------------------------------
  1232. // check setup
  1233. if (std::strlen(label) < 6)
  1234. {
  1235. pData->engine->setLastError("invalid application setup received");
  1236. return false;
  1237. }
  1238. for (int i=4; --i >= 0;) {
  1239. CARLA_SAFE_ASSERT_RETURN(label[i] >= '0' && label[i] <= '0'+64, false);
  1240. }
  1241. for (int i=6; --i >= 4;) {
  1242. CARLA_SAFE_ASSERT_RETURN(label[i] >= '0' && label[i] < '0'+0x4f, false);
  1243. }
  1244. fInfo.aIns = static_cast<uint8_t>(label[0] - '0');
  1245. fInfo.aOuts = static_cast<uint8_t>(label[1] - '0');
  1246. fInfo.mIns = static_cast<uint8_t>(carla_minPositive(label[2] - '0', 1));
  1247. fInfo.mOuts = static_cast<uint8_t>(carla_minPositive(label[3] - '0', 1));
  1248. fInfo.setupLabel = label;
  1249. // ---------------------------------------------------------------
  1250. // set project unique id
  1251. if (label[6] == '\0')
  1252. setupUniqueProjectID();
  1253. // ---------------------------------------------------------------
  1254. // set icon
  1255. pData->iconName = carla_strdup_safe("application");
  1256. // ---------------------------------------------------------------
  1257. // set info
  1258. pData->filename = carla_strdup(filename);
  1259. if (name != nullptr && name[0] != '\0')
  1260. pData->name = pData->engine->getUniquePluginName(name);
  1261. else
  1262. pData->name = pData->engine->getUniquePluginName("Jack Application");
  1263. std::srand(static_cast<uint>(std::time(nullptr)));
  1264. // ---------------------------------------------------------------
  1265. // init sem/shm
  1266. if (! fShmAudioPool.initializeServer())
  1267. {
  1268. carla_stderr("Failed to initialize shared memory audio pool");
  1269. return false;
  1270. }
  1271. if (! fShmRtClientControl.initializeServer())
  1272. {
  1273. carla_stderr("Failed to initialize RT client control");
  1274. fShmAudioPool.clear();
  1275. return false;
  1276. }
  1277. if (! fShmNonRtClientControl.initializeServer())
  1278. {
  1279. carla_stderr("Failed to initialize Non-RT client control");
  1280. fShmRtClientControl.clear();
  1281. fShmAudioPool.clear();
  1282. return false;
  1283. }
  1284. if (! fShmNonRtServerControl.initializeServer())
  1285. {
  1286. carla_stderr("Failed to initialize Non-RT server control");
  1287. fShmNonRtClientControl.clear();
  1288. fShmRtClientControl.clear();
  1289. fShmAudioPool.clear();
  1290. return false;
  1291. }
  1292. // ---------------------------------------------------------------
  1293. // setup hints and options
  1294. fSetupHints = static_cast<uint>(label[5] - '0');
  1295. // FIXME dryWet broken
  1296. pData->hints = PLUGIN_IS_BRIDGE | PLUGIN_OPTION_FIXED_BUFFERS;
  1297. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1298. pData->hints |= /*PLUGIN_CAN_DRYWET |*/ PLUGIN_CAN_VOLUME | PLUGIN_CAN_BALANCE;
  1299. #endif
  1300. //fInfo.optionsAvailable = optionAv;
  1301. if (fSetupHints & LIBJACK_FLAG_CONTROL_WINDOW)
  1302. pData->hints |= PLUGIN_HAS_CUSTOM_UI;
  1303. // ---------------------------------------------------------------
  1304. // init bridge thread
  1305. {
  1306. char shmIdsStr[6*4+1];
  1307. carla_zeroChars(shmIdsStr, 6*4+1);
  1308. std::strncpy(shmIdsStr+6*0, &fShmAudioPool.filename[fShmAudioPool.filename.length()-6], 6);
  1309. std::strncpy(shmIdsStr+6*1, &fShmRtClientControl.filename[fShmRtClientControl.filename.length()-6], 6);
  1310. std::strncpy(shmIdsStr+6*2, &fShmNonRtClientControl.filename[fShmNonRtClientControl.filename.length()-6], 6);
  1311. std::strncpy(shmIdsStr+6*3, &fShmNonRtServerControl.filename[fShmNonRtServerControl.filename.length()-6], 6);
  1312. fBridgeThread.setData(shmIdsStr, fInfo.setupLabel);
  1313. }
  1314. if (! restartBridgeThread())
  1315. return false;
  1316. // ---------------------------------------------------------------
  1317. // register client
  1318. if (pData->name == nullptr)
  1319. pData->name = pData->engine->getUniquePluginName("unknown");
  1320. pData->client = pData->engine->addClient(this);
  1321. if (pData->client == nullptr || ! pData->client->isOk())
  1322. {
  1323. pData->engine->setLastError("Failed to register plugin client");
  1324. return false;
  1325. }
  1326. return true;
  1327. }
  1328. private:
  1329. bool fInitiated;
  1330. bool fInitError;
  1331. bool fTimedOut;
  1332. bool fTimedError;
  1333. bool fProcCanceled;
  1334. uint fBufferSize;
  1335. uint fProcWaitTime;
  1336. uint fSetupHints;
  1337. CarlaPluginJackThread fBridgeThread;
  1338. BridgeAudioPool fShmAudioPool;
  1339. BridgeRtClientControl fShmRtClientControl;
  1340. BridgeNonRtClientControl fShmNonRtClientControl;
  1341. BridgeNonRtServerControl fShmNonRtServerControl;
  1342. struct Info {
  1343. uint8_t aIns, aOuts;
  1344. uint8_t mIns, mOuts;
  1345. uint optionsAvailable;
  1346. CarlaString setupLabel;
  1347. std::vector<uint8_t> chunk;
  1348. Info()
  1349. : aIns(0),
  1350. aOuts(0),
  1351. mIns(0),
  1352. mOuts(0),
  1353. optionsAvailable(0),
  1354. setupLabel(),
  1355. chunk() {}
  1356. CARLA_DECLARE_NON_COPY_STRUCT(Info)
  1357. } fInfo;
  1358. void handleProcessStopped() noexcept
  1359. {
  1360. const bool wasActive = pData->active;
  1361. pData->active = false;
  1362. if (wasActive)
  1363. {
  1364. pData->engine->callback(true, true,
  1365. ENGINE_CALLBACK_PARAMETER_VALUE_CHANGED,
  1366. pData->id,
  1367. PARAMETER_ACTIVE,
  1368. 0, 0,
  1369. 0.0f,
  1370. nullptr);
  1371. }
  1372. if (pData->hints & PLUGIN_HAS_CUSTOM_UI)
  1373. pData->engine->callback(true, true,
  1374. ENGINE_CALLBACK_UI_STATE_CHANGED,
  1375. pData->id,
  1376. 0,
  1377. 0, 0, 0.0f, nullptr);
  1378. }
  1379. void resizeAudioPool(const uint32_t bufferSize)
  1380. {
  1381. fShmAudioPool.resize(bufferSize, static_cast<uint32_t>(fInfo.aIns+fInfo.aOuts), 0);
  1382. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientSetAudioPool);
  1383. fShmRtClientControl.writeULong(static_cast<uint64_t>(fShmAudioPool.dataSize));
  1384. fShmRtClientControl.commitWrite();
  1385. waitForClient("resize-pool", 5000);
  1386. }
  1387. void setupUniqueProjectID()
  1388. {
  1389. const char* const engineProjectFilename = pData->engine->getCurrentProjectFilename();
  1390. carla_stdout("setupUniqueProjectID %s", engineProjectFilename);
  1391. if (engineProjectFilename == nullptr || engineProjectFilename[0] == '\0')
  1392. return;
  1393. const File file(engineProjectFilename);
  1394. CARLA_SAFE_ASSERT_RETURN(file.existsAsFile(),);
  1395. CARLA_SAFE_ASSERT_RETURN(file.getFileExtension().isNotEmpty(),);
  1396. char code[6];
  1397. code[5] = '\0';
  1398. for (;;)
  1399. {
  1400. static const char* const kValidChars =
  1401. "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  1402. "abcdefghijklmnopqrstuvwxyz"
  1403. "0123456789";
  1404. static const size_t kValidCharsLen(std::strlen(kValidChars)-1U);
  1405. code[0] = kValidChars[safe_rand(kValidCharsLen)];
  1406. code[1] = kValidChars[safe_rand(kValidCharsLen)];
  1407. code[2] = kValidChars[safe_rand(kValidCharsLen)];
  1408. code[3] = kValidChars[safe_rand(kValidCharsLen)];
  1409. code[4] = kValidChars[safe_rand(kValidCharsLen)];
  1410. const File newFile(file.withFileExtension(code));
  1411. if (newFile.existsAsFile())
  1412. continue;
  1413. fInfo.setupLabel += code;
  1414. carla_stdout("new label %s", fInfo.setupLabel.buffer());
  1415. break;
  1416. }
  1417. }
  1418. bool restartBridgeThread()
  1419. {
  1420. fInitiated = false;
  1421. fInitError = false;
  1422. fTimedError = false;
  1423. // reset memory
  1424. fProcCanceled = false;
  1425. fShmRtClientControl.data->procFlags = 0;
  1426. carla_zeroStruct(fShmRtClientControl.data->timeInfo);
  1427. carla_zeroBytes(fShmRtClientControl.data->midiOut, kBridgeRtClientDataMidiOutSize);
  1428. fShmRtClientControl.clearData();
  1429. fShmNonRtClientControl.clearData();
  1430. fShmNonRtServerControl.clearData();
  1431. // initial values
  1432. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientVersion);
  1433. fShmNonRtClientControl.writeUInt(CARLA_PLUGIN_BRIDGE_API_VERSION_CURRENT);
  1434. fShmNonRtClientControl.writeUInt(static_cast<uint32_t>(sizeof(BridgeRtClientData)));
  1435. fShmNonRtClientControl.writeUInt(static_cast<uint32_t>(sizeof(BridgeNonRtClientData)));
  1436. fShmNonRtClientControl.writeUInt(static_cast<uint32_t>(sizeof(BridgeNonRtServerData)));
  1437. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientInitialSetup);
  1438. fShmNonRtClientControl.writeUInt(pData->engine->getBufferSize());
  1439. fShmNonRtClientControl.writeDouble(pData->engine->getSampleRate());
  1440. fShmNonRtClientControl.commitWrite();
  1441. if (fShmAudioPool.dataSize != 0)
  1442. {
  1443. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientSetAudioPool);
  1444. fShmRtClientControl.writeULong(static_cast<uint64_t>(fShmAudioPool.dataSize));
  1445. fShmRtClientControl.commitWrite();
  1446. }
  1447. else
  1448. {
  1449. // testing dummy message
  1450. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientNull);
  1451. fShmRtClientControl.commitWrite();
  1452. }
  1453. fBridgeThread.startThread();
  1454. const bool needsCancelableAction = ! pData->engine->isLoadingProject();
  1455. const bool needsEngineIdle = pData->engine->getType() != kEngineTypePlugin;
  1456. CarlaString actionName;
  1457. if (needsCancelableAction)
  1458. {
  1459. if (fSetupHints & LIBJACK_FLAG_EXTERNAL_START)
  1460. {
  1461. const EngineOptions& options(pData->engine->getOptions());
  1462. CarlaString binaryDir(options.binaryDir);
  1463. char* const hwVars = fBridgeThread.getEnvVarsToExport();
  1464. actionName = "Waiting for external JACK application start, please use the following environment variables:\n";
  1465. actionName += hwVars;
  1466. delete[] hwVars;
  1467. }
  1468. else
  1469. {
  1470. actionName = "Loading JACK application";
  1471. }
  1472. pData->engine->setActionCanceled(false);
  1473. pData->engine->callback(true, true,
  1474. ENGINE_CALLBACK_CANCELABLE_ACTION,
  1475. pData->id,
  1476. 1,
  1477. 0, 0, 0.0f,
  1478. actionName.buffer());
  1479. }
  1480. for (;fBridgeThread.isThreadRunning();)
  1481. {
  1482. pData->engine->callback(true, false, ENGINE_CALLBACK_IDLE, 0, 0, 0, 0, 0.0f, nullptr);
  1483. if (needsEngineIdle)
  1484. pData->engine->idle();
  1485. idle();
  1486. if (fInitiated)
  1487. break;
  1488. if (pData->engine->isAboutToClose() || pData->engine->wasActionCanceled())
  1489. break;
  1490. carla_msleep(5);
  1491. }
  1492. if (needsCancelableAction)
  1493. {
  1494. pData->engine->callback(true, true,
  1495. ENGINE_CALLBACK_CANCELABLE_ACTION,
  1496. pData->id,
  1497. 0,
  1498. 0, 0, 0.0f,
  1499. actionName.buffer());
  1500. }
  1501. if (fInitError || ! fInitiated)
  1502. {
  1503. fBridgeThread.stopThread(6000);
  1504. if (! fInitError)
  1505. pData->engine->setLastError("Timeout while waiting for a response from plugin-bridge\n"
  1506. "(or the plugin crashed on initialization?)");
  1507. return false;
  1508. }
  1509. return true;
  1510. }
  1511. void waitForClient(const char* const action, const uint msecs)
  1512. {
  1513. CARLA_SAFE_ASSERT_RETURN(! fTimedOut,);
  1514. CARLA_SAFE_ASSERT_RETURN(! fTimedError,);
  1515. if (fShmRtClientControl.waitForClient(msecs))
  1516. return;
  1517. fTimedOut = true;
  1518. carla_stderr2("waitForClient(%s) timed out", action);
  1519. }
  1520. CARLA_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(CarlaPluginJack)
  1521. };
  1522. CARLA_BACKEND_END_NAMESPACE
  1523. #endif // CARLA_OS_LINUX
  1524. // -------------------------------------------------------------------------------------------------------------------
  1525. CARLA_BACKEND_START_NAMESPACE
  1526. CarlaPlugin* CarlaPlugin::newJackApp(const Initializer& init)
  1527. {
  1528. carla_debug("CarlaPlugin::newJackApp({%p, \"%s\", \"%s\", \"%s\"})", init.engine, init.filename, init.name, init.label);
  1529. #ifdef CARLA_OS_LINUX
  1530. CarlaPluginJack* const plugin(new CarlaPluginJack(init.engine, init.id));
  1531. if (! plugin->init(init.filename, init.name, init.label))
  1532. {
  1533. delete plugin;
  1534. return nullptr;
  1535. }
  1536. return plugin;
  1537. #else
  1538. init.engine->setLastError("JACK Application support not available");
  1539. return nullptr;
  1540. #endif
  1541. }
  1542. CARLA_BACKEND_END_NAMESPACE
  1543. // -------------------------------------------------------------------------------------------------------------------