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.

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