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.

3337 lines
120KB

  1. /*
  2. * Carla Plugin Bridge
  3. * Copyright (C) 2011-2023 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 "CarlaBackendUtils.hpp"
  19. #include "CarlaBase64Utils.hpp"
  20. #include "CarlaBridgeUtils.hpp"
  21. #include "CarlaEngineUtils.hpp"
  22. #include "CarlaMathUtils.hpp"
  23. #include "CarlaPipeUtils.hpp"
  24. #include "CarlaScopeUtils.hpp"
  25. #include "CarlaShmUtils.hpp"
  26. #include "CarlaThread.hpp"
  27. #include "jackbridge/JackBridge.hpp"
  28. #include <ctime>
  29. #include "water/files/File.h"
  30. #include "water/misc/Time.h"
  31. #include "water/threads/ChildProcess.h"
  32. // ---------------------------------------------------------------------------------------------------------------------
  33. using water::ChildProcess;
  34. using water::File;
  35. using water::String;
  36. using water::StringArray;
  37. using water::Time;
  38. CARLA_BACKEND_START_NAMESPACE
  39. // ---------------------------------------------------------------------------------------------------------------------
  40. // Fallback data
  41. static const ExternalMidiNote kExternalMidiNoteFallback = { -1, 0, 0 };
  42. // ---------------------------------------------------------------------------------------------------------------------
  43. static String findWinePrefix(const String filename, const int recursionLimit = 10)
  44. {
  45. if (recursionLimit == 0 || filename.length() < 5 || ! filename.contains("/"))
  46. return "";
  47. const String path(filename.upToLastOccurrenceOf("/", false, false));
  48. if (File(path + "/dosdevices").isDirectory())
  49. return path;
  50. return findWinePrefix(path, recursionLimit-1);
  51. }
  52. // ---------------------------------------------------------------------------------------------------------------------
  53. struct BridgeParamInfo {
  54. float value;
  55. CarlaString name;
  56. CarlaString symbol;
  57. CarlaString unit;
  58. BridgeParamInfo() noexcept
  59. : value(0.0f),
  60. name(),
  61. symbol(),
  62. unit() {}
  63. CARLA_DECLARE_NON_COPYABLE(BridgeParamInfo)
  64. };
  65. // ---------------------------------------------------------------------------------------------------------------------
  66. class CarlaPluginBridgeThread : public CarlaThread
  67. {
  68. public:
  69. CarlaPluginBridgeThread(CarlaEngine* const engine, CarlaPlugin* const plugin) noexcept
  70. : CarlaThread("CarlaPluginBridgeThread"),
  71. kEngine(engine),
  72. kPlugin(plugin),
  73. fBinaryArchName(),
  74. fBridgeBinary(),
  75. fLabel(),
  76. fShmIds(),
  77. #ifndef CARLA_OS_WIN
  78. fWinePrefix(),
  79. #endif
  80. fProcess() {}
  81. void setData(
  82. #ifndef CARLA_OS_WIN
  83. const char* const winePrefix,
  84. #endif
  85. const char* const binaryArchName,
  86. const char* const bridgeBinary,
  87. const char* const label,
  88. const char* const shmIds) noexcept
  89. {
  90. CARLA_SAFE_ASSERT_RETURN(bridgeBinary != nullptr && bridgeBinary[0] != '\0',);
  91. CARLA_SAFE_ASSERT_RETURN(shmIds != nullptr && shmIds[0] != '\0',);
  92. CARLA_SAFE_ASSERT(! isThreadRunning());
  93. #ifndef CARLA_OS_WIN
  94. fWinePrefix = winePrefix;
  95. #endif
  96. fBinaryArchName = binaryArchName;
  97. fBridgeBinary = bridgeBinary;
  98. fShmIds = shmIds;
  99. if (label != nullptr)
  100. fLabel = label;
  101. if (fLabel.isEmpty())
  102. fLabel = "(none)";
  103. }
  104. uintptr_t getProcessPID() const noexcept
  105. {
  106. CARLA_SAFE_ASSERT_RETURN(fProcess != nullptr, 0);
  107. return (uintptr_t)fProcess->getPID();
  108. }
  109. protected:
  110. void run()
  111. {
  112. if (fProcess == nullptr)
  113. {
  114. fProcess = new ChildProcess();
  115. }
  116. else if (fProcess->isRunning())
  117. {
  118. carla_stderr("CarlaPluginBridgeThread::run() - already running");
  119. }
  120. char strBuf[STR_MAX+1];
  121. strBuf[STR_MAX] = '\0';
  122. const EngineOptions& options(kEngine->getOptions());
  123. String filename(kPlugin->getFilename());
  124. if (filename.isEmpty())
  125. filename = "(none)";
  126. StringArray arguments;
  127. #ifndef CARLA_OS_WIN
  128. // start with "wine" if needed
  129. if (fBridgeBinary.endsWithIgnoreCase(".exe"))
  130. {
  131. String wineCMD;
  132. if (options.wine.executable != nullptr && options.wine.executable[0] != '\0')
  133. {
  134. wineCMD = options.wine.executable;
  135. if (fBridgeBinary.endsWithIgnoreCase("64.exe")
  136. && options.wine.executable[0] == CARLA_OS_SEP
  137. && File(wineCMD + "64").existsAsFile())
  138. wineCMD += "64";
  139. }
  140. else
  141. {
  142. wineCMD = "wine";
  143. }
  144. arguments.add(wineCMD);
  145. }
  146. #endif
  147. // setup binary arch
  148. ChildProcess::Type childType;
  149. #ifdef CARLA_OS_MAC
  150. if (fBinaryArchName == "arm64")
  151. childType = ChildProcess::TypeARM;
  152. else if (fBinaryArchName == "x86_64")
  153. childType = ChildProcess::TypeIntel;
  154. else
  155. #endif
  156. childType = ChildProcess::TypeAny;
  157. // bridge binary
  158. arguments.add(fBridgeBinary);
  159. // plugin type
  160. arguments.add(getPluginTypeAsString(kPlugin->getType()));
  161. // filename
  162. arguments.add(filename);
  163. // label
  164. arguments.add(fLabel);
  165. // uniqueId
  166. arguments.add(String(static_cast<water::int64>(kPlugin->getUniqueId())));
  167. bool started;
  168. {
  169. const ScopedEngineEnvironmentLocker _seel(kEngine);
  170. #ifdef CARLA_OS_LINUX
  171. const CarlaScopedEnvVar sev1("LD_LIBRARY_PATH", nullptr);
  172. const CarlaScopedEnvVar sev2("LD_PRELOAD", nullptr);
  173. #endif
  174. carla_setenv("ENGINE_OPTION_FORCE_STEREO", bool2str(options.forceStereo));
  175. carla_setenv("ENGINE_OPTION_PREFER_PLUGIN_BRIDGES", bool2str(options.preferPluginBridges));
  176. carla_setenv("ENGINE_OPTION_PREFER_UI_BRIDGES", bool2str(options.preferUiBridges));
  177. carla_setenv("ENGINE_OPTION_UIS_ALWAYS_ON_TOP", bool2str(options.uisAlwaysOnTop));
  178. std::snprintf(strBuf, STR_MAX, "%u", options.maxParameters);
  179. carla_setenv("ENGINE_OPTION_MAX_PARAMETERS", strBuf);
  180. std::snprintf(strBuf, STR_MAX, "%u", options.uiBridgesTimeout);
  181. carla_setenv("ENGINE_OPTION_UI_BRIDGES_TIMEOUT",strBuf);
  182. if (options.pathLADSPA != nullptr)
  183. carla_setenv("ENGINE_OPTION_PLUGIN_PATH_LADSPA", options.pathLADSPA);
  184. else
  185. carla_setenv("ENGINE_OPTION_PLUGIN_PATH_LADSPA", "");
  186. if (options.pathDSSI != nullptr)
  187. carla_setenv("ENGINE_OPTION_PLUGIN_PATH_DSSI", options.pathDSSI);
  188. else
  189. carla_setenv("ENGINE_OPTION_PLUGIN_PATH_DSSI", "");
  190. if (options.pathLV2 != nullptr)
  191. carla_setenv("ENGINE_OPTION_PLUGIN_PATH_LV2", options.pathLV2);
  192. else
  193. carla_setenv("ENGINE_OPTION_PLUGIN_PATH_LV2", "");
  194. if (options.pathVST2 != nullptr)
  195. carla_setenv("ENGINE_OPTION_PLUGIN_PATH_VST2", options.pathVST2);
  196. else
  197. carla_setenv("ENGINE_OPTION_PLUGIN_PATH_VST2", "");
  198. if (options.pathVST3 != nullptr)
  199. carla_setenv("ENGINE_OPTION_PLUGIN_PATH_VST3", options.pathVST3);
  200. else
  201. carla_setenv("ENGINE_OPTION_PLUGIN_PATH_VST3", "");
  202. if (options.pathSF2 != nullptr)
  203. carla_setenv("ENGINE_OPTION_PLUGIN_PATH_SF2", options.pathSF2);
  204. else
  205. carla_setenv("ENGINE_OPTION_PLUGIN_PATH_SF2", "");
  206. if (options.pathSFZ != nullptr)
  207. carla_setenv("ENGINE_OPTION_PLUGIN_PATH_SFZ", options.pathSFZ);
  208. else
  209. carla_setenv("ENGINE_OPTION_PLUGIN_PATH_SFZ", "");
  210. if (options.pathJSFX != nullptr)
  211. carla_setenv("ENGINE_OPTION_PLUGIN_PATH_JSFX", options.pathJSFX);
  212. else
  213. carla_setenv("ENGINE_OPTION_PLUGIN_PATH_JSFX", "");
  214. if (options.binaryDir != nullptr)
  215. carla_setenv("ENGINE_OPTION_PATH_BINARIES", options.binaryDir);
  216. else
  217. carla_setenv("ENGINE_OPTION_PATH_BINARIES", "");
  218. if (options.resourceDir != nullptr)
  219. carla_setenv("ENGINE_OPTION_PATH_RESOURCES", options.resourceDir);
  220. else
  221. carla_setenv("ENGINE_OPTION_PATH_RESOURCES", "");
  222. carla_setenv("ENGINE_OPTION_PREVENT_BAD_BEHAVIOUR", bool2str(options.preventBadBehaviour));
  223. std::snprintf(strBuf, STR_MAX, P_UINTPTR, options.frontendWinId);
  224. carla_setenv("ENGINE_OPTION_FRONTEND_WIN_ID", strBuf);
  225. carla_setenv("ENGINE_BRIDGE_SHM_IDS", fShmIds.toRawUTF8());
  226. #ifndef CARLA_OS_WIN
  227. if (fWinePrefix.isNotEmpty())
  228. {
  229. carla_setenv("WINEDEBUG", "-all");
  230. carla_setenv("WINEPREFIX", fWinePrefix.toRawUTF8());
  231. if (options.wine.rtPrio)
  232. {
  233. carla_setenv("STAGING_SHARED_MEMORY", "1");
  234. carla_setenv("WINE_RT_POLICY", "FF");
  235. std::snprintf(strBuf, STR_MAX, "%i", options.wine.baseRtPrio);
  236. carla_setenv("STAGING_RT_PRIORITY_BASE", strBuf);
  237. carla_setenv("WINE_RT", strBuf);
  238. carla_setenv("WINE_RT_PRIO", strBuf);
  239. std::snprintf(strBuf, STR_MAX, "%i", options.wine.serverRtPrio);
  240. carla_setenv("STAGING_RT_PRIORITY_SERVER", strBuf);
  241. carla_setenv("WINE_SVR_RT", strBuf);
  242. carla_stdout("Using WINEPREFIX '%s', with base RT prio %i and server RT prio %i",
  243. fWinePrefix.toRawUTF8(), options.wine.baseRtPrio, options.wine.serverRtPrio);
  244. }
  245. else
  246. {
  247. carla_unsetenv("STAGING_SHARED_MEMORY");
  248. carla_unsetenv("WINE_RT_POLICY");
  249. carla_unsetenv("STAGING_RT_PRIORITY_BASE");
  250. carla_unsetenv("STAGING_RT_PRIORITY_SERVER");
  251. carla_unsetenv("WINE_RT");
  252. carla_unsetenv("WINE_RT_PRIO");
  253. carla_unsetenv("WINE_SVR_RT");
  254. carla_stdout("Using WINEPREFIX '%s', without RT priorities", fWinePrefix.toRawUTF8());
  255. }
  256. }
  257. #endif
  258. carla_stdout("Starting plugin bridge, command is:\n%s \"%s\" \"%s\" \"%s\" " P_INT64,
  259. fBridgeBinary.toRawUTF8(), getPluginTypeAsString(kPlugin->getType()), filename.toRawUTF8(), fLabel.toRawUTF8(), kPlugin->getUniqueId());
  260. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  261. const File projFolder(kEngine->getCurrentProjectFolder());
  262. if (projFolder.isNotNull())
  263. {
  264. const File oldFolder(File::getCurrentWorkingDirectory());
  265. projFolder.setAsCurrentWorkingDirectory();
  266. started = fProcess->start(arguments, childType);
  267. oldFolder.setAsCurrentWorkingDirectory();
  268. }
  269. else
  270. #endif
  271. {
  272. started = fProcess->start(arguments, childType);
  273. }
  274. }
  275. if (! started)
  276. {
  277. carla_stdout("failed!");
  278. fProcess = nullptr;
  279. return;
  280. }
  281. for (; fProcess->isRunning() && ! shouldThreadExit();)
  282. carla_sleep(1);
  283. // we only get here if bridge crashed or thread asked to exit
  284. if (fProcess->isRunning() && shouldThreadExit())
  285. {
  286. fProcess->waitForProcessToFinish(2000);
  287. if (fProcess->isRunning())
  288. {
  289. carla_stdout("CarlaPluginBridgeThread::run() - bridge refused to close, force kill now");
  290. fProcess->kill();
  291. }
  292. else
  293. {
  294. carla_stdout("CarlaPluginBridgeThread::run() - bridge auto-closed successfully");
  295. }
  296. }
  297. else
  298. {
  299. // forced quit, may have crashed
  300. if (fProcess->getExitCodeAndClearPID() != 0)
  301. {
  302. carla_stderr("CarlaPluginBridgeThread::run() - bridge crashed");
  303. CarlaString errorString("Plugin '" + CarlaString(kPlugin->getName()) + "' has crashed!\n"
  304. "Saving now will lose its current settings.\n"
  305. "Please remove this plugin, and not rely on it from this point.");
  306. kEngine->callback(true, true,
  307. ENGINE_CALLBACK_ERROR, kPlugin->getId(), 0, 0, 0, 0.0f, errorString);
  308. }
  309. }
  310. fProcess = nullptr;
  311. }
  312. private:
  313. CarlaEngine* const kEngine;
  314. CarlaPlugin* const kPlugin;
  315. String fBinaryArchName;
  316. String fBridgeBinary;
  317. String fLabel;
  318. String fShmIds;
  319. #ifndef CARLA_OS_WIN
  320. String fWinePrefix;
  321. #endif
  322. CarlaScopedPointer<ChildProcess> fProcess;
  323. CARLA_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(CarlaPluginBridgeThread)
  324. };
  325. // ---------------------------------------------------------------------------------------------------------------------
  326. class CarlaPluginBridge : public CarlaPlugin
  327. {
  328. public:
  329. CarlaPluginBridge(CarlaEngine* const engine, const uint id, const BinaryType btype, const PluginType ptype)
  330. : CarlaPlugin(engine, id),
  331. fBinaryType(btype),
  332. fPluginType(ptype),
  333. fBridgeVersion(6), // before kPluginBridgeNonRtServerVersion was a thing, API was at 6
  334. fInitiated(false),
  335. fInitError(false),
  336. fSaved(true),
  337. fTimedOut(false),
  338. fTimedError(false),
  339. fBufferSize(engine->getBufferSize()),
  340. fProcWaitTime(0),
  341. fPendingEmbedCustomUI(0),
  342. fBridgeBinary(),
  343. fBridgeThread(engine, this),
  344. fShmAudioPool(),
  345. fShmRtClientControl(),
  346. fShmNonRtClientControl(),
  347. fShmNonRtServerControl(),
  348. #ifndef CARLA_OS_WIN
  349. fWinePrefix(),
  350. #endif
  351. fReceivingParamText(),
  352. fInfo(),
  353. fUniqueId(0),
  354. fLatency(0),
  355. fParams(nullptr)
  356. {
  357. carla_debug("CarlaPluginBridge::CarlaPluginBridge(%p, %i, %s, %s)", engine, id, BinaryType2Str(btype), PluginType2Str(ptype));
  358. pData->hints |= PLUGIN_IS_BRIDGE;
  359. }
  360. ~CarlaPluginBridge() override
  361. {
  362. carla_debug("CarlaPluginBridge::~CarlaPluginBridge()");
  363. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  364. // close UI
  365. if (pData->hints & PLUGIN_HAS_CUSTOM_UI)
  366. pData->transientTryCounter = 0;
  367. #endif
  368. pData->singleMutex.lock();
  369. pData->masterMutex.lock();
  370. if (pData->client != nullptr && pData->client->isActive())
  371. pData->client->deactivate(true);
  372. if (pData->active)
  373. {
  374. deactivate();
  375. pData->active = false;
  376. }
  377. if (fBridgeThread.isThreadRunning())
  378. {
  379. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientQuit);
  380. fShmNonRtClientControl.commitWrite();
  381. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientQuit);
  382. fShmRtClientControl.commitWrite();
  383. if (! fTimedOut)
  384. waitForClient("stopping", 3000);
  385. }
  386. fBridgeThread.stopThread(3000);
  387. fShmNonRtServerControl.clear();
  388. fShmNonRtClientControl.clear();
  389. fShmRtClientControl.clear();
  390. fShmAudioPool.clear();
  391. clearBuffers();
  392. fInfo.chunk.clear();
  393. }
  394. // -------------------------------------------------------------------
  395. // Information (base)
  396. BinaryType getBinaryType() const noexcept override
  397. {
  398. return fBinaryType;
  399. }
  400. PluginType getType() const noexcept override
  401. {
  402. return fPluginType;
  403. }
  404. PluginCategory getCategory() const noexcept override
  405. {
  406. return fInfo.category;
  407. }
  408. int64_t getUniqueId() const noexcept override
  409. {
  410. return fUniqueId;
  411. }
  412. uint32_t getLatencyInFrames() const noexcept override
  413. {
  414. return fLatency;
  415. }
  416. // -------------------------------------------------------------------
  417. // Information (count)
  418. uint32_t getMidiInCount() const noexcept override
  419. {
  420. return fInfo.mIns;
  421. }
  422. uint32_t getMidiOutCount() const noexcept override
  423. {
  424. return fInfo.mOuts;
  425. }
  426. // -------------------------------------------------------------------
  427. // Information (current data)
  428. std::size_t getChunkData(void** const dataPtr) noexcept override
  429. {
  430. CARLA_SAFE_ASSERT_RETURN(pData->options & PLUGIN_OPTION_USE_CHUNKS, 0);
  431. CARLA_SAFE_ASSERT_RETURN(dataPtr != nullptr, 0);
  432. waitForSaved();
  433. CARLA_SAFE_ASSERT_RETURN(fInfo.chunk.size() > 0, 0);
  434. #ifdef CARLA_PROPER_CPP11_SUPPORT
  435. *dataPtr = fInfo.chunk.data();
  436. #else
  437. *dataPtr = &fInfo.chunk.front();
  438. #endif
  439. return fInfo.chunk.size();
  440. }
  441. // -------------------------------------------------------------------
  442. // Information (per-plugin data)
  443. uint getOptionsAvailable() const noexcept override
  444. {
  445. return fInfo.optionsAvailable;
  446. }
  447. float getParameterValue(const uint32_t parameterId) const noexcept override
  448. {
  449. CARLA_SAFE_ASSERT_RETURN(parameterId < pData->param.count, 0.0f);
  450. return fParams[parameterId].value;
  451. }
  452. bool getLabel(char* const strBuf) const noexcept override
  453. {
  454. std::strncpy(strBuf, fInfo.label, STR_MAX);
  455. return true;
  456. }
  457. bool getMaker(char* const strBuf) const noexcept override
  458. {
  459. std::strncpy(strBuf, fInfo.maker, STR_MAX);
  460. return true;
  461. }
  462. bool getCopyright(char* const strBuf) const noexcept override
  463. {
  464. std::strncpy(strBuf, fInfo.copyright, STR_MAX);
  465. return true;
  466. }
  467. bool getRealName(char* const strBuf) const noexcept override
  468. {
  469. std::strncpy(strBuf, fInfo.name, STR_MAX);
  470. return true;
  471. }
  472. bool getParameterName(const uint32_t parameterId, char* const strBuf) const noexcept override
  473. {
  474. CARLA_SAFE_ASSERT_RETURN(parameterId < pData->param.count, false);
  475. std::strncpy(strBuf, fParams[parameterId].name.buffer(), STR_MAX);
  476. return true;
  477. }
  478. bool getParameterText(const uint32_t parameterId, char* const strBuf) noexcept override
  479. {
  480. CARLA_SAFE_ASSERT_RETURN(parameterId < pData->param.count, false);
  481. CARLA_SAFE_ASSERT_RETURN(! fReceivingParamText.isCurrentlyWaitingData(), false);
  482. const int32_t parameterIdi = static_cast<int32_t>(parameterId);
  483. fReceivingParamText.setTargetData(parameterIdi, strBuf);
  484. {
  485. const CarlaMutexLocker _cml(fShmNonRtClientControl.mutex);
  486. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientGetParameterText);
  487. fShmNonRtClientControl.writeInt(parameterIdi);
  488. fShmNonRtClientControl.commitWrite();
  489. }
  490. if (waitForParameterText())
  491. return true;
  492. std::snprintf(strBuf, STR_MAX, "%.12g", static_cast<double>(fParams[parameterId].value));
  493. return false;
  494. }
  495. bool getParameterSymbol(const uint32_t parameterId, char* const strBuf) const noexcept override
  496. {
  497. CARLA_SAFE_ASSERT_RETURN(parameterId < pData->param.count, false);
  498. std::strncpy(strBuf, fParams[parameterId].symbol.buffer(), STR_MAX);
  499. return true;
  500. }
  501. bool getParameterUnit(const uint32_t parameterId, char* const strBuf) const noexcept override
  502. {
  503. CARLA_SAFE_ASSERT_RETURN(parameterId < pData->param.count, false);
  504. std::strncpy(strBuf, fParams[parameterId].unit.buffer(), STR_MAX);
  505. return true;
  506. }
  507. // -------------------------------------------------------------------
  508. // Set data (state)
  509. void prepareForSave(bool) noexcept override
  510. {
  511. fSaved = false;
  512. {
  513. const CarlaMutexLocker _cml(fShmNonRtClientControl.mutex);
  514. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientPrepareForSave);
  515. fShmNonRtClientControl.commitWrite();
  516. }
  517. }
  518. bool waitForParameterText()
  519. {
  520. bool success;
  521. if (fReceivingParamText.wasDataReceived(&success))
  522. return success;
  523. const uint32_t timeoutEnd = Time::getMillisecondCounter() + 500; // 500 ms
  524. const bool needsEngineIdle = pData->engine->getType() != kEngineTypePlugin;
  525. for (; Time::getMillisecondCounter() < timeoutEnd && fBridgeThread.isThreadRunning();)
  526. {
  527. if (fReceivingParamText.wasDataReceived(&success))
  528. return success;
  529. if (needsEngineIdle)
  530. pData->engine->idle();
  531. carla_msleep(5);
  532. }
  533. if (! fBridgeThread.isThreadRunning())
  534. {
  535. carla_stderr("CarlaPluginBridge::waitForParameterText() - Bridge is not running");
  536. return false;
  537. }
  538. carla_stderr("CarlaPluginBridge::waitForParameterText() - Timeout while requesting text");
  539. return false;
  540. }
  541. void waitForSaved()
  542. {
  543. if (fSaved)
  544. return;
  545. // TODO: only wait 1 minute for NI plugins
  546. const uint32_t timeoutEnd = Time::getMillisecondCounter() + 60*1000; // 60 secs, 1 minute
  547. const bool needsEngineIdle = pData->engine->getType() != kEngineTypePlugin;
  548. for (; Time::getMillisecondCounter() < timeoutEnd && fBridgeThread.isThreadRunning();)
  549. {
  550. pData->engine->callback(true, true, ENGINE_CALLBACK_IDLE, 0, 0, 0, 0, 0.0f, nullptr);
  551. if (needsEngineIdle)
  552. pData->engine->idle();
  553. if (fSaved)
  554. break;
  555. carla_msleep(20);
  556. }
  557. if (! fBridgeThread.isThreadRunning())
  558. return carla_stderr("CarlaPluginBridge::waitForSaved() - Bridge is not running");
  559. if (! fSaved)
  560. return carla_stderr("CarlaPluginBridge::waitForSaved() - Timeout while requesting save state");
  561. }
  562. // -------------------------------------------------------------------
  563. // Set data (internal stuff)
  564. void setOption(const uint option, const bool yesNo, const bool sendCallback) override
  565. {
  566. {
  567. const CarlaMutexLocker _cml(fShmNonRtClientControl.mutex);
  568. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientSetOption);
  569. fShmNonRtClientControl.writeUInt(option);
  570. fShmNonRtClientControl.writeBool(yesNo);
  571. fShmNonRtClientControl.commitWrite();
  572. }
  573. CarlaPlugin::setOption(option, yesNo, sendCallback);
  574. }
  575. void setCtrlChannel(const int8_t channel, const bool sendOsc, const bool sendCallback) noexcept override
  576. {
  577. CARLA_SAFE_ASSERT_RETURN(sendOsc || sendCallback,);
  578. {
  579. const CarlaMutexLocker _cml(fShmNonRtClientControl.mutex);
  580. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientSetCtrlChannel);
  581. fShmNonRtClientControl.writeShort(channel);
  582. fShmNonRtClientControl.commitWrite();
  583. }
  584. CarlaPlugin::setCtrlChannel(channel, sendOsc, sendCallback);
  585. }
  586. void setName(const char* const newName) override
  587. {
  588. CarlaPlugin::setName(newName);
  589. if (pData->uiTitle.isEmpty() && fBridgeVersion >= 8)
  590. _setUiTitleFromName();
  591. }
  592. // -------------------------------------------------------------------
  593. // Set data (plugin-specific stuff)
  594. void setParameterValue(const uint32_t parameterId, const float value, const bool sendGui, const bool sendOsc, const bool sendCallback) noexcept override
  595. {
  596. CARLA_SAFE_ASSERT_RETURN(parameterId < pData->param.count,);
  597. CARLA_SAFE_ASSERT_RETURN(sendGui || sendOsc || sendCallback,);
  598. const float fixedValue(pData->param.getFixedValue(parameterId, value));
  599. fParams[parameterId].value = fixedValue;
  600. {
  601. const CarlaMutexLocker _cml(fShmNonRtClientControl.mutex);
  602. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientSetParameterValue);
  603. fShmNonRtClientControl.writeUInt(parameterId);
  604. fShmNonRtClientControl.writeFloat(value);
  605. fShmNonRtClientControl.commitWrite();
  606. fShmNonRtClientControl.waitIfDataIsReachingLimit();
  607. }
  608. CarlaPlugin::setParameterValue(parameterId, fixedValue, sendGui, sendOsc, sendCallback);
  609. }
  610. void setParameterValueRT(const uint32_t parameterId, const float value, const uint32_t frameOffset, const bool sendCallbackLater) noexcept override
  611. {
  612. CARLA_SAFE_ASSERT_RETURN(parameterId < pData->param.count,);
  613. const float fixedValue(pData->param.getFixedValue(parameterId, value));
  614. fParams[parameterId].value = fixedValue;
  615. {
  616. const CarlaMutexLocker _cml(fShmNonRtClientControl.mutex);
  617. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientSetParameterValue);
  618. fShmNonRtClientControl.writeUInt(parameterId);
  619. fShmNonRtClientControl.writeFloat(value);
  620. fShmNonRtClientControl.commitWrite();
  621. fShmNonRtClientControl.waitIfDataIsReachingLimit();
  622. }
  623. CarlaPlugin::setParameterValueRT(parameterId, fixedValue, frameOffset, sendCallbackLater);
  624. }
  625. void setParameterMidiChannel(const uint32_t parameterId, const uint8_t channel, const bool sendOsc, const bool sendCallback) noexcept override
  626. {
  627. CARLA_SAFE_ASSERT_RETURN(parameterId < pData->param.count,);
  628. CARLA_SAFE_ASSERT_RETURN(channel < MAX_MIDI_CHANNELS,);
  629. CARLA_SAFE_ASSERT_RETURN(sendOsc || sendCallback,);
  630. {
  631. const CarlaMutexLocker _cml(fShmNonRtClientControl.mutex);
  632. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientSetParameterMidiChannel);
  633. fShmNonRtClientControl.writeUInt(parameterId);
  634. fShmNonRtClientControl.writeByte(channel);
  635. fShmNonRtClientControl.commitWrite();
  636. }
  637. CarlaPlugin::setParameterMidiChannel(parameterId, channel, sendOsc, sendCallback);
  638. }
  639. void setParameterMappedControlIndex(const uint32_t parameterId, const int16_t index,
  640. const bool sendOsc, const bool sendCallback,
  641. const bool reconfigureNow) noexcept override
  642. {
  643. CARLA_SAFE_ASSERT_RETURN(parameterId < pData->param.count,);
  644. CARLA_SAFE_ASSERT_RETURN(index >= CONTROL_INDEX_NONE && index <= CONTROL_INDEX_MAX_ALLOWED,);
  645. CARLA_SAFE_ASSERT_RETURN(sendOsc || sendCallback,);
  646. {
  647. const CarlaMutexLocker _cml(fShmNonRtClientControl.mutex);
  648. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientSetParameterMappedControlIndex);
  649. fShmNonRtClientControl.writeUInt(parameterId);
  650. fShmNonRtClientControl.writeShort(index);
  651. fShmNonRtClientControl.commitWrite();
  652. }
  653. CarlaPlugin::setParameterMappedControlIndex(parameterId, index, sendOsc, sendCallback, reconfigureNow);
  654. }
  655. void setParameterMappedRange(const uint32_t parameterId, const float minimum, const float maximum, const bool sendOsc, const bool sendCallback) noexcept override
  656. {
  657. CARLA_SAFE_ASSERT_RETURN(parameterId < pData->param.count,);
  658. CARLA_SAFE_ASSERT_RETURN(sendOsc || sendCallback,);
  659. // kPluginBridgeNonRtClientSetParameterMappedRange was added in API 7
  660. if (fBridgeVersion >= 7)
  661. {
  662. const CarlaMutexLocker _cml(fShmNonRtClientControl.mutex);
  663. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientSetParameterMappedRange);
  664. fShmNonRtClientControl.writeUInt(parameterId);
  665. fShmNonRtClientControl.writeFloat(minimum);
  666. fShmNonRtClientControl.writeFloat(maximum);
  667. fShmNonRtClientControl.commitWrite();
  668. }
  669. CarlaPlugin::setParameterMappedRange(parameterId, minimum, maximum, sendOsc, sendCallback);
  670. }
  671. void setProgram(const int32_t index, const bool sendGui, const bool sendOsc, const bool sendCallback, const bool doingInit) noexcept override
  672. {
  673. CARLA_SAFE_ASSERT_RETURN(index >= -1 && index < static_cast<int32_t>(pData->prog.count),);
  674. CARLA_SAFE_ASSERT_RETURN(sendGui || sendOsc || sendCallback || doingInit,);
  675. {
  676. const CarlaMutexLocker _cml(fShmNonRtClientControl.mutex);
  677. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientSetProgram);
  678. fShmNonRtClientControl.writeInt(index);
  679. fShmNonRtClientControl.commitWrite();
  680. }
  681. CarlaPlugin::setProgram(index, sendGui, sendOsc, sendCallback, doingInit);
  682. }
  683. void setProgramRT(const uint32_t index, const bool sendCallbackLater) noexcept override
  684. {
  685. CARLA_SAFE_ASSERT_RETURN(index < pData->prog.count,);
  686. {
  687. const CarlaMutexLocker _cml(fShmNonRtClientControl.mutex);
  688. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientSetProgram);
  689. fShmNonRtClientControl.writeInt(static_cast<int32_t>(index));
  690. fShmNonRtClientControl.commitWrite();
  691. }
  692. CarlaPlugin::setProgramRT(index, sendCallbackLater);
  693. }
  694. void setMidiProgram(const int32_t index, const bool sendGui, const bool sendOsc, const bool sendCallback, const bool doingInit) noexcept override
  695. {
  696. CARLA_SAFE_ASSERT_RETURN(index >= -1 && index < static_cast<int32_t>(pData->midiprog.count),);
  697. CARLA_SAFE_ASSERT_RETURN(sendGui || sendOsc || sendCallback || doingInit,);
  698. {
  699. const CarlaMutexLocker _cml(fShmNonRtClientControl.mutex);
  700. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientSetMidiProgram);
  701. fShmNonRtClientControl.writeInt(index);
  702. fShmNonRtClientControl.commitWrite();
  703. }
  704. CarlaPlugin::setMidiProgram(index, sendGui, sendOsc, sendCallback, doingInit);
  705. }
  706. void setMidiProgramRT(const uint32_t uindex, const bool sendCallbackLater) noexcept override
  707. {
  708. CARLA_SAFE_ASSERT_RETURN(uindex < pData->midiprog.count,);
  709. {
  710. const CarlaMutexLocker _cml(fShmNonRtClientControl.mutex);
  711. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientSetMidiProgram);
  712. fShmNonRtClientControl.writeInt(static_cast<int32_t>(uindex));
  713. fShmNonRtClientControl.commitWrite();
  714. }
  715. CarlaPlugin::setMidiProgramRT(uindex, sendCallbackLater);
  716. }
  717. void setCustomData(const char* const type, const char* const key, const char* const value, const bool sendGui) override
  718. {
  719. CARLA_SAFE_ASSERT_RETURN(type != nullptr && type[0] != '\0',);
  720. CARLA_SAFE_ASSERT_RETURN(key != nullptr && key[0] != '\0',);
  721. CARLA_SAFE_ASSERT_RETURN(value != nullptr,);
  722. if (std::strcmp(type, CUSTOM_DATA_TYPE_PROPERTY) == 0)
  723. return CarlaPlugin::setCustomData(type, key, value, sendGui);
  724. if (std::strcmp(type, CUSTOM_DATA_TYPE_STRING) == 0 && std::strcmp(key, "__CarlaPingOnOff__") == 0)
  725. {
  726. const CarlaMutexLocker _cml(fShmNonRtClientControl.mutex);
  727. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientPingOnOff);
  728. fShmNonRtClientControl.writeBool(std::strcmp(value, "true") == 0);
  729. fShmNonRtClientControl.commitWrite();
  730. return;
  731. }
  732. const uint32_t maxLocalValueLen = fBridgeVersion >= 10 ? 4096 : 16384;
  733. const uint32_t typeLen = static_cast<uint32_t>(std::strlen(type));
  734. const uint32_t keyLen = static_cast<uint32_t>(std::strlen(key));
  735. const uint32_t valueLen = static_cast<uint32_t>(std::strlen(value));
  736. {
  737. const CarlaMutexLocker _cml(fShmNonRtClientControl.mutex);
  738. if (valueLen > maxLocalValueLen)
  739. fShmNonRtClientControl.waitIfDataIsReachingLimit();
  740. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientSetCustomData);
  741. fShmNonRtClientControl.writeUInt(typeLen);
  742. fShmNonRtClientControl.writeCustomData(type, typeLen);
  743. fShmNonRtClientControl.writeUInt(keyLen);
  744. fShmNonRtClientControl.writeCustomData(key, keyLen);
  745. fShmNonRtClientControl.writeUInt(valueLen);
  746. if (valueLen > 0)
  747. {
  748. if (valueLen > maxLocalValueLen)
  749. {
  750. String filePath(File::getSpecialLocation(File::tempDirectory).getFullPathName());
  751. filePath += CARLA_OS_SEP_STR ".CarlaCustomData_";
  752. filePath += fShmAudioPool.getFilenameSuffix();
  753. if (File(filePath).replaceWithText(value))
  754. {
  755. const uint32_t ulength = static_cast<uint32_t>(filePath.length());
  756. fShmNonRtClientControl.writeUInt(ulength);
  757. fShmNonRtClientControl.writeCustomData(filePath.toRawUTF8(), ulength);
  758. }
  759. else
  760. {
  761. fShmNonRtClientControl.writeUInt(0);
  762. }
  763. }
  764. else
  765. {
  766. fShmNonRtClientControl.writeCustomData(value, valueLen);
  767. }
  768. }
  769. fShmNonRtClientControl.commitWrite();
  770. }
  771. CarlaPlugin::setCustomData(type, key, value, sendGui);
  772. }
  773. void setChunkData(const void* const data, const std::size_t dataSize) override
  774. {
  775. CARLA_SAFE_ASSERT_RETURN(pData->options & PLUGIN_OPTION_USE_CHUNKS,);
  776. CARLA_SAFE_ASSERT_RETURN(data != nullptr,);
  777. CARLA_SAFE_ASSERT_RETURN(dataSize > 0,);
  778. CarlaString dataBase64(CarlaString::asBase64(data, dataSize));
  779. CARLA_SAFE_ASSERT_RETURN(dataBase64.length() > 0,);
  780. String filePath(File::getSpecialLocation(File::tempDirectory).getFullPathName());
  781. filePath += CARLA_OS_SEP_STR ".CarlaChunk_";
  782. filePath += fShmAudioPool.getFilenameSuffix();
  783. if (File(filePath).replaceWithText(dataBase64.buffer()))
  784. {
  785. const uint32_t ulength = static_cast<uint32_t>(filePath.length());
  786. const CarlaMutexLocker _cml(fShmNonRtClientControl.mutex);
  787. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientSetChunkDataFile);
  788. fShmNonRtClientControl.writeUInt(ulength);
  789. fShmNonRtClientControl.writeCustomData(filePath.toRawUTF8(), ulength);
  790. fShmNonRtClientControl.commitWrite();
  791. }
  792. // save data internally as well
  793. fInfo.chunk.resize(dataSize);
  794. #ifdef CARLA_PROPER_CPP11_SUPPORT
  795. std::memcpy(fInfo.chunk.data(), data, dataSize);
  796. #else
  797. std::memcpy(&fInfo.chunk.front(), data, dataSize);
  798. #endif
  799. }
  800. // -------------------------------------------------------------------
  801. // Set ui stuff
  802. void setCustomUITitle(const char* const title) noexcept override
  803. {
  804. carla_debug("CarlaPluginBridge::setCustomUITitle(%s)", title);
  805. if (fBridgeVersion >= 8)
  806. {
  807. const uint32_t size = static_cast<uint32_t>(std::strlen(title));
  808. const CarlaMutexLocker _cml(fShmNonRtClientControl.mutex);
  809. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientSetWindowTitle);
  810. fShmNonRtClientControl.writeUInt(size);
  811. fShmNonRtClientControl.writeCustomData(title, size);
  812. fShmNonRtClientControl.commitWrite();
  813. }
  814. CarlaPlugin::setCustomUITitle(title);
  815. }
  816. void showCustomUI(const bool yesNo) override
  817. {
  818. if (yesNo && pData->uiTitle.isEmpty() && fBridgeVersion >= 8)
  819. _setUiTitleFromName();
  820. {
  821. const CarlaMutexLocker _cml(fShmNonRtClientControl.mutex);
  822. fShmNonRtClientControl.writeOpcode(yesNo ? kPluginBridgeNonRtClientShowUI : kPluginBridgeNonRtClientHideUI);
  823. fShmNonRtClientControl.commitWrite();
  824. }
  825. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  826. if (yesNo)
  827. {
  828. pData->tryTransient();
  829. }
  830. else
  831. {
  832. pData->transientTryCounter = 0;
  833. }
  834. #endif
  835. }
  836. void* embedCustomUI(void* const ptr) override
  837. {
  838. if (fBridgeVersion < 9)
  839. return nullptr;
  840. fPendingEmbedCustomUI = 0;
  841. {
  842. const CarlaMutexLocker _cml(fShmNonRtClientControl.mutex);
  843. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientEmbedUI);
  844. fShmNonRtClientControl.writeULong(reinterpret_cast<uint64_t>(ptr));
  845. fShmNonRtClientControl.commitWrite();
  846. }
  847. const uint32_t timeoutEnd = Time::getMillisecondCounter() + 15*1000; // 15 secs
  848. const bool needsEngineIdle = pData->engine->getType() != kEngineTypePlugin;
  849. for (; Time::getMillisecondCounter() < timeoutEnd && fBridgeThread.isThreadRunning();)
  850. {
  851. pData->engine->callback(true, true, ENGINE_CALLBACK_IDLE, 0, 0, 0, 0, 0.0f, nullptr);
  852. if (needsEngineIdle)
  853. pData->engine->idle();
  854. if (fPendingEmbedCustomUI != 0)
  855. {
  856. if (fPendingEmbedCustomUI == 1)
  857. fPendingEmbedCustomUI = 0;
  858. break;
  859. }
  860. carla_msleep(20);
  861. }
  862. return reinterpret_cast<void*>(fPendingEmbedCustomUI);
  863. }
  864. void idle() override
  865. {
  866. if (fBridgeThread.isThreadRunning())
  867. {
  868. if (fInitiated && fTimedOut && pData->active)
  869. setActive(false, true, true);
  870. {
  871. const CarlaMutexLocker _cml(fShmNonRtClientControl.mutex);
  872. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientPing);
  873. fShmNonRtClientControl.commitWrite();
  874. }
  875. try {
  876. handleNonRtData();
  877. } CARLA_SAFE_EXCEPTION("handleNonRtData");
  878. }
  879. else if (fInitiated)
  880. {
  881. fTimedOut = true;
  882. fTimedError = true;
  883. fInitiated = false;
  884. handleProcessStopped();
  885. }
  886. CarlaPlugin::idle();
  887. }
  888. // -------------------------------------------------------------------
  889. // Plugin state
  890. void reload() override
  891. {
  892. CARLA_SAFE_ASSERT_RETURN(pData->engine != nullptr,);
  893. carla_debug("CarlaPluginBridge::reload() - start");
  894. const EngineProcessMode processMode(pData->engine->getProccessMode());
  895. // Safely disable plugin for reload
  896. const ScopedDisabler sd(this);
  897. // cleanup of previous data
  898. pData->audioIn.clear();
  899. pData->audioOut.clear();
  900. pData->cvIn.clear();
  901. pData->cvOut.clear();
  902. pData->event.clear();
  903. bool needsCtrlIn, needsCtrlOut;
  904. needsCtrlIn = needsCtrlOut = false;
  905. if (fInfo.aIns > 0)
  906. {
  907. pData->audioIn.createNew(fInfo.aIns);
  908. }
  909. if (fInfo.aOuts > 0)
  910. {
  911. pData->audioOut.createNew(fInfo.aOuts);
  912. needsCtrlIn = true;
  913. }
  914. if (fInfo.cvIns > 0)
  915. {
  916. pData->cvIn.createNew(fInfo.cvIns);
  917. }
  918. if (fInfo.cvOuts > 0)
  919. {
  920. pData->cvOut.createNew(fInfo.cvOuts);
  921. }
  922. if (fInfo.mIns > 0)
  923. needsCtrlIn = true;
  924. if (fInfo.mOuts > 0)
  925. needsCtrlOut = true;
  926. const uint portNameSize(pData->engine->getMaxPortNameSize());
  927. CarlaString portName;
  928. // Audio Ins
  929. for (uint32_t j=0; j < fInfo.aIns; ++j)
  930. {
  931. portName.clear();
  932. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  933. {
  934. portName = pData->name;
  935. portName += ":";
  936. }
  937. if (fInfo.aInNames != nullptr && fInfo.aInNames[j] != nullptr)
  938. {
  939. portName += fInfo.aInNames[j];
  940. }
  941. else if (fInfo.aIns > 1)
  942. {
  943. portName += "input_";
  944. portName += CarlaString(j+1);
  945. }
  946. else
  947. portName += "input";
  948. portName.truncate(portNameSize);
  949. pData->audioIn.ports[j].port = (CarlaEngineAudioPort*)pData->client->addPort(kEnginePortTypeAudio, portName, true, j);
  950. pData->audioIn.ports[j].rindex = j;
  951. }
  952. // Audio Outs
  953. for (uint32_t j=0; j < fInfo.aOuts; ++j)
  954. {
  955. portName.clear();
  956. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  957. {
  958. portName = pData->name;
  959. portName += ":";
  960. }
  961. if (fInfo.aOutNames != nullptr && fInfo.aOutNames[j] != nullptr)
  962. {
  963. portName += fInfo.aOutNames[j];
  964. }
  965. else if (fInfo.aOuts > 1)
  966. {
  967. portName += "output_";
  968. portName += CarlaString(j+1);
  969. }
  970. else
  971. portName += "output";
  972. portName.truncate(portNameSize);
  973. pData->audioOut.ports[j].port = (CarlaEngineAudioPort*)pData->client->addPort(kEnginePortTypeAudio, portName, false, j);
  974. pData->audioOut.ports[j].rindex = j;
  975. }
  976. // TODO - MIDI
  977. // CV Ins
  978. for (uint32_t j=0; j < fInfo.cvIns; ++j)
  979. {
  980. portName.clear();
  981. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  982. {
  983. portName = pData->name;
  984. portName += ":";
  985. }
  986. if (fInfo.cvInNames != nullptr && fInfo.cvInNames[j] != nullptr)
  987. {
  988. portName += fInfo.cvInNames[j];
  989. }
  990. else if (fInfo.cvIns > 1)
  991. {
  992. portName += "cv_input_";
  993. portName += CarlaString(j+1);
  994. }
  995. else
  996. portName += "cv_input";
  997. portName.truncate(portNameSize);
  998. pData->cvIn.ports[j].port = (CarlaEngineCVPort*)pData->client->addPort(kEnginePortTypeCV, portName, true, j);
  999. pData->cvIn.ports[j].rindex = j;
  1000. }
  1001. // CV Outs
  1002. for (uint32_t j=0; j < fInfo.cvOuts; ++j)
  1003. {
  1004. portName.clear();
  1005. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  1006. {
  1007. portName = pData->name;
  1008. portName += ":";
  1009. }
  1010. if (fInfo.cvOutNames != nullptr && fInfo.cvOutNames[j] != nullptr)
  1011. {
  1012. portName += fInfo.cvOutNames[j];
  1013. }
  1014. else if (fInfo.cvOuts > 1)
  1015. {
  1016. portName += "cv_output_";
  1017. portName += CarlaString(j+1);
  1018. }
  1019. else
  1020. portName += "cv_output";
  1021. portName.truncate(portNameSize);
  1022. pData->cvOut.ports[j].port = (CarlaEngineCVPort*)pData->client->addPort(kEnginePortTypeCV, portName, false, j);
  1023. pData->cvOut.ports[j].rindex = j;
  1024. }
  1025. if (needsCtrlIn)
  1026. {
  1027. portName.clear();
  1028. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  1029. {
  1030. portName = pData->name;
  1031. portName += ":";
  1032. }
  1033. portName += "event-in";
  1034. portName.truncate(portNameSize);
  1035. pData->event.portIn = (CarlaEngineEventPort*)pData->client->addPort(kEnginePortTypeEvent, portName, true, 0);
  1036. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1037. pData->event.cvSourcePorts = pData->client->createCVSourcePorts();
  1038. #endif
  1039. }
  1040. if (needsCtrlOut)
  1041. {
  1042. portName.clear();
  1043. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  1044. {
  1045. portName = pData->name;
  1046. portName += ":";
  1047. }
  1048. portName += "event-out";
  1049. portName.truncate(portNameSize);
  1050. pData->event.portOut = (CarlaEngineEventPort*)pData->client->addPort(kEnginePortTypeEvent, portName, false, 0);
  1051. }
  1052. // extra plugin hints
  1053. pData->extraHints = 0x0;
  1054. if (fInfo.mIns > 0)
  1055. pData->extraHints |= PLUGIN_EXTRA_HINT_HAS_MIDI_IN;
  1056. if (fInfo.mOuts > 0)
  1057. pData->extraHints |= PLUGIN_EXTRA_HINT_HAS_MIDI_OUT;
  1058. bufferSizeChanged(pData->engine->getBufferSize());
  1059. reloadPrograms(true);
  1060. carla_debug("CarlaPluginBridge::reload() - end");
  1061. }
  1062. // -------------------------------------------------------------------
  1063. // Plugin processing
  1064. void activate() noexcept override
  1065. {
  1066. if (! fBridgeThread.isThreadRunning())
  1067. {
  1068. CARLA_SAFE_ASSERT_RETURN(restartBridgeThread(),);
  1069. }
  1070. {
  1071. const CarlaMutexLocker _cml(fShmNonRtClientControl.mutex);
  1072. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientActivate);
  1073. fShmNonRtClientControl.commitWrite();
  1074. }
  1075. fTimedOut = false;
  1076. try {
  1077. waitForClient("activate", 2000);
  1078. } CARLA_SAFE_EXCEPTION("activate - waitForClient");
  1079. }
  1080. void deactivate() noexcept override
  1081. {
  1082. CARLA_SAFE_ASSERT_RETURN(! fTimedError,);
  1083. {
  1084. const CarlaMutexLocker _cml(fShmNonRtClientControl.mutex);
  1085. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientDeactivate);
  1086. fShmNonRtClientControl.commitWrite();
  1087. }
  1088. fTimedOut = false;
  1089. try {
  1090. waitForClient("deactivate", 2000);
  1091. } CARLA_SAFE_EXCEPTION("deactivate - waitForClient");
  1092. }
  1093. void process(const float* const* const audioIn,
  1094. float** const audioOut,
  1095. const float* const* const cvIn,
  1096. float** const cvOut,
  1097. const uint32_t frames) override
  1098. {
  1099. // --------------------------------------------------------------------------------------------------------
  1100. // Check if active
  1101. if (fTimedOut || fTimedError || ! pData->active)
  1102. {
  1103. // disable any output sound
  1104. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  1105. carla_zeroFloats(audioOut[i], frames);
  1106. for (uint32_t i=0; i < pData->cvOut.count; ++i)
  1107. carla_zeroFloats(cvOut[i], frames);
  1108. return;
  1109. }
  1110. // --------------------------------------------------------------------------------------------------------
  1111. // Check if needs reset
  1112. if (pData->needsReset)
  1113. {
  1114. // TODO
  1115. pData->needsReset = false;
  1116. }
  1117. // --------------------------------------------------------------------------------------------------------
  1118. // Event Input
  1119. if (pData->event.portIn != nullptr)
  1120. {
  1121. // ----------------------------------------------------------------------------------------------------
  1122. // MIDI Input (External)
  1123. if (pData->extNotes.mutex.tryLock())
  1124. {
  1125. for (RtLinkedList<ExternalMidiNote>::Itenerator it = pData->extNotes.data.begin2(); it.valid(); it.next())
  1126. {
  1127. const ExternalMidiNote& note(it.getValue(kExternalMidiNoteFallback));
  1128. CARLA_SAFE_ASSERT_CONTINUE(note.channel >= 0 && note.channel < MAX_MIDI_CHANNELS);
  1129. uint8_t data1, data2, data3;
  1130. data1 = uint8_t((note.velo > 0 ? MIDI_STATUS_NOTE_ON : MIDI_STATUS_NOTE_OFF) | (note.channel & MIDI_CHANNEL_BIT));
  1131. data2 = note.note;
  1132. data3 = note.velo;
  1133. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientMidiEvent);
  1134. fShmRtClientControl.writeUInt(0); // time
  1135. fShmRtClientControl.writeByte(0); // port
  1136. fShmRtClientControl.writeByte(3); // size
  1137. fShmRtClientControl.writeByte(data1);
  1138. fShmRtClientControl.writeByte(data2);
  1139. fShmRtClientControl.writeByte(data3);
  1140. fShmRtClientControl.commitWrite();
  1141. }
  1142. pData->extNotes.data.clear();
  1143. pData->extNotes.mutex.unlock();
  1144. } // End of MIDI Input (External)
  1145. // ----------------------------------------------------------------------------------------------------
  1146. // Event Input (System)
  1147. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1148. bool allNotesOffSent = false;
  1149. if (cvIn != nullptr && pData->event.cvSourcePorts != nullptr)
  1150. {
  1151. const bool isSampleAccurate = (pData->options & PLUGIN_OPTION_FIXED_BUFFERS) == 0x0;
  1152. pData->event.cvSourcePorts->initPortBuffers(cvIn + pData->cvIn.count, frames, isSampleAccurate, pData->event.portIn);
  1153. }
  1154. #endif
  1155. for (uint32_t i=0, numEvents=pData->event.portIn->getEventCount(); i < numEvents; ++i)
  1156. {
  1157. EngineEvent& event(pData->event.portIn->getEvent(i));
  1158. // Control change
  1159. switch (event.type)
  1160. {
  1161. case kEngineEventTypeNull:
  1162. break;
  1163. case kEngineEventTypeControl: {
  1164. EngineControlEvent& ctrlEvent = event.ctrl;
  1165. switch (ctrlEvent.type)
  1166. {
  1167. case kEngineControlEventTypeNull:
  1168. break;
  1169. case kEngineControlEventTypeParameter: {
  1170. float value;
  1171. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1172. // non-midi
  1173. if (event.channel == kEngineEventNonMidiChannel)
  1174. {
  1175. const uint32_t k = ctrlEvent.param;
  1176. CARLA_SAFE_ASSERT_CONTINUE(k < pData->param.count);
  1177. ctrlEvent.handled = true;
  1178. value = pData->param.getFinalUnnormalizedValue(k, ctrlEvent.normalizedValue);
  1179. setParameterValueRT(k, value, event.time, true);
  1180. continue;
  1181. }
  1182. // Control backend stuff
  1183. if (event.channel == pData->ctrlChannel)
  1184. {
  1185. if (MIDI_IS_CONTROL_BREATH_CONTROLLER(ctrlEvent.param) && (pData->hints & PLUGIN_CAN_DRYWET) != 0)
  1186. {
  1187. ctrlEvent.handled = true;
  1188. value = ctrlEvent.normalizedValue;
  1189. setDryWetRT(value, true);
  1190. }
  1191. else if (MIDI_IS_CONTROL_CHANNEL_VOLUME(ctrlEvent.param) && (pData->hints & PLUGIN_CAN_VOLUME) != 0)
  1192. {
  1193. ctrlEvent.handled = true;
  1194. value = ctrlEvent.normalizedValue*127.0f/100.0f;
  1195. setVolumeRT(value, true);
  1196. }
  1197. else if (MIDI_IS_CONTROL_BALANCE(ctrlEvent.param) && (pData->hints & PLUGIN_CAN_BALANCE) != 0)
  1198. {
  1199. float left, right;
  1200. value = ctrlEvent.normalizedValue/0.5f - 1.0f;
  1201. if (value < 0.0f)
  1202. {
  1203. left = -1.0f;
  1204. right = (value*2.0f)+1.0f;
  1205. }
  1206. else if (value > 0.0f)
  1207. {
  1208. left = (value*2.0f)-1.0f;
  1209. right = 1.0f;
  1210. }
  1211. else
  1212. {
  1213. left = -1.0f;
  1214. right = 1.0f;
  1215. }
  1216. ctrlEvent.handled = true;
  1217. setBalanceLeftRT(left, true);
  1218. setBalanceRightRT(right, true);
  1219. }
  1220. }
  1221. #endif
  1222. // Control plugin parameters
  1223. for (uint32_t k=0; k < pData->param.count; ++k)
  1224. {
  1225. if (pData->param.data[k].midiChannel != event.channel)
  1226. continue;
  1227. if (pData->param.data[k].mappedControlIndex != ctrlEvent.param)
  1228. continue;
  1229. if (pData->param.data[k].type != PARAMETER_INPUT)
  1230. continue;
  1231. if ((pData->param.data[k].hints & PARAMETER_IS_AUTOMATABLE) == 0)
  1232. continue;
  1233. ctrlEvent.handled = true;
  1234. value = pData->param.getFinalUnnormalizedValue(k, ctrlEvent.normalizedValue);
  1235. setParameterValueRT(k, value, event.time, true);
  1236. }
  1237. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1238. if (! ctrlEvent.handled)
  1239. checkForMidiLearn(event);
  1240. #endif
  1241. if ((pData->options & PLUGIN_OPTION_SEND_CONTROL_CHANGES) != 0 && ctrlEvent.param < MAX_MIDI_VALUE)
  1242. {
  1243. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientMidiEvent);
  1244. fShmRtClientControl.writeUInt(event.time);
  1245. fShmRtClientControl.writeByte(0); // port
  1246. fShmRtClientControl.writeByte(3); // size
  1247. fShmRtClientControl.writeByte(uint8_t(MIDI_STATUS_CONTROL_CHANGE | (event.channel & MIDI_CHANNEL_BIT)));
  1248. fShmRtClientControl.writeByte(uint8_t(ctrlEvent.param));
  1249. fShmRtClientControl.writeByte(uint8_t(ctrlEvent.normalizedValue*127.0f + 0.5f));
  1250. }
  1251. break;
  1252. }
  1253. case kEngineControlEventTypeMidiBank:
  1254. if (pData->options & PLUGIN_OPTION_MAP_PROGRAM_CHANGES)
  1255. {
  1256. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientControlEventMidiBank);
  1257. fShmRtClientControl.writeUInt(event.time);
  1258. fShmRtClientControl.writeByte(event.channel);
  1259. fShmRtClientControl.writeUShort(event.ctrl.param);
  1260. fShmRtClientControl.commitWrite();
  1261. }
  1262. else if ((pData->options & PLUGIN_OPTION_SEND_PROGRAM_CHANGES) != 0)
  1263. {
  1264. // VST2's that use banks usually require both a MSB bank message and a LSB bank message. The MSB bank message can just be 0
  1265. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientMidiEvent);
  1266. fShmRtClientControl.writeUInt(event.time);
  1267. fShmRtClientControl.writeByte(0); // port
  1268. fShmRtClientControl.writeByte(3); // size
  1269. fShmRtClientControl.writeByte(uint8_t(MIDI_STATUS_CONTROL_CHANGE | (event.channel & MIDI_CHANNEL_BIT)));
  1270. fShmRtClientControl.writeByte(MIDI_CONTROL_BANK_SELECT);
  1271. fShmRtClientControl.writeByte(0);
  1272. fShmRtClientControl.commitWrite();
  1273. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientMidiEvent);
  1274. fShmRtClientControl.writeUInt(event.time);
  1275. fShmRtClientControl.writeByte(0); // port
  1276. fShmRtClientControl.writeByte(3); // size
  1277. fShmRtClientControl.writeByte(uint8_t(MIDI_STATUS_CONTROL_CHANGE | (event.channel & MIDI_CHANNEL_BIT)));
  1278. fShmRtClientControl.writeByte(MIDI_CONTROL_BANK_SELECT__LSB);
  1279. fShmRtClientControl.writeByte(uint8_t(event.ctrl.param));
  1280. fShmRtClientControl.commitWrite();
  1281. }
  1282. break;
  1283. case kEngineControlEventTypeMidiProgram:
  1284. if (pData->options & PLUGIN_OPTION_MAP_PROGRAM_CHANGES || pData->options & PLUGIN_OPTION_SEND_PROGRAM_CHANGES)
  1285. {
  1286. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientControlEventMidiProgram);
  1287. fShmRtClientControl.writeUInt(event.time);
  1288. fShmRtClientControl.writeByte(event.channel);
  1289. fShmRtClientControl.writeUShort(event.ctrl.param);
  1290. fShmRtClientControl.commitWrite();
  1291. }
  1292. break;
  1293. case kEngineControlEventTypeAllSoundOff:
  1294. if (pData->options & PLUGIN_OPTION_SEND_ALL_SOUND_OFF)
  1295. {
  1296. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientControlEventAllSoundOff);
  1297. fShmRtClientControl.writeUInt(event.time);
  1298. fShmRtClientControl.writeByte(event.channel);
  1299. fShmRtClientControl.commitWrite();
  1300. }
  1301. break;
  1302. case kEngineControlEventTypeAllNotesOff:
  1303. if (pData->options & PLUGIN_OPTION_SEND_ALL_SOUND_OFF)
  1304. {
  1305. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1306. if (event.channel == pData->ctrlChannel && ! allNotesOffSent)
  1307. {
  1308. allNotesOffSent = true;
  1309. postponeRtAllNotesOff();
  1310. }
  1311. #endif
  1312. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientControlEventAllNotesOff);
  1313. fShmRtClientControl.writeUInt(event.time);
  1314. fShmRtClientControl.writeByte(event.channel);
  1315. fShmRtClientControl.commitWrite();
  1316. }
  1317. break;
  1318. } // switch (ctrlEvent.type)
  1319. break;
  1320. } // case kEngineEventTypeControl
  1321. case kEngineEventTypeMidi: {
  1322. const EngineMidiEvent& midiEvent(event.midi);
  1323. if (midiEvent.size == 0 || midiEvent.size >= MAX_MIDI_VALUE)
  1324. continue;
  1325. const uint8_t* const midiData(midiEvent.size > EngineMidiEvent::kDataSize ? midiEvent.dataExt : midiEvent.data);
  1326. uint8_t status = uint8_t(MIDI_GET_STATUS_FROM_DATA(midiData));
  1327. if ((status == MIDI_STATUS_NOTE_OFF || status == MIDI_STATUS_NOTE_ON) && (pData->options & PLUGIN_OPTION_SKIP_SENDING_NOTES))
  1328. continue;
  1329. if (status == MIDI_STATUS_CHANNEL_PRESSURE && (pData->options & PLUGIN_OPTION_SEND_CHANNEL_PRESSURE) == 0)
  1330. continue;
  1331. if (status == MIDI_STATUS_CONTROL_CHANGE && (pData->options & PLUGIN_OPTION_SEND_CONTROL_CHANGES) == 0)
  1332. continue;
  1333. if (status == MIDI_STATUS_POLYPHONIC_AFTERTOUCH && (pData->options & PLUGIN_OPTION_SEND_NOTE_AFTERTOUCH) == 0)
  1334. continue;
  1335. if (status == MIDI_STATUS_PITCH_WHEEL_CONTROL && (pData->options & PLUGIN_OPTION_SEND_PITCHBEND) == 0)
  1336. continue;
  1337. // Fix bad note-off
  1338. if (status == MIDI_STATUS_NOTE_ON && midiData[2] == 0)
  1339. status = MIDI_STATUS_NOTE_OFF;
  1340. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientMidiEvent);
  1341. fShmRtClientControl.writeUInt(event.time);
  1342. fShmRtClientControl.writeByte(midiEvent.port);
  1343. fShmRtClientControl.writeByte(midiEvent.size);
  1344. fShmRtClientControl.writeByte(uint8_t(midiData[0] | (event.channel & MIDI_CHANNEL_BIT)));
  1345. for (uint8_t j=1; j < midiEvent.size; ++j)
  1346. fShmRtClientControl.writeByte(midiData[j]);
  1347. fShmRtClientControl.commitWrite();
  1348. if (status == MIDI_STATUS_NOTE_ON)
  1349. {
  1350. pData->postponeNoteOnRtEvent(true, event.channel, midiData[1], midiData[2]);
  1351. }
  1352. else if (status == MIDI_STATUS_NOTE_OFF)
  1353. {
  1354. pData->postponeNoteOffRtEvent(true, event.channel, midiData[1]);
  1355. }
  1356. } break;
  1357. }
  1358. }
  1359. pData->postRtEvents.trySplice();
  1360. } // End of Event Input
  1361. if (! processSingle(audioIn, audioOut, cvIn, cvOut, frames))
  1362. return;
  1363. // --------------------------------------------------------------------------------------------------------
  1364. // Control and MIDI Output
  1365. if (pData->event.portOut != nullptr)
  1366. {
  1367. float value;
  1368. for (uint32_t k=0; k < pData->param.count; ++k)
  1369. {
  1370. if (pData->param.data[k].type != PARAMETER_OUTPUT)
  1371. continue;
  1372. if (pData->param.data[k].mappedControlIndex > 0)
  1373. {
  1374. value = pData->param.ranges[k].getNormalizedValue(fParams[k].value);
  1375. pData->event.portOut->writeControlEvent(0,
  1376. pData->param.data[k].midiChannel,
  1377. kEngineControlEventTypeParameter,
  1378. static_cast<uint16_t>(pData->param.data[k].mappedControlIndex),
  1379. -1,
  1380. value);
  1381. }
  1382. }
  1383. uint32_t time;
  1384. uint8_t port, size;
  1385. const uint8_t* midiData(fShmRtClientControl.data->midiOut);
  1386. for (std::size_t read=0; read<kBridgeRtClientDataMidiOutSize-kBridgeBaseMidiOutHeaderSize;)
  1387. {
  1388. // get time
  1389. time = *(const uint32_t*)midiData;
  1390. midiData += 4;
  1391. // get port and size
  1392. port = *midiData++;
  1393. size = *midiData++;
  1394. if (size == 0)
  1395. break;
  1396. // store midi data advancing as needed
  1397. uint8_t data[size];
  1398. for (uint8_t j=0; j<size; ++j)
  1399. data[j] = *midiData++;
  1400. pData->event.portOut->writeMidiEvent(time, size, data);
  1401. read += kBridgeBaseMidiOutHeaderSize + size;
  1402. }
  1403. // TODO
  1404. (void)port;
  1405. } // End of Control and MIDI Output
  1406. }
  1407. bool processSingle(const float* const* const audioIn, float** const audioOut,
  1408. const float* const* const cvIn, float** const cvOut, const uint32_t frames)
  1409. {
  1410. CARLA_SAFE_ASSERT_RETURN(! fTimedError, false);
  1411. CARLA_SAFE_ASSERT_RETURN(frames > 0, false);
  1412. CARLA_SAFE_ASSERT_RETURN(frames <= fBufferSize, false);
  1413. if (pData->audioIn.count > 0)
  1414. {
  1415. CARLA_SAFE_ASSERT_RETURN(audioIn != nullptr, false);
  1416. }
  1417. if (pData->audioOut.count > 0)
  1418. {
  1419. CARLA_SAFE_ASSERT_RETURN(audioOut != nullptr, false);
  1420. }
  1421. if (pData->cvIn.count > 0)
  1422. {
  1423. CARLA_SAFE_ASSERT_RETURN(cvIn != nullptr, false);
  1424. }
  1425. if (pData->cvOut.count > 0)
  1426. {
  1427. CARLA_SAFE_ASSERT_RETURN(cvOut != nullptr, false);
  1428. }
  1429. // --------------------------------------------------------------------------------------------------------
  1430. // Try lock, silence otherwise
  1431. #ifndef STOAT_TEST_BUILD
  1432. if (pData->engine->isOffline())
  1433. {
  1434. pData->singleMutex.lock();
  1435. }
  1436. else
  1437. #endif
  1438. if (! pData->singleMutex.tryLock())
  1439. {
  1440. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  1441. carla_zeroFloats(audioOut[i], frames);
  1442. for (uint32_t i=0; i < pData->cvOut.count; ++i)
  1443. carla_zeroFloats(cvOut[i], frames);
  1444. return false;
  1445. }
  1446. // --------------------------------------------------------------------------------------------------------
  1447. // Reset audio buffers
  1448. for (uint32_t i=0; i < pData->audioIn.count; ++i)
  1449. carla_copyFloats(fShmAudioPool.data + (i * fBufferSize), audioIn[i], frames);
  1450. for (uint32_t i=0; i < pData->cvIn.count; ++i)
  1451. carla_copyFloats(fShmAudioPool.data + ((pData->audioIn.count + pData->audioOut.count + i) * fBufferSize), cvIn[i], frames);
  1452. // --------------------------------------------------------------------------------------------------------
  1453. // TimeInfo
  1454. const EngineTimeInfo timeInfo(pData->engine->getTimeInfo());
  1455. BridgeTimeInfo& bridgeTimeInfo(fShmRtClientControl.data->timeInfo);
  1456. bridgeTimeInfo.playing = timeInfo.playing;
  1457. bridgeTimeInfo.frame = timeInfo.frame;
  1458. bridgeTimeInfo.usecs = timeInfo.usecs;
  1459. bridgeTimeInfo.validFlags = timeInfo.bbt.valid ? kPluginBridgeTimeInfoValidBBT : 0x0;
  1460. if (timeInfo.bbt.valid)
  1461. {
  1462. bridgeTimeInfo.bar = timeInfo.bbt.bar;
  1463. bridgeTimeInfo.beat = timeInfo.bbt.beat;
  1464. bridgeTimeInfo.tick = timeInfo.bbt.tick;
  1465. bridgeTimeInfo.beatsPerBar = timeInfo.bbt.beatsPerBar;
  1466. bridgeTimeInfo.beatType = timeInfo.bbt.beatType;
  1467. bridgeTimeInfo.ticksPerBeat = timeInfo.bbt.ticksPerBeat;
  1468. bridgeTimeInfo.beatsPerMinute = timeInfo.bbt.beatsPerMinute;
  1469. bridgeTimeInfo.barStartTick = timeInfo.bbt.barStartTick;
  1470. }
  1471. // --------------------------------------------------------------------------------------------------------
  1472. // Run plugin
  1473. {
  1474. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientProcess);
  1475. fShmRtClientControl.writeUInt(frames);
  1476. fShmRtClientControl.commitWrite();
  1477. }
  1478. waitForClient("process", fProcWaitTime);
  1479. if (fTimedOut)
  1480. {
  1481. pData->singleMutex.unlock();
  1482. return false;
  1483. }
  1484. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  1485. carla_copyFloats(audioOut[i], fShmAudioPool.data + ((pData->audioIn.count + i) * fBufferSize), frames);
  1486. for (uint32_t i=0; i < pData->cvOut.count; ++i)
  1487. carla_copyFloats(cvOut[i], fShmAudioPool.data + ((pData->audioIn.count + pData->audioOut.count + pData->cvIn.count + i) * fBufferSize), frames);
  1488. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1489. // --------------------------------------------------------------------------------------------------------
  1490. // Post-processing (dry/wet, volume and balance)
  1491. {
  1492. const bool doVolume = (pData->hints & PLUGIN_CAN_VOLUME) != 0 && carla_isNotEqual(pData->postProc.volume, 1.0f);
  1493. const bool doDryWet = (pData->hints & PLUGIN_CAN_DRYWET) != 0 && carla_isNotEqual(pData->postProc.dryWet, 1.0f);
  1494. const bool doBalance = (pData->hints & PLUGIN_CAN_BALANCE) != 0 && ! (carla_isEqual(pData->postProc.balanceLeft, -1.0f) && carla_isEqual(pData->postProc.balanceRight, 1.0f));
  1495. const bool isMono = (pData->audioIn.count == 1);
  1496. bool isPair;
  1497. float bufValue, oldBufLeft[doBalance ? frames : 1];
  1498. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  1499. {
  1500. // Dry/Wet
  1501. if (doDryWet)
  1502. {
  1503. const uint32_t c = isMono ? 0 : i;
  1504. for (uint32_t k=0; k < frames; ++k)
  1505. {
  1506. # ifndef BUILD_BRIDGE
  1507. if (k < pData->latency.frames && pData->latency.buffers != nullptr)
  1508. bufValue = pData->latency.buffers[c][k];
  1509. else if (pData->latency.frames < frames)
  1510. bufValue = audioIn[c][k-pData->latency.frames];
  1511. else
  1512. # endif
  1513. bufValue = audioIn[c][k];
  1514. audioOut[i][k] = (audioOut[i][k] * pData->postProc.dryWet) + (bufValue * (1.0f - pData->postProc.dryWet));
  1515. }
  1516. }
  1517. // Balance
  1518. if (doBalance)
  1519. {
  1520. isPair = (i % 2 == 0);
  1521. if (isPair)
  1522. {
  1523. CARLA_ASSERT(i+1 < pData->audioOut.count);
  1524. carla_copyFloats(oldBufLeft, audioOut[i], frames);
  1525. }
  1526. float balRangeL = (pData->postProc.balanceLeft + 1.0f)/2.0f;
  1527. float balRangeR = (pData->postProc.balanceRight + 1.0f)/2.0f;
  1528. for (uint32_t k=0; k < frames; ++k)
  1529. {
  1530. if (isPair)
  1531. {
  1532. // left
  1533. audioOut[i][k] = oldBufLeft[k] * (1.0f - balRangeL);
  1534. audioOut[i][k] += audioOut[i+1][k] * (1.0f - balRangeR);
  1535. }
  1536. else
  1537. {
  1538. // right
  1539. audioOut[i][k] = audioOut[i][k] * balRangeR;
  1540. audioOut[i][k] += oldBufLeft[k] * balRangeL;
  1541. }
  1542. }
  1543. }
  1544. // Volume (and buffer copy)
  1545. if (doVolume)
  1546. {
  1547. for (uint32_t k=0; k < frames; ++k)
  1548. audioOut[i][k] *= pData->postProc.volume;
  1549. }
  1550. }
  1551. } // End of Post-processing
  1552. # ifndef BUILD_BRIDGE
  1553. // --------------------------------------------------------------------------------------------------------
  1554. // Save latency values for next callback
  1555. if (pData->latency.frames != 0 && pData->latency.buffers != nullptr)
  1556. {
  1557. const uint32_t latframes = pData->latency.frames;
  1558. if (latframes <= frames)
  1559. {
  1560. for (uint32_t i=0; i < pData->audioIn.count; ++i)
  1561. carla_copyFloats(pData->latency.buffers[i], audioIn[i]+(frames-latframes), latframes);
  1562. }
  1563. else
  1564. {
  1565. const uint32_t diff = latframes - frames;
  1566. for (uint32_t i=0, k; i<pData->audioIn.count; ++i)
  1567. {
  1568. // push back buffer by 'frames'
  1569. for (k=0; k < diff; ++k)
  1570. pData->latency.buffers[i][k] = pData->latency.buffers[i][k+frames];
  1571. // put current input at the end
  1572. for (uint32_t j=0; k < latframes; ++j, ++k)
  1573. pData->latency.buffers[i][k] = audioIn[i][j];
  1574. }
  1575. }
  1576. }
  1577. # endif
  1578. #endif // BUILD_BRIDGE_ALTERNATIVE_ARCH
  1579. // --------------------------------------------------------------------------------------------------------
  1580. pData->singleMutex.unlock();
  1581. return true;
  1582. }
  1583. void bufferSizeChanged(const uint32_t newBufferSize) override
  1584. {
  1585. fBufferSize = newBufferSize;
  1586. resizeAudioPool(newBufferSize);
  1587. {
  1588. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientSetBufferSize);
  1589. fShmRtClientControl.writeUInt(newBufferSize);
  1590. fShmRtClientControl.commitWrite();
  1591. }
  1592. //fProcWaitTime = newBufferSize*1000/pData->engine->getSampleRate();
  1593. fProcWaitTime = 1000;
  1594. waitForClient("buffersize", 1000);
  1595. }
  1596. void sampleRateChanged(const double newSampleRate) override
  1597. {
  1598. {
  1599. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientSetSampleRate);
  1600. fShmRtClientControl.writeDouble(newSampleRate);
  1601. fShmRtClientControl.commitWrite();
  1602. }
  1603. //fProcWaitTime = pData->engine->getBufferSize()*1000/newSampleRate;
  1604. fProcWaitTime = 1000;
  1605. waitForClient("samplerate", 1000);
  1606. }
  1607. void offlineModeChanged(const bool isOffline) override
  1608. {
  1609. {
  1610. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientSetOnline);
  1611. fShmRtClientControl.writeBool(isOffline);
  1612. fShmRtClientControl.commitWrite();
  1613. }
  1614. waitForClient("offline", 1000);
  1615. }
  1616. // -------------------------------------------------------------------
  1617. // Plugin buffers
  1618. void clearBuffers() noexcept override
  1619. {
  1620. if (fParams != nullptr)
  1621. {
  1622. delete[] fParams;
  1623. fParams = nullptr;
  1624. }
  1625. CarlaPlugin::clearBuffers();
  1626. }
  1627. // -------------------------------------------------------------------
  1628. // Post-poned UI Stuff
  1629. void uiParameterChange(const uint32_t index, const float value) noexcept override
  1630. {
  1631. CARLA_SAFE_ASSERT_RETURN(index < pData->param.count,);
  1632. const CarlaMutexLocker _cml(fShmNonRtClientControl.mutex);
  1633. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientUiParameterChange);
  1634. fShmNonRtClientControl.writeUInt(index);
  1635. fShmNonRtClientControl.writeFloat(value);
  1636. fShmNonRtClientControl.commitWrite();
  1637. }
  1638. void uiProgramChange(const uint32_t index) noexcept override
  1639. {
  1640. CARLA_SAFE_ASSERT_RETURN(index < pData->prog.count,);
  1641. const CarlaMutexLocker _cml(fShmNonRtClientControl.mutex);
  1642. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientUiProgramChange);
  1643. fShmNonRtClientControl.writeUInt(index);
  1644. fShmNonRtClientControl.commitWrite();
  1645. }
  1646. void uiMidiProgramChange(const uint32_t index) noexcept override
  1647. {
  1648. CARLA_SAFE_ASSERT_RETURN(index < pData->midiprog.count,);
  1649. const CarlaMutexLocker _cml(fShmNonRtClientControl.mutex);
  1650. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientUiMidiProgramChange);
  1651. fShmNonRtClientControl.writeUInt(index);
  1652. fShmNonRtClientControl.commitWrite();
  1653. }
  1654. void uiNoteOn(const uint8_t channel, const uint8_t note, const uint8_t velo) noexcept override
  1655. {
  1656. CARLA_SAFE_ASSERT_RETURN(channel < MAX_MIDI_CHANNELS,);
  1657. CARLA_SAFE_ASSERT_RETURN(note < MAX_MIDI_NOTE,);
  1658. CARLA_SAFE_ASSERT_RETURN(velo > 0 && velo < MAX_MIDI_VALUE,);
  1659. const CarlaMutexLocker _cml(fShmNonRtClientControl.mutex);
  1660. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientUiNoteOn);
  1661. fShmNonRtClientControl.writeByte(channel);
  1662. fShmNonRtClientControl.writeByte(note);
  1663. fShmNonRtClientControl.writeByte(velo);
  1664. fShmNonRtClientControl.commitWrite();
  1665. }
  1666. void uiNoteOff(const uint8_t channel, const uint8_t note) noexcept override
  1667. {
  1668. CARLA_SAFE_ASSERT_RETURN(channel < MAX_MIDI_CHANNELS,);
  1669. CARLA_SAFE_ASSERT_RETURN(note < MAX_MIDI_NOTE,);
  1670. const CarlaMutexLocker _cml(fShmNonRtClientControl.mutex);
  1671. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientUiNoteOff);
  1672. fShmNonRtClientControl.writeByte(channel);
  1673. fShmNonRtClientControl.writeByte(note);
  1674. fShmNonRtClientControl.commitWrite();
  1675. }
  1676. // -------------------------------------------------------------------
  1677. // Internal helper functions
  1678. void restoreLV2State(bool) noexcept override
  1679. {
  1680. const CarlaMutexLocker _cml(fShmNonRtClientControl.mutex);
  1681. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientRestoreLV2State);
  1682. fShmNonRtClientControl.commitWrite();
  1683. }
  1684. void waitForBridgeSaveSignal() noexcept override
  1685. {
  1686. // VSTs only save chunks, for which we already have a waitForSaved there
  1687. if (fPluginType != PLUGIN_VST2)
  1688. waitForSaved();
  1689. }
  1690. // -------------------------------------------------------------------
  1691. void handleNonRtData()
  1692. {
  1693. for (; fShmNonRtServerControl.isDataAvailableForReading();)
  1694. {
  1695. const PluginBridgeNonRtServerOpcode opcode(fShmNonRtServerControl.readOpcode());
  1696. #ifdef DEBUG
  1697. if (opcode != kPluginBridgeNonRtServerPong && opcode != kPluginBridgeNonRtServerParameterValue2) {
  1698. carla_debug("CarlaPluginBridge::handleNonRtData() - got opcode: %s", PluginBridgeNonRtServerOpcode2str(opcode));
  1699. }
  1700. #endif
  1701. switch (opcode)
  1702. {
  1703. case kPluginBridgeNonRtServerNull:
  1704. case kPluginBridgeNonRtServerPong:
  1705. break;
  1706. case kPluginBridgeNonRtServerVersion:
  1707. fBridgeVersion = fShmNonRtServerControl.readUInt();
  1708. break;
  1709. case kPluginBridgeNonRtServerPluginInfo1: {
  1710. // uint/category, uint/hints, uint/optionsAvailable, uint/optionsEnabled, long/uniqueId
  1711. const uint32_t category = fShmNonRtServerControl.readUInt();
  1712. const uint32_t hints = fShmNonRtServerControl.readUInt();
  1713. const uint32_t optionAv = fShmNonRtServerControl.readUInt();
  1714. const uint32_t optionEn = fShmNonRtServerControl.readUInt();
  1715. const int64_t uniqueId = fShmNonRtServerControl.readLong();
  1716. if (fUniqueId != 0) {
  1717. CARLA_SAFE_ASSERT_INT2(fUniqueId == uniqueId, fUniqueId, uniqueId);
  1718. }
  1719. pData->hints = hints | PLUGIN_IS_BRIDGE;
  1720. pData->options = optionEn;
  1721. #ifdef HAVE_X11
  1722. if (fBridgeVersion < 9)
  1723. #endif
  1724. {
  1725. pData->hints &= ~PLUGIN_HAS_CUSTOM_EMBED_UI;
  1726. }
  1727. fInfo.category = static_cast<PluginCategory>(category);
  1728. fInfo.optionsAvailable = optionAv;
  1729. } break;
  1730. case kPluginBridgeNonRtServerPluginInfo2: {
  1731. // uint/size, str[] (realName), uint/size, str[] (label), uint/size, str[] (maker), uint/size, str[] (copyright)
  1732. // realName
  1733. const uint32_t realNameSize(fShmNonRtServerControl.readUInt());
  1734. char realName[realNameSize+1];
  1735. carla_zeroChars(realName, realNameSize+1);
  1736. fShmNonRtServerControl.readCustomData(realName, realNameSize);
  1737. // label
  1738. const uint32_t labelSize(fShmNonRtServerControl.readUInt());
  1739. char label[labelSize+1];
  1740. carla_zeroChars(label, labelSize+1);
  1741. fShmNonRtServerControl.readCustomData(label, labelSize);
  1742. // maker
  1743. const uint32_t makerSize(fShmNonRtServerControl.readUInt());
  1744. char maker[makerSize+1];
  1745. carla_zeroChars(maker, makerSize+1);
  1746. fShmNonRtServerControl.readCustomData(maker, makerSize);
  1747. // copyright
  1748. const uint32_t copyrightSize(fShmNonRtServerControl.readUInt());
  1749. char copyright[copyrightSize+1];
  1750. carla_zeroChars(copyright, copyrightSize+1);
  1751. fShmNonRtServerControl.readCustomData(copyright, copyrightSize);
  1752. fInfo.name = realName;
  1753. fInfo.label = label;
  1754. fInfo.maker = maker;
  1755. fInfo.copyright = copyright;
  1756. if (pData->name == nullptr)
  1757. pData->name = pData->engine->getUniquePluginName(realName);
  1758. } break;
  1759. case kPluginBridgeNonRtServerAudioCount: {
  1760. // uint/ins, uint/outs
  1761. fInfo.clear();
  1762. fInfo.aIns = fShmNonRtServerControl.readUInt();
  1763. fInfo.aOuts = fShmNonRtServerControl.readUInt();
  1764. if (fInfo.aIns > 0)
  1765. {
  1766. fInfo.aInNames = new const char*[fInfo.aIns];
  1767. carla_zeroPointers(fInfo.aInNames, fInfo.aIns);
  1768. }
  1769. if (fInfo.aOuts > 0)
  1770. {
  1771. fInfo.aOutNames = new const char*[fInfo.aOuts];
  1772. carla_zeroPointers(fInfo.aOutNames, fInfo.aOuts);
  1773. }
  1774. } break;
  1775. case kPluginBridgeNonRtServerMidiCount: {
  1776. // uint/ins, uint/outs
  1777. fInfo.mIns = fShmNonRtServerControl.readUInt();
  1778. fInfo.mOuts = fShmNonRtServerControl.readUInt();
  1779. } break;
  1780. case kPluginBridgeNonRtServerCvCount: {
  1781. // uint/ins, uint/outs
  1782. fInfo.cvIns = fShmNonRtServerControl.readUInt();
  1783. fInfo.cvOuts = fShmNonRtServerControl.readUInt();
  1784. } break;
  1785. case kPluginBridgeNonRtServerParameterCount: {
  1786. // uint/count
  1787. const uint32_t count = fShmNonRtServerControl.readUInt();
  1788. // delete old data
  1789. pData->param.clear();
  1790. if (fParams != nullptr)
  1791. {
  1792. delete[] fParams;
  1793. fParams = nullptr;
  1794. }
  1795. if (count > 0)
  1796. {
  1797. pData->param.createNew(count, false);
  1798. fParams = new BridgeParamInfo[count];
  1799. // we might not receive all parameter data, so ensure range max is not 0
  1800. for (uint32_t i=0; i<count; ++i)
  1801. {
  1802. pData->param.ranges[i].def = 0.0f;
  1803. pData->param.ranges[i].min = 0.0f;
  1804. pData->param.ranges[i].max = 1.0f;
  1805. pData->param.ranges[i].step = 0.001f;
  1806. pData->param.ranges[i].stepSmall = 0.0001f;
  1807. pData->param.ranges[i].stepLarge = 0.1f;
  1808. }
  1809. }
  1810. } break;
  1811. case kPluginBridgeNonRtServerProgramCount: {
  1812. // uint/count
  1813. pData->prog.clear();
  1814. if (const uint32_t count = fShmNonRtServerControl.readUInt())
  1815. pData->prog.createNew(count);
  1816. } break;
  1817. case kPluginBridgeNonRtServerMidiProgramCount: {
  1818. // uint/count
  1819. pData->midiprog.clear();
  1820. if (const uint32_t count = fShmNonRtServerControl.readUInt())
  1821. pData->midiprog.createNew(count);
  1822. } break;
  1823. case kPluginBridgeNonRtServerPortName: {
  1824. // byte/type, uint/index, uint/size, str[] (name)
  1825. const uint8_t portType = fShmNonRtServerControl.readByte();
  1826. const uint32_t index = fShmNonRtServerControl.readUInt();
  1827. // name
  1828. const uint32_t nameSize(fShmNonRtServerControl.readUInt());
  1829. char* const name = new char[nameSize+1];
  1830. carla_zeroChars(name, nameSize+1);
  1831. fShmNonRtServerControl.readCustomData(name, nameSize);
  1832. CARLA_SAFE_ASSERT_BREAK(portType > kPluginBridgePortNull && portType < kPluginBridgePortTypeCount);
  1833. switch (portType)
  1834. {
  1835. case kPluginBridgePortAudioInput:
  1836. CARLA_SAFE_ASSERT_BREAK(index < fInfo.aIns);
  1837. fInfo.aInNames[index] = name;
  1838. break;
  1839. case kPluginBridgePortAudioOutput:
  1840. CARLA_SAFE_ASSERT_BREAK(index < fInfo.aOuts);
  1841. fInfo.aOutNames[index] = name;
  1842. break;
  1843. }
  1844. } break;
  1845. case kPluginBridgeNonRtServerParameterData1: {
  1846. // uint/index, int/rindex, uint/type, uint/hints, int/cc
  1847. const uint32_t index = fShmNonRtServerControl.readUInt();
  1848. const int32_t rindex = fShmNonRtServerControl.readInt();
  1849. const uint32_t type = fShmNonRtServerControl.readUInt();
  1850. const uint32_t hints = fShmNonRtServerControl.readUInt();
  1851. const int16_t ctrl = fShmNonRtServerControl.readShort();
  1852. CARLA_SAFE_ASSERT_BREAK(ctrl >= CONTROL_INDEX_NONE && ctrl <= CONTROL_INDEX_MAX_ALLOWED);
  1853. CARLA_SAFE_ASSERT_INT2(index < pData->param.count, index, pData->param.count);
  1854. if (index < pData->param.count)
  1855. {
  1856. pData->param.data[index].type = static_cast<ParameterType>(type);
  1857. pData->param.data[index].index = static_cast<int32_t>(index);
  1858. pData->param.data[index].rindex = rindex;
  1859. pData->param.data[index].hints = hints;
  1860. pData->param.data[index].mappedControlIndex = ctrl;
  1861. }
  1862. } break;
  1863. case kPluginBridgeNonRtServerParameterData2: {
  1864. // uint/index, uint/size, str[] (name), uint/size, str[] (unit)
  1865. const uint32_t index = fShmNonRtServerControl.readUInt();
  1866. // name
  1867. const uint32_t nameSize(fShmNonRtServerControl.readUInt());
  1868. char name[nameSize+1];
  1869. carla_zeroChars(name, nameSize+1);
  1870. fShmNonRtServerControl.readCustomData(name, nameSize);
  1871. // symbol
  1872. const uint32_t symbolSize(fShmNonRtServerControl.readUInt());
  1873. char symbol[symbolSize+1];
  1874. carla_zeroChars(symbol, symbolSize+1);
  1875. fShmNonRtServerControl.readCustomData(symbol, symbolSize);
  1876. // unit
  1877. const uint32_t unitSize(fShmNonRtServerControl.readUInt());
  1878. char unit[unitSize+1];
  1879. carla_zeroChars(unit, unitSize+1);
  1880. fShmNonRtServerControl.readCustomData(unit, unitSize);
  1881. CARLA_SAFE_ASSERT_INT2(index < pData->param.count, index, pData->param.count);
  1882. if (index < pData->param.count)
  1883. {
  1884. fParams[index].name = name;
  1885. fParams[index].symbol = symbol;
  1886. fParams[index].unit = unit;
  1887. }
  1888. } break;
  1889. case kPluginBridgeNonRtServerParameterRanges: {
  1890. // uint/index, float/def, float/min, float/max, float/step, float/stepSmall, float/stepLarge
  1891. const uint32_t index = fShmNonRtServerControl.readUInt();
  1892. const float def = fShmNonRtServerControl.readFloat();
  1893. const float min = fShmNonRtServerControl.readFloat();
  1894. const float max = fShmNonRtServerControl.readFloat();
  1895. const float step = fShmNonRtServerControl.readFloat();
  1896. const float stepSmall = fShmNonRtServerControl.readFloat();
  1897. const float stepLarge = fShmNonRtServerControl.readFloat();
  1898. CARLA_SAFE_ASSERT_BREAK(min < max);
  1899. CARLA_SAFE_ASSERT_BREAK(def >= min);
  1900. CARLA_SAFE_ASSERT_BREAK(def <= max);
  1901. CARLA_SAFE_ASSERT_INT2(index < pData->param.count, index, pData->param.count);
  1902. if (index < pData->param.count)
  1903. {
  1904. pData->param.ranges[index].def = def;
  1905. pData->param.ranges[index].min = min;
  1906. pData->param.ranges[index].max = max;
  1907. pData->param.ranges[index].step = step;
  1908. pData->param.ranges[index].stepSmall = stepSmall;
  1909. pData->param.ranges[index].stepLarge = stepLarge;
  1910. }
  1911. } break;
  1912. case kPluginBridgeNonRtServerParameterValue: {
  1913. // uint/index, float/value
  1914. const uint32_t index = fShmNonRtServerControl.readUInt();
  1915. const float value = fShmNonRtServerControl.readFloat();
  1916. if (index < pData->param.count)
  1917. {
  1918. const float fixedValue(pData->param.getFixedValue(index, value));
  1919. if (carla_isNotEqual(fParams[index].value, fixedValue))
  1920. {
  1921. fParams[index].value = fixedValue;
  1922. CarlaPlugin::setParameterValue(index, fixedValue, false, true, true);
  1923. }
  1924. }
  1925. } break;
  1926. case kPluginBridgeNonRtServerParameterValue2: {
  1927. // uint/index, float/value
  1928. const uint32_t index = fShmNonRtServerControl.readUInt();
  1929. const float value = fShmNonRtServerControl.readFloat();
  1930. if (index < pData->param.count)
  1931. {
  1932. const float fixedValue(pData->param.getFixedValue(index, value));
  1933. fParams[index].value = fixedValue;
  1934. }
  1935. } break;
  1936. case kPluginBridgeNonRtServerParameterTouch: {
  1937. // uint/index, bool/touch
  1938. const uint32_t index = fShmNonRtServerControl.readUInt();
  1939. const bool touch = fShmNonRtServerControl.readBool();
  1940. pData->engine->touchPluginParameter(pData->id, index, touch);
  1941. } break;
  1942. case kPluginBridgeNonRtServerDefaultValue: {
  1943. // uint/index, float/value
  1944. const uint32_t index = fShmNonRtServerControl.readUInt();
  1945. const float value = fShmNonRtServerControl.readFloat();
  1946. if (index < pData->param.count)
  1947. pData->param.ranges[index].def = value;
  1948. } break;
  1949. case kPluginBridgeNonRtServerCurrentProgram: {
  1950. // int/index
  1951. const int32_t index = fShmNonRtServerControl.readInt();
  1952. CARLA_SAFE_ASSERT_BREAK(index >= -1);
  1953. CARLA_SAFE_ASSERT_INT2(index < static_cast<int32_t>(pData->prog.count), index, pData->prog.count);
  1954. CarlaPlugin::setProgram(index, false, true, true);
  1955. } break;
  1956. case kPluginBridgeNonRtServerCurrentMidiProgram: {
  1957. // int/index
  1958. const int32_t index = fShmNonRtServerControl.readInt();
  1959. CARLA_SAFE_ASSERT_BREAK(index >= -1);
  1960. CARLA_SAFE_ASSERT_INT2(index < static_cast<int32_t>(pData->midiprog.count), index, pData->midiprog.count);
  1961. CarlaPlugin::setMidiProgram(index, false, true, true);
  1962. } break;
  1963. case kPluginBridgeNonRtServerProgramName: {
  1964. // uint/index, uint/size, str[] (name)
  1965. const uint32_t index = fShmNonRtServerControl.readUInt();
  1966. // name
  1967. const uint32_t nameSize(fShmNonRtServerControl.readUInt());
  1968. char name[nameSize+1];
  1969. carla_zeroChars(name, nameSize+1);
  1970. fShmNonRtServerControl.readCustomData(name, nameSize);
  1971. CARLA_SAFE_ASSERT_INT2(index < pData->prog.count, index, pData->prog.count);
  1972. if (index < pData->prog.count)
  1973. {
  1974. if (pData->prog.names[index] != nullptr)
  1975. delete[] pData->prog.names[index];
  1976. pData->prog.names[index] = carla_strdup(name);
  1977. }
  1978. } break;
  1979. case kPluginBridgeNonRtServerMidiProgramData: {
  1980. // uint/index, uint/bank, uint/program, uint/size, str[] (name)
  1981. const uint32_t index = fShmNonRtServerControl.readUInt();
  1982. const uint32_t bank = fShmNonRtServerControl.readUInt();
  1983. const uint32_t program = fShmNonRtServerControl.readUInt();
  1984. // name
  1985. const uint32_t nameSize(fShmNonRtServerControl.readUInt());
  1986. char name[nameSize+1];
  1987. carla_zeroChars(name, nameSize+1);
  1988. fShmNonRtServerControl.readCustomData(name, nameSize);
  1989. CARLA_SAFE_ASSERT_INT2(index < pData->midiprog.count, index, pData->midiprog.count);
  1990. if (index < pData->midiprog.count)
  1991. {
  1992. if (pData->midiprog.data[index].name != nullptr)
  1993. delete[] pData->midiprog.data[index].name;
  1994. pData->midiprog.data[index].bank = bank;
  1995. pData->midiprog.data[index].program = program;
  1996. pData->midiprog.data[index].name = carla_strdup(name);
  1997. }
  1998. } break;
  1999. case kPluginBridgeNonRtServerSetCustomData: {
  2000. // uint/size, str[], uint/size, str[], uint/size, str[]
  2001. const uint32_t maxLocalValueLen = fBridgeVersion >= 10 ? 4096 : 16384;
  2002. // type
  2003. const uint32_t typeSize = fShmNonRtServerControl.readUInt();
  2004. char type[typeSize+1];
  2005. carla_zeroChars(type, typeSize+1);
  2006. fShmNonRtServerControl.readCustomData(type, typeSize);
  2007. // key
  2008. const uint32_t keySize = fShmNonRtServerControl.readUInt();
  2009. char key[keySize+1];
  2010. carla_zeroChars(key, keySize+1);
  2011. fShmNonRtServerControl.readCustomData(key, keySize);
  2012. // value
  2013. const uint32_t valueSize = fShmNonRtServerControl.readUInt();
  2014. // special case for big values
  2015. if (valueSize > maxLocalValueLen)
  2016. {
  2017. const uint32_t bigValueFilePathSize = fShmNonRtServerControl.readUInt();
  2018. char bigValueFilePath[bigValueFilePathSize+1];
  2019. carla_zeroChars(bigValueFilePath, bigValueFilePathSize+1);
  2020. fShmNonRtServerControl.readCustomData(bigValueFilePath, bigValueFilePathSize);
  2021. String realBigValueFilePath(bigValueFilePath);
  2022. #ifndef CARLA_OS_WIN
  2023. // Using Wine, fix temp dir
  2024. if (fBinaryType == BINARY_WIN32 || fBinaryType == BINARY_WIN64)
  2025. {
  2026. const StringArray driveLetterSplit(StringArray::fromTokens(realBigValueFilePath, ":/", ""));
  2027. carla_stdout("big value save path BEFORE => %s", realBigValueFilePath.toRawUTF8());
  2028. realBigValueFilePath = fWinePrefix;
  2029. realBigValueFilePath += "/drive_";
  2030. realBigValueFilePath += driveLetterSplit[0].toLowerCase();
  2031. realBigValueFilePath += driveLetterSplit[1];
  2032. realBigValueFilePath = realBigValueFilePath.replace("\\", "/");
  2033. carla_stdout("big value save path AFTER => %s", realBigValueFilePath.toRawUTF8());
  2034. }
  2035. #endif
  2036. const File bigValueFile(realBigValueFilePath);
  2037. CARLA_SAFE_ASSERT_BREAK(bigValueFile.existsAsFile());
  2038. CarlaPlugin::setCustomData(type, key, bigValueFile.loadFileAsString().toRawUTF8(), false);
  2039. bigValueFile.deleteFile();
  2040. }
  2041. else
  2042. {
  2043. char value[valueSize+1];
  2044. carla_zeroChars(value, valueSize+1);
  2045. if (valueSize > 0)
  2046. fShmNonRtServerControl.readCustomData(value, valueSize);
  2047. CarlaPlugin::setCustomData(type, key, value, false);
  2048. }
  2049. } break;
  2050. case kPluginBridgeNonRtServerSetChunkDataFile: {
  2051. // uint/size, str[] (filename)
  2052. // chunkFilePath
  2053. const uint32_t chunkFilePathSize = fShmNonRtServerControl.readUInt();
  2054. char chunkFilePath[chunkFilePathSize+1];
  2055. carla_zeroChars(chunkFilePath, chunkFilePathSize+1);
  2056. fShmNonRtServerControl.readCustomData(chunkFilePath, chunkFilePathSize);
  2057. String realChunkFilePath(chunkFilePath);
  2058. #ifndef CARLA_OS_WIN
  2059. // Using Wine, fix temp dir
  2060. if (fBinaryType == BINARY_WIN32 || fBinaryType == BINARY_WIN64)
  2061. {
  2062. const StringArray driveLetterSplit(StringArray::fromTokens(realChunkFilePath, ":/", ""));
  2063. carla_stdout("chunk save path BEFORE => %s", realChunkFilePath.toRawUTF8());
  2064. realChunkFilePath = fWinePrefix;
  2065. realChunkFilePath += "/drive_";
  2066. realChunkFilePath += driveLetterSplit[0].toLowerCase();
  2067. realChunkFilePath += driveLetterSplit[1];
  2068. realChunkFilePath = realChunkFilePath.replace("\\", "/");
  2069. carla_stdout("chunk save path AFTER => %s", realChunkFilePath.toRawUTF8());
  2070. }
  2071. #endif
  2072. const File chunkFile(realChunkFilePath);
  2073. CARLA_SAFE_ASSERT_BREAK(chunkFile.existsAsFile());
  2074. fInfo.chunk = carla_getChunkFromBase64String(chunkFile.loadFileAsString().toRawUTF8());
  2075. chunkFile.deleteFile();
  2076. } break;
  2077. case kPluginBridgeNonRtServerSetLatency:
  2078. // uint
  2079. fLatency = fShmNonRtServerControl.readUInt();
  2080. #ifndef BUILD_BRIDGE
  2081. if (! fInitiated)
  2082. pData->latency.recreateBuffers(std::max(fInfo.aIns, fInfo.aOuts), fLatency);
  2083. #endif
  2084. break;
  2085. case kPluginBridgeNonRtServerSetParameterText: {
  2086. const int32_t index = fShmNonRtServerControl.readInt();
  2087. const uint32_t textSize(fShmNonRtServerControl.readUInt());
  2088. char text[textSize+1];
  2089. carla_zeroChars(text, textSize+1);
  2090. fShmNonRtServerControl.readCustomData(text, textSize);
  2091. fReceivingParamText.setReceivedData(index, text, textSize);
  2092. } break;
  2093. case kPluginBridgeNonRtServerReady:
  2094. fInitiated = true;
  2095. break;
  2096. case kPluginBridgeNonRtServerSaved:
  2097. fSaved = true;
  2098. break;
  2099. case kPluginBridgeNonRtServerRespEmbedUI:
  2100. fPendingEmbedCustomUI = fShmNonRtServerControl.readULong();
  2101. break;
  2102. case kPluginBridgeNonRtServerResizeEmbedUI: {
  2103. const uint width = fShmNonRtServerControl.readUInt();
  2104. const uint height = fShmNonRtServerControl.readUInt();
  2105. pData->engine->callback(true, true, ENGINE_CALLBACK_EMBED_UI_RESIZED, pData->id,
  2106. static_cast<int>(width), static_cast<int>(height),
  2107. 0, 0.0f, nullptr);
  2108. } break;
  2109. case kPluginBridgeNonRtServerUiClosed:
  2110. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  2111. pData->transientTryCounter = 0;
  2112. #endif
  2113. pData->engine->callback(true, true, ENGINE_CALLBACK_UI_STATE_CHANGED, pData->id,
  2114. 0, 0, 0, 0.0f, nullptr);
  2115. break;
  2116. case kPluginBridgeNonRtServerError: {
  2117. // error
  2118. const uint32_t errorSize(fShmNonRtServerControl.readUInt());
  2119. char error[errorSize+1];
  2120. carla_zeroChars(error, errorSize+1);
  2121. fShmNonRtServerControl.readCustomData(error, errorSize);
  2122. if (fInitiated)
  2123. {
  2124. pData->engine->callback(true, true, ENGINE_CALLBACK_ERROR, pData->id, 0, 0, 0, 0.0f, error);
  2125. // just in case
  2126. pData->engine->setLastError(error);
  2127. fInitError = true;
  2128. }
  2129. else
  2130. {
  2131. pData->engine->setLastError(error);
  2132. fInitError = true;
  2133. fInitiated = true;
  2134. }
  2135. } break;
  2136. }
  2137. }
  2138. }
  2139. // -------------------------------------------------------------------
  2140. uintptr_t getUiBridgeProcessId() const noexcept override
  2141. {
  2142. return fBridgeThread.getProcessPID();
  2143. }
  2144. const void* getExtraStuff() const noexcept override
  2145. {
  2146. return fBridgeBinary.isNotEmpty() ? fBridgeBinary.buffer() : nullptr;
  2147. }
  2148. // -------------------------------------------------------------------
  2149. bool init(CarlaPluginPtr plugin,
  2150. const char* const filename,
  2151. const char* const name,
  2152. const char* const label,
  2153. const int64_t uniqueId,
  2154. const uint options,
  2155. const char* const binaryArchName,
  2156. const char* const bridgeBinary)
  2157. {
  2158. CARLA_SAFE_ASSERT_RETURN(pData->engine != nullptr, false);
  2159. // ---------------------------------------------------------------
  2160. // first checks
  2161. if (pData->client != nullptr)
  2162. {
  2163. pData->engine->setLastError("Plugin client is already registered");
  2164. return false;
  2165. }
  2166. if (bridgeBinary == nullptr || bridgeBinary[0] == '\0')
  2167. {
  2168. pData->engine->setLastError("null bridge binary");
  2169. return false;
  2170. }
  2171. // ---------------------------------------------------------------
  2172. // set info
  2173. if (name != nullptr && name[0] != '\0')
  2174. pData->name = pData->engine->getUniquePluginName(name);
  2175. if (filename != nullptr && filename[0] != '\0')
  2176. pData->filename = carla_strdup(filename);
  2177. else
  2178. pData->filename = carla_strdup("");
  2179. fUniqueId = uniqueId;
  2180. fBridgeBinary = bridgeBinary;
  2181. std::srand(static_cast<uint>(std::time(nullptr)));
  2182. // ---------------------------------------------------------------
  2183. // init sem/shm
  2184. if (! fShmAudioPool.initializeServer())
  2185. {
  2186. carla_stderr("Failed to initialize shared memory audio pool");
  2187. return false;
  2188. }
  2189. if (! fShmRtClientControl.initializeServer())
  2190. {
  2191. carla_stderr("Failed to initialize RT client control");
  2192. fShmAudioPool.clear();
  2193. return false;
  2194. }
  2195. if (! fShmNonRtClientControl.initializeServer())
  2196. {
  2197. carla_stderr("Failed to initialize Non-RT client control");
  2198. fShmRtClientControl.clear();
  2199. fShmAudioPool.clear();
  2200. return false;
  2201. }
  2202. if (! fShmNonRtServerControl.initializeServer())
  2203. {
  2204. carla_stderr("Failed to initialize Non-RT server control");
  2205. fShmNonRtClientControl.clear();
  2206. fShmRtClientControl.clear();
  2207. fShmAudioPool.clear();
  2208. return false;
  2209. }
  2210. #ifndef CARLA_OS_WIN
  2211. // ---------------------------------------------------------------
  2212. // set wine prefix
  2213. if (fBridgeBinary.contains(".exe", true))
  2214. {
  2215. const EngineOptions& engineOptions(pData->engine->getOptions());
  2216. if (engineOptions.wine.autoPrefix)
  2217. fWinePrefix = findWinePrefix(pData->filename);
  2218. if (fWinePrefix.isEmpty())
  2219. {
  2220. const char* const envWinePrefix(std::getenv("WINEPREFIX"));
  2221. if (envWinePrefix != nullptr && envWinePrefix[0] != '\0')
  2222. fWinePrefix = envWinePrefix;
  2223. else if (engineOptions.wine.fallbackPrefix != nullptr && engineOptions.wine.fallbackPrefix[0] != '\0')
  2224. fWinePrefix = engineOptions.wine.fallbackPrefix;
  2225. else
  2226. fWinePrefix = File::getSpecialLocation(File::userHomeDirectory).getFullPathName() + "/.wine";
  2227. }
  2228. }
  2229. #endif
  2230. // ---------------------------------------------------------------
  2231. // init bridge thread
  2232. {
  2233. char shmIdsStr[6*4+1];
  2234. carla_zeroChars(shmIdsStr, 6*4+1);
  2235. std::strncpy(shmIdsStr+6*0, &fShmAudioPool.filename[fShmAudioPool.filename.length()-6], 6);
  2236. std::strncpy(shmIdsStr+6*1, &fShmRtClientControl.filename[fShmRtClientControl.filename.length()-6], 6);
  2237. std::strncpy(shmIdsStr+6*2, &fShmNonRtClientControl.filename[fShmNonRtClientControl.filename.length()-6], 6);
  2238. std::strncpy(shmIdsStr+6*3, &fShmNonRtServerControl.filename[fShmNonRtServerControl.filename.length()-6], 6);
  2239. fBridgeThread.setData(
  2240. #ifndef CARLA_OS_WIN
  2241. fWinePrefix.toRawUTF8(),
  2242. #endif
  2243. binaryArchName, bridgeBinary, label, shmIdsStr);
  2244. }
  2245. if (! restartBridgeThread())
  2246. return false;
  2247. // ---------------------------------------------------------------
  2248. // register client
  2249. if (pData->name == nullptr)
  2250. {
  2251. if (label != nullptr && label[0] != '\0')
  2252. pData->name = pData->engine->getUniquePluginName(label);
  2253. else
  2254. pData->name = pData->engine->getUniquePluginName("unknown");
  2255. }
  2256. pData->client = pData->engine->addClient(plugin);
  2257. if (pData->client == nullptr || ! pData->client->isOk())
  2258. {
  2259. pData->engine->setLastError("Failed to register plugin client");
  2260. return false;
  2261. }
  2262. // ---------------------------------------------------------------
  2263. // set options
  2264. pData->options = 0x0;
  2265. if ((fInfo.optionsAvailable & PLUGIN_OPTION_FIXED_BUFFERS) == 0x0)
  2266. pData->options |= PLUGIN_OPTION_FIXED_BUFFERS;
  2267. else if (isPluginOptionEnabled(options, PLUGIN_OPTION_FIXED_BUFFERS))
  2268. pData->options |= PLUGIN_OPTION_FIXED_BUFFERS;
  2269. if (pData->engine->getOptions().forceStereo)
  2270. {
  2271. pData->options |= PLUGIN_OPTION_FORCE_STEREO;
  2272. }
  2273. else if (fInfo.optionsAvailable & PLUGIN_OPTION_FORCE_STEREO)
  2274. {
  2275. if (options & PLUGIN_OPTION_FORCE_STEREO)
  2276. pData->options |= PLUGIN_OPTION_FORCE_STEREO;
  2277. }
  2278. if (fInfo.optionsAvailable & PLUGIN_OPTION_USE_CHUNKS)
  2279. if (isPluginOptionEnabled(options, PLUGIN_OPTION_USE_CHUNKS))
  2280. pData->options |= PLUGIN_OPTION_USE_CHUNKS;
  2281. if (fInfo.optionsAvailable & PLUGIN_OPTION_SEND_CONTROL_CHANGES)
  2282. if (isPluginOptionEnabled(options, PLUGIN_OPTION_SEND_CONTROL_CHANGES))
  2283. pData->options |= PLUGIN_OPTION_SEND_CONTROL_CHANGES;
  2284. if (fInfo.optionsAvailable & PLUGIN_OPTION_SEND_CHANNEL_PRESSURE)
  2285. if (isPluginOptionEnabled(options, PLUGIN_OPTION_SEND_CHANNEL_PRESSURE))
  2286. pData->options |= PLUGIN_OPTION_SEND_CHANNEL_PRESSURE;
  2287. if (fInfo.optionsAvailable & PLUGIN_OPTION_SEND_NOTE_AFTERTOUCH)
  2288. if (isPluginOptionEnabled(options, PLUGIN_OPTION_SEND_NOTE_AFTERTOUCH))
  2289. pData->options |= PLUGIN_OPTION_SEND_NOTE_AFTERTOUCH;
  2290. if (fInfo.optionsAvailable & PLUGIN_OPTION_SEND_PITCHBEND)
  2291. if (isPluginOptionEnabled(options, PLUGIN_OPTION_SEND_PITCHBEND))
  2292. pData->options |= PLUGIN_OPTION_SEND_PITCHBEND;
  2293. if (fInfo.optionsAvailable & PLUGIN_OPTION_SEND_ALL_SOUND_OFF)
  2294. if (isPluginOptionEnabled(options, PLUGIN_OPTION_SEND_ALL_SOUND_OFF))
  2295. pData->options |= PLUGIN_OPTION_SEND_ALL_SOUND_OFF;
  2296. if (fInfo.optionsAvailable & PLUGIN_OPTION_SKIP_SENDING_NOTES)
  2297. if (isPluginOptionInverseEnabled(options, PLUGIN_OPTION_SKIP_SENDING_NOTES))
  2298. pData->options |= PLUGIN_OPTION_SKIP_SENDING_NOTES;
  2299. if (fInfo.optionsAvailable & PLUGIN_OPTION_SEND_PROGRAM_CHANGES)
  2300. {
  2301. if (isPluginOptionEnabled(options, PLUGIN_OPTION_SEND_PROGRAM_CHANGES))
  2302. pData->options |= PLUGIN_OPTION_SEND_PROGRAM_CHANGES;
  2303. }
  2304. else if (fInfo.optionsAvailable & PLUGIN_OPTION_MAP_PROGRAM_CHANGES)
  2305. {
  2306. if (isPluginOptionEnabled(options, PLUGIN_OPTION_MAP_PROGRAM_CHANGES))
  2307. pData->options |= PLUGIN_OPTION_MAP_PROGRAM_CHANGES;
  2308. }
  2309. // kPluginBridgeNonRtClientSetOptions was added in API 7
  2310. if (fBridgeVersion >= 7)
  2311. {
  2312. const CarlaMutexLocker _cml(fShmNonRtClientControl.mutex);
  2313. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientSetOptions);
  2314. fShmNonRtClientControl.writeUInt(pData->options);
  2315. fShmNonRtClientControl.commitWrite();
  2316. }
  2317. return true;
  2318. }
  2319. private:
  2320. const BinaryType fBinaryType;
  2321. const PluginType fPluginType;
  2322. uint fBridgeVersion;
  2323. bool fInitiated;
  2324. bool fInitError;
  2325. bool fSaved;
  2326. bool fTimedOut;
  2327. bool fTimedError;
  2328. uint fBufferSize;
  2329. uint fProcWaitTime;
  2330. uint64_t fPendingEmbedCustomUI;
  2331. CarlaString fBridgeBinary;
  2332. CarlaPluginBridgeThread fBridgeThread;
  2333. BridgeAudioPool fShmAudioPool;
  2334. BridgeRtClientControl fShmRtClientControl;
  2335. BridgeNonRtClientControl fShmNonRtClientControl;
  2336. BridgeNonRtServerControl fShmNonRtServerControl;
  2337. #ifndef CARLA_OS_WIN
  2338. String fWinePrefix;
  2339. #endif
  2340. class ReceivingParamText {
  2341. public:
  2342. ReceivingParamText() noexcept
  2343. : dataRecv(false),
  2344. dataOk(false),
  2345. index(-1),
  2346. strBuf(nullptr),
  2347. mutex() {}
  2348. bool isCurrentlyWaitingData() const noexcept
  2349. {
  2350. return index >= 0;
  2351. }
  2352. bool wasDataReceived(bool* const success) const noexcept
  2353. {
  2354. *success = dataOk;
  2355. return dataRecv;
  2356. }
  2357. void setTargetData(const int32_t i, char* const b) noexcept
  2358. {
  2359. const CarlaMutexLocker cml(mutex);
  2360. dataOk = false;
  2361. dataRecv = false;
  2362. index = i;
  2363. strBuf = b;
  2364. }
  2365. void setReceivedData(const int32_t i, const char* const b, const uint blen) noexcept
  2366. {
  2367. CarlaScopedValueSetter<bool> svs(dataRecv, false, true);
  2368. const CarlaMutexLocker cml(mutex);
  2369. // make backup and reset data
  2370. const int32_t indexCopy = index;
  2371. char* const strBufCopy = strBuf;
  2372. index = -1;
  2373. strBuf = nullptr;
  2374. CARLA_SAFE_ASSERT_RETURN(indexCopy == i,);
  2375. CARLA_SAFE_ASSERT_RETURN(strBufCopy != nullptr,);
  2376. std::strncpy(strBufCopy, b, std::min(blen, STR_MAX-1U));
  2377. dataOk = true;
  2378. }
  2379. private:
  2380. bool dataRecv;
  2381. bool dataOk;
  2382. int32_t index;
  2383. char* strBuf;
  2384. CarlaMutex mutex;
  2385. CARLA_DECLARE_NON_COPYABLE(ReceivingParamText)
  2386. } fReceivingParamText;
  2387. struct Info {
  2388. uint32_t aIns, aOuts;
  2389. uint32_t cvIns, cvOuts;
  2390. uint32_t mIns, mOuts;
  2391. PluginCategory category;
  2392. uint optionsAvailable;
  2393. CarlaString name;
  2394. CarlaString label;
  2395. CarlaString maker;
  2396. CarlaString copyright;
  2397. const char** aInNames;
  2398. const char** aOutNames;
  2399. const char** cvInNames;
  2400. const char** cvOutNames;
  2401. std::vector<uint8_t> chunk;
  2402. Info()
  2403. : aIns(0),
  2404. aOuts(0),
  2405. cvIns(0),
  2406. cvOuts(0),
  2407. mIns(0),
  2408. mOuts(0),
  2409. category(PLUGIN_CATEGORY_NONE),
  2410. optionsAvailable(0),
  2411. name(),
  2412. label(),
  2413. maker(),
  2414. copyright(),
  2415. aInNames(nullptr),
  2416. aOutNames(nullptr),
  2417. cvInNames(nullptr),
  2418. cvOutNames(nullptr),
  2419. chunk() {}
  2420. ~Info()
  2421. {
  2422. clear();
  2423. }
  2424. void clear()
  2425. {
  2426. if (aInNames != nullptr)
  2427. {
  2428. CARLA_SAFE_ASSERT_INT(aIns > 0, aIns);
  2429. for (uint32_t i=0; i<aIns; ++i)
  2430. delete[] aInNames[i];
  2431. delete[] aInNames;
  2432. aInNames = nullptr;
  2433. }
  2434. if (aOutNames != nullptr)
  2435. {
  2436. CARLA_SAFE_ASSERT_INT(aOuts > 0, aOuts);
  2437. for (uint32_t i=0; i<aOuts; ++i)
  2438. delete[] aOutNames[i];
  2439. delete[] aOutNames;
  2440. aOutNames = nullptr;
  2441. }
  2442. if (cvInNames != nullptr)
  2443. {
  2444. CARLA_SAFE_ASSERT_INT(cvIns > 0, cvIns);
  2445. for (uint32_t i=0; i<cvIns; ++i)
  2446. delete[] cvInNames[i];
  2447. delete[] cvInNames;
  2448. cvInNames = nullptr;
  2449. }
  2450. if (cvOutNames != nullptr)
  2451. {
  2452. CARLA_SAFE_ASSERT_INT(cvOuts > 0, cvOuts);
  2453. for (uint32_t i=0; i<cvOuts; ++i)
  2454. delete[] cvOutNames[i];
  2455. delete[] cvOutNames;
  2456. cvOutNames = nullptr;
  2457. }
  2458. aIns = aOuts = cvIns = cvOuts = 0;
  2459. }
  2460. CARLA_DECLARE_NON_COPYABLE(Info)
  2461. } fInfo;
  2462. int64_t fUniqueId;
  2463. uint32_t fLatency;
  2464. BridgeParamInfo* fParams;
  2465. void handleProcessStopped() noexcept
  2466. {
  2467. const bool wasActive = pData->active;
  2468. pData->active = false;
  2469. if (wasActive)
  2470. {
  2471. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  2472. pData->engine->callback(true, true,
  2473. ENGINE_CALLBACK_PARAMETER_VALUE_CHANGED,
  2474. pData->id,
  2475. PARAMETER_ACTIVE,
  2476. 0, 0,
  2477. 0.0f,
  2478. nullptr);
  2479. #endif
  2480. }
  2481. if (pData->hints & PLUGIN_HAS_CUSTOM_UI)
  2482. {
  2483. pData->engine->callback(true, true,
  2484. ENGINE_CALLBACK_UI_STATE_CHANGED,
  2485. pData->id,
  2486. 0,
  2487. 0, 0, 0.0f, nullptr);
  2488. }
  2489. }
  2490. void resizeAudioPool(const uint32_t bufferSize)
  2491. {
  2492. fShmAudioPool.resize(bufferSize, fInfo.aIns+fInfo.aOuts, fInfo.cvIns+fInfo.cvOuts);
  2493. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientSetAudioPool);
  2494. fShmRtClientControl.writeULong(static_cast<uint64_t>(fShmAudioPool.dataSize));
  2495. fShmRtClientControl.commitWrite();
  2496. waitForClient("resize-pool", 5000);
  2497. }
  2498. void waitForClient(const char* const action, const uint msecs)
  2499. {
  2500. CARLA_SAFE_ASSERT_RETURN(! fTimedOut,);
  2501. CARLA_SAFE_ASSERT_RETURN(! fTimedError,);
  2502. if (fShmRtClientControl.waitForClient(msecs))
  2503. return;
  2504. fTimedOut = true;
  2505. carla_stderr2("waitForClient(%s) timed out", action);
  2506. }
  2507. bool restartBridgeThread()
  2508. {
  2509. fInitiated = false;
  2510. fInitError = false;
  2511. fTimedError = false;
  2512. // reset memory
  2513. fShmRtClientControl.data->procFlags = 0;
  2514. carla_zeroStruct(fShmRtClientControl.data->timeInfo);
  2515. carla_zeroBytes(fShmRtClientControl.data->midiOut, kBridgeRtClientDataMidiOutSize);
  2516. fShmRtClientControl.clearData();
  2517. fShmNonRtClientControl.clearData();
  2518. fShmNonRtServerControl.clearData();
  2519. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientVersion);
  2520. fShmNonRtClientControl.writeUInt(CARLA_PLUGIN_BRIDGE_API_VERSION_CURRENT);
  2521. fShmNonRtClientControl.writeUInt(static_cast<uint32_t>(sizeof(BridgeRtClientData)));
  2522. fShmNonRtClientControl.writeUInt(static_cast<uint32_t>(sizeof(BridgeNonRtClientData)));
  2523. fShmNonRtClientControl.writeUInt(static_cast<uint32_t>(sizeof(BridgeNonRtServerData)));
  2524. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientInitialSetup);
  2525. fShmNonRtClientControl.writeUInt(pData->engine->getBufferSize());
  2526. fShmNonRtClientControl.writeDouble(pData->engine->getSampleRate());
  2527. fShmNonRtClientControl.commitWrite();
  2528. if (fShmAudioPool.dataSize != 0)
  2529. {
  2530. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientSetAudioPool);
  2531. fShmRtClientControl.writeULong(static_cast<uint64_t>(fShmAudioPool.dataSize));
  2532. fShmRtClientControl.commitWrite();
  2533. }
  2534. else
  2535. {
  2536. // testing dummy message
  2537. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientNull);
  2538. fShmRtClientControl.commitWrite();
  2539. }
  2540. fBridgeThread.startThread();
  2541. const bool needsEngineIdle = pData->engine->getType() != kEngineTypePlugin;
  2542. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  2543. const bool needsCancelableAction = ! pData->engine->isLoadingProject();
  2544. if (needsCancelableAction)
  2545. {
  2546. pData->engine->setActionCanceled(false);
  2547. pData->engine->callback(true, true,
  2548. ENGINE_CALLBACK_CANCELABLE_ACTION,
  2549. pData->id,
  2550. 1,
  2551. 0, 0, 0.0f,
  2552. "Loading plugin bridge");
  2553. }
  2554. #endif
  2555. for (;fBridgeThread.isThreadRunning();)
  2556. {
  2557. pData->engine->callback(true, true, ENGINE_CALLBACK_IDLE, 0, 0, 0, 0, 0.0f, nullptr);
  2558. if (needsEngineIdle)
  2559. pData->engine->idle();
  2560. idle();
  2561. if (fInitiated)
  2562. break;
  2563. if (pData->engine->isAboutToClose() || pData->engine->wasActionCanceled())
  2564. break;
  2565. carla_msleep(5);
  2566. }
  2567. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  2568. if (needsCancelableAction)
  2569. {
  2570. pData->engine->callback(true, true,
  2571. ENGINE_CALLBACK_CANCELABLE_ACTION,
  2572. pData->id,
  2573. 0,
  2574. 0, 0, 0.0f,
  2575. "Loading JACK application");
  2576. }
  2577. #endif
  2578. if (fInitError || ! fInitiated)
  2579. {
  2580. fBridgeThread.stopThread(6000);
  2581. if (! fInitError)
  2582. pData->engine->setLastError("Timeout while waiting for a response from plugin-bridge\n"
  2583. "(or the plugin crashed on initialization?)");
  2584. return false;
  2585. }
  2586. if (const size_t dataSize = fInfo.chunk.size())
  2587. {
  2588. #ifdef CARLA_PROPER_CPP11_SUPPORT
  2589. void* data = fInfo.chunk.data();
  2590. #else
  2591. void* data = &fInfo.chunk.front();
  2592. #endif
  2593. CarlaString dataBase64(CarlaString::asBase64(data, dataSize));
  2594. CARLA_SAFE_ASSERT_RETURN(dataBase64.length() > 0, true);
  2595. String filePath(File::getSpecialLocation(File::tempDirectory).getFullPathName());
  2596. filePath += CARLA_OS_SEP_STR ".CarlaChunk_";
  2597. filePath += fShmAudioPool.getFilenameSuffix();
  2598. if (File(filePath).replaceWithText(dataBase64.buffer()))
  2599. {
  2600. const uint32_t ulength(static_cast<uint32_t>(filePath.length()));
  2601. const CarlaMutexLocker _cml(fShmNonRtClientControl.mutex);
  2602. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientSetChunkDataFile);
  2603. fShmNonRtClientControl.writeUInt(ulength);
  2604. fShmNonRtClientControl.writeCustomData(filePath.toRawUTF8(), ulength);
  2605. fShmNonRtClientControl.commitWrite();
  2606. }
  2607. }
  2608. return true;
  2609. }
  2610. void _setUiTitleFromName()
  2611. {
  2612. CarlaString uiName(pData->name);
  2613. uiName += " (GUI)";
  2614. const uint32_t size = static_cast<uint32_t>(uiName.length());
  2615. const CarlaMutexLocker _cml(fShmNonRtClientControl.mutex);
  2616. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientSetWindowTitle);
  2617. fShmNonRtClientControl.writeUInt(size);
  2618. fShmNonRtClientControl.writeCustomData(uiName.buffer(), size);
  2619. fShmNonRtClientControl.commitWrite();
  2620. }
  2621. CARLA_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(CarlaPluginBridge)
  2622. };
  2623. CARLA_BACKEND_END_NAMESPACE
  2624. // ---------------------------------------------------------------------------------------------------------------------
  2625. CARLA_BACKEND_START_NAMESPACE
  2626. CarlaPluginPtr CarlaPlugin::newBridge(const Initializer& init,
  2627. const BinaryType btype,
  2628. const PluginType ptype,
  2629. const char* const binaryArchName,
  2630. const char* bridgeBinary)
  2631. {
  2632. carla_debug("CarlaPlugin::newBridge({%p, \"%s\", \"%s\", \"%s\"}, %s, %s, \"%s\", \"%s\")",
  2633. init.engine, init.filename, init.name, init.label,
  2634. BinaryType2Str(btype), PluginType2Str(ptype), binaryArchName, bridgeBinary);
  2635. if (bridgeBinary == nullptr || bridgeBinary[0] == '\0')
  2636. {
  2637. init.engine->setLastError("Bridge not possible, bridge-binary not found");
  2638. return nullptr;
  2639. }
  2640. #ifndef CARLA_OS_WIN
  2641. // FIXME: somewhere, somehow, we end up with double slashes, wine doesn't like that.
  2642. if (std::strncmp(bridgeBinary, "//", 2) == 0)
  2643. ++bridgeBinary;
  2644. #endif
  2645. std::shared_ptr<CarlaPluginBridge> plugin(new CarlaPluginBridge(init.engine, init.id, btype, ptype));
  2646. if (! plugin->init(plugin, init.filename, init.name, init.label, init.uniqueId, init.options, binaryArchName, bridgeBinary))
  2647. return nullptr;
  2648. return plugin;
  2649. }
  2650. CARLA_BACKEND_END_NAMESPACE
  2651. // ---------------------------------------------------------------------------------------------------------------------
  2652. #ifndef BUILD_BRIDGE
  2653. # include "CarlaBridgeUtils.cpp"
  2654. #endif
  2655. // ---------------------------------------------------------------------------------------------------------------------