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.

3336 lines
120KB

  1. /*
  2. * Carla Plugin Bridge
  3. * Copyright (C) 2011-2022 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 typeLen = static_cast<uint32_t>(std::strlen(type));
  733. const uint32_t keyLen = static_cast<uint32_t>(std::strlen(key));
  734. const uint32_t valueLen = static_cast<uint32_t>(std::strlen(value));
  735. /*
  736. if (valueLen > 16384)
  737. fShmNonRtClientControl.waitIfDataIsReachingLimit();
  738. */
  739. {
  740. const CarlaMutexLocker _cml(fShmNonRtClientControl.mutex);
  741. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientSetCustomData);
  742. fShmNonRtClientControl.writeUInt(typeLen);
  743. fShmNonRtClientControl.writeCustomData(type, typeLen);
  744. fShmNonRtClientControl.writeUInt(keyLen);
  745. fShmNonRtClientControl.writeCustomData(key, keyLen);
  746. fShmNonRtClientControl.writeUInt(valueLen);
  747. if (valueLen > 0)
  748. {
  749. if (valueLen > 16384)
  750. {
  751. String filePath(File::getSpecialLocation(File::tempDirectory).getFullPathName());
  752. filePath += CARLA_OS_SEP_STR ".CarlaCustomData_";
  753. filePath += fShmAudioPool.getFilenameSuffix();
  754. if (File(filePath).replaceWithText(value))
  755. {
  756. const uint32_t ulength = static_cast<uint32_t>(filePath.length());
  757. fShmNonRtClientControl.writeUInt(ulength);
  758. fShmNonRtClientControl.writeCustomData(filePath.toRawUTF8(), ulength);
  759. }
  760. else
  761. {
  762. fShmNonRtClientControl.writeUInt(0);
  763. }
  764. }
  765. else
  766. {
  767. fShmNonRtClientControl.writeCustomData(value, valueLen);
  768. }
  769. }
  770. fShmNonRtClientControl.commitWrite();
  771. }
  772. CarlaPlugin::setCustomData(type, key, value, sendGui);
  773. }
  774. void setChunkData(const void* const data, const std::size_t dataSize) override
  775. {
  776. CARLA_SAFE_ASSERT_RETURN(pData->options & PLUGIN_OPTION_USE_CHUNKS,);
  777. CARLA_SAFE_ASSERT_RETURN(data != nullptr,);
  778. CARLA_SAFE_ASSERT_RETURN(dataSize > 0,);
  779. CarlaString dataBase64(CarlaString::asBase64(data, dataSize));
  780. CARLA_SAFE_ASSERT_RETURN(dataBase64.length() > 0,);
  781. String filePath(File::getSpecialLocation(File::tempDirectory).getFullPathName());
  782. filePath += CARLA_OS_SEP_STR ".CarlaChunk_";
  783. filePath += fShmAudioPool.getFilenameSuffix();
  784. if (File(filePath).replaceWithText(dataBase64.buffer()))
  785. {
  786. const uint32_t ulength = static_cast<uint32_t>(filePath.length());
  787. const CarlaMutexLocker _cml(fShmNonRtClientControl.mutex);
  788. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientSetChunkDataFile);
  789. fShmNonRtClientControl.writeUInt(ulength);
  790. fShmNonRtClientControl.writeCustomData(filePath.toRawUTF8(), ulength);
  791. fShmNonRtClientControl.commitWrite();
  792. }
  793. // save data internally as well
  794. fInfo.chunk.resize(dataSize);
  795. #ifdef CARLA_PROPER_CPP11_SUPPORT
  796. std::memcpy(fInfo.chunk.data(), data, dataSize);
  797. #else
  798. std::memcpy(&fInfo.chunk.front(), data, dataSize);
  799. #endif
  800. }
  801. // -------------------------------------------------------------------
  802. // Set ui stuff
  803. void setCustomUITitle(const char* const title) noexcept override
  804. {
  805. carla_debug("CarlaPluginBridge::setCustomUITitle(%s)", title);
  806. if (fBridgeVersion >= 8)
  807. {
  808. const uint32_t size = static_cast<uint32_t>(std::strlen(title));
  809. const CarlaMutexLocker _cml(fShmNonRtClientControl.mutex);
  810. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientSetWindowTitle);
  811. fShmNonRtClientControl.writeUInt(size);
  812. fShmNonRtClientControl.writeCustomData(title, size);
  813. fShmNonRtClientControl.commitWrite();
  814. }
  815. CarlaPlugin::setCustomUITitle(title);
  816. }
  817. void showCustomUI(const bool yesNo) override
  818. {
  819. if (yesNo && pData->uiTitle.isEmpty() && fBridgeVersion >= 8)
  820. _setUiTitleFromName();
  821. {
  822. const CarlaMutexLocker _cml(fShmNonRtClientControl.mutex);
  823. fShmNonRtClientControl.writeOpcode(yesNo ? kPluginBridgeNonRtClientShowUI : kPluginBridgeNonRtClientHideUI);
  824. fShmNonRtClientControl.commitWrite();
  825. }
  826. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  827. if (yesNo)
  828. {
  829. pData->tryTransient();
  830. }
  831. else
  832. {
  833. pData->transientTryCounter = 0;
  834. }
  835. #endif
  836. }
  837. void* embedCustomUI(void* const ptr) override
  838. {
  839. if (fBridgeVersion < 9)
  840. return nullptr;
  841. fPendingEmbedCustomUI = 0;
  842. {
  843. const CarlaMutexLocker _cml(fShmNonRtClientControl.mutex);
  844. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientEmbedUI);
  845. fShmNonRtClientControl.writeULong(reinterpret_cast<uint64_t>(ptr));
  846. fShmNonRtClientControl.commitWrite();
  847. }
  848. const uint32_t timeoutEnd = Time::getMillisecondCounter() + 15*1000; // 15 secs
  849. const bool needsEngineIdle = pData->engine->getType() != kEngineTypePlugin;
  850. for (; Time::getMillisecondCounter() < timeoutEnd && fBridgeThread.isThreadRunning();)
  851. {
  852. pData->engine->callback(true, true, ENGINE_CALLBACK_IDLE, 0, 0, 0, 0, 0.0f, nullptr);
  853. if (needsEngineIdle)
  854. pData->engine->idle();
  855. if (fPendingEmbedCustomUI != 0)
  856. {
  857. if (fPendingEmbedCustomUI == 1)
  858. fPendingEmbedCustomUI = 0;
  859. break;
  860. }
  861. carla_msleep(20);
  862. }
  863. return reinterpret_cast<void*>(fPendingEmbedCustomUI);
  864. }
  865. void idle() override
  866. {
  867. if (fBridgeThread.isThreadRunning())
  868. {
  869. if (fInitiated && fTimedOut && pData->active)
  870. setActive(false, true, true);
  871. {
  872. const CarlaMutexLocker _cml(fShmNonRtClientControl.mutex);
  873. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientPing);
  874. fShmNonRtClientControl.commitWrite();
  875. }
  876. try {
  877. handleNonRtData();
  878. } CARLA_SAFE_EXCEPTION("handleNonRtData");
  879. }
  880. else if (fInitiated)
  881. {
  882. fTimedOut = true;
  883. fTimedError = true;
  884. fInitiated = false;
  885. handleProcessStopped();
  886. }
  887. CarlaPlugin::idle();
  888. }
  889. // -------------------------------------------------------------------
  890. // Plugin state
  891. void reload() override
  892. {
  893. CARLA_SAFE_ASSERT_RETURN(pData->engine != nullptr,);
  894. carla_debug("CarlaPluginBridge::reload() - start");
  895. const EngineProcessMode processMode(pData->engine->getProccessMode());
  896. // Safely disable plugin for reload
  897. const ScopedDisabler sd(this);
  898. // cleanup of previous data
  899. pData->audioIn.clear();
  900. pData->audioOut.clear();
  901. pData->cvIn.clear();
  902. pData->cvOut.clear();
  903. pData->event.clear();
  904. bool needsCtrlIn, needsCtrlOut;
  905. needsCtrlIn = needsCtrlOut = false;
  906. if (fInfo.aIns > 0)
  907. {
  908. pData->audioIn.createNew(fInfo.aIns);
  909. }
  910. if (fInfo.aOuts > 0)
  911. {
  912. pData->audioOut.createNew(fInfo.aOuts);
  913. needsCtrlIn = true;
  914. }
  915. if (fInfo.cvIns > 0)
  916. {
  917. pData->cvIn.createNew(fInfo.cvIns);
  918. }
  919. if (fInfo.cvOuts > 0)
  920. {
  921. pData->cvOut.createNew(fInfo.cvOuts);
  922. }
  923. if (fInfo.mIns > 0)
  924. needsCtrlIn = true;
  925. if (fInfo.mOuts > 0)
  926. needsCtrlOut = true;
  927. const uint portNameSize(pData->engine->getMaxPortNameSize());
  928. CarlaString portName;
  929. // Audio Ins
  930. for (uint32_t j=0; j < fInfo.aIns; ++j)
  931. {
  932. portName.clear();
  933. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  934. {
  935. portName = pData->name;
  936. portName += ":";
  937. }
  938. if (fInfo.aInNames != nullptr && fInfo.aInNames[j] != nullptr)
  939. {
  940. portName += fInfo.aInNames[j];
  941. }
  942. else if (fInfo.aIns > 1)
  943. {
  944. portName += "input_";
  945. portName += CarlaString(j+1);
  946. }
  947. else
  948. portName += "input";
  949. portName.truncate(portNameSize);
  950. pData->audioIn.ports[j].port = (CarlaEngineAudioPort*)pData->client->addPort(kEnginePortTypeAudio, portName, true, j);
  951. pData->audioIn.ports[j].rindex = j;
  952. }
  953. // Audio Outs
  954. for (uint32_t j=0; j < fInfo.aOuts; ++j)
  955. {
  956. portName.clear();
  957. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  958. {
  959. portName = pData->name;
  960. portName += ":";
  961. }
  962. if (fInfo.aOutNames != nullptr && fInfo.aOutNames[j] != nullptr)
  963. {
  964. portName += fInfo.aOutNames[j];
  965. }
  966. else if (fInfo.aOuts > 1)
  967. {
  968. portName += "output_";
  969. portName += CarlaString(j+1);
  970. }
  971. else
  972. portName += "output";
  973. portName.truncate(portNameSize);
  974. pData->audioOut.ports[j].port = (CarlaEngineAudioPort*)pData->client->addPort(kEnginePortTypeAudio, portName, false, j);
  975. pData->audioOut.ports[j].rindex = j;
  976. }
  977. // TODO - MIDI
  978. // CV Ins
  979. for (uint32_t j=0; j < fInfo.cvIns; ++j)
  980. {
  981. portName.clear();
  982. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  983. {
  984. portName = pData->name;
  985. portName += ":";
  986. }
  987. if (fInfo.cvInNames != nullptr && fInfo.cvInNames[j] != nullptr)
  988. {
  989. portName += fInfo.cvInNames[j];
  990. }
  991. else if (fInfo.cvIns > 1)
  992. {
  993. portName += "cv_input_";
  994. portName += CarlaString(j+1);
  995. }
  996. else
  997. portName += "cv_input";
  998. portName.truncate(portNameSize);
  999. pData->cvIn.ports[j].port = (CarlaEngineCVPort*)pData->client->addPort(kEnginePortTypeCV, portName, true, j);
  1000. pData->cvIn.ports[j].rindex = j;
  1001. }
  1002. // CV Outs
  1003. for (uint32_t j=0; j < fInfo.cvOuts; ++j)
  1004. {
  1005. portName.clear();
  1006. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  1007. {
  1008. portName = pData->name;
  1009. portName += ":";
  1010. }
  1011. if (fInfo.cvOutNames != nullptr && fInfo.cvOutNames[j] != nullptr)
  1012. {
  1013. portName += fInfo.cvOutNames[j];
  1014. }
  1015. else if (fInfo.cvOuts > 1)
  1016. {
  1017. portName += "cv_output_";
  1018. portName += CarlaString(j+1);
  1019. }
  1020. else
  1021. portName += "cv_output";
  1022. portName.truncate(portNameSize);
  1023. pData->cvOut.ports[j].port = (CarlaEngineCVPort*)pData->client->addPort(kEnginePortTypeCV, portName, false, j);
  1024. pData->cvOut.ports[j].rindex = j;
  1025. }
  1026. if (needsCtrlIn)
  1027. {
  1028. portName.clear();
  1029. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  1030. {
  1031. portName = pData->name;
  1032. portName += ":";
  1033. }
  1034. portName += "event-in";
  1035. portName.truncate(portNameSize);
  1036. pData->event.portIn = (CarlaEngineEventPort*)pData->client->addPort(kEnginePortTypeEvent, portName, true, 0);
  1037. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1038. pData->event.cvSourcePorts = pData->client->createCVSourcePorts();
  1039. #endif
  1040. }
  1041. if (needsCtrlOut)
  1042. {
  1043. portName.clear();
  1044. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  1045. {
  1046. portName = pData->name;
  1047. portName += ":";
  1048. }
  1049. portName += "event-out";
  1050. portName.truncate(portNameSize);
  1051. pData->event.portOut = (CarlaEngineEventPort*)pData->client->addPort(kEnginePortTypeEvent, portName, false, 0);
  1052. }
  1053. // extra plugin hints
  1054. pData->extraHints = 0x0;
  1055. if (fInfo.mIns > 0)
  1056. pData->extraHints |= PLUGIN_EXTRA_HINT_HAS_MIDI_IN;
  1057. if (fInfo.mOuts > 0)
  1058. pData->extraHints |= PLUGIN_EXTRA_HINT_HAS_MIDI_OUT;
  1059. bufferSizeChanged(pData->engine->getBufferSize());
  1060. reloadPrograms(true);
  1061. carla_debug("CarlaPluginBridge::reload() - end");
  1062. }
  1063. // -------------------------------------------------------------------
  1064. // Plugin processing
  1065. void activate() noexcept override
  1066. {
  1067. if (! fBridgeThread.isThreadRunning())
  1068. {
  1069. CARLA_SAFE_ASSERT_RETURN(restartBridgeThread(),);
  1070. }
  1071. {
  1072. const CarlaMutexLocker _cml(fShmNonRtClientControl.mutex);
  1073. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientActivate);
  1074. fShmNonRtClientControl.commitWrite();
  1075. }
  1076. fTimedOut = false;
  1077. try {
  1078. waitForClient("activate", 2000);
  1079. } CARLA_SAFE_EXCEPTION("activate - waitForClient");
  1080. }
  1081. void deactivate() noexcept override
  1082. {
  1083. CARLA_SAFE_ASSERT_RETURN(! fTimedError,);
  1084. {
  1085. const CarlaMutexLocker _cml(fShmNonRtClientControl.mutex);
  1086. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientDeactivate);
  1087. fShmNonRtClientControl.commitWrite();
  1088. }
  1089. fTimedOut = false;
  1090. try {
  1091. waitForClient("deactivate", 2000);
  1092. } CARLA_SAFE_EXCEPTION("deactivate - waitForClient");
  1093. }
  1094. void process(const float* const* const audioIn,
  1095. float** const audioOut,
  1096. const float* const* const cvIn,
  1097. float** const cvOut,
  1098. const uint32_t frames) override
  1099. {
  1100. // --------------------------------------------------------------------------------------------------------
  1101. // Check if active
  1102. if (fTimedOut || fTimedError || ! pData->active)
  1103. {
  1104. // disable any output sound
  1105. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  1106. carla_zeroFloats(audioOut[i], frames);
  1107. for (uint32_t i=0; i < pData->cvOut.count; ++i)
  1108. carla_zeroFloats(cvOut[i], frames);
  1109. return;
  1110. }
  1111. // --------------------------------------------------------------------------------------------------------
  1112. // Check if needs reset
  1113. if (pData->needsReset)
  1114. {
  1115. // TODO
  1116. pData->needsReset = false;
  1117. }
  1118. // --------------------------------------------------------------------------------------------------------
  1119. // Event Input
  1120. if (pData->event.portIn != nullptr)
  1121. {
  1122. // ----------------------------------------------------------------------------------------------------
  1123. // MIDI Input (External)
  1124. if (pData->extNotes.mutex.tryLock())
  1125. {
  1126. for (RtLinkedList<ExternalMidiNote>::Itenerator it = pData->extNotes.data.begin2(); it.valid(); it.next())
  1127. {
  1128. const ExternalMidiNote& note(it.getValue(kExternalMidiNoteFallback));
  1129. CARLA_SAFE_ASSERT_CONTINUE(note.channel >= 0 && note.channel < MAX_MIDI_CHANNELS);
  1130. uint8_t data1, data2, data3;
  1131. data1 = uint8_t((note.velo > 0 ? MIDI_STATUS_NOTE_ON : MIDI_STATUS_NOTE_OFF) | (note.channel & MIDI_CHANNEL_BIT));
  1132. data2 = note.note;
  1133. data3 = note.velo;
  1134. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientMidiEvent);
  1135. fShmRtClientControl.writeUInt(0); // time
  1136. fShmRtClientControl.writeByte(0); // port
  1137. fShmRtClientControl.writeByte(3); // size
  1138. fShmRtClientControl.writeByte(data1);
  1139. fShmRtClientControl.writeByte(data2);
  1140. fShmRtClientControl.writeByte(data3);
  1141. fShmRtClientControl.commitWrite();
  1142. }
  1143. pData->extNotes.data.clear();
  1144. pData->extNotes.mutex.unlock();
  1145. } // End of MIDI Input (External)
  1146. // ----------------------------------------------------------------------------------------------------
  1147. // Event Input (System)
  1148. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1149. bool allNotesOffSent = false;
  1150. if (cvIn != nullptr && pData->event.cvSourcePorts != nullptr)
  1151. {
  1152. const bool isSampleAccurate = (pData->options & PLUGIN_OPTION_FIXED_BUFFERS) == 0x0;
  1153. pData->event.cvSourcePorts->initPortBuffers(cvIn + pData->cvIn.count, frames, isSampleAccurate, pData->event.portIn);
  1154. }
  1155. #endif
  1156. for (uint32_t i=0, numEvents=pData->event.portIn->getEventCount(); i < numEvents; ++i)
  1157. {
  1158. EngineEvent& event(pData->event.portIn->getEvent(i));
  1159. // Control change
  1160. switch (event.type)
  1161. {
  1162. case kEngineEventTypeNull:
  1163. break;
  1164. case kEngineEventTypeControl: {
  1165. EngineControlEvent& ctrlEvent = event.ctrl;
  1166. switch (ctrlEvent.type)
  1167. {
  1168. case kEngineControlEventTypeNull:
  1169. break;
  1170. case kEngineControlEventTypeParameter: {
  1171. float value;
  1172. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1173. // non-midi
  1174. if (event.channel == kEngineEventNonMidiChannel)
  1175. {
  1176. const uint32_t k = ctrlEvent.param;
  1177. CARLA_SAFE_ASSERT_CONTINUE(k < pData->param.count);
  1178. ctrlEvent.handled = true;
  1179. value = pData->param.getFinalUnnormalizedValue(k, ctrlEvent.normalizedValue);
  1180. setParameterValueRT(k, value, event.time, true);
  1181. continue;
  1182. }
  1183. // Control backend stuff
  1184. if (event.channel == pData->ctrlChannel)
  1185. {
  1186. if (MIDI_IS_CONTROL_BREATH_CONTROLLER(ctrlEvent.param) && (pData->hints & PLUGIN_CAN_DRYWET) != 0)
  1187. {
  1188. ctrlEvent.handled = true;
  1189. value = ctrlEvent.normalizedValue;
  1190. setDryWetRT(value, true);
  1191. }
  1192. else if (MIDI_IS_CONTROL_CHANNEL_VOLUME(ctrlEvent.param) && (pData->hints & PLUGIN_CAN_VOLUME) != 0)
  1193. {
  1194. ctrlEvent.handled = true;
  1195. value = ctrlEvent.normalizedValue*127.0f/100.0f;
  1196. setVolumeRT(value, true);
  1197. }
  1198. else if (MIDI_IS_CONTROL_BALANCE(ctrlEvent.param) && (pData->hints & PLUGIN_CAN_BALANCE) != 0)
  1199. {
  1200. float left, right;
  1201. value = ctrlEvent.normalizedValue/0.5f - 1.0f;
  1202. if (value < 0.0f)
  1203. {
  1204. left = -1.0f;
  1205. right = (value*2.0f)+1.0f;
  1206. }
  1207. else if (value > 0.0f)
  1208. {
  1209. left = (value*2.0f)-1.0f;
  1210. right = 1.0f;
  1211. }
  1212. else
  1213. {
  1214. left = -1.0f;
  1215. right = 1.0f;
  1216. }
  1217. ctrlEvent.handled = true;
  1218. setBalanceLeftRT(left, true);
  1219. setBalanceRightRT(right, true);
  1220. }
  1221. }
  1222. #endif
  1223. // Control plugin parameters
  1224. for (uint32_t k=0; k < pData->param.count; ++k)
  1225. {
  1226. if (pData->param.data[k].midiChannel != event.channel)
  1227. continue;
  1228. if (pData->param.data[k].mappedControlIndex != ctrlEvent.param)
  1229. continue;
  1230. if (pData->param.data[k].type != PARAMETER_INPUT)
  1231. continue;
  1232. if ((pData->param.data[k].hints & PARAMETER_IS_AUTOMATABLE) == 0)
  1233. continue;
  1234. ctrlEvent.handled = true;
  1235. value = pData->param.getFinalUnnormalizedValue(k, ctrlEvent.normalizedValue);
  1236. setParameterValueRT(k, value, event.time, true);
  1237. }
  1238. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1239. if (! ctrlEvent.handled)
  1240. checkForMidiLearn(event);
  1241. #endif
  1242. if ((pData->options & PLUGIN_OPTION_SEND_CONTROL_CHANGES) != 0 && ctrlEvent.param < MAX_MIDI_VALUE)
  1243. {
  1244. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientMidiEvent);
  1245. fShmRtClientControl.writeUInt(event.time);
  1246. fShmRtClientControl.writeByte(0); // port
  1247. fShmRtClientControl.writeByte(3); // size
  1248. fShmRtClientControl.writeByte(uint8_t(MIDI_STATUS_CONTROL_CHANGE | (event.channel & MIDI_CHANNEL_BIT)));
  1249. fShmRtClientControl.writeByte(uint8_t(ctrlEvent.param));
  1250. fShmRtClientControl.writeByte(uint8_t(ctrlEvent.normalizedValue*127.0f + 0.5f));
  1251. }
  1252. break;
  1253. }
  1254. case kEngineControlEventTypeMidiBank:
  1255. if (pData->options & PLUGIN_OPTION_MAP_PROGRAM_CHANGES)
  1256. {
  1257. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientControlEventMidiBank);
  1258. fShmRtClientControl.writeUInt(event.time);
  1259. fShmRtClientControl.writeByte(event.channel);
  1260. fShmRtClientControl.writeUShort(event.ctrl.param);
  1261. fShmRtClientControl.commitWrite();
  1262. }
  1263. else if ((pData->options & PLUGIN_OPTION_SEND_PROGRAM_CHANGES) != 0)
  1264. {
  1265. // 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
  1266. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientMidiEvent);
  1267. fShmRtClientControl.writeUInt(event.time);
  1268. fShmRtClientControl.writeByte(0); // port
  1269. fShmRtClientControl.writeByte(3); // size
  1270. fShmRtClientControl.writeByte(uint8_t(MIDI_STATUS_CONTROL_CHANGE | (event.channel & MIDI_CHANNEL_BIT)));
  1271. fShmRtClientControl.writeByte(MIDI_CONTROL_BANK_SELECT);
  1272. fShmRtClientControl.writeByte(0);
  1273. fShmRtClientControl.commitWrite();
  1274. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientMidiEvent);
  1275. fShmRtClientControl.writeUInt(event.time);
  1276. fShmRtClientControl.writeByte(0); // port
  1277. fShmRtClientControl.writeByte(3); // size
  1278. fShmRtClientControl.writeByte(uint8_t(MIDI_STATUS_CONTROL_CHANGE | (event.channel & MIDI_CHANNEL_BIT)));
  1279. fShmRtClientControl.writeByte(MIDI_CONTROL_BANK_SELECT__LSB);
  1280. fShmRtClientControl.writeByte(uint8_t(event.ctrl.param));
  1281. fShmRtClientControl.commitWrite();
  1282. }
  1283. break;
  1284. case kEngineControlEventTypeMidiProgram:
  1285. if (pData->options & PLUGIN_OPTION_MAP_PROGRAM_CHANGES || pData->options & PLUGIN_OPTION_SEND_PROGRAM_CHANGES)
  1286. {
  1287. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientControlEventMidiProgram);
  1288. fShmRtClientControl.writeUInt(event.time);
  1289. fShmRtClientControl.writeByte(event.channel);
  1290. fShmRtClientControl.writeUShort(event.ctrl.param);
  1291. fShmRtClientControl.commitWrite();
  1292. }
  1293. break;
  1294. case kEngineControlEventTypeAllSoundOff:
  1295. if (pData->options & PLUGIN_OPTION_SEND_ALL_SOUND_OFF)
  1296. {
  1297. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientControlEventAllSoundOff);
  1298. fShmRtClientControl.writeUInt(event.time);
  1299. fShmRtClientControl.writeByte(event.channel);
  1300. fShmRtClientControl.commitWrite();
  1301. }
  1302. break;
  1303. case kEngineControlEventTypeAllNotesOff:
  1304. if (pData->options & PLUGIN_OPTION_SEND_ALL_SOUND_OFF)
  1305. {
  1306. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1307. if (event.channel == pData->ctrlChannel && ! allNotesOffSent)
  1308. {
  1309. allNotesOffSent = true;
  1310. postponeRtAllNotesOff();
  1311. }
  1312. #endif
  1313. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientControlEventAllNotesOff);
  1314. fShmRtClientControl.writeUInt(event.time);
  1315. fShmRtClientControl.writeByte(event.channel);
  1316. fShmRtClientControl.commitWrite();
  1317. }
  1318. break;
  1319. } // switch (ctrlEvent.type)
  1320. break;
  1321. } // case kEngineEventTypeControl
  1322. case kEngineEventTypeMidi: {
  1323. const EngineMidiEvent& midiEvent(event.midi);
  1324. if (midiEvent.size == 0 || midiEvent.size >= MAX_MIDI_VALUE)
  1325. continue;
  1326. const uint8_t* const midiData(midiEvent.size > EngineMidiEvent::kDataSize ? midiEvent.dataExt : midiEvent.data);
  1327. uint8_t status = uint8_t(MIDI_GET_STATUS_FROM_DATA(midiData));
  1328. if ((status == MIDI_STATUS_NOTE_OFF || status == MIDI_STATUS_NOTE_ON) && (pData->options & PLUGIN_OPTION_SKIP_SENDING_NOTES))
  1329. continue;
  1330. if (status == MIDI_STATUS_CHANNEL_PRESSURE && (pData->options & PLUGIN_OPTION_SEND_CHANNEL_PRESSURE) == 0)
  1331. continue;
  1332. if (status == MIDI_STATUS_CONTROL_CHANGE && (pData->options & PLUGIN_OPTION_SEND_CONTROL_CHANGES) == 0)
  1333. continue;
  1334. if (status == MIDI_STATUS_POLYPHONIC_AFTERTOUCH && (pData->options & PLUGIN_OPTION_SEND_NOTE_AFTERTOUCH) == 0)
  1335. continue;
  1336. if (status == MIDI_STATUS_PITCH_WHEEL_CONTROL && (pData->options & PLUGIN_OPTION_SEND_PITCHBEND) == 0)
  1337. continue;
  1338. // Fix bad note-off
  1339. if (status == MIDI_STATUS_NOTE_ON && midiData[2] == 0)
  1340. status = MIDI_STATUS_NOTE_OFF;
  1341. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientMidiEvent);
  1342. fShmRtClientControl.writeUInt(event.time);
  1343. fShmRtClientControl.writeByte(midiEvent.port);
  1344. fShmRtClientControl.writeByte(midiEvent.size);
  1345. fShmRtClientControl.writeByte(uint8_t(midiData[0] | (event.channel & MIDI_CHANNEL_BIT)));
  1346. for (uint8_t j=1; j < midiEvent.size; ++j)
  1347. fShmRtClientControl.writeByte(midiData[j]);
  1348. fShmRtClientControl.commitWrite();
  1349. if (status == MIDI_STATUS_NOTE_ON)
  1350. {
  1351. pData->postponeNoteOnRtEvent(true, event.channel, midiData[1], midiData[2]);
  1352. }
  1353. else if (status == MIDI_STATUS_NOTE_OFF)
  1354. {
  1355. pData->postponeNoteOffRtEvent(true, event.channel, midiData[1]);
  1356. }
  1357. } break;
  1358. }
  1359. }
  1360. pData->postRtEvents.trySplice();
  1361. } // End of Event Input
  1362. if (! processSingle(audioIn, audioOut, cvIn, cvOut, frames))
  1363. return;
  1364. // --------------------------------------------------------------------------------------------------------
  1365. // Control and MIDI Output
  1366. if (pData->event.portOut != nullptr)
  1367. {
  1368. float value;
  1369. for (uint32_t k=0; k < pData->param.count; ++k)
  1370. {
  1371. if (pData->param.data[k].type != PARAMETER_OUTPUT)
  1372. continue;
  1373. if (pData->param.data[k].mappedControlIndex > 0)
  1374. {
  1375. value = pData->param.ranges[k].getNormalizedValue(fParams[k].value);
  1376. pData->event.portOut->writeControlEvent(0,
  1377. pData->param.data[k].midiChannel,
  1378. kEngineControlEventTypeParameter,
  1379. static_cast<uint16_t>(pData->param.data[k].mappedControlIndex),
  1380. -1,
  1381. value);
  1382. }
  1383. }
  1384. uint32_t time;
  1385. uint8_t port, size;
  1386. const uint8_t* midiData(fShmRtClientControl.data->midiOut);
  1387. for (std::size_t read=0; read<kBridgeRtClientDataMidiOutSize-kBridgeBaseMidiOutHeaderSize;)
  1388. {
  1389. // get time
  1390. time = *(const uint32_t*)midiData;
  1391. midiData += 4;
  1392. // get port and size
  1393. port = *midiData++;
  1394. size = *midiData++;
  1395. if (size == 0)
  1396. break;
  1397. // store midi data advancing as needed
  1398. uint8_t data[size];
  1399. for (uint8_t j=0; j<size; ++j)
  1400. data[j] = *midiData++;
  1401. pData->event.portOut->writeMidiEvent(time, size, data);
  1402. read += kBridgeBaseMidiOutHeaderSize + size;
  1403. }
  1404. // TODO
  1405. (void)port;
  1406. } // End of Control and MIDI Output
  1407. }
  1408. bool processSingle(const float* const* const audioIn, float** const audioOut,
  1409. const float* const* const cvIn, float** const cvOut, const uint32_t frames)
  1410. {
  1411. CARLA_SAFE_ASSERT_RETURN(! fTimedError, false);
  1412. CARLA_SAFE_ASSERT_RETURN(frames > 0, false);
  1413. CARLA_SAFE_ASSERT_RETURN(frames <= fBufferSize, false);
  1414. if (pData->audioIn.count > 0)
  1415. {
  1416. CARLA_SAFE_ASSERT_RETURN(audioIn != nullptr, false);
  1417. }
  1418. if (pData->audioOut.count > 0)
  1419. {
  1420. CARLA_SAFE_ASSERT_RETURN(audioOut != nullptr, false);
  1421. }
  1422. if (pData->cvIn.count > 0)
  1423. {
  1424. CARLA_SAFE_ASSERT_RETURN(cvIn != nullptr, false);
  1425. }
  1426. if (pData->cvOut.count > 0)
  1427. {
  1428. CARLA_SAFE_ASSERT_RETURN(cvOut != nullptr, false);
  1429. }
  1430. // --------------------------------------------------------------------------------------------------------
  1431. // Try lock, silence otherwise
  1432. #ifndef STOAT_TEST_BUILD
  1433. if (pData->engine->isOffline())
  1434. {
  1435. pData->singleMutex.lock();
  1436. }
  1437. else
  1438. #endif
  1439. if (! pData->singleMutex.tryLock())
  1440. {
  1441. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  1442. carla_zeroFloats(audioOut[i], frames);
  1443. for (uint32_t i=0; i < pData->cvOut.count; ++i)
  1444. carla_zeroFloats(cvOut[i], frames);
  1445. return false;
  1446. }
  1447. // --------------------------------------------------------------------------------------------------------
  1448. // Reset audio buffers
  1449. for (uint32_t i=0; i < pData->audioIn.count; ++i)
  1450. carla_copyFloats(fShmAudioPool.data + (i * fBufferSize), audioIn[i], frames);
  1451. for (uint32_t i=0; i < pData->cvIn.count; ++i)
  1452. carla_copyFloats(fShmAudioPool.data + ((pData->audioIn.count + pData->audioOut.count + i) * fBufferSize), cvIn[i], frames);
  1453. // --------------------------------------------------------------------------------------------------------
  1454. // TimeInfo
  1455. const EngineTimeInfo timeInfo(pData->engine->getTimeInfo());
  1456. BridgeTimeInfo& bridgeTimeInfo(fShmRtClientControl.data->timeInfo);
  1457. bridgeTimeInfo.playing = timeInfo.playing;
  1458. bridgeTimeInfo.frame = timeInfo.frame;
  1459. bridgeTimeInfo.usecs = timeInfo.usecs;
  1460. bridgeTimeInfo.validFlags = timeInfo.bbt.valid ? kPluginBridgeTimeInfoValidBBT : 0x0;
  1461. if (timeInfo.bbt.valid)
  1462. {
  1463. bridgeTimeInfo.bar = timeInfo.bbt.bar;
  1464. bridgeTimeInfo.beat = timeInfo.bbt.beat;
  1465. bridgeTimeInfo.tick = timeInfo.bbt.tick;
  1466. bridgeTimeInfo.beatsPerBar = timeInfo.bbt.beatsPerBar;
  1467. bridgeTimeInfo.beatType = timeInfo.bbt.beatType;
  1468. bridgeTimeInfo.ticksPerBeat = timeInfo.bbt.ticksPerBeat;
  1469. bridgeTimeInfo.beatsPerMinute = timeInfo.bbt.beatsPerMinute;
  1470. bridgeTimeInfo.barStartTick = timeInfo.bbt.barStartTick;
  1471. }
  1472. // --------------------------------------------------------------------------------------------------------
  1473. // Run plugin
  1474. {
  1475. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientProcess);
  1476. fShmRtClientControl.writeUInt(frames);
  1477. fShmRtClientControl.commitWrite();
  1478. }
  1479. waitForClient("process", fProcWaitTime);
  1480. if (fTimedOut)
  1481. {
  1482. pData->singleMutex.unlock();
  1483. return false;
  1484. }
  1485. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  1486. carla_copyFloats(audioOut[i], fShmAudioPool.data + ((pData->audioIn.count + i) * fBufferSize), frames);
  1487. for (uint32_t i=0; i < pData->cvOut.count; ++i)
  1488. carla_copyFloats(cvOut[i], fShmAudioPool.data + ((pData->audioIn.count + pData->audioOut.count + pData->cvIn.count + i) * fBufferSize), frames);
  1489. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1490. // --------------------------------------------------------------------------------------------------------
  1491. // Post-processing (dry/wet, volume and balance)
  1492. {
  1493. const bool doVolume = (pData->hints & PLUGIN_CAN_VOLUME) != 0 && carla_isNotEqual(pData->postProc.volume, 1.0f);
  1494. const bool doDryWet = (pData->hints & PLUGIN_CAN_DRYWET) != 0 && carla_isNotEqual(pData->postProc.dryWet, 1.0f);
  1495. const bool doBalance = (pData->hints & PLUGIN_CAN_BALANCE) != 0 && ! (carla_isEqual(pData->postProc.balanceLeft, -1.0f) && carla_isEqual(pData->postProc.balanceRight, 1.0f));
  1496. const bool isMono = (pData->audioIn.count == 1);
  1497. bool isPair;
  1498. float bufValue, oldBufLeft[doBalance ? frames : 1];
  1499. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  1500. {
  1501. // Dry/Wet
  1502. if (doDryWet)
  1503. {
  1504. const uint32_t c = isMono ? 0 : i;
  1505. for (uint32_t k=0; k < frames; ++k)
  1506. {
  1507. # ifndef BUILD_BRIDGE
  1508. if (k < pData->latency.frames && pData->latency.buffers != nullptr)
  1509. bufValue = pData->latency.buffers[c][k];
  1510. else if (pData->latency.frames < frames)
  1511. bufValue = audioIn[c][k-pData->latency.frames];
  1512. else
  1513. # endif
  1514. bufValue = audioIn[c][k];
  1515. audioOut[i][k] = (audioOut[i][k] * pData->postProc.dryWet) + (bufValue * (1.0f - pData->postProc.dryWet));
  1516. }
  1517. }
  1518. // Balance
  1519. if (doBalance)
  1520. {
  1521. isPair = (i % 2 == 0);
  1522. if (isPair)
  1523. {
  1524. CARLA_ASSERT(i+1 < pData->audioOut.count);
  1525. carla_copyFloats(oldBufLeft, audioOut[i], frames);
  1526. }
  1527. float balRangeL = (pData->postProc.balanceLeft + 1.0f)/2.0f;
  1528. float balRangeR = (pData->postProc.balanceRight + 1.0f)/2.0f;
  1529. for (uint32_t k=0; k < frames; ++k)
  1530. {
  1531. if (isPair)
  1532. {
  1533. // left
  1534. audioOut[i][k] = oldBufLeft[k] * (1.0f - balRangeL);
  1535. audioOut[i][k] += audioOut[i+1][k] * (1.0f - balRangeR);
  1536. }
  1537. else
  1538. {
  1539. // right
  1540. audioOut[i][k] = audioOut[i][k] * balRangeR;
  1541. audioOut[i][k] += oldBufLeft[k] * balRangeL;
  1542. }
  1543. }
  1544. }
  1545. // Volume (and buffer copy)
  1546. if (doVolume)
  1547. {
  1548. for (uint32_t k=0; k < frames; ++k)
  1549. audioOut[i][k] *= pData->postProc.volume;
  1550. }
  1551. }
  1552. } // End of Post-processing
  1553. # ifndef BUILD_BRIDGE
  1554. // --------------------------------------------------------------------------------------------------------
  1555. // Save latency values for next callback
  1556. if (pData->latency.frames != 0 && pData->latency.buffers != nullptr)
  1557. {
  1558. const uint32_t latframes = pData->latency.frames;
  1559. if (latframes <= frames)
  1560. {
  1561. for (uint32_t i=0; i < pData->audioIn.count; ++i)
  1562. carla_copyFloats(pData->latency.buffers[i], audioIn[i]+(frames-latframes), latframes);
  1563. }
  1564. else
  1565. {
  1566. const uint32_t diff = latframes - frames;
  1567. for (uint32_t i=0, k; i<pData->audioIn.count; ++i)
  1568. {
  1569. // push back buffer by 'frames'
  1570. for (k=0; k < diff; ++k)
  1571. pData->latency.buffers[i][k] = pData->latency.buffers[i][k+frames];
  1572. // put current input at the end
  1573. for (uint32_t j=0; k < latframes; ++j, ++k)
  1574. pData->latency.buffers[i][k] = audioIn[i][j];
  1575. }
  1576. }
  1577. }
  1578. # endif
  1579. #endif // BUILD_BRIDGE_ALTERNATIVE_ARCH
  1580. // --------------------------------------------------------------------------------------------------------
  1581. pData->singleMutex.unlock();
  1582. return true;
  1583. }
  1584. void bufferSizeChanged(const uint32_t newBufferSize) override
  1585. {
  1586. fBufferSize = newBufferSize;
  1587. resizeAudioPool(newBufferSize);
  1588. {
  1589. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientSetBufferSize);
  1590. fShmRtClientControl.writeUInt(newBufferSize);
  1591. fShmRtClientControl.commitWrite();
  1592. }
  1593. //fProcWaitTime = newBufferSize*1000/pData->engine->getSampleRate();
  1594. fProcWaitTime = 1000;
  1595. waitForClient("buffersize", 1000);
  1596. }
  1597. void sampleRateChanged(const double newSampleRate) override
  1598. {
  1599. {
  1600. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientSetSampleRate);
  1601. fShmRtClientControl.writeDouble(newSampleRate);
  1602. fShmRtClientControl.commitWrite();
  1603. }
  1604. //fProcWaitTime = pData->engine->getBufferSize()*1000/newSampleRate;
  1605. fProcWaitTime = 1000;
  1606. waitForClient("samplerate", 1000);
  1607. }
  1608. void offlineModeChanged(const bool isOffline) override
  1609. {
  1610. {
  1611. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientSetOnline);
  1612. fShmRtClientControl.writeBool(isOffline);
  1613. fShmRtClientControl.commitWrite();
  1614. }
  1615. waitForClient("offline", 1000);
  1616. }
  1617. // -------------------------------------------------------------------
  1618. // Plugin buffers
  1619. void clearBuffers() noexcept override
  1620. {
  1621. if (fParams != nullptr)
  1622. {
  1623. delete[] fParams;
  1624. fParams = nullptr;
  1625. }
  1626. CarlaPlugin::clearBuffers();
  1627. }
  1628. // -------------------------------------------------------------------
  1629. // Post-poned UI Stuff
  1630. void uiParameterChange(const uint32_t index, const float value) noexcept override
  1631. {
  1632. CARLA_SAFE_ASSERT_RETURN(index < pData->param.count,);
  1633. const CarlaMutexLocker _cml(fShmNonRtClientControl.mutex);
  1634. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientUiParameterChange);
  1635. fShmNonRtClientControl.writeUInt(index);
  1636. fShmNonRtClientControl.writeFloat(value);
  1637. fShmNonRtClientControl.commitWrite();
  1638. }
  1639. void uiProgramChange(const uint32_t index) noexcept override
  1640. {
  1641. CARLA_SAFE_ASSERT_RETURN(index < pData->prog.count,);
  1642. const CarlaMutexLocker _cml(fShmNonRtClientControl.mutex);
  1643. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientUiProgramChange);
  1644. fShmNonRtClientControl.writeUInt(index);
  1645. fShmNonRtClientControl.commitWrite();
  1646. }
  1647. void uiMidiProgramChange(const uint32_t index) noexcept override
  1648. {
  1649. CARLA_SAFE_ASSERT_RETURN(index < pData->midiprog.count,);
  1650. const CarlaMutexLocker _cml(fShmNonRtClientControl.mutex);
  1651. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientUiMidiProgramChange);
  1652. fShmNonRtClientControl.writeUInt(index);
  1653. fShmNonRtClientControl.commitWrite();
  1654. }
  1655. void uiNoteOn(const uint8_t channel, const uint8_t note, const uint8_t velo) noexcept override
  1656. {
  1657. CARLA_SAFE_ASSERT_RETURN(channel < MAX_MIDI_CHANNELS,);
  1658. CARLA_SAFE_ASSERT_RETURN(note < MAX_MIDI_NOTE,);
  1659. CARLA_SAFE_ASSERT_RETURN(velo > 0 && velo < MAX_MIDI_VALUE,);
  1660. const CarlaMutexLocker _cml(fShmNonRtClientControl.mutex);
  1661. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientUiNoteOn);
  1662. fShmNonRtClientControl.writeByte(channel);
  1663. fShmNonRtClientControl.writeByte(note);
  1664. fShmNonRtClientControl.writeByte(velo);
  1665. fShmNonRtClientControl.commitWrite();
  1666. }
  1667. void uiNoteOff(const uint8_t channel, const uint8_t note) noexcept override
  1668. {
  1669. CARLA_SAFE_ASSERT_RETURN(channel < MAX_MIDI_CHANNELS,);
  1670. CARLA_SAFE_ASSERT_RETURN(note < MAX_MIDI_NOTE,);
  1671. const CarlaMutexLocker _cml(fShmNonRtClientControl.mutex);
  1672. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientUiNoteOff);
  1673. fShmNonRtClientControl.writeByte(channel);
  1674. fShmNonRtClientControl.writeByte(note);
  1675. fShmNonRtClientControl.commitWrite();
  1676. }
  1677. // -------------------------------------------------------------------
  1678. // Internal helper functions
  1679. void restoreLV2State(bool) noexcept override
  1680. {
  1681. const CarlaMutexLocker _cml(fShmNonRtClientControl.mutex);
  1682. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientRestoreLV2State);
  1683. fShmNonRtClientControl.commitWrite();
  1684. }
  1685. void waitForBridgeSaveSignal() noexcept override
  1686. {
  1687. // VSTs only save chunks, for which we already have a waitForSaved there
  1688. if (fPluginType != PLUGIN_VST2)
  1689. waitForSaved();
  1690. }
  1691. // -------------------------------------------------------------------
  1692. void handleNonRtData()
  1693. {
  1694. for (; fShmNonRtServerControl.isDataAvailableForReading();)
  1695. {
  1696. const PluginBridgeNonRtServerOpcode opcode(fShmNonRtServerControl.readOpcode());
  1697. #ifdef DEBUG
  1698. if (opcode != kPluginBridgeNonRtServerPong && opcode != kPluginBridgeNonRtServerParameterValue2) {
  1699. carla_debug("CarlaPluginBridge::handleNonRtData() - got opcode: %s", PluginBridgeNonRtServerOpcode2str(opcode));
  1700. }
  1701. #endif
  1702. switch (opcode)
  1703. {
  1704. case kPluginBridgeNonRtServerNull:
  1705. case kPluginBridgeNonRtServerPong:
  1706. break;
  1707. case kPluginBridgeNonRtServerVersion:
  1708. fBridgeVersion = fShmNonRtServerControl.readUInt();
  1709. break;
  1710. case kPluginBridgeNonRtServerPluginInfo1: {
  1711. // uint/category, uint/hints, uint/optionsAvailable, uint/optionsEnabled, long/uniqueId
  1712. const uint32_t category = fShmNonRtServerControl.readUInt();
  1713. const uint32_t hints = fShmNonRtServerControl.readUInt();
  1714. const uint32_t optionAv = fShmNonRtServerControl.readUInt();
  1715. const uint32_t optionEn = fShmNonRtServerControl.readUInt();
  1716. const int64_t uniqueId = fShmNonRtServerControl.readLong();
  1717. if (fUniqueId != 0) {
  1718. CARLA_SAFE_ASSERT_INT2(fUniqueId == uniqueId, fUniqueId, uniqueId);
  1719. }
  1720. pData->hints = hints | PLUGIN_IS_BRIDGE;
  1721. pData->options = optionEn;
  1722. #ifdef HAVE_X11
  1723. if (fBridgeVersion < 9)
  1724. #endif
  1725. {
  1726. pData->hints &= ~PLUGIN_HAS_CUSTOM_EMBED_UI;
  1727. }
  1728. fInfo.category = static_cast<PluginCategory>(category);
  1729. fInfo.optionsAvailable = optionAv;
  1730. } break;
  1731. case kPluginBridgeNonRtServerPluginInfo2: {
  1732. // uint/size, str[] (realName), uint/size, str[] (label), uint/size, str[] (maker), uint/size, str[] (copyright)
  1733. // realName
  1734. const uint32_t realNameSize(fShmNonRtServerControl.readUInt());
  1735. char realName[realNameSize+1];
  1736. carla_zeroChars(realName, realNameSize+1);
  1737. fShmNonRtServerControl.readCustomData(realName, realNameSize);
  1738. // label
  1739. const uint32_t labelSize(fShmNonRtServerControl.readUInt());
  1740. char label[labelSize+1];
  1741. carla_zeroChars(label, labelSize+1);
  1742. fShmNonRtServerControl.readCustomData(label, labelSize);
  1743. // maker
  1744. const uint32_t makerSize(fShmNonRtServerControl.readUInt());
  1745. char maker[makerSize+1];
  1746. carla_zeroChars(maker, makerSize+1);
  1747. fShmNonRtServerControl.readCustomData(maker, makerSize);
  1748. // copyright
  1749. const uint32_t copyrightSize(fShmNonRtServerControl.readUInt());
  1750. char copyright[copyrightSize+1];
  1751. carla_zeroChars(copyright, copyrightSize+1);
  1752. fShmNonRtServerControl.readCustomData(copyright, copyrightSize);
  1753. fInfo.name = realName;
  1754. fInfo.label = label;
  1755. fInfo.maker = maker;
  1756. fInfo.copyright = copyright;
  1757. if (pData->name == nullptr)
  1758. pData->name = pData->engine->getUniquePluginName(realName);
  1759. } break;
  1760. case kPluginBridgeNonRtServerAudioCount: {
  1761. // uint/ins, uint/outs
  1762. fInfo.clear();
  1763. fInfo.aIns = fShmNonRtServerControl.readUInt();
  1764. fInfo.aOuts = fShmNonRtServerControl.readUInt();
  1765. if (fInfo.aIns > 0)
  1766. {
  1767. fInfo.aInNames = new const char*[fInfo.aIns];
  1768. carla_zeroPointers(fInfo.aInNames, fInfo.aIns);
  1769. }
  1770. if (fInfo.aOuts > 0)
  1771. {
  1772. fInfo.aOutNames = new const char*[fInfo.aOuts];
  1773. carla_zeroPointers(fInfo.aOutNames, fInfo.aOuts);
  1774. }
  1775. } break;
  1776. case kPluginBridgeNonRtServerMidiCount: {
  1777. // uint/ins, uint/outs
  1778. fInfo.mIns = fShmNonRtServerControl.readUInt();
  1779. fInfo.mOuts = fShmNonRtServerControl.readUInt();
  1780. } break;
  1781. case kPluginBridgeNonRtServerCvCount: {
  1782. // uint/ins, uint/outs
  1783. fInfo.cvIns = fShmNonRtServerControl.readUInt();
  1784. fInfo.cvOuts = fShmNonRtServerControl.readUInt();
  1785. } break;
  1786. case kPluginBridgeNonRtServerParameterCount: {
  1787. // uint/count
  1788. const uint32_t count = fShmNonRtServerControl.readUInt();
  1789. // delete old data
  1790. pData->param.clear();
  1791. if (fParams != nullptr)
  1792. {
  1793. delete[] fParams;
  1794. fParams = nullptr;
  1795. }
  1796. if (count > 0)
  1797. {
  1798. pData->param.createNew(count, false);
  1799. fParams = new BridgeParamInfo[count];
  1800. // we might not receive all parameter data, so ensure range max is not 0
  1801. for (uint32_t i=0; i<count; ++i)
  1802. {
  1803. pData->param.ranges[i].def = 0.0f;
  1804. pData->param.ranges[i].min = 0.0f;
  1805. pData->param.ranges[i].max = 1.0f;
  1806. pData->param.ranges[i].step = 0.001f;
  1807. pData->param.ranges[i].stepSmall = 0.0001f;
  1808. pData->param.ranges[i].stepLarge = 0.1f;
  1809. }
  1810. }
  1811. } break;
  1812. case kPluginBridgeNonRtServerProgramCount: {
  1813. // uint/count
  1814. pData->prog.clear();
  1815. if (const uint32_t count = fShmNonRtServerControl.readUInt())
  1816. pData->prog.createNew(count);
  1817. } break;
  1818. case kPluginBridgeNonRtServerMidiProgramCount: {
  1819. // uint/count
  1820. pData->midiprog.clear();
  1821. if (const uint32_t count = fShmNonRtServerControl.readUInt())
  1822. pData->midiprog.createNew(count);
  1823. } break;
  1824. case kPluginBridgeNonRtServerPortName: {
  1825. // byte/type, uint/index, uint/size, str[] (name)
  1826. const uint8_t portType = fShmNonRtServerControl.readByte();
  1827. const uint32_t index = fShmNonRtServerControl.readUInt();
  1828. // name
  1829. const uint32_t nameSize(fShmNonRtServerControl.readUInt());
  1830. char* const name = new char[nameSize+1];
  1831. carla_zeroChars(name, nameSize+1);
  1832. fShmNonRtServerControl.readCustomData(name, nameSize);
  1833. CARLA_SAFE_ASSERT_BREAK(portType > kPluginBridgePortNull && portType < kPluginBridgePortTypeCount);
  1834. switch (portType)
  1835. {
  1836. case kPluginBridgePortAudioInput:
  1837. CARLA_SAFE_ASSERT_BREAK(index < fInfo.aIns);
  1838. fInfo.aInNames[index] = name;
  1839. break;
  1840. case kPluginBridgePortAudioOutput:
  1841. CARLA_SAFE_ASSERT_BREAK(index < fInfo.aOuts);
  1842. fInfo.aOutNames[index] = name;
  1843. break;
  1844. }
  1845. } break;
  1846. case kPluginBridgeNonRtServerParameterData1: {
  1847. // uint/index, int/rindex, uint/type, uint/hints, int/cc
  1848. const uint32_t index = fShmNonRtServerControl.readUInt();
  1849. const int32_t rindex = fShmNonRtServerControl.readInt();
  1850. const uint32_t type = fShmNonRtServerControl.readUInt();
  1851. const uint32_t hints = fShmNonRtServerControl.readUInt();
  1852. const int16_t ctrl = fShmNonRtServerControl.readShort();
  1853. CARLA_SAFE_ASSERT_BREAK(ctrl >= CONTROL_INDEX_NONE && ctrl <= CONTROL_INDEX_MAX_ALLOWED);
  1854. CARLA_SAFE_ASSERT_INT2(index < pData->param.count, index, pData->param.count);
  1855. if (index < pData->param.count)
  1856. {
  1857. pData->param.data[index].type = static_cast<ParameterType>(type);
  1858. pData->param.data[index].index = static_cast<int32_t>(index);
  1859. pData->param.data[index].rindex = rindex;
  1860. pData->param.data[index].hints = hints;
  1861. pData->param.data[index].mappedControlIndex = ctrl;
  1862. }
  1863. } break;
  1864. case kPluginBridgeNonRtServerParameterData2: {
  1865. // uint/index, uint/size, str[] (name), uint/size, str[] (unit)
  1866. const uint32_t index = fShmNonRtServerControl.readUInt();
  1867. // name
  1868. const uint32_t nameSize(fShmNonRtServerControl.readUInt());
  1869. char name[nameSize+1];
  1870. carla_zeroChars(name, nameSize+1);
  1871. fShmNonRtServerControl.readCustomData(name, nameSize);
  1872. // symbol
  1873. const uint32_t symbolSize(fShmNonRtServerControl.readUInt());
  1874. char symbol[symbolSize+1];
  1875. carla_zeroChars(symbol, symbolSize+1);
  1876. fShmNonRtServerControl.readCustomData(symbol, symbolSize);
  1877. // unit
  1878. const uint32_t unitSize(fShmNonRtServerControl.readUInt());
  1879. char unit[unitSize+1];
  1880. carla_zeroChars(unit, unitSize+1);
  1881. fShmNonRtServerControl.readCustomData(unit, unitSize);
  1882. CARLA_SAFE_ASSERT_INT2(index < pData->param.count, index, pData->param.count);
  1883. if (index < pData->param.count)
  1884. {
  1885. fParams[index].name = name;
  1886. fParams[index].symbol = symbol;
  1887. fParams[index].unit = unit;
  1888. }
  1889. } break;
  1890. case kPluginBridgeNonRtServerParameterRanges: {
  1891. // uint/index, float/def, float/min, float/max, float/step, float/stepSmall, float/stepLarge
  1892. const uint32_t index = fShmNonRtServerControl.readUInt();
  1893. const float def = fShmNonRtServerControl.readFloat();
  1894. const float min = fShmNonRtServerControl.readFloat();
  1895. const float max = fShmNonRtServerControl.readFloat();
  1896. const float step = fShmNonRtServerControl.readFloat();
  1897. const float stepSmall = fShmNonRtServerControl.readFloat();
  1898. const float stepLarge = fShmNonRtServerControl.readFloat();
  1899. CARLA_SAFE_ASSERT_BREAK(min < max);
  1900. CARLA_SAFE_ASSERT_BREAK(def >= min);
  1901. CARLA_SAFE_ASSERT_BREAK(def <= max);
  1902. CARLA_SAFE_ASSERT_INT2(index < pData->param.count, index, pData->param.count);
  1903. if (index < pData->param.count)
  1904. {
  1905. pData->param.ranges[index].def = def;
  1906. pData->param.ranges[index].min = min;
  1907. pData->param.ranges[index].max = max;
  1908. pData->param.ranges[index].step = step;
  1909. pData->param.ranges[index].stepSmall = stepSmall;
  1910. pData->param.ranges[index].stepLarge = stepLarge;
  1911. }
  1912. } break;
  1913. case kPluginBridgeNonRtServerParameterValue: {
  1914. // uint/index, float/value
  1915. const uint32_t index = fShmNonRtServerControl.readUInt();
  1916. const float value = fShmNonRtServerControl.readFloat();
  1917. if (index < pData->param.count)
  1918. {
  1919. const float fixedValue(pData->param.getFixedValue(index, value));
  1920. if (carla_isNotEqual(fParams[index].value, fixedValue))
  1921. {
  1922. fParams[index].value = fixedValue;
  1923. CarlaPlugin::setParameterValue(index, fixedValue, false, true, true);
  1924. }
  1925. }
  1926. } break;
  1927. case kPluginBridgeNonRtServerParameterValue2: {
  1928. // uint/index, float/value
  1929. const uint32_t index = fShmNonRtServerControl.readUInt();
  1930. const float value = fShmNonRtServerControl.readFloat();
  1931. if (index < pData->param.count)
  1932. {
  1933. const float fixedValue(pData->param.getFixedValue(index, value));
  1934. fParams[index].value = fixedValue;
  1935. }
  1936. } break;
  1937. case kPluginBridgeNonRtServerParameterTouch: {
  1938. // uint/index, bool/touch
  1939. const uint32_t index = fShmNonRtServerControl.readUInt();
  1940. const bool touch = fShmNonRtServerControl.readBool();
  1941. pData->engine->touchPluginParameter(pData->id, index, touch);
  1942. } break;
  1943. case kPluginBridgeNonRtServerDefaultValue: {
  1944. // uint/index, float/value
  1945. const uint32_t index = fShmNonRtServerControl.readUInt();
  1946. const float value = fShmNonRtServerControl.readFloat();
  1947. if (index < pData->param.count)
  1948. pData->param.ranges[index].def = value;
  1949. } break;
  1950. case kPluginBridgeNonRtServerCurrentProgram: {
  1951. // int/index
  1952. const int32_t index = fShmNonRtServerControl.readInt();
  1953. CARLA_SAFE_ASSERT_BREAK(index >= -1);
  1954. CARLA_SAFE_ASSERT_INT2(index < static_cast<int32_t>(pData->prog.count), index, pData->prog.count);
  1955. CarlaPlugin::setProgram(index, false, true, true);
  1956. } break;
  1957. case kPluginBridgeNonRtServerCurrentMidiProgram: {
  1958. // int/index
  1959. const int32_t index = fShmNonRtServerControl.readInt();
  1960. CARLA_SAFE_ASSERT_BREAK(index >= -1);
  1961. CARLA_SAFE_ASSERT_INT2(index < static_cast<int32_t>(pData->midiprog.count), index, pData->midiprog.count);
  1962. CarlaPlugin::setMidiProgram(index, false, true, true);
  1963. } break;
  1964. case kPluginBridgeNonRtServerProgramName: {
  1965. // uint/index, uint/size, str[] (name)
  1966. const uint32_t index = fShmNonRtServerControl.readUInt();
  1967. // name
  1968. const uint32_t nameSize(fShmNonRtServerControl.readUInt());
  1969. char name[nameSize+1];
  1970. carla_zeroChars(name, nameSize+1);
  1971. fShmNonRtServerControl.readCustomData(name, nameSize);
  1972. CARLA_SAFE_ASSERT_INT2(index < pData->prog.count, index, pData->prog.count);
  1973. if (index < pData->prog.count)
  1974. {
  1975. if (pData->prog.names[index] != nullptr)
  1976. delete[] pData->prog.names[index];
  1977. pData->prog.names[index] = carla_strdup(name);
  1978. }
  1979. } break;
  1980. case kPluginBridgeNonRtServerMidiProgramData: {
  1981. // uint/index, uint/bank, uint/program, uint/size, str[] (name)
  1982. const uint32_t index = fShmNonRtServerControl.readUInt();
  1983. const uint32_t bank = fShmNonRtServerControl.readUInt();
  1984. const uint32_t program = fShmNonRtServerControl.readUInt();
  1985. // name
  1986. const uint32_t nameSize(fShmNonRtServerControl.readUInt());
  1987. char name[nameSize+1];
  1988. carla_zeroChars(name, nameSize+1);
  1989. fShmNonRtServerControl.readCustomData(name, nameSize);
  1990. CARLA_SAFE_ASSERT_INT2(index < pData->midiprog.count, index, pData->midiprog.count);
  1991. if (index < pData->midiprog.count)
  1992. {
  1993. if (pData->midiprog.data[index].name != nullptr)
  1994. delete[] pData->midiprog.data[index].name;
  1995. pData->midiprog.data[index].bank = bank;
  1996. pData->midiprog.data[index].program = program;
  1997. pData->midiprog.data[index].name = carla_strdup(name);
  1998. }
  1999. } break;
  2000. case kPluginBridgeNonRtServerSetCustomData: {
  2001. // uint/size, str[], uint/size, str[], uint/size, str[]
  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 > 16384)
  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. // ---------------------------------------------------------------------------------------------------------------------