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.

3312 lines
118KB

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