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.

1943 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);
  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);
  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);
  820. setBalanceRightRT(right);
  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. event.channel,
  902. midiData[1],
  903. midiData[2],
  904. 0.0f);
  905. }
  906. else if (status == MIDI_STATUS_NOTE_OFF)
  907. {
  908. pData->postponeRtEvent(kPluginPostRtEventNoteOff,
  909. event.channel,
  910. midiData[1],
  911. 0, 0.0f);
  912. }
  913. } break;
  914. }
  915. }
  916. pData->postRtEvents.trySplice();
  917. } // End of Event Input
  918. if (! processSingle(audioIn, audioOut, frames))
  919. return;
  920. // --------------------------------------------------------------------------------------------------------
  921. // MIDI Output
  922. if (pData->event.portOut != nullptr)
  923. {
  924. uint32_t time;
  925. uint8_t port, size;
  926. const uint8_t* midiData(fShmRtClientControl.data->midiOut);
  927. for (std::size_t read=0; read<kBridgeRtClientDataMidiOutSize-kBridgeBaseMidiOutHeaderSize;)
  928. {
  929. // get time
  930. time = *(const uint32_t*)midiData;
  931. midiData += 4;
  932. // get port and size
  933. port = *midiData++;
  934. size = *midiData++;
  935. if (size == 0)
  936. break;
  937. // store midi data advancing as needed
  938. uint8_t data[size];
  939. for (uint8_t j=0; j<size; ++j)
  940. data[j] = *midiData++;
  941. pData->event.portOut->writeMidiEvent(time, size, data);
  942. read += kBridgeBaseMidiOutHeaderSize + size;
  943. }
  944. // TODO
  945. (void)port;
  946. } // End of Control and MIDI Output
  947. }
  948. bool processSingle(const float** const audioIn, float** const audioOut, const uint32_t frames)
  949. {
  950. CARLA_SAFE_ASSERT_RETURN(! fTimedError, false);
  951. CARLA_SAFE_ASSERT_RETURN(frames > 0, false);
  952. CARLA_SAFE_ASSERT_RETURN(frames <= fBufferSize, false);
  953. if (pData->audioIn.count > 0)
  954. {
  955. CARLA_SAFE_ASSERT_RETURN(audioIn != nullptr, false);
  956. }
  957. if (pData->audioOut.count > 0)
  958. {
  959. CARLA_SAFE_ASSERT_RETURN(audioOut != nullptr, false);
  960. }
  961. // --------------------------------------------------------------------------------------------------------
  962. // Try lock, silence otherwise
  963. #ifndef STOAT_TEST_BUILD
  964. if (pData->engine->isOffline())
  965. {
  966. pData->singleMutex.lock();
  967. }
  968. else
  969. #endif
  970. if (! pData->singleMutex.tryLock())
  971. {
  972. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  973. carla_zeroFloats(audioOut[i], frames);
  974. return false;
  975. }
  976. // --------------------------------------------------------------------------------------------------------
  977. // Reset audio buffers
  978. for (uint32_t i=0; i < fInfo.aIns; ++i)
  979. carla_copyFloats(fShmAudioPool.data + (i * fBufferSize), audioIn[i], frames);
  980. // --------------------------------------------------------------------------------------------------------
  981. // TimeInfo
  982. const EngineTimeInfo timeInfo(pData->engine->getTimeInfo());
  983. BridgeTimeInfo& bridgeTimeInfo(fShmRtClientControl.data->timeInfo);
  984. bridgeTimeInfo.playing = timeInfo.playing;
  985. bridgeTimeInfo.frame = timeInfo.frame;
  986. bridgeTimeInfo.usecs = timeInfo.usecs;
  987. bridgeTimeInfo.validFlags = timeInfo.bbt.valid ? kPluginBridgeTimeInfoValidBBT : 0x0;
  988. if (timeInfo.bbt.valid)
  989. {
  990. bridgeTimeInfo.bar = timeInfo.bbt.bar;
  991. bridgeTimeInfo.beat = timeInfo.bbt.beat;
  992. bridgeTimeInfo.tick = timeInfo.bbt.tick;
  993. bridgeTimeInfo.beatsPerBar = timeInfo.bbt.beatsPerBar;
  994. bridgeTimeInfo.beatType = timeInfo.bbt.beatType;
  995. bridgeTimeInfo.ticksPerBeat = timeInfo.bbt.ticksPerBeat;
  996. bridgeTimeInfo.beatsPerMinute = timeInfo.bbt.beatsPerMinute;
  997. bridgeTimeInfo.barStartTick = timeInfo.bbt.barStartTick;
  998. }
  999. // --------------------------------------------------------------------------------------------------------
  1000. // Run plugin
  1001. {
  1002. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientProcess);
  1003. fShmRtClientControl.writeUInt(frames);
  1004. fShmRtClientControl.commitWrite();
  1005. }
  1006. waitForClient("process", fProcWaitTime);
  1007. if (fTimedOut)
  1008. {
  1009. pData->singleMutex.unlock();
  1010. return false;
  1011. }
  1012. if (fShmRtClientControl.data->procFlags)
  1013. {
  1014. fInitiated = false;
  1015. fProcCanceled = true;
  1016. }
  1017. for (uint32_t i=0; i < fInfo.aOuts; ++i)
  1018. carla_copyFloats(audioOut[i], fShmAudioPool.data + ((i + fInfo.aIns) * fBufferSize), frames);
  1019. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1020. // --------------------------------------------------------------------------------------------------------
  1021. // Post-processing (dry/wet, volume and balance)
  1022. {
  1023. const bool doVolume = (pData->hints & PLUGIN_CAN_VOLUME) != 0 && carla_isNotEqual(pData->postProc.volume, 1.0f);
  1024. const bool doDryWet = (pData->hints & PLUGIN_CAN_DRYWET) != 0 && carla_isNotEqual(pData->postProc.dryWet, 1.0f);
  1025. const bool doBalance = (pData->hints & PLUGIN_CAN_BALANCE) != 0 && ! (carla_isEqual(pData->postProc.balanceLeft, -1.0f) && carla_isEqual(pData->postProc.balanceRight, 1.0f));
  1026. const bool isMono = (pData->audioIn.count == 1);
  1027. bool isPair;
  1028. float bufValue, oldBufLeft[doBalance ? frames : 1];
  1029. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  1030. {
  1031. // Dry/Wet
  1032. if (doDryWet)
  1033. {
  1034. const uint32_t c = isMono ? 0 : i;
  1035. for (uint32_t k=0; k < frames; ++k)
  1036. {
  1037. bufValue = audioIn[c][k];
  1038. audioOut[i][k] = (audioOut[i][k] * pData->postProc.dryWet) + (bufValue * (1.0f - pData->postProc.dryWet));
  1039. }
  1040. }
  1041. // Balance
  1042. if (doBalance)
  1043. {
  1044. isPair = (i % 2 == 0);
  1045. if (isPair)
  1046. {
  1047. CARLA_ASSERT(i+1 < pData->audioOut.count);
  1048. carla_copyFloats(oldBufLeft, audioOut[i], frames);
  1049. }
  1050. float balRangeL = (pData->postProc.balanceLeft + 1.0f)/2.0f;
  1051. float balRangeR = (pData->postProc.balanceRight + 1.0f)/2.0f;
  1052. for (uint32_t k=0; k < frames; ++k)
  1053. {
  1054. if (isPair)
  1055. {
  1056. // left
  1057. audioOut[i][k] = oldBufLeft[k] * (1.0f - balRangeL);
  1058. audioOut[i][k] += audioOut[i+1][k] * (1.0f - balRangeR);
  1059. }
  1060. else
  1061. {
  1062. // right
  1063. audioOut[i][k] = audioOut[i][k] * balRangeR;
  1064. audioOut[i][k] += oldBufLeft[k] * balRangeL;
  1065. }
  1066. }
  1067. }
  1068. // Volume (and buffer copy)
  1069. if (doVolume)
  1070. {
  1071. for (uint32_t k=0; k < frames; ++k)
  1072. audioOut[i][k] *= pData->postProc.volume;
  1073. }
  1074. }
  1075. } // End of Post-processing
  1076. #endif
  1077. // --------------------------------------------------------------------------------------------------------
  1078. pData->singleMutex.unlock();
  1079. return true;
  1080. }
  1081. void bufferSizeChanged(const uint32_t newBufferSize) override
  1082. {
  1083. fBufferSize = newBufferSize;
  1084. resizeAudioPool(newBufferSize);
  1085. {
  1086. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientSetBufferSize);
  1087. fShmRtClientControl.writeUInt(newBufferSize);
  1088. fShmRtClientControl.commitWrite();
  1089. }
  1090. //fProcWaitTime = newBufferSize*1000/pData->engine->getSampleRate();
  1091. fProcWaitTime = 1000;
  1092. waitForClient("buffersize", 1000);
  1093. }
  1094. void sampleRateChanged(const double newSampleRate) override
  1095. {
  1096. {
  1097. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientSetSampleRate);
  1098. fShmRtClientControl.writeDouble(newSampleRate);
  1099. fShmRtClientControl.commitWrite();
  1100. }
  1101. //fProcWaitTime = pData->engine->getBufferSize()*1000/newSampleRate;
  1102. fProcWaitTime = 1000;
  1103. waitForClient("samplerate", 1000);
  1104. }
  1105. void offlineModeChanged(const bool isOffline) override
  1106. {
  1107. {
  1108. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientSetOnline);
  1109. fShmRtClientControl.writeBool(isOffline);
  1110. fShmRtClientControl.commitWrite();
  1111. }
  1112. waitForClient("offline", 1000);
  1113. }
  1114. // -------------------------------------------------------------------
  1115. // Post-poned UI Stuff
  1116. // -------------------------------------------------------------------
  1117. void handleNonRtData()
  1118. {
  1119. for (; fShmNonRtServerControl.isDataAvailableForReading();)
  1120. {
  1121. const PluginBridgeNonRtServerOpcode opcode(fShmNonRtServerControl.readOpcode());
  1122. //#ifdef DEBUG
  1123. if (opcode != kPluginBridgeNonRtServerPong)
  1124. {
  1125. carla_debug("CarlaPluginJack::handleNonRtData() - got opcode: %s", PluginBridgeNonRtServerOpcode2str(opcode));
  1126. }
  1127. //#endif
  1128. switch (opcode)
  1129. {
  1130. case kPluginBridgeNonRtServerNull:
  1131. case kPluginBridgeNonRtServerPong:
  1132. case kPluginBridgeNonRtServerPluginInfo1:
  1133. case kPluginBridgeNonRtServerPluginInfo2:
  1134. case kPluginBridgeNonRtServerAudioCount:
  1135. case kPluginBridgeNonRtServerMidiCount:
  1136. case kPluginBridgeNonRtServerCvCount:
  1137. case kPluginBridgeNonRtServerParameterCount:
  1138. case kPluginBridgeNonRtServerProgramCount:
  1139. case kPluginBridgeNonRtServerMidiProgramCount:
  1140. case kPluginBridgeNonRtServerPortName:
  1141. case kPluginBridgeNonRtServerParameterData1:
  1142. case kPluginBridgeNonRtServerParameterData2:
  1143. case kPluginBridgeNonRtServerParameterRanges:
  1144. case kPluginBridgeNonRtServerParameterValue:
  1145. case kPluginBridgeNonRtServerParameterValue2:
  1146. case kPluginBridgeNonRtServerParameterTouch:
  1147. case kPluginBridgeNonRtServerDefaultValue:
  1148. case kPluginBridgeNonRtServerCurrentProgram:
  1149. case kPluginBridgeNonRtServerCurrentMidiProgram:
  1150. case kPluginBridgeNonRtServerProgramName:
  1151. case kPluginBridgeNonRtServerMidiProgramData:
  1152. case kPluginBridgeNonRtServerSetCustomData:
  1153. break;
  1154. case kPluginBridgeNonRtServerSetChunkDataFile:
  1155. // uint/size, str[] (filename)
  1156. if (const uint32_t chunkFilePathSize = fShmNonRtServerControl.readUInt())
  1157. {
  1158. char chunkFilePath[chunkFilePathSize];
  1159. fShmNonRtServerControl.readCustomData(chunkFilePath, chunkFilePathSize);
  1160. }
  1161. break;
  1162. case kPluginBridgeNonRtServerSetLatency:
  1163. case kPluginBridgeNonRtServerSetParameterText:
  1164. break;
  1165. case kPluginBridgeNonRtServerReady:
  1166. fInitiated = true;
  1167. break;
  1168. case kPluginBridgeNonRtServerSaved:
  1169. break;
  1170. case kPluginBridgeNonRtServerUiClosed:
  1171. pData->engine->callback(true, true,
  1172. ENGINE_CALLBACK_UI_STATE_CHANGED,
  1173. pData->id,
  1174. 0,
  1175. 0, 0, 0.0f, nullptr);
  1176. break;
  1177. case kPluginBridgeNonRtServerError: {
  1178. // error
  1179. const uint32_t errorSize(fShmNonRtServerControl.readUInt());
  1180. char error[errorSize+1];
  1181. carla_zeroChars(error, errorSize+1);
  1182. fShmNonRtServerControl.readCustomData(error, errorSize);
  1183. if (fInitiated)
  1184. {
  1185. pData->engine->callback(true, true, ENGINE_CALLBACK_ERROR, pData->id, 0, 0, 0, 0.0f, error);
  1186. // just in case
  1187. pData->engine->setLastError(error);
  1188. fInitError = true;
  1189. }
  1190. else
  1191. {
  1192. pData->engine->setLastError(error);
  1193. fInitError = true;
  1194. fInitiated = true;
  1195. }
  1196. } break;
  1197. }
  1198. }
  1199. }
  1200. // -------------------------------------------------------------------
  1201. uintptr_t getUiBridgeProcessId() const noexcept override
  1202. {
  1203. return fBridgeThread.getProcessID();
  1204. }
  1205. // -------------------------------------------------------------------
  1206. bool init(const char* const filename, const char* const name, const char* const label)
  1207. {
  1208. CARLA_SAFE_ASSERT_RETURN(pData->engine != nullptr, false);
  1209. // ---------------------------------------------------------------
  1210. // first checks
  1211. if (pData->client != nullptr)
  1212. {
  1213. pData->engine->setLastError("Plugin client is already registered");
  1214. return false;
  1215. }
  1216. if (filename == nullptr || filename[0] == '\0')
  1217. {
  1218. pData->engine->setLastError("null filename");
  1219. return false;
  1220. }
  1221. if (label == nullptr || label[0] == '\0')
  1222. {
  1223. pData->engine->setLastError("null label");
  1224. return false;
  1225. }
  1226. // ---------------------------------------------------------------
  1227. // check setup
  1228. if (std::strlen(label) < 6)
  1229. {
  1230. pData->engine->setLastError("invalid application setup received");
  1231. return false;
  1232. }
  1233. for (int i=4; --i >= 0;) {
  1234. CARLA_SAFE_ASSERT_RETURN(label[i] >= '0' && label[i] <= '0'+64, false);
  1235. }
  1236. for (int i=6; --i >= 4;) {
  1237. CARLA_SAFE_ASSERT_RETURN(label[i] >= '0' && label[i] < '0'+0x4f, false);
  1238. }
  1239. fInfo.aIns = static_cast<uint8_t>(label[0] - '0');
  1240. fInfo.aOuts = static_cast<uint8_t>(label[1] - '0');
  1241. fInfo.mIns = static_cast<uint8_t>(carla_minPositive(label[2] - '0', 1));
  1242. fInfo.mOuts = static_cast<uint8_t>(carla_minPositive(label[3] - '0', 1));
  1243. fInfo.setupLabel = label;
  1244. // ---------------------------------------------------------------
  1245. // set project unique id
  1246. if (label[6] == '\0')
  1247. setupUniqueProjectID();
  1248. // ---------------------------------------------------------------
  1249. // set icon
  1250. pData->iconName = carla_strdup_safe("application");
  1251. // ---------------------------------------------------------------
  1252. // set info
  1253. pData->filename = carla_strdup(filename);
  1254. if (name != nullptr && name[0] != '\0')
  1255. pData->name = pData->engine->getUniquePluginName(name);
  1256. else
  1257. pData->name = pData->engine->getUniquePluginName("Jack Application");
  1258. std::srand(static_cast<uint>(std::time(nullptr)));
  1259. // ---------------------------------------------------------------
  1260. // init sem/shm
  1261. if (! fShmAudioPool.initializeServer())
  1262. {
  1263. carla_stderr("Failed to initialize shared memory audio pool");
  1264. return false;
  1265. }
  1266. if (! fShmRtClientControl.initializeServer())
  1267. {
  1268. carla_stderr("Failed to initialize RT client control");
  1269. fShmAudioPool.clear();
  1270. return false;
  1271. }
  1272. if (! fShmNonRtClientControl.initializeServer())
  1273. {
  1274. carla_stderr("Failed to initialize Non-RT client control");
  1275. fShmRtClientControl.clear();
  1276. fShmAudioPool.clear();
  1277. return false;
  1278. }
  1279. if (! fShmNonRtServerControl.initializeServer())
  1280. {
  1281. carla_stderr("Failed to initialize Non-RT server control");
  1282. fShmNonRtClientControl.clear();
  1283. fShmRtClientControl.clear();
  1284. fShmAudioPool.clear();
  1285. return false;
  1286. }
  1287. // ---------------------------------------------------------------
  1288. // setup hints and options
  1289. fSetupHints = static_cast<uint>(label[5] - '0');
  1290. // FIXME dryWet broken
  1291. pData->hints = PLUGIN_IS_BRIDGE | PLUGIN_OPTION_FIXED_BUFFERS;
  1292. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1293. pData->hints |= /*PLUGIN_CAN_DRYWET |*/ PLUGIN_CAN_VOLUME | PLUGIN_CAN_BALANCE;
  1294. #endif
  1295. //fInfo.optionsAvailable = optionAv;
  1296. if (fSetupHints & LIBJACK_FLAG_CONTROL_WINDOW)
  1297. pData->hints |= PLUGIN_HAS_CUSTOM_UI;
  1298. // ---------------------------------------------------------------
  1299. // init bridge thread
  1300. {
  1301. char shmIdsStr[6*4+1];
  1302. carla_zeroChars(shmIdsStr, 6*4+1);
  1303. std::strncpy(shmIdsStr+6*0, &fShmAudioPool.filename[fShmAudioPool.filename.length()-6], 6);
  1304. std::strncpy(shmIdsStr+6*1, &fShmRtClientControl.filename[fShmRtClientControl.filename.length()-6], 6);
  1305. std::strncpy(shmIdsStr+6*2, &fShmNonRtClientControl.filename[fShmNonRtClientControl.filename.length()-6], 6);
  1306. std::strncpy(shmIdsStr+6*3, &fShmNonRtServerControl.filename[fShmNonRtServerControl.filename.length()-6], 6);
  1307. fBridgeThread.setData(shmIdsStr, fInfo.setupLabel);
  1308. }
  1309. if (! restartBridgeThread())
  1310. return false;
  1311. // ---------------------------------------------------------------
  1312. // register client
  1313. if (pData->name == nullptr)
  1314. pData->name = pData->engine->getUniquePluginName("unknown");
  1315. pData->client = pData->engine->addClient(this);
  1316. if (pData->client == nullptr || ! pData->client->isOk())
  1317. {
  1318. pData->engine->setLastError("Failed to register plugin client");
  1319. return false;
  1320. }
  1321. return true;
  1322. }
  1323. private:
  1324. bool fInitiated;
  1325. bool fInitError;
  1326. bool fTimedOut;
  1327. bool fTimedError;
  1328. bool fProcCanceled;
  1329. uint fBufferSize;
  1330. uint fProcWaitTime;
  1331. uint fSetupHints;
  1332. CarlaPluginJackThread fBridgeThread;
  1333. BridgeAudioPool fShmAudioPool;
  1334. BridgeRtClientControl fShmRtClientControl;
  1335. BridgeNonRtClientControl fShmNonRtClientControl;
  1336. BridgeNonRtServerControl fShmNonRtServerControl;
  1337. struct Info {
  1338. uint8_t aIns, aOuts;
  1339. uint8_t mIns, mOuts;
  1340. uint optionsAvailable;
  1341. CarlaString setupLabel;
  1342. std::vector<uint8_t> chunk;
  1343. Info()
  1344. : aIns(0),
  1345. aOuts(0),
  1346. mIns(0),
  1347. mOuts(0),
  1348. optionsAvailable(0),
  1349. setupLabel(),
  1350. chunk() {}
  1351. CARLA_DECLARE_NON_COPY_STRUCT(Info)
  1352. } fInfo;
  1353. void handleProcessStopped() noexcept
  1354. {
  1355. const bool wasActive = pData->active;
  1356. pData->active = false;
  1357. if (wasActive)
  1358. {
  1359. pData->engine->callback(true, true,
  1360. ENGINE_CALLBACK_PARAMETER_VALUE_CHANGED,
  1361. pData->id,
  1362. PARAMETER_ACTIVE,
  1363. 0, 0,
  1364. 0.0f,
  1365. nullptr);
  1366. }
  1367. if (pData->hints & PLUGIN_HAS_CUSTOM_UI)
  1368. pData->engine->callback(true, true,
  1369. ENGINE_CALLBACK_UI_STATE_CHANGED,
  1370. pData->id,
  1371. 0,
  1372. 0, 0, 0.0f, nullptr);
  1373. }
  1374. void resizeAudioPool(const uint32_t bufferSize)
  1375. {
  1376. fShmAudioPool.resize(bufferSize, static_cast<uint32_t>(fInfo.aIns+fInfo.aOuts), 0);
  1377. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientSetAudioPool);
  1378. fShmRtClientControl.writeULong(static_cast<uint64_t>(fShmAudioPool.dataSize));
  1379. fShmRtClientControl.commitWrite();
  1380. waitForClient("resize-pool", 5000);
  1381. }
  1382. void setupUniqueProjectID()
  1383. {
  1384. const char* const engineProjectFilename = pData->engine->getCurrentProjectFilename();
  1385. carla_stdout("setupUniqueProjectID %s", engineProjectFilename);
  1386. if (engineProjectFilename == nullptr || engineProjectFilename[0] == '\0')
  1387. return;
  1388. const File file(engineProjectFilename);
  1389. CARLA_SAFE_ASSERT_RETURN(file.existsAsFile(),);
  1390. CARLA_SAFE_ASSERT_RETURN(file.getFileExtension().isNotEmpty(),);
  1391. char code[6];
  1392. code[5] = '\0';
  1393. for (;;)
  1394. {
  1395. static const char* const kValidChars =
  1396. "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  1397. "abcdefghijklmnopqrstuvwxyz"
  1398. "0123456789";
  1399. static const size_t kValidCharsLen(std::strlen(kValidChars)-1U);
  1400. code[0] = kValidChars[safe_rand(kValidCharsLen)];
  1401. code[1] = kValidChars[safe_rand(kValidCharsLen)];
  1402. code[2] = kValidChars[safe_rand(kValidCharsLen)];
  1403. code[3] = kValidChars[safe_rand(kValidCharsLen)];
  1404. code[4] = kValidChars[safe_rand(kValidCharsLen)];
  1405. const File newFile(file.withFileExtension(code));
  1406. if (newFile.existsAsFile())
  1407. continue;
  1408. fInfo.setupLabel += code;
  1409. carla_stdout("new label %s", fInfo.setupLabel.buffer());
  1410. break;
  1411. }
  1412. }
  1413. bool restartBridgeThread()
  1414. {
  1415. fInitiated = false;
  1416. fInitError = false;
  1417. fTimedError = false;
  1418. // reset memory
  1419. fProcCanceled = false;
  1420. fShmRtClientControl.data->procFlags = 0;
  1421. carla_zeroStruct(fShmRtClientControl.data->timeInfo);
  1422. carla_zeroBytes(fShmRtClientControl.data->midiOut, kBridgeRtClientDataMidiOutSize);
  1423. fShmRtClientControl.clearData();
  1424. fShmNonRtClientControl.clearData();
  1425. fShmNonRtServerControl.clearData();
  1426. // initial values
  1427. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientVersion);
  1428. fShmNonRtClientControl.writeUInt(CARLA_PLUGIN_BRIDGE_API_VERSION);
  1429. fShmNonRtClientControl.writeUInt(static_cast<uint32_t>(sizeof(BridgeRtClientData)));
  1430. fShmNonRtClientControl.writeUInt(static_cast<uint32_t>(sizeof(BridgeNonRtClientData)));
  1431. fShmNonRtClientControl.writeUInt(static_cast<uint32_t>(sizeof(BridgeNonRtServerData)));
  1432. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientInitialSetup);
  1433. fShmNonRtClientControl.writeUInt(pData->engine->getBufferSize());
  1434. fShmNonRtClientControl.writeDouble(pData->engine->getSampleRate());
  1435. fShmNonRtClientControl.commitWrite();
  1436. if (fShmAudioPool.dataSize != 0)
  1437. {
  1438. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientSetAudioPool);
  1439. fShmRtClientControl.writeULong(static_cast<uint64_t>(fShmAudioPool.dataSize));
  1440. fShmRtClientControl.commitWrite();
  1441. }
  1442. else
  1443. {
  1444. // testing dummy message
  1445. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientNull);
  1446. fShmRtClientControl.commitWrite();
  1447. }
  1448. fBridgeThread.startThread();
  1449. const bool needsCancelableAction = ! pData->engine->isLoadingProject();
  1450. const bool needsEngineIdle = pData->engine->getType() != kEngineTypePlugin;
  1451. CarlaString actionName;
  1452. if (needsCancelableAction)
  1453. {
  1454. if (fSetupHints & LIBJACK_FLAG_EXTERNAL_START)
  1455. {
  1456. const EngineOptions& options(pData->engine->getOptions());
  1457. CarlaString binaryDir(options.binaryDir);
  1458. char* const hwVars = fBridgeThread.getEnvVarsToExport();
  1459. actionName = "Waiting for external JACK application start, please use the following environment variables:\n";
  1460. actionName += hwVars;
  1461. delete[] hwVars;
  1462. }
  1463. else
  1464. {
  1465. actionName = "Loading JACK application";
  1466. }
  1467. pData->engine->setActionCanceled(false);
  1468. pData->engine->callback(true, true,
  1469. ENGINE_CALLBACK_CANCELABLE_ACTION,
  1470. pData->id,
  1471. 1,
  1472. 0, 0, 0.0f,
  1473. actionName.buffer());
  1474. }
  1475. for (;fBridgeThread.isThreadRunning();)
  1476. {
  1477. pData->engine->callback(true, false, ENGINE_CALLBACK_IDLE, 0, 0, 0, 0, 0.0f, nullptr);
  1478. if (needsEngineIdle)
  1479. pData->engine->idle();
  1480. idle();
  1481. if (fInitiated)
  1482. break;
  1483. if (pData->engine->isAboutToClose() || pData->engine->wasActionCanceled())
  1484. break;
  1485. carla_msleep(5);
  1486. }
  1487. if (needsCancelableAction)
  1488. {
  1489. pData->engine->callback(true, true,
  1490. ENGINE_CALLBACK_CANCELABLE_ACTION,
  1491. pData->id,
  1492. 0,
  1493. 0, 0, 0.0f,
  1494. actionName.buffer());
  1495. }
  1496. if (fInitError || ! fInitiated)
  1497. {
  1498. fBridgeThread.stopThread(6000);
  1499. if (! fInitError)
  1500. pData->engine->setLastError("Timeout while waiting for a response from plugin-bridge\n"
  1501. "(or the plugin crashed on initialization?)");
  1502. return false;
  1503. }
  1504. return true;
  1505. }
  1506. void waitForClient(const char* const action, const uint msecs)
  1507. {
  1508. CARLA_SAFE_ASSERT_RETURN(! fTimedOut,);
  1509. CARLA_SAFE_ASSERT_RETURN(! fTimedError,);
  1510. if (fShmRtClientControl.waitForClient(msecs))
  1511. return;
  1512. fTimedOut = true;
  1513. carla_stderr2("waitForClient(%s) timed out", action);
  1514. }
  1515. CARLA_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(CarlaPluginJack)
  1516. };
  1517. CARLA_BACKEND_END_NAMESPACE
  1518. #endif // CARLA_OS_LINUX
  1519. // -------------------------------------------------------------------------------------------------------------------
  1520. CARLA_BACKEND_START_NAMESPACE
  1521. CarlaPlugin* CarlaPlugin::newJackApp(const Initializer& init)
  1522. {
  1523. carla_debug("CarlaPlugin::newJackApp({%p, \"%s\", \"%s\", \"%s\"})", init.engine, init.filename, init.name, init.label);
  1524. #ifdef CARLA_OS_LINUX
  1525. CarlaPluginJack* const plugin(new CarlaPluginJack(init.engine, init.id));
  1526. if (! plugin->init(init.filename, init.name, init.label))
  1527. {
  1528. delete plugin;
  1529. return nullptr;
  1530. }
  1531. return plugin;
  1532. #else
  1533. init.engine->setLastError("JACK Application support not available");
  1534. return nullptr;
  1535. #endif
  1536. }
  1537. CARLA_BACKEND_END_NAMESPACE
  1538. // -------------------------------------------------------------------------------------------------------------------