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.

1877 lines
62KB

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