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.

3309 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[size];
  1424. for (uint8_t j=0; j<size; ++j)
  1425. data[j] = *midiData++;
  1426. pData->event.portOut->writeMidiEvent(time, size, data);
  1427. read += kBridgeBaseMidiOutHeaderSize + size;
  1428. }
  1429. // TODO
  1430. (void)port;
  1431. } // End of Control and MIDI Output
  1432. }
  1433. bool processSingle(const float* const* const audioIn, float** const audioOut,
  1434. const float* const* const cvIn, float** const cvOut, const uint32_t frames)
  1435. {
  1436. CARLA_SAFE_ASSERT_RETURN(! fTimedError, false);
  1437. CARLA_SAFE_ASSERT_RETURN(frames > 0, false);
  1438. CARLA_SAFE_ASSERT_RETURN(frames <= fBufferSize, false);
  1439. if (pData->audioIn.count > 0)
  1440. {
  1441. CARLA_SAFE_ASSERT_RETURN(audioIn != nullptr, false);
  1442. }
  1443. if (pData->audioOut.count > 0)
  1444. {
  1445. CARLA_SAFE_ASSERT_RETURN(audioOut != nullptr, false);
  1446. }
  1447. if (pData->cvIn.count > 0)
  1448. {
  1449. CARLA_SAFE_ASSERT_RETURN(cvIn != nullptr, false);
  1450. }
  1451. if (pData->cvOut.count > 0)
  1452. {
  1453. CARLA_SAFE_ASSERT_RETURN(cvOut != nullptr, false);
  1454. }
  1455. // --------------------------------------------------------------------------------------------------------
  1456. // Try lock, silence otherwise
  1457. #ifndef STOAT_TEST_BUILD
  1458. if (pData->engine->isOffline())
  1459. {
  1460. pData->singleMutex.lock();
  1461. }
  1462. else
  1463. #endif
  1464. if (! pData->singleMutex.tryLock())
  1465. {
  1466. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  1467. carla_zeroFloats(audioOut[i], frames);
  1468. for (uint32_t i=0; i < pData->cvOut.count; ++i)
  1469. carla_zeroFloats(cvOut[i], frames);
  1470. return false;
  1471. }
  1472. // --------------------------------------------------------------------------------------------------------
  1473. // Reset audio buffers
  1474. for (uint32_t i=0; i < pData->audioIn.count; ++i)
  1475. carla_copyFloats(fShmAudioPool.data + (i * fBufferSize), audioIn[i], frames);
  1476. for (uint32_t i=0; i < pData->cvIn.count; ++i)
  1477. carla_copyFloats(fShmAudioPool.data + ((pData->audioIn.count + pData->audioOut.count + i) * fBufferSize), cvIn[i], frames);
  1478. // --------------------------------------------------------------------------------------------------------
  1479. // TimeInfo
  1480. const EngineTimeInfo timeInfo(pData->engine->getTimeInfo());
  1481. BridgeTimeInfo& bridgeTimeInfo(fShmRtClientControl.data->timeInfo);
  1482. bridgeTimeInfo.playing = timeInfo.playing;
  1483. bridgeTimeInfo.frame = timeInfo.frame;
  1484. bridgeTimeInfo.usecs = timeInfo.usecs;
  1485. bridgeTimeInfo.validFlags = timeInfo.bbt.valid ? kPluginBridgeTimeInfoValidBBT : 0x0;
  1486. if (timeInfo.bbt.valid)
  1487. {
  1488. bridgeTimeInfo.bar = timeInfo.bbt.bar;
  1489. bridgeTimeInfo.beat = timeInfo.bbt.beat;
  1490. bridgeTimeInfo.tick = timeInfo.bbt.tick;
  1491. bridgeTimeInfo.beatsPerBar = timeInfo.bbt.beatsPerBar;
  1492. bridgeTimeInfo.beatType = timeInfo.bbt.beatType;
  1493. bridgeTimeInfo.ticksPerBeat = timeInfo.bbt.ticksPerBeat;
  1494. bridgeTimeInfo.beatsPerMinute = timeInfo.bbt.beatsPerMinute;
  1495. bridgeTimeInfo.barStartTick = timeInfo.bbt.barStartTick;
  1496. }
  1497. // --------------------------------------------------------------------------------------------------------
  1498. // Run plugin
  1499. {
  1500. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientProcess);
  1501. fShmRtClientControl.writeUInt(frames);
  1502. fShmRtClientControl.commitWrite();
  1503. }
  1504. waitForClient("process", fProcWaitTime);
  1505. if (fTimedOut)
  1506. {
  1507. pData->singleMutex.unlock();
  1508. return false;
  1509. }
  1510. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  1511. carla_copyFloats(audioOut[i], fShmAudioPool.data + ((pData->audioIn.count + i) * fBufferSize), frames);
  1512. for (uint32_t i=0; i < pData->cvOut.count; ++i)
  1513. carla_copyFloats(cvOut[i], fShmAudioPool.data + ((pData->audioIn.count + pData->audioOut.count + pData->cvIn.count + i) * fBufferSize), frames);
  1514. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1515. // --------------------------------------------------------------------------------------------------------
  1516. // Post-processing (dry/wet, volume and balance)
  1517. {
  1518. const bool doVolume = (pData->hints & PLUGIN_CAN_VOLUME) != 0 && carla_isNotEqual(pData->postProc.volume, 1.0f);
  1519. const bool doDryWet = (pData->hints & PLUGIN_CAN_DRYWET) != 0 && carla_isNotEqual(pData->postProc.dryWet, 1.0f);
  1520. const bool doBalance = (pData->hints & PLUGIN_CAN_BALANCE) != 0 && ! (carla_isEqual(pData->postProc.balanceLeft, -1.0f) && carla_isEqual(pData->postProc.balanceRight, 1.0f));
  1521. const bool isMono = (pData->audioIn.count == 1);
  1522. bool isPair;
  1523. float bufValue, oldBufLeft[doBalance ? frames : 1];
  1524. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  1525. {
  1526. // Dry/Wet
  1527. if (doDryWet)
  1528. {
  1529. const uint32_t c = isMono ? 0 : i;
  1530. for (uint32_t k=0; k < frames; ++k)
  1531. {
  1532. # ifndef BUILD_BRIDGE
  1533. if (k < pData->latency.frames && pData->latency.buffers != nullptr)
  1534. bufValue = pData->latency.buffers[c][k];
  1535. else if (pData->latency.frames < frames)
  1536. bufValue = audioIn[c][k-pData->latency.frames];
  1537. else
  1538. # endif
  1539. bufValue = audioIn[c][k];
  1540. audioOut[i][k] = (audioOut[i][k] * pData->postProc.dryWet) + (bufValue * (1.0f - pData->postProc.dryWet));
  1541. }
  1542. }
  1543. // Balance
  1544. if (doBalance)
  1545. {
  1546. isPair = (i % 2 == 0);
  1547. if (isPair)
  1548. {
  1549. CARLA_ASSERT(i+1 < pData->audioOut.count);
  1550. carla_copyFloats(oldBufLeft, audioOut[i], frames);
  1551. }
  1552. float balRangeL = (pData->postProc.balanceLeft + 1.0f)/2.0f;
  1553. float balRangeR = (pData->postProc.balanceRight + 1.0f)/2.0f;
  1554. for (uint32_t k=0; k < frames; ++k)
  1555. {
  1556. if (isPair)
  1557. {
  1558. // left
  1559. audioOut[i][k] = oldBufLeft[k] * (1.0f - balRangeL);
  1560. audioOut[i][k] += audioOut[i+1][k] * (1.0f - balRangeR);
  1561. }
  1562. else
  1563. {
  1564. // right
  1565. audioOut[i][k] = audioOut[i][k] * balRangeR;
  1566. audioOut[i][k] += oldBufLeft[k] * balRangeL;
  1567. }
  1568. }
  1569. }
  1570. // Volume (and buffer copy)
  1571. if (doVolume)
  1572. {
  1573. for (uint32_t k=0; k < frames; ++k)
  1574. audioOut[i][k] *= pData->postProc.volume;
  1575. }
  1576. }
  1577. } // End of Post-processing
  1578. # ifndef BUILD_BRIDGE
  1579. // --------------------------------------------------------------------------------------------------------
  1580. // Save latency values for next callback
  1581. if (pData->latency.frames != 0 && pData->latency.buffers != nullptr)
  1582. {
  1583. const uint32_t latframes = pData->latency.frames;
  1584. if (latframes <= frames)
  1585. {
  1586. for (uint32_t i=0; i < pData->audioIn.count; ++i)
  1587. carla_copyFloats(pData->latency.buffers[i], audioIn[i]+(frames-latframes), latframes);
  1588. }
  1589. else
  1590. {
  1591. const uint32_t diff = latframes - frames;
  1592. for (uint32_t i=0, k; i<pData->audioIn.count; ++i)
  1593. {
  1594. // push back buffer by 'frames'
  1595. for (k=0; k < diff; ++k)
  1596. pData->latency.buffers[i][k] = pData->latency.buffers[i][k+frames];
  1597. // put current input at the end
  1598. for (uint32_t j=0; k < latframes; ++j, ++k)
  1599. pData->latency.buffers[i][k] = audioIn[i][j];
  1600. }
  1601. }
  1602. }
  1603. # endif
  1604. #endif // BUILD_BRIDGE_ALTERNATIVE_ARCH
  1605. // --------------------------------------------------------------------------------------------------------
  1606. pData->singleMutex.unlock();
  1607. return true;
  1608. }
  1609. void bufferSizeChanged(const uint32_t newBufferSize) override
  1610. {
  1611. fBufferSize = newBufferSize;
  1612. resizeAudioPool(newBufferSize);
  1613. {
  1614. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientSetBufferSize);
  1615. fShmRtClientControl.writeUInt(newBufferSize);
  1616. fShmRtClientControl.commitWrite();
  1617. }
  1618. //fProcWaitTime = newBufferSize*1000/pData->engine->getSampleRate();
  1619. fProcWaitTime = 1000;
  1620. waitForClient("buffersize", 1000);
  1621. }
  1622. void sampleRateChanged(const double newSampleRate) override
  1623. {
  1624. {
  1625. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientSetSampleRate);
  1626. fShmRtClientControl.writeDouble(newSampleRate);
  1627. fShmRtClientControl.commitWrite();
  1628. }
  1629. //fProcWaitTime = pData->engine->getBufferSize()*1000/newSampleRate;
  1630. fProcWaitTime = 1000;
  1631. waitForClient("samplerate", 1000);
  1632. }
  1633. void offlineModeChanged(const bool isOffline) override
  1634. {
  1635. {
  1636. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientSetOnline);
  1637. fShmRtClientControl.writeBool(isOffline);
  1638. fShmRtClientControl.commitWrite();
  1639. }
  1640. waitForClient("offline", 1000);
  1641. }
  1642. // -------------------------------------------------------------------
  1643. // Plugin buffers
  1644. void clearBuffers() noexcept override
  1645. {
  1646. if (fParams != nullptr)
  1647. {
  1648. delete[] fParams;
  1649. fParams = nullptr;
  1650. }
  1651. CarlaPlugin::clearBuffers();
  1652. }
  1653. // -------------------------------------------------------------------
  1654. // Post-poned UI Stuff
  1655. void uiParameterChange(const uint32_t index, const float value) noexcept override
  1656. {
  1657. CARLA_SAFE_ASSERT_RETURN(index < pData->param.count,);
  1658. const CarlaMutexLocker _cml(fShmNonRtClientControl.mutex);
  1659. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientUiParameterChange);
  1660. fShmNonRtClientControl.writeUInt(index);
  1661. fShmNonRtClientControl.writeFloat(value);
  1662. fShmNonRtClientControl.commitWrite();
  1663. }
  1664. void uiProgramChange(const uint32_t index) noexcept override
  1665. {
  1666. CARLA_SAFE_ASSERT_RETURN(index < pData->prog.count,);
  1667. const CarlaMutexLocker _cml(fShmNonRtClientControl.mutex);
  1668. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientUiProgramChange);
  1669. fShmNonRtClientControl.writeUInt(index);
  1670. fShmNonRtClientControl.commitWrite();
  1671. }
  1672. void uiMidiProgramChange(const uint32_t index) noexcept override
  1673. {
  1674. CARLA_SAFE_ASSERT_RETURN(index < pData->midiprog.count,);
  1675. const CarlaMutexLocker _cml(fShmNonRtClientControl.mutex);
  1676. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientUiMidiProgramChange);
  1677. fShmNonRtClientControl.writeUInt(index);
  1678. fShmNonRtClientControl.commitWrite();
  1679. }
  1680. void uiNoteOn(const uint8_t channel, const uint8_t note, const uint8_t velo) noexcept override
  1681. {
  1682. CARLA_SAFE_ASSERT_RETURN(channel < MAX_MIDI_CHANNELS,);
  1683. CARLA_SAFE_ASSERT_RETURN(note < MAX_MIDI_NOTE,);
  1684. CARLA_SAFE_ASSERT_RETURN(velo > 0 && velo < MAX_MIDI_VALUE,);
  1685. const CarlaMutexLocker _cml(fShmNonRtClientControl.mutex);
  1686. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientUiNoteOn);
  1687. fShmNonRtClientControl.writeByte(channel);
  1688. fShmNonRtClientControl.writeByte(note);
  1689. fShmNonRtClientControl.writeByte(velo);
  1690. fShmNonRtClientControl.commitWrite();
  1691. }
  1692. void uiNoteOff(const uint8_t channel, const uint8_t note) noexcept override
  1693. {
  1694. CARLA_SAFE_ASSERT_RETURN(channel < MAX_MIDI_CHANNELS,);
  1695. CARLA_SAFE_ASSERT_RETURN(note < MAX_MIDI_NOTE,);
  1696. const CarlaMutexLocker _cml(fShmNonRtClientControl.mutex);
  1697. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientUiNoteOff);
  1698. fShmNonRtClientControl.writeByte(channel);
  1699. fShmNonRtClientControl.writeByte(note);
  1700. fShmNonRtClientControl.commitWrite();
  1701. }
  1702. // -------------------------------------------------------------------
  1703. // Internal helper functions
  1704. void restoreLV2State(bool) noexcept override
  1705. {
  1706. const CarlaMutexLocker _cml(fShmNonRtClientControl.mutex);
  1707. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientRestoreLV2State);
  1708. fShmNonRtClientControl.commitWrite();
  1709. }
  1710. void waitForBridgeSaveSignal() noexcept override
  1711. {
  1712. // VSTs only save chunks, for which we already have a waitForSaved there
  1713. if (fPluginType != PLUGIN_VST2)
  1714. waitForSaved();
  1715. }
  1716. // -------------------------------------------------------------------
  1717. void handleNonRtData()
  1718. {
  1719. for (; fShmNonRtServerControl.isDataAvailableForReading();)
  1720. {
  1721. const PluginBridgeNonRtServerOpcode opcode(fShmNonRtServerControl.readOpcode());
  1722. #ifdef DEBUG
  1723. if (opcode != kPluginBridgeNonRtServerPong && opcode != kPluginBridgeNonRtServerParameterValue2) {
  1724. carla_debug("CarlaPluginBridge::handleNonRtData() - got opcode: %s", PluginBridgeNonRtServerOpcode2str(opcode));
  1725. }
  1726. #endif
  1727. switch (opcode)
  1728. {
  1729. case kPluginBridgeNonRtServerNull:
  1730. case kPluginBridgeNonRtServerPong:
  1731. break;
  1732. case kPluginBridgeNonRtServerVersion:
  1733. fBridgeVersion = fShmNonRtServerControl.readUInt();
  1734. break;
  1735. case kPluginBridgeNonRtServerPluginInfo1: {
  1736. // uint/category, uint/hints, uint/optionsAvailable, uint/optionsEnabled, long/uniqueId
  1737. const uint32_t category = fShmNonRtServerControl.readUInt();
  1738. const uint32_t hints = fShmNonRtServerControl.readUInt();
  1739. const uint32_t optionAv = fShmNonRtServerControl.readUInt();
  1740. const uint32_t optionEn = fShmNonRtServerControl.readUInt();
  1741. const int64_t uniqueId = fShmNonRtServerControl.readLong();
  1742. if (fUniqueId != 0) {
  1743. CARLA_SAFE_ASSERT_INT2(fUniqueId == uniqueId, fUniqueId, uniqueId);
  1744. }
  1745. pData->hints = hints | PLUGIN_IS_BRIDGE;
  1746. pData->options = optionEn;
  1747. #ifdef HAVE_X11
  1748. if (fBridgeVersion < 9 || fBinaryType == BINARY_WIN32 || fBinaryType == BINARY_WIN64)
  1749. #endif
  1750. {
  1751. pData->hints &= ~PLUGIN_HAS_CUSTOM_EMBED_UI;
  1752. }
  1753. fInfo.category = static_cast<PluginCategory>(category);
  1754. fInfo.optionsAvailable = optionAv;
  1755. } break;
  1756. case kPluginBridgeNonRtServerPluginInfo2: {
  1757. // uint/size, str[] (realName), uint/size, str[] (label), uint/size, str[] (maker), uint/size, str[] (copyright)
  1758. // realName
  1759. const BridgeTextReader realName(fShmNonRtServerControl);
  1760. // label
  1761. const BridgeTextReader label(fShmNonRtServerControl);
  1762. // maker
  1763. const BridgeTextReader maker(fShmNonRtServerControl);
  1764. // copyright
  1765. const BridgeTextReader copyright(fShmNonRtServerControl);
  1766. fInfo.name = realName.text;
  1767. fInfo.label = label.text;
  1768. fInfo.maker = maker.text;
  1769. fInfo.copyright = copyright.text;
  1770. if (pData->name == nullptr)
  1771. pData->name = pData->engine->getUniquePluginName(realName.text);
  1772. } break;
  1773. case kPluginBridgeNonRtServerAudioCount: {
  1774. // uint/ins, uint/outs
  1775. fInfo.clear();
  1776. fInfo.aIns = fShmNonRtServerControl.readUInt();
  1777. fInfo.aOuts = fShmNonRtServerControl.readUInt();
  1778. if (fInfo.aIns > 0)
  1779. {
  1780. fInfo.aInNames = new const char*[fInfo.aIns];
  1781. carla_zeroPointers(fInfo.aInNames, fInfo.aIns);
  1782. }
  1783. if (fInfo.aOuts > 0)
  1784. {
  1785. fInfo.aOutNames = new const char*[fInfo.aOuts];
  1786. carla_zeroPointers(fInfo.aOutNames, fInfo.aOuts);
  1787. }
  1788. } break;
  1789. case kPluginBridgeNonRtServerMidiCount: {
  1790. // uint/ins, uint/outs
  1791. fInfo.mIns = fShmNonRtServerControl.readUInt();
  1792. fInfo.mOuts = fShmNonRtServerControl.readUInt();
  1793. } break;
  1794. case kPluginBridgeNonRtServerCvCount: {
  1795. // uint/ins, uint/outs
  1796. fInfo.cvIns = fShmNonRtServerControl.readUInt();
  1797. fInfo.cvOuts = fShmNonRtServerControl.readUInt();
  1798. } break;
  1799. case kPluginBridgeNonRtServerParameterCount: {
  1800. // uint/count
  1801. const uint32_t count = fShmNonRtServerControl.readUInt();
  1802. // delete old data
  1803. pData->param.clear();
  1804. if (fParams != nullptr)
  1805. {
  1806. delete[] fParams;
  1807. fParams = nullptr;
  1808. }
  1809. if (count > 0)
  1810. {
  1811. pData->param.createNew(count, false);
  1812. fParams = new BridgeParamInfo[count];
  1813. // we might not receive all parameter data, so ensure range max is not 0
  1814. for (uint32_t i=0; i<count; ++i)
  1815. {
  1816. pData->param.ranges[i].def = 0.0f;
  1817. pData->param.ranges[i].min = 0.0f;
  1818. pData->param.ranges[i].max = 1.0f;
  1819. pData->param.ranges[i].step = 0.001f;
  1820. pData->param.ranges[i].stepSmall = 0.0001f;
  1821. pData->param.ranges[i].stepLarge = 0.1f;
  1822. }
  1823. }
  1824. } break;
  1825. case kPluginBridgeNonRtServerProgramCount: {
  1826. // uint/count
  1827. pData->prog.clear();
  1828. if (const uint32_t count = fShmNonRtServerControl.readUInt())
  1829. pData->prog.createNew(count);
  1830. } break;
  1831. case kPluginBridgeNonRtServerMidiProgramCount: {
  1832. // uint/count
  1833. pData->midiprog.clear();
  1834. if (const uint32_t count = fShmNonRtServerControl.readUInt())
  1835. pData->midiprog.createNew(count);
  1836. } break;
  1837. case kPluginBridgeNonRtServerPortName: {
  1838. // byte/type, uint/index, uint/size, str[] (name)
  1839. const uint8_t portType = fShmNonRtServerControl.readByte();
  1840. const uint32_t index = fShmNonRtServerControl.readUInt();
  1841. // name
  1842. const BridgeTextReader name(fShmNonRtServerControl);
  1843. CARLA_SAFE_ASSERT_BREAK(portType > kPluginBridgePortNull && portType < kPluginBridgePortTypeCount);
  1844. switch (portType)
  1845. {
  1846. case kPluginBridgePortAudioInput:
  1847. CARLA_SAFE_ASSERT_BREAK(index < fInfo.aIns);
  1848. fInfo.aInNames[index] = name.text;
  1849. break;
  1850. case kPluginBridgePortAudioOutput:
  1851. CARLA_SAFE_ASSERT_BREAK(index < fInfo.aOuts);
  1852. fInfo.aOutNames[index] = name.text;
  1853. break;
  1854. }
  1855. } break;
  1856. case kPluginBridgeNonRtServerParameterData1: {
  1857. // uint/index, int/rindex, uint/type, uint/hints, short/cc
  1858. const uint32_t index = fShmNonRtServerControl.readUInt();
  1859. const int32_t rindex = fShmNonRtServerControl.readInt();
  1860. const uint32_t type = fShmNonRtServerControl.readUInt();
  1861. const uint32_t hints = fShmNonRtServerControl.readUInt();
  1862. const int16_t ctrl = fShmNonRtServerControl.readShort();
  1863. CARLA_SAFE_ASSERT_INT_BREAK(ctrl >= CONTROL_INDEX_NONE && ctrl <= CONTROL_INDEX_MAX_ALLOWED, ctrl);
  1864. CARLA_SAFE_ASSERT_UINT2_BREAK(index < pData->param.count, index, pData->param.count);
  1865. pData->param.data[index].type = static_cast<ParameterType>(type);
  1866. pData->param.data[index].index = static_cast<int32_t>(index);
  1867. pData->param.data[index].rindex = rindex;
  1868. pData->param.data[index].hints = hints;
  1869. pData->param.data[index].mappedControlIndex = ctrl;
  1870. } break;
  1871. case kPluginBridgeNonRtServerParameterData2: {
  1872. // uint/index, uint/size, str[] (name), uint/size, str[] (unit)
  1873. const uint32_t index = fShmNonRtServerControl.readUInt();
  1874. // name
  1875. const BridgeTextReader name(fShmNonRtServerControl);
  1876. // symbol
  1877. const BridgeTextReader symbol(fShmNonRtServerControl);
  1878. // unit
  1879. const BridgeTextReader unit(fShmNonRtServerControl);
  1880. CARLA_SAFE_ASSERT_UINT2_BREAK(index < pData->param.count, index, pData->param.count);
  1881. fParams[index].name = name.text;
  1882. fParams[index].symbol = symbol.text;
  1883. fParams[index].unit = unit.text;
  1884. } break;
  1885. case kPluginBridgeNonRtServerParameterRanges: {
  1886. // uint/index, float/def, float/min, float/max, float/step, float/stepSmall, float/stepLarge
  1887. const uint32_t index = fShmNonRtServerControl.readUInt();
  1888. const float def = fShmNonRtServerControl.readFloat();
  1889. const float min = fShmNonRtServerControl.readFloat();
  1890. const float max = fShmNonRtServerControl.readFloat();
  1891. const float step = fShmNonRtServerControl.readFloat();
  1892. const float stepSmall = fShmNonRtServerControl.readFloat();
  1893. const float stepLarge = fShmNonRtServerControl.readFloat();
  1894. CARLA_SAFE_ASSERT_BREAK(min < max);
  1895. CARLA_SAFE_ASSERT_BREAK(def >= min);
  1896. CARLA_SAFE_ASSERT_BREAK(def <= max);
  1897. CARLA_SAFE_ASSERT_UINT2_BREAK(index < pData->param.count, index, pData->param.count);
  1898. pData->param.ranges[index].def = def;
  1899. pData->param.ranges[index].min = min;
  1900. pData->param.ranges[index].max = max;
  1901. pData->param.ranges[index].step = step;
  1902. pData->param.ranges[index].stepSmall = stepSmall;
  1903. pData->param.ranges[index].stepLarge = stepLarge;
  1904. } break;
  1905. case kPluginBridgeNonRtServerParameterValue: {
  1906. // uint/index, float/value
  1907. const uint32_t index = fShmNonRtServerControl.readUInt();
  1908. const float value = fShmNonRtServerControl.readFloat();
  1909. if (index < pData->param.count)
  1910. {
  1911. const float fixedValue(pData->param.getFixedValue(index, value));
  1912. if (carla_isNotEqual(fParams[index].value, fixedValue))
  1913. {
  1914. fParams[index].value = fixedValue;
  1915. CarlaPlugin::setParameterValue(index, fixedValue, false, true, true);
  1916. }
  1917. }
  1918. } break;
  1919. case kPluginBridgeNonRtServerParameterValue2: {
  1920. // uint/index, float/value
  1921. const uint32_t index = fShmNonRtServerControl.readUInt();
  1922. const float value = fShmNonRtServerControl.readFloat();
  1923. if (index < pData->param.count)
  1924. {
  1925. const float fixedValue(pData->param.getFixedValue(index, value));
  1926. fParams[index].value = fixedValue;
  1927. }
  1928. } break;
  1929. case kPluginBridgeNonRtServerParameterTouch: {
  1930. // uint/index, bool/touch
  1931. const uint32_t index = fShmNonRtServerControl.readUInt();
  1932. const bool touch = fShmNonRtServerControl.readBool();
  1933. pData->engine->touchPluginParameter(pData->id, index, touch);
  1934. } break;
  1935. case kPluginBridgeNonRtServerDefaultValue: {
  1936. // uint/index, float/value
  1937. const uint32_t index = fShmNonRtServerControl.readUInt();
  1938. const float value = fShmNonRtServerControl.readFloat();
  1939. if (index < pData->param.count)
  1940. pData->param.ranges[index].def = value;
  1941. } break;
  1942. case kPluginBridgeNonRtServerCurrentProgram: {
  1943. // int/index
  1944. const int32_t index = fShmNonRtServerControl.readInt();
  1945. CARLA_SAFE_ASSERT_BREAK(index >= -1);
  1946. CARLA_SAFE_ASSERT_INT2(index < static_cast<int32_t>(pData->prog.count), index, pData->prog.count);
  1947. CarlaPlugin::setProgram(index, false, true, true);
  1948. } break;
  1949. case kPluginBridgeNonRtServerCurrentMidiProgram: {
  1950. // int/index
  1951. const int32_t index = fShmNonRtServerControl.readInt();
  1952. CARLA_SAFE_ASSERT_BREAK(index >= -1);
  1953. CARLA_SAFE_ASSERT_INT2(index < static_cast<int32_t>(pData->midiprog.count), index, pData->midiprog.count);
  1954. CarlaPlugin::setMidiProgram(index, false, true, true);
  1955. } break;
  1956. case kPluginBridgeNonRtServerProgramName: {
  1957. // uint/index, uint/size, str[] (name)
  1958. const uint32_t index = fShmNonRtServerControl.readUInt();
  1959. // name
  1960. const BridgeTextReader name(fShmNonRtServerControl);
  1961. CARLA_SAFE_ASSERT_INT2(index < pData->prog.count, index, pData->prog.count);
  1962. if (index < pData->prog.count)
  1963. {
  1964. if (pData->prog.names[index] != nullptr)
  1965. delete[] pData->prog.names[index];
  1966. pData->prog.names[index] = carla_strdup(name.text);
  1967. }
  1968. } break;
  1969. case kPluginBridgeNonRtServerMidiProgramData: {
  1970. // uint/index, uint/bank, uint/program, uint/size, str[] (name)
  1971. const uint32_t index = fShmNonRtServerControl.readUInt();
  1972. const uint32_t bank = fShmNonRtServerControl.readUInt();
  1973. const uint32_t program = fShmNonRtServerControl.readUInt();
  1974. // name
  1975. const BridgeTextReader name(fShmNonRtServerControl);
  1976. CARLA_SAFE_ASSERT_INT2(index < pData->midiprog.count, index, pData->midiprog.count);
  1977. if (index < pData->midiprog.count)
  1978. {
  1979. if (pData->midiprog.data[index].name != nullptr)
  1980. delete[] pData->midiprog.data[index].name;
  1981. pData->midiprog.data[index].bank = bank;
  1982. pData->midiprog.data[index].program = program;
  1983. pData->midiprog.data[index].name = carla_strdup(name.text);
  1984. }
  1985. } break;
  1986. case kPluginBridgeNonRtServerSetCustomData: {
  1987. // uint/size, str[], uint/size, str[], uint/size, str[]
  1988. // type
  1989. const BridgeTextReader type(fShmNonRtServerControl);
  1990. // key
  1991. const BridgeTextReader key(fShmNonRtServerControl);
  1992. // value
  1993. const uint32_t valueSize = fShmNonRtServerControl.readUInt();
  1994. // special case for big values
  1995. if (valueSize > 16384)
  1996. {
  1997. const BridgeTextReader bigValueFilePath(fShmNonRtServerControl);
  1998. String realBigValueFilePath(bigValueFilePath.text);
  1999. #ifndef CARLA_OS_WIN
  2000. // Using Wine, fix temp dir
  2001. if (fBinaryType == BINARY_WIN32 || fBinaryType == BINARY_WIN64)
  2002. {
  2003. const StringArray driveLetterSplit(StringArray::fromTokens(realBigValueFilePath, ":/", ""));
  2004. carla_stdout("big value save path BEFORE => %s", realBigValueFilePath.toRawUTF8());
  2005. realBigValueFilePath = fWinePrefix;
  2006. realBigValueFilePath += "/drive_";
  2007. realBigValueFilePath += driveLetterSplit[0].toLowerCase();
  2008. realBigValueFilePath += driveLetterSplit[1];
  2009. realBigValueFilePath = realBigValueFilePath.replace("\\", "/");
  2010. carla_stdout("big value save path AFTER => %s", realBigValueFilePath.toRawUTF8());
  2011. }
  2012. #endif
  2013. const File bigValueFile(realBigValueFilePath);
  2014. CARLA_SAFE_ASSERT_BREAK(bigValueFile.existsAsFile());
  2015. CarlaPlugin::setCustomData(type.text, key.text, bigValueFile.loadFileAsString().toRawUTF8(), false);
  2016. bigValueFile.deleteFile();
  2017. }
  2018. else
  2019. {
  2020. const BridgeTextReader value(fShmNonRtServerControl, valueSize);
  2021. CarlaPlugin::setCustomData(type.text, key.text, value.text, false);
  2022. }
  2023. } break;
  2024. case kPluginBridgeNonRtServerSetChunkDataFile: {
  2025. // uint/size, str[] (filename)
  2026. // chunkFilePath
  2027. const BridgeTextReader chunkFilePath(fShmNonRtServerControl);
  2028. String realChunkFilePath(chunkFilePath.text);
  2029. #ifndef CARLA_OS_WIN
  2030. // Using Wine, fix temp dir
  2031. if (fBinaryType == BINARY_WIN32 || fBinaryType == BINARY_WIN64)
  2032. {
  2033. const StringArray driveLetterSplit(StringArray::fromTokens(realChunkFilePath, ":/", ""));
  2034. carla_stdout("chunk save path BEFORE => %s", realChunkFilePath.toRawUTF8());
  2035. realChunkFilePath = fWinePrefix;
  2036. realChunkFilePath += "/drive_";
  2037. realChunkFilePath += driveLetterSplit[0].toLowerCase();
  2038. realChunkFilePath += driveLetterSplit[1];
  2039. realChunkFilePath = realChunkFilePath.replace("\\", "/");
  2040. carla_stdout("chunk save path AFTER => %s", realChunkFilePath.toRawUTF8());
  2041. }
  2042. #endif
  2043. const File chunkFile(realChunkFilePath);
  2044. CARLA_SAFE_ASSERT_BREAK(chunkFile.existsAsFile());
  2045. fInfo.chunk = carla_getChunkFromBase64String(chunkFile.loadFileAsString().toRawUTF8());
  2046. chunkFile.deleteFile();
  2047. } break;
  2048. case kPluginBridgeNonRtServerSetLatency:
  2049. // uint
  2050. fLatency = fShmNonRtServerControl.readUInt();
  2051. #ifndef BUILD_BRIDGE
  2052. if (! fInitiated)
  2053. pData->latency.recreateBuffers(std::max(fInfo.aIns, fInfo.aOuts), fLatency);
  2054. #endif
  2055. break;
  2056. case kPluginBridgeNonRtServerSetParameterText: {
  2057. const int32_t index = fShmNonRtServerControl.readInt();
  2058. const uint32_t textSize = fShmNonRtServerControl.readUInt();
  2059. const BridgeTextReader text(fShmNonRtServerControl, textSize);
  2060. fReceivingParamText.setReceivedData(index, text.text, textSize);
  2061. } break;
  2062. case kPluginBridgeNonRtServerReady:
  2063. fInitiated = true;
  2064. break;
  2065. case kPluginBridgeNonRtServerSaved:
  2066. fSaved = true;
  2067. break;
  2068. case kPluginBridgeNonRtServerRespEmbedUI:
  2069. fPendingEmbedCustomUI = fShmNonRtServerControl.readULong();
  2070. break;
  2071. case kPluginBridgeNonRtServerResizeEmbedUI: {
  2072. const uint width = fShmNonRtServerControl.readUInt();
  2073. const uint height = fShmNonRtServerControl.readUInt();
  2074. pData->engine->callback(true, true, ENGINE_CALLBACK_EMBED_UI_RESIZED, pData->id,
  2075. static_cast<int>(width), static_cast<int>(height),
  2076. 0, 0.0f, nullptr);
  2077. } break;
  2078. case kPluginBridgeNonRtServerUiClosed:
  2079. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  2080. pData->transientTryCounter = 0;
  2081. #endif
  2082. pData->engine->callback(true, true, ENGINE_CALLBACK_UI_STATE_CHANGED, pData->id,
  2083. 0, 0, 0, 0.0f, nullptr);
  2084. break;
  2085. case kPluginBridgeNonRtServerError: {
  2086. // error
  2087. const BridgeTextReader error(fShmNonRtServerControl);
  2088. if (fInitiated)
  2089. {
  2090. pData->engine->callback(true, true, ENGINE_CALLBACK_ERROR, pData->id, 0, 0, 0, 0.0f, error.text);
  2091. // just in case
  2092. pData->engine->setLastError(error.text);
  2093. fInitError = true;
  2094. }
  2095. else
  2096. {
  2097. pData->engine->setLastError(error.text);
  2098. fInitError = true;
  2099. fInitiated = true;
  2100. }
  2101. } break;
  2102. }
  2103. }
  2104. }
  2105. // -------------------------------------------------------------------
  2106. uintptr_t getUiBridgeProcessId() const noexcept override
  2107. {
  2108. return fBridgeThread.getProcessPID();
  2109. }
  2110. const void* getExtraStuff() const noexcept override
  2111. {
  2112. return fBridgeBinary.isNotEmpty() ? fBridgeBinary.buffer() : nullptr;
  2113. }
  2114. // -------------------------------------------------------------------
  2115. bool init(CarlaPluginPtr plugin,
  2116. const char* const filename,
  2117. const char* const name,
  2118. const char* const label,
  2119. const int64_t uniqueId,
  2120. const uint options,
  2121. const char* const binaryArchName,
  2122. const char* const bridgeBinary)
  2123. {
  2124. CARLA_SAFE_ASSERT_RETURN(pData->engine != nullptr, false);
  2125. // ---------------------------------------------------------------
  2126. // first checks
  2127. if (pData->client != nullptr)
  2128. {
  2129. pData->engine->setLastError("Plugin client is already registered");
  2130. return false;
  2131. }
  2132. if (bridgeBinary == nullptr || bridgeBinary[0] == '\0')
  2133. {
  2134. pData->engine->setLastError("null bridge binary");
  2135. return false;
  2136. }
  2137. // ---------------------------------------------------------------
  2138. // set info
  2139. if (name != nullptr && name[0] != '\0')
  2140. pData->name = pData->engine->getUniquePluginName(name);
  2141. if (filename != nullptr && filename[0] != '\0')
  2142. pData->filename = carla_strdup(filename);
  2143. else
  2144. pData->filename = carla_strdup("");
  2145. fUniqueId = uniqueId;
  2146. fBridgeBinary = bridgeBinary;
  2147. std::srand(static_cast<uint>(std::time(nullptr)));
  2148. // ---------------------------------------------------------------
  2149. // init sem/shm
  2150. if (! fShmAudioPool.initializeServer())
  2151. {
  2152. carla_stderr("Failed to initialize shared memory audio pool");
  2153. return false;
  2154. }
  2155. if (! fShmRtClientControl.initializeServer())
  2156. {
  2157. carla_stderr("Failed to initialize RT client control");
  2158. fShmAudioPool.clear();
  2159. return false;
  2160. }
  2161. if (! fShmNonRtClientControl.initializeServer())
  2162. {
  2163. carla_stderr("Failed to initialize Non-RT client control");
  2164. fShmRtClientControl.clear();
  2165. fShmAudioPool.clear();
  2166. return false;
  2167. }
  2168. if (! fShmNonRtServerControl.initializeServer())
  2169. {
  2170. carla_stderr("Failed to initialize Non-RT server control");
  2171. fShmNonRtClientControl.clear();
  2172. fShmRtClientControl.clear();
  2173. fShmAudioPool.clear();
  2174. return false;
  2175. }
  2176. #ifndef CARLA_OS_WIN
  2177. // ---------------------------------------------------------------
  2178. // set wine prefix
  2179. if (fBridgeBinary.contains(".exe", true))
  2180. {
  2181. const EngineOptions& engineOptions(pData->engine->getOptions());
  2182. if (engineOptions.wine.autoPrefix)
  2183. fWinePrefix = findWinePrefix(pData->filename);
  2184. if (fWinePrefix.isEmpty())
  2185. {
  2186. const char* const envWinePrefix(std::getenv("WINEPREFIX"));
  2187. if (envWinePrefix != nullptr && envWinePrefix[0] != '\0')
  2188. fWinePrefix = envWinePrefix;
  2189. else if (engineOptions.wine.fallbackPrefix != nullptr && engineOptions.wine.fallbackPrefix[0] != '\0')
  2190. fWinePrefix = engineOptions.wine.fallbackPrefix;
  2191. else
  2192. fWinePrefix = File::getSpecialLocation(File::userHomeDirectory).getFullPathName() + "/.wine";
  2193. }
  2194. }
  2195. #endif
  2196. // ---------------------------------------------------------------
  2197. // init bridge thread
  2198. {
  2199. char shmIdsStr[6*4+1];
  2200. carla_zeroChars(shmIdsStr, 6*4+1);
  2201. std::strncpy(shmIdsStr+6*0, &fShmAudioPool.filename[fShmAudioPool.filename.length()-6], 6);
  2202. std::strncpy(shmIdsStr+6*1, &fShmRtClientControl.filename[fShmRtClientControl.filename.length()-6], 6);
  2203. std::strncpy(shmIdsStr+6*2, &fShmNonRtClientControl.filename[fShmNonRtClientControl.filename.length()-6], 6);
  2204. std::strncpy(shmIdsStr+6*3, &fShmNonRtServerControl.filename[fShmNonRtServerControl.filename.length()-6], 6);
  2205. fBridgeThread.setData(
  2206. #ifndef CARLA_OS_WIN
  2207. fWinePrefix.toRawUTF8(),
  2208. #endif
  2209. binaryArchName, bridgeBinary, label, shmIdsStr);
  2210. }
  2211. if (! restartBridgeThread())
  2212. return false;
  2213. // ---------------------------------------------------------------
  2214. // register client
  2215. if (pData->name == nullptr)
  2216. {
  2217. if (label != nullptr && label[0] != '\0')
  2218. pData->name = pData->engine->getUniquePluginName(label);
  2219. else
  2220. pData->name = pData->engine->getUniquePluginName("unknown");
  2221. }
  2222. pData->client = pData->engine->addClient(plugin);
  2223. if (pData->client == nullptr || ! pData->client->isOk())
  2224. {
  2225. pData->engine->setLastError("Failed to register plugin client");
  2226. return false;
  2227. }
  2228. // ---------------------------------------------------------------
  2229. // set options
  2230. pData->options = 0x0;
  2231. if ((fInfo.optionsAvailable & PLUGIN_OPTION_FIXED_BUFFERS) == 0x0)
  2232. pData->options |= PLUGIN_OPTION_FIXED_BUFFERS;
  2233. else if (isPluginOptionEnabled(options, PLUGIN_OPTION_FIXED_BUFFERS))
  2234. pData->options |= PLUGIN_OPTION_FIXED_BUFFERS;
  2235. if (pData->engine->getOptions().forceStereo)
  2236. {
  2237. pData->options |= PLUGIN_OPTION_FORCE_STEREO;
  2238. }
  2239. else if (fInfo.optionsAvailable & PLUGIN_OPTION_FORCE_STEREO)
  2240. {
  2241. if (options & PLUGIN_OPTION_FORCE_STEREO)
  2242. pData->options |= PLUGIN_OPTION_FORCE_STEREO;
  2243. }
  2244. if (fInfo.optionsAvailable & PLUGIN_OPTION_USE_CHUNKS)
  2245. if (isPluginOptionEnabled(options, PLUGIN_OPTION_USE_CHUNKS))
  2246. pData->options |= PLUGIN_OPTION_USE_CHUNKS;
  2247. if (fInfo.optionsAvailable & PLUGIN_OPTION_SEND_CONTROL_CHANGES)
  2248. if (isPluginOptionEnabled(options, PLUGIN_OPTION_SEND_CONTROL_CHANGES))
  2249. pData->options |= PLUGIN_OPTION_SEND_CONTROL_CHANGES;
  2250. if (fInfo.optionsAvailable & PLUGIN_OPTION_SEND_CHANNEL_PRESSURE)
  2251. if (isPluginOptionEnabled(options, PLUGIN_OPTION_SEND_CHANNEL_PRESSURE))
  2252. pData->options |= PLUGIN_OPTION_SEND_CHANNEL_PRESSURE;
  2253. if (fInfo.optionsAvailable & PLUGIN_OPTION_SEND_NOTE_AFTERTOUCH)
  2254. if (isPluginOptionEnabled(options, PLUGIN_OPTION_SEND_NOTE_AFTERTOUCH))
  2255. pData->options |= PLUGIN_OPTION_SEND_NOTE_AFTERTOUCH;
  2256. if (fInfo.optionsAvailable & PLUGIN_OPTION_SEND_PITCHBEND)
  2257. if (isPluginOptionEnabled(options, PLUGIN_OPTION_SEND_PITCHBEND))
  2258. pData->options |= PLUGIN_OPTION_SEND_PITCHBEND;
  2259. if (fInfo.optionsAvailable & PLUGIN_OPTION_SEND_ALL_SOUND_OFF)
  2260. if (isPluginOptionEnabled(options, PLUGIN_OPTION_SEND_ALL_SOUND_OFF))
  2261. pData->options |= PLUGIN_OPTION_SEND_ALL_SOUND_OFF;
  2262. if (fInfo.optionsAvailable & PLUGIN_OPTION_SKIP_SENDING_NOTES)
  2263. if (isPluginOptionInverseEnabled(options, PLUGIN_OPTION_SKIP_SENDING_NOTES))
  2264. pData->options |= PLUGIN_OPTION_SKIP_SENDING_NOTES;
  2265. if (fInfo.optionsAvailable & PLUGIN_OPTION_SEND_PROGRAM_CHANGES)
  2266. {
  2267. if (isPluginOptionEnabled(options, PLUGIN_OPTION_SEND_PROGRAM_CHANGES))
  2268. pData->options |= PLUGIN_OPTION_SEND_PROGRAM_CHANGES;
  2269. }
  2270. else if (fInfo.optionsAvailable & PLUGIN_OPTION_MAP_PROGRAM_CHANGES)
  2271. {
  2272. if (isPluginOptionEnabled(options, PLUGIN_OPTION_MAP_PROGRAM_CHANGES))
  2273. pData->options |= PLUGIN_OPTION_MAP_PROGRAM_CHANGES;
  2274. }
  2275. // kPluginBridgeNonRtClientSetOptions was added in API 7
  2276. if (fBridgeVersion >= 7)
  2277. {
  2278. const CarlaMutexLocker _cml(fShmNonRtClientControl.mutex);
  2279. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientSetOptions);
  2280. fShmNonRtClientControl.writeUInt(pData->options);
  2281. fShmNonRtClientControl.commitWrite();
  2282. }
  2283. return true;
  2284. }
  2285. private:
  2286. const BinaryType fBinaryType;
  2287. const PluginType fPluginType;
  2288. uint fBridgeVersion;
  2289. bool fInitiated;
  2290. bool fInitError;
  2291. bool fSaved;
  2292. bool fTimedOut;
  2293. bool fTimedError;
  2294. uint fBufferSize;
  2295. uint fProcWaitTime;
  2296. uint64_t fPendingEmbedCustomUI;
  2297. CarlaString fBridgeBinary;
  2298. CarlaPluginBridgeThread fBridgeThread;
  2299. BridgeAudioPool fShmAudioPool;
  2300. BridgeRtClientControl fShmRtClientControl;
  2301. BridgeNonRtClientControl fShmNonRtClientControl;
  2302. BridgeNonRtServerControl fShmNonRtServerControl;
  2303. #ifndef CARLA_OS_WIN
  2304. String fWinePrefix;
  2305. #endif
  2306. class ReceivingParamText {
  2307. public:
  2308. ReceivingParamText() noexcept
  2309. : dataRecv(false),
  2310. dataOk(false),
  2311. index(-1),
  2312. strBuf(nullptr),
  2313. mutex() {}
  2314. bool isCurrentlyWaitingData() const noexcept
  2315. {
  2316. return index >= 0;
  2317. }
  2318. bool wasDataReceived(bool* const success) const noexcept
  2319. {
  2320. *success = dataOk;
  2321. return dataRecv;
  2322. }
  2323. void setTargetData(const int32_t i, char* const b) noexcept
  2324. {
  2325. const CarlaMutexLocker cml(mutex);
  2326. dataOk = false;
  2327. dataRecv = false;
  2328. index = i;
  2329. strBuf = b;
  2330. }
  2331. void setReceivedData(const int32_t i, const char* const b, const uint blen) noexcept
  2332. {
  2333. CarlaScopedValueSetter<bool> svs(dataRecv, false, true);
  2334. const CarlaMutexLocker cml(mutex);
  2335. // make backup and reset data
  2336. const int32_t indexCopy = index;
  2337. char* const strBufCopy = strBuf;
  2338. index = -1;
  2339. strBuf = nullptr;
  2340. CARLA_SAFE_ASSERT_RETURN(indexCopy == i,);
  2341. CARLA_SAFE_ASSERT_RETURN(strBufCopy != nullptr,);
  2342. std::strncpy(strBufCopy, b, std::min(blen, STR_MAX-1U));
  2343. dataOk = true;
  2344. }
  2345. private:
  2346. bool dataRecv;
  2347. bool dataOk;
  2348. int32_t index;
  2349. char* strBuf;
  2350. CarlaMutex mutex;
  2351. CARLA_DECLARE_NON_COPYABLE(ReceivingParamText)
  2352. } fReceivingParamText;
  2353. struct Info {
  2354. uint32_t aIns, aOuts;
  2355. uint32_t cvIns, cvOuts;
  2356. uint32_t mIns, mOuts;
  2357. PluginCategory category;
  2358. uint optionsAvailable;
  2359. CarlaString name;
  2360. CarlaString label;
  2361. CarlaString maker;
  2362. CarlaString copyright;
  2363. const char** aInNames;
  2364. const char** aOutNames;
  2365. const char** cvInNames;
  2366. const char** cvOutNames;
  2367. std::vector<uint8_t> chunk;
  2368. Info()
  2369. : aIns(0),
  2370. aOuts(0),
  2371. cvIns(0),
  2372. cvOuts(0),
  2373. mIns(0),
  2374. mOuts(0),
  2375. category(PLUGIN_CATEGORY_NONE),
  2376. optionsAvailable(0),
  2377. name(),
  2378. label(),
  2379. maker(),
  2380. copyright(),
  2381. aInNames(nullptr),
  2382. aOutNames(nullptr),
  2383. cvInNames(nullptr),
  2384. cvOutNames(nullptr),
  2385. chunk() {}
  2386. ~Info()
  2387. {
  2388. clear();
  2389. }
  2390. void clear()
  2391. {
  2392. if (aInNames != nullptr)
  2393. {
  2394. CARLA_SAFE_ASSERT_INT(aIns > 0, aIns);
  2395. for (uint32_t i=0; i<aIns; ++i)
  2396. delete[] aInNames[i];
  2397. delete[] aInNames;
  2398. aInNames = nullptr;
  2399. }
  2400. if (aOutNames != nullptr)
  2401. {
  2402. CARLA_SAFE_ASSERT_INT(aOuts > 0, aOuts);
  2403. for (uint32_t i=0; i<aOuts; ++i)
  2404. delete[] aOutNames[i];
  2405. delete[] aOutNames;
  2406. aOutNames = nullptr;
  2407. }
  2408. if (cvInNames != nullptr)
  2409. {
  2410. CARLA_SAFE_ASSERT_INT(cvIns > 0, cvIns);
  2411. for (uint32_t i=0; i<cvIns; ++i)
  2412. delete[] cvInNames[i];
  2413. delete[] cvInNames;
  2414. cvInNames = nullptr;
  2415. }
  2416. if (cvOutNames != nullptr)
  2417. {
  2418. CARLA_SAFE_ASSERT_INT(cvOuts > 0, cvOuts);
  2419. for (uint32_t i=0; i<cvOuts; ++i)
  2420. delete[] cvOutNames[i];
  2421. delete[] cvOutNames;
  2422. cvOutNames = nullptr;
  2423. }
  2424. aIns = aOuts = cvIns = cvOuts = 0;
  2425. }
  2426. CARLA_DECLARE_NON_COPYABLE(Info)
  2427. } fInfo;
  2428. int64_t fUniqueId;
  2429. uint32_t fLatency;
  2430. BridgeParamInfo* fParams;
  2431. void handleProcessStopped() noexcept
  2432. {
  2433. const bool wasActive = pData->active;
  2434. pData->active = false;
  2435. if (wasActive)
  2436. {
  2437. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  2438. pData->engine->callback(true, true,
  2439. ENGINE_CALLBACK_PARAMETER_VALUE_CHANGED,
  2440. pData->id,
  2441. PARAMETER_ACTIVE,
  2442. 0, 0,
  2443. 0.0f,
  2444. nullptr);
  2445. #endif
  2446. }
  2447. if (pData->hints & PLUGIN_HAS_CUSTOM_UI)
  2448. {
  2449. pData->engine->callback(true, true,
  2450. ENGINE_CALLBACK_UI_STATE_CHANGED,
  2451. pData->id,
  2452. 0,
  2453. 0, 0, 0.0f, nullptr);
  2454. }
  2455. }
  2456. void resizeAudioPool(const uint32_t bufferSize)
  2457. {
  2458. fShmAudioPool.resize(bufferSize, fInfo.aIns+fInfo.aOuts, fInfo.cvIns+fInfo.cvOuts);
  2459. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientSetAudioPool);
  2460. fShmRtClientControl.writeULong(static_cast<uint64_t>(fShmAudioPool.dataSize));
  2461. fShmRtClientControl.commitWrite();
  2462. waitForClient("resize-pool", 5000);
  2463. }
  2464. void waitForClient(const char* const action, const uint msecs)
  2465. {
  2466. CARLA_SAFE_ASSERT_RETURN(! fTimedOut,);
  2467. CARLA_SAFE_ASSERT_RETURN(! fTimedError,);
  2468. if (fShmRtClientControl.waitForClient(msecs))
  2469. return;
  2470. fTimedOut = true;
  2471. carla_stderr2("waitForClient(%s) timed out", action);
  2472. }
  2473. bool restartBridgeThread()
  2474. {
  2475. fInitiated = false;
  2476. fInitError = false;
  2477. fTimedError = false;
  2478. // reset memory
  2479. fShmRtClientControl.data->procFlags = 0;
  2480. carla_zeroStruct(fShmRtClientControl.data->timeInfo);
  2481. carla_zeroBytes(fShmRtClientControl.data->midiOut, kBridgeRtClientDataMidiOutSize);
  2482. fShmRtClientControl.clearData();
  2483. fShmNonRtClientControl.clearData();
  2484. fShmNonRtServerControl.clearData();
  2485. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientVersion);
  2486. fShmNonRtClientControl.writeUInt(CARLA_PLUGIN_BRIDGE_API_VERSION_CURRENT);
  2487. fShmNonRtClientControl.writeUInt(static_cast<uint32_t>(sizeof(BridgeRtClientData)));
  2488. fShmNonRtClientControl.writeUInt(static_cast<uint32_t>(sizeof(BridgeNonRtClientData)));
  2489. fShmNonRtClientControl.writeUInt(static_cast<uint32_t>(sizeof(BridgeNonRtServerData)));
  2490. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientInitialSetup);
  2491. fShmNonRtClientControl.writeUInt(pData->engine->getBufferSize());
  2492. fShmNonRtClientControl.writeDouble(pData->engine->getSampleRate());
  2493. fShmNonRtClientControl.commitWrite();
  2494. if (fShmAudioPool.dataSize != 0)
  2495. {
  2496. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientSetAudioPool);
  2497. fShmRtClientControl.writeULong(static_cast<uint64_t>(fShmAudioPool.dataSize));
  2498. fShmRtClientControl.commitWrite();
  2499. }
  2500. else
  2501. {
  2502. // testing dummy message
  2503. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientNull);
  2504. fShmRtClientControl.commitWrite();
  2505. }
  2506. fBridgeThread.startThread();
  2507. const bool needsEngineIdle = pData->engine->getType() != kEngineTypePlugin;
  2508. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  2509. const bool needsCancelableAction = ! pData->engine->isLoadingProject();
  2510. if (needsCancelableAction)
  2511. {
  2512. pData->engine->setActionCanceled(false);
  2513. pData->engine->callback(true, true,
  2514. ENGINE_CALLBACK_CANCELABLE_ACTION,
  2515. pData->id,
  2516. 1,
  2517. 0, 0, 0.0f,
  2518. "Loading plugin bridge");
  2519. }
  2520. #endif
  2521. for (;fBridgeThread.isThreadRunning();)
  2522. {
  2523. pData->engine->callback(true, true, ENGINE_CALLBACK_IDLE, 0, 0, 0, 0, 0.0f, nullptr);
  2524. if (needsEngineIdle)
  2525. pData->engine->idle();
  2526. idle();
  2527. if (fInitiated)
  2528. break;
  2529. if (pData->engine->isAboutToClose() || pData->engine->wasActionCanceled())
  2530. break;
  2531. carla_msleep(5);
  2532. }
  2533. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  2534. if (needsCancelableAction)
  2535. {
  2536. pData->engine->callback(true, true,
  2537. ENGINE_CALLBACK_CANCELABLE_ACTION,
  2538. pData->id,
  2539. 0,
  2540. 0, 0, 0.0f,
  2541. "Loading plugin bridge");
  2542. }
  2543. #endif
  2544. if (fInitError || ! fInitiated)
  2545. {
  2546. fBridgeThread.stopThread(6000);
  2547. if (! fInitError)
  2548. pData->engine->setLastError("Timeout while waiting for a response from plugin-bridge\n"
  2549. "(or the plugin crashed on initialization?)");
  2550. return false;
  2551. }
  2552. if (const size_t dataSize = fInfo.chunk.size())
  2553. {
  2554. #ifdef CARLA_PROPER_CPP11_SUPPORT
  2555. void* data = fInfo.chunk.data();
  2556. #else
  2557. void* data = &fInfo.chunk.front();
  2558. #endif
  2559. CarlaString dataBase64(CarlaString::asBase64(data, dataSize));
  2560. CARLA_SAFE_ASSERT_RETURN(dataBase64.length() > 0, true);
  2561. String filePath(File::getSpecialLocation(File::tempDirectory).getFullPathName());
  2562. filePath += CARLA_OS_SEP_STR ".CarlaChunk_";
  2563. filePath += fShmAudioPool.getFilenameSuffix();
  2564. if (File(filePath).replaceWithText(dataBase64.buffer()))
  2565. {
  2566. const uint32_t ulength(static_cast<uint32_t>(filePath.length()));
  2567. const CarlaMutexLocker _cml(fShmNonRtClientControl.mutex);
  2568. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientSetChunkDataFile);
  2569. fShmNonRtClientControl.writeUInt(ulength);
  2570. fShmNonRtClientControl.writeCustomData(filePath.toRawUTF8(), ulength);
  2571. fShmNonRtClientControl.commitWrite();
  2572. }
  2573. }
  2574. return true;
  2575. }
  2576. void _setUiTitleFromName()
  2577. {
  2578. CarlaString uiName(pData->name);
  2579. uiName += " (GUI)";
  2580. const uint32_t size = static_cast<uint32_t>(uiName.length());
  2581. const CarlaMutexLocker _cml(fShmNonRtClientControl.mutex);
  2582. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientSetWindowTitle);
  2583. fShmNonRtClientControl.writeUInt(size);
  2584. fShmNonRtClientControl.writeCustomData(uiName.buffer(), size);
  2585. fShmNonRtClientControl.commitWrite();
  2586. }
  2587. CARLA_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(CarlaPluginBridge)
  2588. };
  2589. CARLA_BACKEND_END_NAMESPACE
  2590. // ---------------------------------------------------------------------------------------------------------------------
  2591. CARLA_BACKEND_START_NAMESPACE
  2592. CarlaPluginPtr CarlaPlugin::newBridge(const Initializer& init,
  2593. const BinaryType btype,
  2594. const PluginType ptype,
  2595. const char* const binaryArchName,
  2596. const char* bridgeBinary)
  2597. {
  2598. carla_debug("CarlaPlugin::newBridge({%p, \"%s\", \"%s\", \"%s\"}, %s, %s, \"%s\", \"%s\")",
  2599. init.engine, init.filename, init.name, init.label,
  2600. BinaryType2Str(btype), PluginType2Str(ptype), binaryArchName, bridgeBinary);
  2601. if (bridgeBinary == nullptr || bridgeBinary[0] == '\0')
  2602. {
  2603. init.engine->setLastError("Bridge not possible, bridge-binary not found");
  2604. return nullptr;
  2605. }
  2606. #ifndef CARLA_OS_WIN
  2607. // FIXME: somewhere, somehow, we end up with double slashes, wine doesn't like that.
  2608. if (std::strncmp(bridgeBinary, "//", 2) == 0)
  2609. ++bridgeBinary;
  2610. #endif
  2611. std::shared_ptr<CarlaPluginBridge> plugin(new CarlaPluginBridge(init.engine, init.id, btype, ptype));
  2612. if (! plugin->init(plugin, init.filename, init.name, init.label, init.uniqueId, init.options, binaryArchName, bridgeBinary))
  2613. return nullptr;
  2614. return plugin;
  2615. }
  2616. CARLA_BACKEND_END_NAMESPACE
  2617. // ---------------------------------------------------------------------------------------------------------------------
  2618. #ifndef BUILD_BRIDGE
  2619. # include "CarlaBridgeUtils.cpp"
  2620. #endif
  2621. // ---------------------------------------------------------------------------------------------------------------------