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.

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