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.

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