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.

3090 lines
110KB

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