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.

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