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.

2462 lines
88KB

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