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.

1830 lines
60KB

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