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.

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