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.

3327 lines
119KB

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