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.

1852 lines
61KB

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