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.

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