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.

1846 lines
65KB

  1. /*
  2. * Carla Plugin, LADSPA implementation
  3. * Copyright (C) 2011-2018 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 "CarlaEngine.hpp"
  19. #include "CarlaLadspaUtils.hpp"
  20. #include "CarlaMathUtils.hpp"
  21. CARLA_BACKEND_START_NAMESPACE
  22. // -----------------------------------------------------
  23. class CarlaPluginLADSPA : public CarlaPlugin
  24. {
  25. public:
  26. CarlaPluginLADSPA(CarlaEngine* const engine, const uint id) noexcept
  27. : CarlaPlugin(engine, id),
  28. fHandles(),
  29. fDescriptor(nullptr),
  30. fRdfDescriptor(nullptr),
  31. fAudioInBuffers(nullptr),
  32. fAudioOutBuffers(nullptr),
  33. fExtraStereoBuffer(),
  34. fParamBuffers(nullptr),
  35. fLatencyIndex(-1),
  36. fForcedStereoIn(false),
  37. fForcedStereoOut(false),
  38. fNeedsFixedBuffers(false)
  39. {
  40. carla_debug("CarlaPluginLADSPA::CarlaPluginLADSPA(%p, %i)", engine, id);
  41. carla_zeroPointers(fExtraStereoBuffer, 2);
  42. }
  43. ~CarlaPluginLADSPA() noexcept override
  44. {
  45. carla_debug("CarlaPluginLADSPA::~CarlaPluginLADSPA()");
  46. pData->singleMutex.lock();
  47. pData->masterMutex.lock();
  48. if (pData->client != nullptr && pData->client->isActive())
  49. pData->client->deactivate();
  50. if (pData->active)
  51. {
  52. deactivate();
  53. pData->active = false;
  54. }
  55. if (fDescriptor != nullptr)
  56. {
  57. if (fDescriptor->cleanup != nullptr)
  58. {
  59. for (LinkedList<LADSPA_Handle>::Itenerator it = fHandles.begin2(); it.valid(); it.next())
  60. {
  61. LADSPA_Handle const handle(it.getValue(nullptr));
  62. CARLA_SAFE_ASSERT_CONTINUE(handle != nullptr);
  63. try {
  64. fDescriptor->cleanup(handle);
  65. } CARLA_SAFE_EXCEPTION("LADSPA cleanup");
  66. }
  67. }
  68. fHandles.clear();
  69. fDescriptor = nullptr;
  70. }
  71. if (fRdfDescriptor != nullptr)
  72. {
  73. delete fRdfDescriptor;
  74. fRdfDescriptor = nullptr;
  75. }
  76. clearBuffers();
  77. }
  78. // -------------------------------------------------------------------
  79. // Information (base)
  80. PluginType getType() const noexcept override
  81. {
  82. return PLUGIN_LADSPA;
  83. }
  84. PluginCategory getCategory() const noexcept override
  85. {
  86. if (fRdfDescriptor != nullptr)
  87. {
  88. const LADSPA_PluginType category(fRdfDescriptor->Type);
  89. // Specific Types
  90. if (category & (LADSPA_PLUGIN_DELAY|LADSPA_PLUGIN_REVERB))
  91. return PLUGIN_CATEGORY_DELAY;
  92. if (category & (LADSPA_PLUGIN_PHASER|LADSPA_PLUGIN_FLANGER|LADSPA_PLUGIN_CHORUS))
  93. return PLUGIN_CATEGORY_MODULATOR;
  94. if (category & (LADSPA_PLUGIN_AMPLIFIER))
  95. return PLUGIN_CATEGORY_DYNAMICS;
  96. if (category & (LADSPA_PLUGIN_UTILITY|LADSPA_PLUGIN_SPECTRAL|LADSPA_PLUGIN_FREQUENCY_METER))
  97. return PLUGIN_CATEGORY_UTILITY;
  98. // Pre-set LADSPA Types
  99. if (LADSPA_IS_PLUGIN_DYNAMICS(category))
  100. return PLUGIN_CATEGORY_DYNAMICS;
  101. if (LADSPA_IS_PLUGIN_AMPLITUDE(category))
  102. return PLUGIN_CATEGORY_MODULATOR;
  103. if (LADSPA_IS_PLUGIN_EQ(category))
  104. return PLUGIN_CATEGORY_EQ;
  105. if (LADSPA_IS_PLUGIN_FILTER(category))
  106. return PLUGIN_CATEGORY_FILTER;
  107. if (LADSPA_IS_PLUGIN_FREQUENCY(category))
  108. return PLUGIN_CATEGORY_UTILITY;
  109. if (LADSPA_IS_PLUGIN_SIMULATOR(category))
  110. return PLUGIN_CATEGORY_OTHER;
  111. if (LADSPA_IS_PLUGIN_TIME(category))
  112. return PLUGIN_CATEGORY_DELAY;
  113. if (LADSPA_IS_PLUGIN_GENERATOR(category))
  114. return PLUGIN_CATEGORY_SYNTH;
  115. }
  116. return CarlaPlugin::getCategory();
  117. }
  118. int64_t getUniqueId() const noexcept override
  119. {
  120. CARLA_SAFE_ASSERT_RETURN(fDescriptor != nullptr, 0);
  121. return static_cast<int64_t>(fDescriptor->UniqueID);
  122. }
  123. uint32_t getLatencyInFrames() const noexcept override
  124. {
  125. if (fLatencyIndex < 0 || fParamBuffers == nullptr)
  126. return 0;
  127. const float latency(fParamBuffers[fLatencyIndex]);
  128. CARLA_SAFE_ASSERT_RETURN(latency >= 0.0f, 0);
  129. return static_cast<uint32_t>(latency);
  130. }
  131. // -------------------------------------------------------------------
  132. // Information (count)
  133. uint32_t getParameterScalePointCount(const uint32_t parameterId) const noexcept override
  134. {
  135. CARLA_SAFE_ASSERT_RETURN(parameterId < pData->param.count, 0);
  136. if (fRdfDescriptor == nullptr)
  137. return 0;
  138. const int32_t rindex(pData->param.data[parameterId].rindex);
  139. CARLA_SAFE_ASSERT_RETURN(rindex >= 0, 0);
  140. if (rindex >= static_cast<int32_t>(fRdfDescriptor->PortCount))
  141. return 0;
  142. const LADSPA_RDF_Port& port(fRdfDescriptor->Ports[rindex]);
  143. return static_cast<uint32_t>(port.ScalePointCount);
  144. }
  145. // -------------------------------------------------------------------
  146. // Information (current data)
  147. // nothing
  148. // -------------------------------------------------------------------
  149. // Information (per-plugin data)
  150. uint getOptionsAvailable() const noexcept override
  151. {
  152. uint options = 0x0;
  153. // can't disable fixed buffers if using latency
  154. if (fLatencyIndex == -1 && ! fNeedsFixedBuffers)
  155. options |= PLUGIN_OPTION_FIXED_BUFFERS;
  156. // can't disable forced stereo if enabled in the engine
  157. if (pData->engine->getOptions().forceStereo)
  158. pass();
  159. // if inputs or outputs are just 1, then yes we can force stereo
  160. else if (pData->audioIn.count == 1 || pData->audioOut.count == 1 || fForcedStereoIn || fForcedStereoOut)
  161. options |= PLUGIN_OPTION_FORCE_STEREO;
  162. return options;
  163. }
  164. float getParameterValue(const uint32_t parameterId) const noexcept override
  165. {
  166. CARLA_SAFE_ASSERT_RETURN(fParamBuffers != nullptr, 0.0f);
  167. CARLA_SAFE_ASSERT_RETURN(parameterId < pData->param.count, 0.0f);
  168. // bad plugins might have set output values out of bounds
  169. if (pData->param.data[parameterId].type == PARAMETER_OUTPUT)
  170. return pData->param.ranges[parameterId].getFixedValue(fParamBuffers[parameterId]);
  171. // not output, should be fine
  172. return fParamBuffers[parameterId];
  173. }
  174. float getParameterScalePointValue(const uint32_t parameterId, const uint32_t scalePointId) const noexcept override
  175. {
  176. CARLA_SAFE_ASSERT_RETURN(fRdfDescriptor != nullptr, 0.0f);
  177. CARLA_SAFE_ASSERT_RETURN(parameterId < pData->param.count, 0.0f);
  178. const int32_t rindex(pData->param.data[parameterId].rindex);
  179. CARLA_SAFE_ASSERT_RETURN(rindex >= 0, 0.0f);
  180. CARLA_SAFE_ASSERT_RETURN(rindex < static_cast<int32_t>(fRdfDescriptor->PortCount), 0.0f);
  181. const LADSPA_RDF_Port& port(fRdfDescriptor->Ports[rindex]);
  182. CARLA_SAFE_ASSERT_RETURN(scalePointId < port.ScalePointCount, 0.0f);
  183. const LADSPA_RDF_ScalePoint& scalePoint(port.ScalePoints[scalePointId]);
  184. return pData->param.ranges[parameterId].getFixedValue(scalePoint.Value);
  185. }
  186. void getLabel(char* const strBuf) const noexcept override
  187. {
  188. CARLA_SAFE_ASSERT_RETURN(fDescriptor != nullptr, nullStrBuf(strBuf));
  189. CARLA_SAFE_ASSERT_RETURN(fDescriptor->Label != nullptr, nullStrBuf(strBuf));
  190. std::strncpy(strBuf, fDescriptor->Label, STR_MAX);
  191. }
  192. void getMaker(char* const strBuf) const noexcept override
  193. {
  194. CARLA_SAFE_ASSERT_RETURN(fDescriptor != nullptr, nullStrBuf(strBuf));
  195. CARLA_SAFE_ASSERT_RETURN(fDescriptor->Maker != nullptr, nullStrBuf(strBuf));
  196. if (fRdfDescriptor != nullptr && fRdfDescriptor->Creator != nullptr)
  197. {
  198. std::strncpy(strBuf, fRdfDescriptor->Creator, STR_MAX);
  199. return;
  200. }
  201. std::strncpy(strBuf, fDescriptor->Maker, STR_MAX);
  202. }
  203. void getCopyright(char* const strBuf) const noexcept override
  204. {
  205. CARLA_SAFE_ASSERT_RETURN(fDescriptor != nullptr, nullStrBuf(strBuf));
  206. CARLA_SAFE_ASSERT_RETURN(fDescriptor->Copyright != nullptr, nullStrBuf(strBuf));
  207. std::strncpy(strBuf, fDescriptor->Copyright, STR_MAX);
  208. }
  209. void getRealName(char* const strBuf) const noexcept override
  210. {
  211. CARLA_SAFE_ASSERT_RETURN(fDescriptor != nullptr, nullStrBuf(strBuf));
  212. CARLA_SAFE_ASSERT_RETURN(fDescriptor->Name != nullptr, nullStrBuf(strBuf));
  213. if (fRdfDescriptor != nullptr && fRdfDescriptor->Title != nullptr)
  214. {
  215. std::strncpy(strBuf, fRdfDescriptor->Title, STR_MAX);
  216. return;
  217. }
  218. std::strncpy(strBuf, fDescriptor->Name, STR_MAX);
  219. }
  220. void getParameterName(const uint32_t parameterId, char* const strBuf) const noexcept override
  221. {
  222. CARLA_SAFE_ASSERT_RETURN(fDescriptor != nullptr, nullStrBuf(strBuf));
  223. CARLA_SAFE_ASSERT_RETURN(parameterId < pData->param.count, nullStrBuf(strBuf));
  224. const int32_t rindex(pData->param.data[parameterId].rindex);
  225. CARLA_SAFE_ASSERT_RETURN(rindex >= 0, nullStrBuf(strBuf));
  226. CARLA_SAFE_ASSERT_RETURN(rindex < static_cast<int32_t>(fDescriptor->PortCount), nullStrBuf(strBuf));
  227. CARLA_SAFE_ASSERT_RETURN(fDescriptor->PortNames[rindex] != nullptr, nullStrBuf(strBuf));
  228. if (getSeparatedParameterNameOrUnit(fDescriptor->PortNames[rindex], strBuf, true))
  229. return;
  230. std::strncpy(strBuf, fDescriptor->PortNames[rindex], STR_MAX);
  231. }
  232. void getParameterUnit(const uint32_t parameterId, char* const strBuf) const noexcept override
  233. {
  234. CARLA_SAFE_ASSERT_RETURN(parameterId < pData->param.count, nullStrBuf(strBuf));
  235. const int32_t rindex(pData->param.data[parameterId].rindex);
  236. CARLA_SAFE_ASSERT_RETURN(rindex >= 0, nullStrBuf(strBuf));
  237. if (fRdfDescriptor != nullptr && rindex < static_cast<int32_t>(fRdfDescriptor->PortCount))
  238. {
  239. const LADSPA_RDF_Port& port(fRdfDescriptor->Ports[rindex]);
  240. if (LADSPA_PORT_HAS_UNIT(port.Hints))
  241. {
  242. switch (port.Unit)
  243. {
  244. case LADSPA_UNIT_DB:
  245. std::strncpy(strBuf, "dB", STR_MAX);
  246. return;
  247. case LADSPA_UNIT_COEF:
  248. std::strncpy(strBuf, "(coef)", STR_MAX);
  249. return;
  250. case LADSPA_UNIT_HZ:
  251. std::strncpy(strBuf, "Hz", STR_MAX);
  252. return;
  253. case LADSPA_UNIT_S:
  254. std::strncpy(strBuf, "s", STR_MAX);
  255. return;
  256. case LADSPA_UNIT_MS:
  257. std::strncpy(strBuf, "ms", STR_MAX);
  258. return;
  259. case LADSPA_UNIT_MIN:
  260. std::strncpy(strBuf, "min", STR_MAX);
  261. return;
  262. }
  263. }
  264. }
  265. CARLA_SAFE_ASSERT_RETURN(rindex < static_cast<int32_t>(fDescriptor->PortCount), nullStrBuf(strBuf));
  266. CARLA_SAFE_ASSERT_RETURN(fDescriptor->PortNames[rindex] != nullptr, nullStrBuf(strBuf));
  267. if (getSeparatedParameterNameOrUnit(fDescriptor->PortNames[rindex], strBuf, false))
  268. return;
  269. nullStrBuf(strBuf);
  270. }
  271. void getParameterSymbol(const uint32_t parameterId, char* const strBuf) const noexcept override
  272. {
  273. CARLA_SAFE_ASSERT_RETURN(parameterId < pData->param.count, nullStrBuf(strBuf));
  274. if (fRdfDescriptor == nullptr)
  275. return nullStrBuf(strBuf);
  276. const int32_t rindex(pData->param.data[parameterId].rindex);
  277. CARLA_SAFE_ASSERT_RETURN(rindex >= 0, nullStrBuf(strBuf));
  278. if (rindex >= static_cast<int32_t>(fRdfDescriptor->PortCount))
  279. return nullStrBuf(strBuf);
  280. const LADSPA_RDF_Port& port(fRdfDescriptor->Ports[rindex]);
  281. if (! LADSPA_PORT_HAS_LABEL(port.Hints))
  282. return nullStrBuf(strBuf);
  283. CARLA_SAFE_ASSERT_RETURN(port.Label != nullptr, nullStrBuf(strBuf));
  284. std::strncpy(strBuf, port.Label, STR_MAX);
  285. }
  286. void getParameterScalePointLabel(const uint32_t parameterId, const uint32_t scalePointId, char* const strBuf) const noexcept override
  287. {
  288. CARLA_SAFE_ASSERT_RETURN(fRdfDescriptor != nullptr, nullStrBuf(strBuf));
  289. CARLA_SAFE_ASSERT_RETURN(parameterId < pData->param.count, nullStrBuf(strBuf));
  290. const int32_t rindex(pData->param.data[parameterId].rindex);
  291. CARLA_SAFE_ASSERT_RETURN(rindex >= 0, nullStrBuf(strBuf));
  292. CARLA_SAFE_ASSERT_RETURN(rindex < static_cast<int32_t>(fRdfDescriptor->PortCount), nullStrBuf(strBuf));
  293. const LADSPA_RDF_Port& port(fRdfDescriptor->Ports[rindex]);
  294. CARLA_SAFE_ASSERT_RETURN(scalePointId < port.ScalePointCount, nullStrBuf(strBuf));
  295. const LADSPA_RDF_ScalePoint& scalePoint(port.ScalePoints[scalePointId]);
  296. CARLA_SAFE_ASSERT_RETURN(scalePoint.Label != nullptr, nullStrBuf(strBuf));
  297. std::strncpy(strBuf, scalePoint.Label, STR_MAX);
  298. }
  299. // -------------------------------------------------------------------
  300. // Set data (state)
  301. // nothing
  302. // -------------------------------------------------------------------
  303. // Set data (internal stuff)
  304. // nothing
  305. // -------------------------------------------------------------------
  306. // Set data (plugin-specific stuff)
  307. void setParameterValue(const uint32_t parameterId, const float value, const bool sendGui, const bool sendOsc, const bool sendCallback) noexcept override
  308. {
  309. CARLA_SAFE_ASSERT_RETURN(fParamBuffers != nullptr,);
  310. CARLA_SAFE_ASSERT_RETURN(parameterId < pData->param.count,);
  311. const float fixedValue(pData->param.getFixedValue(parameterId, value));
  312. fParamBuffers[parameterId] = fixedValue;
  313. CarlaPlugin::setParameterValue(parameterId, fixedValue, sendGui, sendOsc, sendCallback);
  314. }
  315. void setParameterValueRT(const uint32_t parameterId, const float value) noexcept override
  316. {
  317. CARLA_SAFE_ASSERT_RETURN(fParamBuffers != nullptr,);
  318. CARLA_SAFE_ASSERT_RETURN(parameterId < pData->param.count,);
  319. const float fixedValue(pData->param.getFixedValue(parameterId, value));
  320. fParamBuffers[parameterId] = fixedValue;
  321. CarlaPlugin::setParameterValueRT(parameterId, fixedValue);
  322. }
  323. // -------------------------------------------------------------------
  324. // Misc
  325. // nothing
  326. // -------------------------------------------------------------------
  327. // Plugin state
  328. void reload() override
  329. {
  330. CARLA_SAFE_ASSERT_RETURN(pData->engine != nullptr,);
  331. CARLA_SAFE_ASSERT_RETURN(fDescriptor != nullptr,);
  332. CARLA_SAFE_ASSERT_RETURN(fHandles.count() > 0,);
  333. carla_debug("CarlaPluginLADSPA::reload() - start");
  334. const EngineProcessMode processMode(pData->engine->getProccessMode());
  335. // Safely disable plugin for reload
  336. const ScopedDisabler sd(this);
  337. if (pData->active)
  338. deactivate();
  339. clearBuffers();
  340. const float sampleRate(static_cast<float>(pData->engine->getSampleRate()));
  341. const uint32_t portCount(getSafePortCount());
  342. uint32_t aIns, aOuts, params;
  343. aIns = aOuts = params = 0;
  344. bool forcedStereoIn, forcedStereoOut;
  345. forcedStereoIn = forcedStereoOut = false;
  346. bool needsCtrlIn, needsCtrlOut;
  347. needsCtrlIn = needsCtrlOut = false;
  348. for (uint32_t i=0; i < portCount; ++i)
  349. {
  350. const LADSPA_PortDescriptor portType(fDescriptor->PortDescriptors[i]);
  351. if (LADSPA_IS_PORT_AUDIO(portType))
  352. {
  353. if (LADSPA_IS_PORT_INPUT(portType))
  354. aIns += 1;
  355. else if (LADSPA_IS_PORT_OUTPUT(portType))
  356. aOuts += 1;
  357. }
  358. else if (LADSPA_IS_PORT_CONTROL(portType))
  359. params += 1;
  360. }
  361. if (pData->options & PLUGIN_OPTION_FORCE_STEREO)
  362. {
  363. if ((aIns == 1 || aOuts == 1) && fHandles.count() == 1 && addInstance())
  364. {
  365. if (aIns == 1)
  366. {
  367. aIns = 2;
  368. forcedStereoIn = true;
  369. }
  370. if (aOuts == 1)
  371. {
  372. aOuts = 2;
  373. forcedStereoOut = true;
  374. }
  375. }
  376. }
  377. if (aIns > 0)
  378. {
  379. pData->audioIn.createNew(aIns);
  380. fAudioInBuffers = new float*[aIns];
  381. for (uint32_t i=0; i < aIns; ++i)
  382. fAudioInBuffers[i] = nullptr;
  383. }
  384. if (aOuts > 0)
  385. {
  386. pData->audioOut.createNew(aOuts);
  387. fAudioOutBuffers = new float*[aOuts];
  388. needsCtrlIn = true;
  389. for (uint32_t i=0; i < aOuts; ++i)
  390. fAudioOutBuffers[i] = nullptr;
  391. }
  392. if (params > 0)
  393. {
  394. pData->param.createNew(params, true);
  395. fParamBuffers = new float[params];
  396. carla_zeroFloats(fParamBuffers, params);
  397. }
  398. const uint portNameSize(pData->engine->getMaxPortNameSize());
  399. CarlaString portName;
  400. for (uint32_t i=0, iAudioIn=0, iAudioOut=0, iCtrl=0; i < portCount; ++i)
  401. {
  402. const LADSPA_PortDescriptor portType = fDescriptor->PortDescriptors[i];
  403. const LADSPA_PortRangeHint portRangeHints = fDescriptor->PortRangeHints[i];
  404. const bool hasPortRDF = (fRdfDescriptor != nullptr && i < fRdfDescriptor->PortCount);
  405. if (LADSPA_IS_PORT_AUDIO(portType))
  406. {
  407. portName.clear();
  408. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  409. {
  410. portName = pData->name;
  411. portName += ":";
  412. }
  413. if (fDescriptor->PortNames[i] != nullptr && fDescriptor->PortNames[i][0] != '\0')
  414. {
  415. portName += fDescriptor->PortNames[i];
  416. }
  417. else
  418. {
  419. if (LADSPA_IS_PORT_INPUT(portType))
  420. {
  421. if (aIns > 1)
  422. {
  423. portName += "audio-in_";
  424. portName += CarlaString(iAudioIn+1);
  425. }
  426. else
  427. portName += "audio-in";
  428. }
  429. else
  430. {
  431. if (aOuts > 1)
  432. {
  433. portName += "audio-out_";
  434. portName += CarlaString(iAudioOut+1);
  435. }
  436. else
  437. portName += "audio-out";
  438. }
  439. }
  440. portName.truncate(portNameSize);
  441. if (LADSPA_IS_PORT_INPUT(portType))
  442. {
  443. const uint32_t j = iAudioIn++;
  444. pData->audioIn.ports[j].port = (CarlaEngineAudioPort*)pData->client->addPort(kEnginePortTypeAudio, portName, true, j);
  445. pData->audioIn.ports[j].rindex = i;
  446. if (forcedStereoIn)
  447. {
  448. portName += "_2";
  449. pData->audioIn.ports[1].port = (CarlaEngineAudioPort*)pData->client->addPort(kEnginePortTypeAudio, portName, true, 1);
  450. pData->audioIn.ports[1].rindex = i;
  451. }
  452. }
  453. else if (LADSPA_IS_PORT_OUTPUT(portType))
  454. {
  455. const uint32_t j = iAudioOut++;
  456. pData->audioOut.ports[j].port = (CarlaEngineAudioPort*)pData->client->addPort(kEnginePortTypeAudio, portName, false, j);
  457. pData->audioOut.ports[j].rindex = i;
  458. if (forcedStereoOut)
  459. {
  460. portName += "_2";
  461. pData->audioOut.ports[1].port = (CarlaEngineAudioPort*)pData->client->addPort(kEnginePortTypeAudio, portName, false, 1);
  462. pData->audioOut.ports[1].rindex = i;
  463. }
  464. }
  465. else
  466. carla_stderr2("WARNING - Got a broken Port (Audio, but not input or output)");
  467. }
  468. else if (LADSPA_IS_PORT_CONTROL(portType))
  469. {
  470. const uint32_t j = iCtrl++;
  471. pData->param.data[j].index = static_cast<int32_t>(j);
  472. pData->param.data[j].rindex = static_cast<int32_t>(i);
  473. const char* const paramName(fDescriptor->PortNames[i] != nullptr ? fDescriptor->PortNames[i] : "unknown");
  474. float min, max, def, step, stepSmall, stepLarge;
  475. // min value
  476. if (LADSPA_IS_HINT_BOUNDED_BELOW(portRangeHints.HintDescriptor))
  477. min = portRangeHints.LowerBound;
  478. else
  479. min = 0.0f;
  480. // max value
  481. if (LADSPA_IS_HINT_BOUNDED_ABOVE(portRangeHints.HintDescriptor))
  482. max = portRangeHints.UpperBound;
  483. else
  484. max = 1.0f;
  485. if (LADSPA_IS_HINT_SAMPLE_RATE(portRangeHints.HintDescriptor))
  486. {
  487. min *= sampleRate;
  488. max *= sampleRate;
  489. pData->param.data[j].hints |= PARAMETER_USES_SAMPLERATE;
  490. }
  491. if (min >= max)
  492. {
  493. carla_stderr2("WARNING - Broken plugin parameter '%s': min >= max", paramName);
  494. max = min + 0.1f;
  495. }
  496. // default value
  497. if (hasPortRDF && LADSPA_PORT_HAS_DEFAULT(fRdfDescriptor->Ports[i].Hints))
  498. def = fRdfDescriptor->Ports[i].Default;
  499. else
  500. def = get_default_ladspa_port_value(portRangeHints.HintDescriptor, min, max);
  501. if (def < min)
  502. def = min;
  503. else if (def > max)
  504. def = max;
  505. if (LADSPA_IS_HINT_TOGGLED(portRangeHints.HintDescriptor))
  506. {
  507. step = max - min;
  508. stepSmall = step;
  509. stepLarge = step;
  510. pData->param.data[j].hints |= PARAMETER_IS_BOOLEAN;
  511. }
  512. else if (LADSPA_IS_HINT_INTEGER(portRangeHints.HintDescriptor))
  513. {
  514. step = 1.0f;
  515. stepSmall = 1.0f;
  516. stepLarge = 10.0f;
  517. pData->param.data[j].hints |= PARAMETER_IS_INTEGER;
  518. }
  519. else
  520. {
  521. const float range = max - min;
  522. step = range/100.0f;
  523. stepSmall = range/1000.0f;
  524. stepLarge = range/10.0f;
  525. }
  526. if (LADSPA_IS_PORT_INPUT(portType))
  527. {
  528. pData->param.data[j].type = PARAMETER_INPUT;
  529. pData->param.data[j].hints |= PARAMETER_IS_ENABLED;
  530. pData->param.data[j].hints |= PARAMETER_IS_AUTOMABLE;
  531. needsCtrlIn = true;
  532. }
  533. else if (LADSPA_IS_PORT_OUTPUT(portType))
  534. {
  535. pData->param.data[j].type = PARAMETER_OUTPUT;
  536. if (std::strcmp(paramName, "latency") == 0 || std::strcmp(paramName, "_latency") == 0)
  537. {
  538. min = 0.0f;
  539. max = sampleRate;
  540. def = 0.0f;
  541. step = 1.0f;
  542. stepSmall = 1.0f;
  543. stepLarge = 1.0f;
  544. pData->param.special[j] = PARAMETER_SPECIAL_LATENCY;
  545. CARLA_SAFE_ASSERT_INT2(fLatencyIndex == static_cast<int32_t>(j), fLatencyIndex, j);
  546. }
  547. else
  548. {
  549. pData->param.data[j].hints |= PARAMETER_IS_ENABLED;
  550. pData->param.data[j].hints |= PARAMETER_IS_AUTOMABLE;
  551. needsCtrlOut = true;
  552. }
  553. }
  554. else
  555. {
  556. carla_stderr2("WARNING - Got a broken Port (Control, but not input or output)");
  557. }
  558. // extra parameter hints
  559. if (LADSPA_IS_HINT_LOGARITHMIC(portRangeHints.HintDescriptor))
  560. pData->param.data[j].hints |= PARAMETER_IS_LOGARITHMIC;
  561. // check for scalepoints, require at least 2 to make it useful
  562. if (hasPortRDF && fRdfDescriptor->Ports[i].ScalePointCount >= 2)
  563. pData->param.data[j].hints |= PARAMETER_USES_SCALEPOINTS;
  564. pData->param.ranges[j].min = min;
  565. pData->param.ranges[j].max = max;
  566. pData->param.ranges[j].def = def;
  567. pData->param.ranges[j].step = step;
  568. pData->param.ranges[j].stepSmall = stepSmall;
  569. pData->param.ranges[j].stepLarge = stepLarge;
  570. // Start parameters in their default values
  571. fParamBuffers[j] = def;
  572. for (LinkedList<LADSPA_Handle>::Itenerator it = fHandles.begin2(); it.valid(); it.next())
  573. {
  574. LADSPA_Handle const handle(it.getValue(nullptr));
  575. CARLA_SAFE_ASSERT_CONTINUE(handle != nullptr);
  576. try {
  577. fDescriptor->connect_port(handle, i, &fParamBuffers[j]);
  578. } CARLA_SAFE_EXCEPTION("LADSPA connect_port (parameter)");
  579. }
  580. }
  581. else
  582. {
  583. // Not Audio or Control
  584. carla_stderr2("ERROR - Got a broken Port (neither Audio or Control)");
  585. for (LinkedList<LADSPA_Handle>::Itenerator it = fHandles.begin2(); it.valid(); it.next())
  586. {
  587. LADSPA_Handle const handle(it.getValue(nullptr));
  588. CARLA_SAFE_ASSERT_CONTINUE(handle != nullptr);
  589. try {
  590. fDescriptor->connect_port(handle, i, nullptr);
  591. } CARLA_SAFE_EXCEPTION("LADSPA connect_port (null)");
  592. }
  593. }
  594. }
  595. if (needsCtrlIn)
  596. {
  597. portName.clear();
  598. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  599. {
  600. portName = pData->name;
  601. portName += ":";
  602. }
  603. portName += "events-in";
  604. portName.truncate(portNameSize);
  605. pData->event.portIn = (CarlaEngineEventPort*)pData->client->addPort(kEnginePortTypeEvent, portName, true, 0);
  606. }
  607. if (needsCtrlOut)
  608. {
  609. portName.clear();
  610. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  611. {
  612. portName = pData->name;
  613. portName += ":";
  614. }
  615. portName += "events-out";
  616. portName.truncate(portNameSize);
  617. pData->event.portOut = (CarlaEngineEventPort*)pData->client->addPort(kEnginePortTypeEvent, portName, false, 0);
  618. }
  619. if (forcedStereoIn || forcedStereoOut)
  620. pData->options |= PLUGIN_OPTION_FORCE_STEREO;
  621. else
  622. pData->options &= ~PLUGIN_OPTION_FORCE_STEREO;
  623. // plugin hints
  624. pData->hints = 0x0;
  625. if (LADSPA_IS_HARD_RT_CAPABLE(fDescriptor->Properties))
  626. pData->hints |= PLUGIN_IS_RTSAFE;
  627. #ifndef BUILD_BRIDGE
  628. if (aOuts > 0 && (aIns == aOuts || aIns == 1))
  629. pData->hints |= PLUGIN_CAN_DRYWET;
  630. if (aOuts > 0)
  631. pData->hints |= PLUGIN_CAN_VOLUME;
  632. if (aOuts >= 2 && aOuts % 2 == 0)
  633. pData->hints |= PLUGIN_CAN_BALANCE;
  634. #endif
  635. // extra plugin hints
  636. pData->extraHints = 0x0;
  637. pData->extraHints |= PLUGIN_EXTRA_HINT_CAN_RUN_RACK;
  638. // check initial latency
  639. findInitialLatencyValue(aIns, aOuts);
  640. fForcedStereoIn = forcedStereoIn;
  641. fForcedStereoOut = forcedStereoOut;
  642. bufferSizeChanged(pData->engine->getBufferSize());
  643. if (pData->active)
  644. activate();
  645. carla_debug("CarlaPluginLADSPA::reload() - end");
  646. }
  647. void findInitialLatencyValue(const uint32_t aIns, const uint32_t aOuts) const
  648. {
  649. if (fLatencyIndex < 0 || fHandles.count() == 0)
  650. return;
  651. // we need to pre-run the plugin so it can update its latency control-port
  652. const LADSPA_Handle handle(fHandles.getFirst(nullptr));
  653. CARLA_SAFE_ASSERT_RETURN(handle != nullptr,);
  654. float tmpIn [(aIns > 0) ? aIns : 1][2];
  655. float tmpOut[(aOuts > 0) ? aOuts : 1][2];
  656. for (uint32_t j=0; j < aIns; ++j)
  657. {
  658. tmpIn[j][0] = 0.0f;
  659. tmpIn[j][1] = 0.0f;
  660. try {
  661. fDescriptor->connect_port(handle, pData->audioIn.ports[j].rindex, tmpIn[j]);
  662. } CARLA_SAFE_EXCEPTION("LADSPA connect_port (latency input)");
  663. }
  664. for (uint32_t j=0; j < aOuts; ++j)
  665. {
  666. tmpOut[j][0] = 0.0f;
  667. tmpOut[j][1] = 0.0f;
  668. try {
  669. fDescriptor->connect_port(handle, pData->audioOut.ports[j].rindex, tmpOut[j]);
  670. } CARLA_SAFE_EXCEPTION("LADSPA connect_port (latency output)");
  671. }
  672. if (fDescriptor->activate != nullptr)
  673. {
  674. try {
  675. fDescriptor->activate(handle);
  676. } CARLA_SAFE_EXCEPTION("LADSPA latency activate");
  677. }
  678. try {
  679. fDescriptor->run(handle, 2);
  680. } CARLA_SAFE_EXCEPTION("LADSPA latency run");
  681. if (fDescriptor->deactivate != nullptr)
  682. {
  683. try {
  684. fDescriptor->deactivate(handle);
  685. } CARLA_SAFE_EXCEPTION("LADSPA latency deactivate");
  686. }
  687. // done, let's get the value
  688. if (const uint32_t latency = getLatencyInFrames())
  689. {
  690. pData->client->setLatency(latency);
  691. #ifndef BUILD_BRIDGE
  692. pData->latency.recreateBuffers(std::max(aIns, aOuts), latency);
  693. #endif
  694. }
  695. }
  696. // -------------------------------------------------------------------
  697. // Plugin processing
  698. void activate() noexcept override
  699. {
  700. CARLA_SAFE_ASSERT_RETURN(fDescriptor != nullptr,);
  701. if (fDescriptor->activate != nullptr)
  702. {
  703. for (LinkedList<LADSPA_Handle>::Itenerator it = fHandles.begin2(); it.valid(); it.next())
  704. {
  705. LADSPA_Handle const handle(it.getValue(nullptr));
  706. CARLA_SAFE_ASSERT_CONTINUE(handle != nullptr);
  707. try {
  708. fDescriptor->activate(handle);
  709. } CARLA_SAFE_EXCEPTION("LADSPA activate");
  710. }
  711. }
  712. }
  713. void deactivate() noexcept override
  714. {
  715. CARLA_SAFE_ASSERT_RETURN(fDescriptor != nullptr,);
  716. if (fDescriptor->deactivate != nullptr)
  717. {
  718. for (LinkedList<LADSPA_Handle>::Itenerator it = fHandles.begin2(); it.valid(); it.next())
  719. {
  720. LADSPA_Handle const handle(it.getValue(nullptr));
  721. CARLA_SAFE_ASSERT_CONTINUE(handle != nullptr);
  722. try {
  723. fDescriptor->deactivate(handle);
  724. } CARLA_SAFE_EXCEPTION("LADSPA deactivate");
  725. }
  726. }
  727. }
  728. void process(const float** const audioIn, float** const audioOut, const float** const, float** const, const uint32_t frames) override
  729. {
  730. // --------------------------------------------------------------------------------------------------------
  731. // Check if active
  732. if (! pData->active)
  733. {
  734. // disable any output sound
  735. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  736. carla_zeroFloats(audioOut[i], frames);
  737. return;
  738. }
  739. // --------------------------------------------------------------------------------------------------------
  740. // Check if needs reset
  741. if (pData->needsReset)
  742. {
  743. // nothing to do
  744. pData->needsReset = false;
  745. }
  746. // --------------------------------------------------------------------------------------------------------
  747. // Event Input and Processing
  748. if (pData->event.portIn != nullptr)
  749. {
  750. // ----------------------------------------------------------------------------------------------------
  751. // Event Input (System)
  752. const bool isSampleAccurate = (pData->options & PLUGIN_OPTION_FIXED_BUFFERS) == 0;
  753. uint32_t timeOffset = 0;
  754. for (uint32_t i=0, numEvents=pData->event.portIn->getEventCount(); i < numEvents; ++i)
  755. {
  756. const EngineEvent& event(pData->event.portIn->getEvent(i));
  757. uint32_t eventTime = event.time;
  758. CARLA_SAFE_ASSERT_CONTINUE(eventTime < frames);
  759. if (eventTime < timeOffset)
  760. {
  761. carla_stderr2("Timing error, eventTime:%u < timeOffset:%u for '%s'",
  762. eventTime, timeOffset, pData->name);
  763. eventTime = timeOffset;
  764. }
  765. if (isSampleAccurate && eventTime > timeOffset)
  766. {
  767. if (processSingle(audioIn, audioOut, eventTime - timeOffset, timeOffset))
  768. timeOffset = eventTime;
  769. }
  770. switch (event.type)
  771. {
  772. case kEngineEventTypeNull:
  773. break;
  774. case kEngineEventTypeControl: {
  775. const EngineControlEvent& ctrlEvent(event.ctrl);
  776. switch (ctrlEvent.type)
  777. {
  778. case kEngineControlEventTypeNull:
  779. break;
  780. case kEngineControlEventTypeParameter: {
  781. #ifndef BUILD_BRIDGE
  782. // Control backend stuff
  783. if (event.channel == pData->ctrlChannel)
  784. {
  785. float value;
  786. if (MIDI_IS_CONTROL_BREATH_CONTROLLER(ctrlEvent.param) && (pData->hints & PLUGIN_CAN_DRYWET) != 0)
  787. {
  788. value = ctrlEvent.value;
  789. setDryWetRT(value);
  790. }
  791. if (MIDI_IS_CONTROL_CHANNEL_VOLUME(ctrlEvent.param) && (pData->hints & PLUGIN_CAN_VOLUME) != 0)
  792. {
  793. value = ctrlEvent.value*127.0f/100.0f;
  794. setVolumeRT(value);
  795. }
  796. if (MIDI_IS_CONTROL_BALANCE(ctrlEvent.param) && (pData->hints & PLUGIN_CAN_BALANCE) != 0)
  797. {
  798. float left, right;
  799. value = ctrlEvent.value/0.5f - 1.0f;
  800. if (value < 0.0f)
  801. {
  802. left = -1.0f;
  803. right = (value*2.0f)+1.0f;
  804. }
  805. else if (value > 0.0f)
  806. {
  807. left = (value*2.0f)-1.0f;
  808. right = 1.0f;
  809. }
  810. else
  811. {
  812. left = -1.0f;
  813. right = 1.0f;
  814. }
  815. setBalanceLeftRT(left);
  816. setBalanceRightRT(right);
  817. }
  818. }
  819. #endif
  820. // Control plugin parameters
  821. for (uint32_t k=0; k < pData->param.count; ++k)
  822. {
  823. if (pData->param.data[k].midiChannel != event.channel)
  824. continue;
  825. if (pData->param.data[k].midiCC != ctrlEvent.param)
  826. continue;
  827. if (pData->param.data[k].type != PARAMETER_INPUT)
  828. continue;
  829. if ((pData->param.data[k].hints & PARAMETER_IS_AUTOMABLE) == 0)
  830. continue;
  831. float value;
  832. if (pData->param.data[k].hints & PARAMETER_IS_BOOLEAN)
  833. {
  834. value = (ctrlEvent.value < 0.5f) ? pData->param.ranges[k].min : pData->param.ranges[k].max;
  835. }
  836. else
  837. {
  838. if (pData->param.data[k].hints & PARAMETER_IS_LOGARITHMIC)
  839. value = pData->param.ranges[k].getUnnormalizedLogValue(ctrlEvent.value);
  840. else
  841. value = pData->param.ranges[k].getUnnormalizedValue(ctrlEvent.value);
  842. if (pData->param.data[k].hints & PARAMETER_IS_INTEGER)
  843. value = std::rint(value);
  844. }
  845. setParameterValueRT(k, value);
  846. }
  847. break;
  848. } // case kEngineControlEventTypeParameter
  849. case kEngineControlEventTypeMidiBank:
  850. case kEngineControlEventTypeMidiProgram:
  851. case kEngineControlEventTypeAllSoundOff:
  852. case kEngineControlEventTypeAllNotesOff:
  853. break;
  854. } // switch (ctrlEvent.type)
  855. break;
  856. } // case kEngineEventTypeControl
  857. case kEngineEventTypeMidi:
  858. break;
  859. } // switch (event.type)
  860. }
  861. pData->postRtEvents.trySplice();
  862. if (frames > timeOffset)
  863. processSingle(audioIn, audioOut, frames - timeOffset, timeOffset);
  864. } // End of Event Input and Processing
  865. // --------------------------------------------------------------------------------------------------------
  866. // Plugin processing (no events)
  867. else
  868. {
  869. processSingle(audioIn, audioOut, frames, 0);
  870. } // End of Plugin processing (no events)
  871. // --------------------------------------------------------------------------------------------------------
  872. // Control Output
  873. if (pData->event.portOut != nullptr)
  874. {
  875. uint8_t channel;
  876. uint16_t param;
  877. float value;
  878. for (uint32_t k=0; k < pData->param.count; ++k)
  879. {
  880. if (pData->param.data[k].type != PARAMETER_OUTPUT)
  881. continue;
  882. pData->param.ranges[k].fixValue(fParamBuffers[k]);
  883. if (pData->param.data[k].midiCC > 0)
  884. {
  885. channel = pData->param.data[k].midiChannel;
  886. param = static_cast<uint16_t>(pData->param.data[k].midiCC);
  887. value = pData->param.ranges[k].getNormalizedValue(fParamBuffers[k]);
  888. pData->event.portOut->writeControlEvent(0, channel, kEngineControlEventTypeParameter, param, value);
  889. }
  890. }
  891. } // End of Control Output
  892. }
  893. bool processSingle(const float** const audioIn, float** const audioOut, const uint32_t frames,
  894. const uint32_t timeOffset)
  895. {
  896. CARLA_SAFE_ASSERT_RETURN(frames > 0, false);
  897. if (pData->audioIn.count > 0)
  898. {
  899. CARLA_SAFE_ASSERT_RETURN(audioIn != nullptr, false);
  900. }
  901. if (pData->audioOut.count > 0)
  902. {
  903. CARLA_SAFE_ASSERT_RETURN(audioOut != nullptr, false);
  904. }
  905. // --------------------------------------------------------------------------------------------------------
  906. // Try lock, silence otherwise
  907. #ifndef STOAT_TEST_BUILD
  908. if (pData->engine->isOffline())
  909. {
  910. pData->singleMutex.lock();
  911. }
  912. else
  913. #endif
  914. if (! pData->singleMutex.tryLock())
  915. {
  916. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  917. {
  918. for (uint32_t k=0; k < frames; ++k)
  919. audioOut[i][k+timeOffset] = 0.0f;
  920. }
  921. return false;
  922. }
  923. // --------------------------------------------------------------------------------------------------------
  924. // Set audio buffers
  925. const bool customMonoOut = pData->audioOut.count == 2 && fForcedStereoOut && ! fForcedStereoIn;
  926. const bool customStereoOut = pData->audioOut.count == 2 && fForcedStereoIn && ! fForcedStereoOut;
  927. if (! customMonoOut)
  928. {
  929. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  930. carla_zeroFloats(fAudioOutBuffers[i], frames);
  931. }
  932. for (uint32_t i=0; i < pData->audioIn.count; ++i)
  933. carla_copyFloats(fAudioInBuffers[i], audioIn[i]+timeOffset, frames);
  934. // --------------------------------------------------------------------------------------------------------
  935. // Run plugin
  936. uint instn = 0;
  937. for (LinkedList<LADSPA_Handle>::Itenerator it = fHandles.begin2(); it.valid(); it.next(), ++instn)
  938. {
  939. LADSPA_Handle const handle(it.getValue(nullptr));
  940. CARLA_SAFE_ASSERT_CONTINUE(handle != nullptr);
  941. // ----------------------------------------------------------------------------------------------------
  942. // Mixdown for forced stereo
  943. if (customMonoOut)
  944. carla_zeroFloats(fAudioOutBuffers[instn], frames);
  945. // ----------------------------------------------------------------------------------------------------
  946. // Run it
  947. try {
  948. fDescriptor->run(handle, frames);
  949. } CARLA_SAFE_EXCEPTION("LADSPA run");
  950. // ----------------------------------------------------------------------------------------------------
  951. // Mixdown for forced stereo
  952. if (customMonoOut)
  953. carla_multiply(fAudioOutBuffers[instn], 0.5f, frames);
  954. else if (customStereoOut)
  955. carla_copyFloats(fExtraStereoBuffer[instn], fAudioOutBuffers[instn], frames);
  956. }
  957. if (customStereoOut)
  958. {
  959. carla_copyFloats(fAudioOutBuffers[0], fExtraStereoBuffer[0], frames);
  960. carla_copyFloats(fAudioOutBuffers[1], fExtraStereoBuffer[1], frames);
  961. }
  962. #ifndef BUILD_BRIDGE
  963. // --------------------------------------------------------------------------------------------------------
  964. // Post-processing (dry/wet, volume and balance)
  965. {
  966. const bool doDryWet = (pData->hints & PLUGIN_CAN_DRYWET) != 0 && carla_isNotEqual(pData->postProc.dryWet, 1.0f);
  967. const bool doBalance = (pData->hints & PLUGIN_CAN_BALANCE) != 0 && ! (carla_isEqual(pData->postProc.balanceLeft, -1.0f) && carla_isEqual(pData->postProc.balanceRight, 1.0f));
  968. const bool isMono = (pData->audioIn.count == 1);
  969. bool isPair;
  970. float bufValue, oldBufLeft[doBalance ? frames : 1];
  971. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  972. {
  973. // Dry/Wet
  974. if (doDryWet)
  975. {
  976. const uint32_t c = isMono ? 0 : i;
  977. for (uint32_t k=0; k < frames; ++k)
  978. {
  979. if (k < pData->latency.frames)
  980. bufValue = pData->latency.buffers[c][k];
  981. else if (pData->latency.frames < frames)
  982. bufValue = fAudioInBuffers[c][k-pData->latency.frames];
  983. else
  984. bufValue = fAudioInBuffers[c][k];
  985. fAudioOutBuffers[i][k] = (fAudioOutBuffers[i][k] * pData->postProc.dryWet) + (bufValue * (1.0f - pData->postProc.dryWet));
  986. }
  987. }
  988. // Balance
  989. if (doBalance)
  990. {
  991. isPair = (i % 2 == 0);
  992. if (isPair)
  993. {
  994. CARLA_ASSERT(i+1 < pData->audioOut.count);
  995. carla_copyFloats(oldBufLeft, fAudioOutBuffers[i], frames);
  996. }
  997. float balRangeL = (pData->postProc.balanceLeft + 1.0f)/2.0f;
  998. float balRangeR = (pData->postProc.balanceRight + 1.0f)/2.0f;
  999. for (uint32_t k=0; k < frames; ++k)
  1000. {
  1001. if (isPair)
  1002. {
  1003. // left
  1004. fAudioOutBuffers[i][k] = oldBufLeft[k] * (1.0f - balRangeL);
  1005. fAudioOutBuffers[i][k] += fAudioOutBuffers[i+1][k] * (1.0f - balRangeR);
  1006. }
  1007. else
  1008. {
  1009. // right
  1010. fAudioOutBuffers[i][k] = fAudioOutBuffers[i][k] * balRangeR;
  1011. fAudioOutBuffers[i][k] += oldBufLeft[k] * balRangeL;
  1012. }
  1013. }
  1014. }
  1015. // Volume (and buffer copy)
  1016. {
  1017. for (uint32_t k=0; k < frames; ++k)
  1018. audioOut[i][k+timeOffset] = fAudioOutBuffers[i][k] * pData->postProc.volume;
  1019. }
  1020. }
  1021. } // End of Post-processing
  1022. // --------------------------------------------------------------------------------------------------------
  1023. // Save latency values for next callback
  1024. if (const uint32_t latframes = pData->latency.frames)
  1025. {
  1026. CARLA_SAFE_ASSERT(timeOffset == 0);
  1027. if (latframes <= frames)
  1028. {
  1029. for (uint32_t i=0; i < pData->audioIn.count; ++i)
  1030. carla_copyFloats(pData->latency.buffers[i], audioIn[i]+(frames-latframes), latframes);
  1031. }
  1032. else
  1033. {
  1034. const uint32_t diff = pData->latency.frames-frames;
  1035. for (uint32_t i=0, k; i<pData->audioIn.count; ++i)
  1036. {
  1037. // push back buffer by 'frames'
  1038. for (k=0; k < diff; ++k)
  1039. pData->latency.buffers[i][k] = pData->latency.buffers[i][k+frames];
  1040. // put current input at the end
  1041. for (uint32_t j=0; k < latframes; ++j, ++k)
  1042. pData->latency.buffers[i][k] = audioIn[i][j];
  1043. }
  1044. }
  1045. }
  1046. #else // BUILD_BRIDGE
  1047. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  1048. {
  1049. for (uint32_t k=0; k < frames; ++k)
  1050. audioOut[i][k+timeOffset] = fAudioOutBuffers[i][k];
  1051. }
  1052. #endif
  1053. // --------------------------------------------------------------------------------------------------------
  1054. pData->singleMutex.unlock();
  1055. return true;
  1056. }
  1057. void bufferSizeChanged(const uint32_t newBufferSize) override
  1058. {
  1059. CARLA_ASSERT_INT(newBufferSize > 0, newBufferSize);
  1060. carla_debug("CarlaPluginLADSPA::bufferSizeChanged(%i) - start", newBufferSize);
  1061. for (uint32_t i=0; i < pData->audioIn.count; ++i)
  1062. {
  1063. if (fAudioInBuffers[i] != nullptr)
  1064. delete[] fAudioInBuffers[i];
  1065. fAudioInBuffers[i] = new float[newBufferSize];
  1066. carla_zeroFloats(fAudioInBuffers[i], newBufferSize);
  1067. }
  1068. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  1069. {
  1070. if (fAudioOutBuffers[i] != nullptr)
  1071. delete[] fAudioOutBuffers[i];
  1072. fAudioOutBuffers[i] = new float[newBufferSize];
  1073. carla_zeroFloats(fAudioOutBuffers[i], newBufferSize);
  1074. }
  1075. if (fExtraStereoBuffer[0] != nullptr)
  1076. {
  1077. delete[] fExtraStereoBuffer[0];
  1078. fExtraStereoBuffer[0] = nullptr;
  1079. }
  1080. if (fExtraStereoBuffer[1] != nullptr)
  1081. {
  1082. delete[] fExtraStereoBuffer[1];
  1083. fExtraStereoBuffer[1] = nullptr;
  1084. }
  1085. if (fForcedStereoIn && pData->audioOut.count == 2)
  1086. {
  1087. fExtraStereoBuffer[0] = new float[newBufferSize];
  1088. fExtraStereoBuffer[1] = new float[newBufferSize];
  1089. carla_zeroFloats(fExtraStereoBuffer[0], newBufferSize);
  1090. carla_zeroFloats(fExtraStereoBuffer[1], newBufferSize);
  1091. }
  1092. reconnectAudioPorts();
  1093. carla_debug("CarlaPluginLADSPA::bufferSizeChanged(%i) - end", newBufferSize);
  1094. }
  1095. void sampleRateChanged(const double newSampleRate) override
  1096. {
  1097. CARLA_ASSERT_INT(newSampleRate > 0.0, newSampleRate);
  1098. carla_stdout("CarlaPluginLADSPA::sampleRateChanged(%g) - start", newSampleRate);
  1099. if (pData->active)
  1100. deactivate();
  1101. const std::size_t instanceCount(fHandles.count());
  1102. if (fDescriptor->cleanup != nullptr)
  1103. {
  1104. for (LinkedList<LADSPA_Handle>::Itenerator it = fHandles.begin2(); it.valid(); it.next())
  1105. {
  1106. LADSPA_Handle const handle(it.getValue(nullptr));
  1107. CARLA_SAFE_ASSERT_CONTINUE(handle != nullptr);
  1108. try {
  1109. fDescriptor->cleanup(handle);
  1110. } CARLA_SAFE_EXCEPTION("LADSPA cleanup");
  1111. }
  1112. }
  1113. fHandles.clear();
  1114. for (std::size_t i=0; i<instanceCount; ++i)
  1115. addInstance();
  1116. reconnectAudioPorts();
  1117. if (pData->active)
  1118. activate();
  1119. carla_stdout("CarlaPluginLADSPA::sampleRateChanged(%g) - end", newSampleRate);
  1120. }
  1121. void reconnectAudioPorts() const noexcept
  1122. {
  1123. if (fForcedStereoIn)
  1124. {
  1125. if (LADSPA_Handle const handle = fHandles.getFirst(nullptr))
  1126. {
  1127. try {
  1128. fDescriptor->connect_port(handle, pData->audioIn.ports[0].rindex, fAudioInBuffers[0]);
  1129. } CARLA_SAFE_EXCEPTION("LADSPA connect_port (forced stereo input, first)");
  1130. }
  1131. if (LADSPA_Handle const handle = fHandles.getLast(nullptr))
  1132. {
  1133. try {
  1134. fDescriptor->connect_port(handle, pData->audioIn.ports[1].rindex, fAudioInBuffers[1]);
  1135. } CARLA_SAFE_EXCEPTION("LADSPA connect_port (forced stereo input, last)");
  1136. }
  1137. }
  1138. else
  1139. {
  1140. for (LinkedList<LADSPA_Handle>::Itenerator it = fHandles.begin2(); it.valid(); it.next())
  1141. {
  1142. LADSPA_Handle const handle(it.getValue(nullptr));
  1143. CARLA_SAFE_ASSERT_CONTINUE(handle != nullptr);
  1144. for (uint32_t i=0; i < pData->audioIn.count; ++i)
  1145. {
  1146. try {
  1147. fDescriptor->connect_port(handle, pData->audioIn.ports[i].rindex, fAudioInBuffers[i]);
  1148. } CARLA_SAFE_EXCEPTION("LADSPA connect_port (audio input)");
  1149. }
  1150. }
  1151. }
  1152. if (fForcedStereoOut)
  1153. {
  1154. if (LADSPA_Handle const handle = fHandles.getFirst(nullptr))
  1155. {
  1156. try {
  1157. fDescriptor->connect_port(handle, pData->audioOut.ports[0].rindex, fAudioOutBuffers[0]);
  1158. } CARLA_SAFE_EXCEPTION("LADSPA connect_port (forced stereo output, first)");
  1159. }
  1160. if (LADSPA_Handle const handle = fHandles.getLast(nullptr))
  1161. {
  1162. try {
  1163. fDescriptor->connect_port(handle, pData->audioOut.ports[1].rindex, fAudioOutBuffers[1]);
  1164. } CARLA_SAFE_EXCEPTION("LADSPA connect_port (forced stereo output, last)");
  1165. }
  1166. }
  1167. else
  1168. {
  1169. for (LinkedList<LADSPA_Handle>::Itenerator it = fHandles.begin2(); it.valid(); it.next())
  1170. {
  1171. LADSPA_Handle const handle(it.getValue(nullptr));
  1172. CARLA_SAFE_ASSERT_CONTINUE(handle != nullptr);
  1173. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  1174. {
  1175. try {
  1176. fDescriptor->connect_port(handle, pData->audioOut.ports[i].rindex, fAudioOutBuffers[i]);
  1177. } CARLA_SAFE_EXCEPTION("LADSPA connect_port (audio output)");
  1178. }
  1179. }
  1180. }
  1181. }
  1182. // -------------------------------------------------------------------
  1183. // Plugin buffers
  1184. void clearBuffers() noexcept override
  1185. {
  1186. carla_debug("CarlaPluginLADSPA::clearBuffers() - start");
  1187. if (fAudioInBuffers != nullptr)
  1188. {
  1189. for (uint32_t i=0; i < pData->audioIn.count; ++i)
  1190. {
  1191. if (fAudioInBuffers[i] != nullptr)
  1192. {
  1193. delete[] fAudioInBuffers[i];
  1194. fAudioInBuffers[i] = nullptr;
  1195. }
  1196. }
  1197. delete[] fAudioInBuffers;
  1198. fAudioInBuffers = nullptr;
  1199. }
  1200. if (fAudioOutBuffers != nullptr)
  1201. {
  1202. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  1203. {
  1204. if (fAudioOutBuffers[i] != nullptr)
  1205. {
  1206. delete[] fAudioOutBuffers[i];
  1207. fAudioOutBuffers[i] = nullptr;
  1208. }
  1209. }
  1210. delete[] fAudioOutBuffers;
  1211. fAudioOutBuffers = nullptr;
  1212. }
  1213. if (fExtraStereoBuffer[0] != nullptr)
  1214. {
  1215. delete[] fExtraStereoBuffer[0];
  1216. fExtraStereoBuffer[0] = nullptr;
  1217. }
  1218. if (fExtraStereoBuffer[1] != nullptr)
  1219. {
  1220. delete[] fExtraStereoBuffer[1];
  1221. fExtraStereoBuffer[1] = nullptr;
  1222. }
  1223. if (fParamBuffers != nullptr)
  1224. {
  1225. delete[] fParamBuffers;
  1226. fParamBuffers = nullptr;
  1227. }
  1228. CarlaPlugin::clearBuffers();
  1229. carla_debug("CarlaPluginLADSPA::clearBuffers() - end");
  1230. }
  1231. // -------------------------------------------------------------------
  1232. const void* getNativeDescriptor() const noexcept override
  1233. {
  1234. return fDescriptor;
  1235. }
  1236. const void* getExtraStuff() const noexcept override
  1237. {
  1238. return fRdfDescriptor;
  1239. }
  1240. // -------------------------------------------------------------------
  1241. bool init(const char* const filename, const char* name, const char* const label, const uint options,
  1242. const LADSPA_RDF_Descriptor* const rdfDescriptor)
  1243. {
  1244. CARLA_SAFE_ASSERT_RETURN(pData->engine != nullptr, false);
  1245. // ---------------------------------------------------------------
  1246. // first checks
  1247. if (pData->client != nullptr)
  1248. {
  1249. pData->engine->setLastError("Plugin client is already registered");
  1250. return false;
  1251. }
  1252. if (filename == nullptr || filename[0] == '\0')
  1253. {
  1254. pData->engine->setLastError("null filename");
  1255. return false;
  1256. }
  1257. // ---------------------------------------------------------------
  1258. // open DLL
  1259. if (! pData->libOpen(filename))
  1260. {
  1261. pData->engine->setLastError(pData->libError(filename));
  1262. return false;
  1263. }
  1264. // ---------------------------------------------------------------
  1265. // get DLL main entry
  1266. const LADSPA_Descriptor_Function descFn = pData->libSymbol<LADSPA_Descriptor_Function>("ladspa_descriptor");
  1267. if (descFn == nullptr)
  1268. {
  1269. pData->engine->setLastError("Could not find the LASDPA Descriptor in the plugin library");
  1270. return false;
  1271. }
  1272. // ---------------------------------------------------------------
  1273. // get descriptor that matches label
  1274. // if label is null, get first valid plugin
  1275. const bool nullLabel = (label == nullptr || label[0] == '\0');
  1276. for (ulong d=0;; ++d)
  1277. {
  1278. try {
  1279. fDescriptor = descFn(d);
  1280. }
  1281. catch(...) {
  1282. carla_stderr2("Caught exception when trying to get LADSPA descriptor");
  1283. fDescriptor = nullptr;
  1284. break;
  1285. }
  1286. if (fDescriptor == nullptr)
  1287. break;
  1288. if (fDescriptor->Label == nullptr || fDescriptor->Label[0] == '\0')
  1289. {
  1290. carla_stderr2("WARNING - Got an invalid label, will not use this plugin");
  1291. fDescriptor = nullptr;
  1292. break;
  1293. }
  1294. if (fDescriptor->run == nullptr)
  1295. {
  1296. carla_stderr2("WARNING - Plugin has no run, cannot use it");
  1297. fDescriptor = nullptr;
  1298. break;
  1299. }
  1300. if (nullLabel || std::strcmp(fDescriptor->Label, label) == 0)
  1301. break;
  1302. }
  1303. if (fDescriptor == nullptr)
  1304. {
  1305. pData->engine->setLastError("Could not find the requested plugin label in the plugin library");
  1306. return false;
  1307. }
  1308. // ---------------------------------------------------------------
  1309. // check for fixed buffer size requirement
  1310. fNeedsFixedBuffers = CarlaString(filename).contains("dssi-vst", true);
  1311. if (fNeedsFixedBuffers && ! pData->engine->usesConstantBufferSize())
  1312. {
  1313. pData->engine->setLastError("Cannot use this plugin under the current engine.\n"
  1314. "The plugin requires a fixed block size which is not possible right now.");
  1315. return false;
  1316. }
  1317. // ---------------------------------------------------------------
  1318. // get info
  1319. if (is_ladspa_rdf_descriptor_valid(rdfDescriptor, fDescriptor))
  1320. fRdfDescriptor = ladspa_rdf_dup(rdfDescriptor);
  1321. if (name == nullptr || name[0] == '\0')
  1322. {
  1323. /**/ if (fRdfDescriptor != nullptr && fRdfDescriptor->Title != nullptr && fRdfDescriptor->Title[0] != '\0')
  1324. name = fRdfDescriptor->Title;
  1325. else if (fDescriptor->Name != nullptr && fDescriptor->Name[0] != '\0')
  1326. name = fDescriptor->Name;
  1327. else
  1328. name = fDescriptor->Label;
  1329. }
  1330. pData->name = pData->engine->getUniquePluginName(name);
  1331. pData->filename = carla_strdup(filename);
  1332. // ---------------------------------------------------------------
  1333. // register client
  1334. pData->client = pData->engine->addClient(this);
  1335. if (pData->client == nullptr || ! pData->client->isOk())
  1336. {
  1337. pData->engine->setLastError("Failed to register plugin client");
  1338. return false;
  1339. }
  1340. // ---------------------------------------------------------------
  1341. // initialize plugin
  1342. if (! addInstance())
  1343. return false;
  1344. // ---------------------------------------------------------------
  1345. // find latency port index
  1346. for (uint32_t i=0, iCtrl=0, count=getSafePortCount(); i<count; ++i)
  1347. {
  1348. const int portType(fDescriptor->PortDescriptors[i]);
  1349. if (! LADSPA_IS_PORT_CONTROL(portType))
  1350. continue;
  1351. const uint32_t index(iCtrl++);
  1352. if (! LADSPA_IS_PORT_OUTPUT(portType))
  1353. continue;
  1354. const char* const portName(fDescriptor->PortNames[i]);
  1355. CARLA_SAFE_ASSERT_BREAK(portName != nullptr);
  1356. if (std::strcmp(portName, "latency") == 0 ||
  1357. std::strcmp(portName, "_latency") == 0)
  1358. {
  1359. fLatencyIndex = static_cast<int32_t>(index);
  1360. break;
  1361. }
  1362. }
  1363. // ---------------------------------------------------------------
  1364. // set default options
  1365. pData->options = 0x0;
  1366. /**/ if (fLatencyIndex >= 0 || fNeedsFixedBuffers)
  1367. pData->options |= PLUGIN_OPTION_FIXED_BUFFERS;
  1368. else if (options & PLUGIN_OPTION_FIXED_BUFFERS)
  1369. pData->options |= PLUGIN_OPTION_FIXED_BUFFERS;
  1370. /**/ if (pData->engine->getOptions().forceStereo)
  1371. pData->options |= PLUGIN_OPTION_FORCE_STEREO;
  1372. else if (options & PLUGIN_OPTION_FORCE_STEREO)
  1373. pData->options |= PLUGIN_OPTION_FORCE_STEREO;
  1374. return true;
  1375. }
  1376. // -------------------------------------------------------------------
  1377. private:
  1378. LinkedList<LADSPA_Handle> fHandles;
  1379. const LADSPA_Descriptor* fDescriptor;
  1380. const LADSPA_RDF_Descriptor* fRdfDescriptor;
  1381. float** fAudioInBuffers;
  1382. float** fAudioOutBuffers;
  1383. float* fExtraStereoBuffer[2]; // used only if forcedStereoIn and audioOut == 2
  1384. float* fParamBuffers;
  1385. int32_t fLatencyIndex; // -1 if invalid
  1386. bool fForcedStereoIn;
  1387. bool fForcedStereoOut;
  1388. bool fNeedsFixedBuffers;
  1389. // -------------------------------------------------------------------
  1390. bool addInstance()
  1391. {
  1392. LADSPA_Handle handle;
  1393. try {
  1394. handle = fDescriptor->instantiate(fDescriptor, static_cast<ulong>(pData->engine->getSampleRate()));
  1395. } CARLA_SAFE_EXCEPTION_RETURN_ERR("LADSPA instantiate", "Plugin failed to initialize");
  1396. for (uint32_t i=0, count=pData->param.count; i<count; ++i)
  1397. {
  1398. const int32_t rindex(pData->param.data[i].rindex);
  1399. CARLA_SAFE_ASSERT_CONTINUE(rindex >= 0);
  1400. try {
  1401. fDescriptor->connect_port(handle, static_cast<ulong>(rindex), &fParamBuffers[i]);
  1402. } CARLA_SAFE_EXCEPTION("LADSPA connect_port");
  1403. }
  1404. if (fHandles.append(handle))
  1405. return true;
  1406. try {
  1407. fDescriptor->cleanup(handle);
  1408. } CARLA_SAFE_EXCEPTION("LADSPA cleanup");
  1409. pData->engine->setLastError("Out of memory");
  1410. return false;
  1411. }
  1412. uint32_t getSafePortCount() const noexcept
  1413. {
  1414. if (fDescriptor->PortCount == 0)
  1415. return 0;
  1416. CARLA_SAFE_ASSERT_RETURN(fDescriptor->PortDescriptors != nullptr, 0);
  1417. CARLA_SAFE_ASSERT_RETURN(fDescriptor->PortRangeHints != nullptr, 0);
  1418. CARLA_SAFE_ASSERT_RETURN(fDescriptor->PortNames != nullptr, 0);
  1419. return static_cast<uint32_t>(fDescriptor->PortCount);
  1420. }
  1421. bool getSeparatedParameterNameOrUnit(const char* const paramName, char* const strBuf, const bool wantName) const noexcept
  1422. {
  1423. if (_getSeparatedParameterNameOrUnitImpl(paramName, strBuf, wantName, true))
  1424. return true;
  1425. if (_getSeparatedParameterNameOrUnitImpl(paramName, strBuf, wantName, false))
  1426. return true;
  1427. return false;
  1428. }
  1429. static bool _getSeparatedParameterNameOrUnitImpl(const char* const paramName, char* const strBuf,
  1430. const bool wantName, const bool useBracket) noexcept
  1431. {
  1432. const char* const sepBracketStart(std::strstr(paramName, useBracket ? " [" : " ("));
  1433. if (sepBracketStart == nullptr)
  1434. return false;
  1435. const char* const sepBracketEnd(std::strstr(sepBracketStart, useBracket ? "]" : ")"));
  1436. if (sepBracketEnd == nullptr)
  1437. return false;
  1438. const std::size_t unitSize(static_cast<std::size_t>(sepBracketEnd-sepBracketStart-2));
  1439. if (unitSize > 7) // very unlikely to have such big unit
  1440. return false;
  1441. const std::size_t sepIndex(std::strlen(paramName)-unitSize-3);
  1442. // just in case
  1443. if (sepIndex+2 >= STR_MAX)
  1444. return false;
  1445. if (wantName)
  1446. {
  1447. std::strncpy(strBuf, paramName, sepIndex);
  1448. strBuf[sepIndex] = '\0';
  1449. }
  1450. else
  1451. {
  1452. std::strncpy(strBuf, paramName+(sepIndex+2), unitSize);
  1453. strBuf[unitSize] = '\0';
  1454. }
  1455. return true;
  1456. }
  1457. // -------------------------------------------------------------------
  1458. CARLA_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(CarlaPluginLADSPA)
  1459. };
  1460. // -------------------------------------------------------------------------------------------------------------------
  1461. CarlaPlugin* CarlaPlugin::newLADSPA(const Initializer& init, const LADSPA_RDF_Descriptor* const rdfDescriptor)
  1462. {
  1463. carla_debug("CarlaPlugin::newLADSPA({%p, \"%s\", \"%s\", \"%s\", " P_INT64 ", %x}, %p)",
  1464. init.engine, init.filename, init.name, init.label, init.uniqueId, init.options, rdfDescriptor);
  1465. CarlaPluginLADSPA* const plugin(new CarlaPluginLADSPA(init.engine, init.id));
  1466. if (! plugin->init(init.filename, init.name, init.label, init.options, rdfDescriptor))
  1467. {
  1468. delete plugin;
  1469. return nullptr;
  1470. }
  1471. return plugin;
  1472. }
  1473. // -------------------------------------------------------------------------------------------------------------------
  1474. CARLA_BACKEND_END_NAMESPACE