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.

3057 lines
109KB

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