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.

1999 lines
67KB

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