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.

2390 lines
86KB

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