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.

2782 lines
97KB

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