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.

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