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.

2849 lines
100KB

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