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.

1994 lines
67KB

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