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.

1941 lines
64KB

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