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.

3320 lines
118KB

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