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.

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