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.

1883 lines
62KB

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