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.

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