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.

1956 lines
66KB

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