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.

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