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.

2818 lines
99KB

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