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.

1836 lines
65KB

  1. /*
  2. * Carla Plugin, LADSPA implementation
  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 "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. // -------------------------------------------------------------------
  316. // Misc
  317. // nothing
  318. // -------------------------------------------------------------------
  319. // Plugin state
  320. void reload() override
  321. {
  322. CARLA_SAFE_ASSERT_RETURN(pData->engine != nullptr,);
  323. CARLA_SAFE_ASSERT_RETURN(fDescriptor != nullptr,);
  324. CARLA_SAFE_ASSERT_RETURN(fHandles.count() > 0,);
  325. carla_debug("CarlaPluginLADSPA::reload() - start");
  326. const EngineProcessMode processMode(pData->engine->getProccessMode());
  327. // Safely disable plugin for reload
  328. const ScopedDisabler sd(this);
  329. if (pData->active)
  330. deactivate();
  331. clearBuffers();
  332. const float sampleRate(static_cast<float>(pData->engine->getSampleRate()));
  333. const uint32_t portCount(getSafePortCount());
  334. uint32_t aIns, aOuts, params;
  335. aIns = aOuts = params = 0;
  336. bool forcedStereoIn, forcedStereoOut;
  337. forcedStereoIn = forcedStereoOut = false;
  338. bool needsCtrlIn, needsCtrlOut;
  339. needsCtrlIn = needsCtrlOut = false;
  340. for (uint32_t i=0; i < portCount; ++i)
  341. {
  342. const LADSPA_PortDescriptor portType(fDescriptor->PortDescriptors[i]);
  343. if (LADSPA_IS_PORT_AUDIO(portType))
  344. {
  345. if (LADSPA_IS_PORT_INPUT(portType))
  346. aIns += 1;
  347. else if (LADSPA_IS_PORT_OUTPUT(portType))
  348. aOuts += 1;
  349. }
  350. else if (LADSPA_IS_PORT_CONTROL(portType))
  351. params += 1;
  352. }
  353. if (pData->options & PLUGIN_OPTION_FORCE_STEREO)
  354. {
  355. if ((aIns == 1 || aOuts == 1) && fHandles.count() == 1 && addInstance())
  356. {
  357. if (aIns == 1)
  358. {
  359. aIns = 2;
  360. forcedStereoIn = true;
  361. }
  362. if (aOuts == 1)
  363. {
  364. aOuts = 2;
  365. forcedStereoOut = true;
  366. }
  367. }
  368. }
  369. if (aIns > 0)
  370. {
  371. pData->audioIn.createNew(aIns);
  372. fAudioInBuffers = new float*[aIns];
  373. for (uint32_t i=0; i < aIns; ++i)
  374. fAudioInBuffers[i] = nullptr;
  375. }
  376. if (aOuts > 0)
  377. {
  378. pData->audioOut.createNew(aOuts);
  379. fAudioOutBuffers = new float*[aOuts];
  380. needsCtrlIn = true;
  381. for (uint32_t i=0; i < aOuts; ++i)
  382. fAudioOutBuffers[i] = nullptr;
  383. }
  384. if (params > 0)
  385. {
  386. pData->param.createNew(params, true);
  387. fParamBuffers = new float[params];
  388. FloatVectorOperations::clear(fParamBuffers, static_cast<int>(params));
  389. }
  390. const uint portNameSize(pData->engine->getMaxPortNameSize());
  391. CarlaString portName;
  392. for (uint32_t i=0, iAudioIn=0, iAudioOut=0, iCtrl=0; i < portCount; ++i)
  393. {
  394. const LADSPA_PortDescriptor portType = fDescriptor->PortDescriptors[i];
  395. const LADSPA_PortRangeHint portRangeHints = fDescriptor->PortRangeHints[i];
  396. const bool hasPortRDF = (fRdfDescriptor != nullptr && i < fRdfDescriptor->PortCount);
  397. if (LADSPA_IS_PORT_AUDIO(portType))
  398. {
  399. portName.clear();
  400. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  401. {
  402. portName = pData->name;
  403. portName += ":";
  404. }
  405. if (fDescriptor->PortNames[i] != nullptr && fDescriptor->PortNames[i][0] != '\0')
  406. {
  407. portName += fDescriptor->PortNames[i];
  408. }
  409. else
  410. {
  411. if (LADSPA_IS_PORT_INPUT(portType))
  412. {
  413. if (aIns > 1)
  414. {
  415. portName += "audio-in_";
  416. portName += CarlaString(iAudioIn+1);
  417. }
  418. else
  419. portName += "audio-in";
  420. }
  421. else
  422. {
  423. if (aOuts > 1)
  424. {
  425. portName += "audio-out_";
  426. portName += CarlaString(iAudioOut+1);
  427. }
  428. else
  429. portName += "audio-out";
  430. }
  431. }
  432. portName.truncate(portNameSize);
  433. if (LADSPA_IS_PORT_INPUT(portType))
  434. {
  435. const uint32_t j = iAudioIn++;
  436. pData->audioIn.ports[j].port = (CarlaEngineAudioPort*)pData->client->addPort(kEnginePortTypeAudio, portName, true, j);
  437. pData->audioIn.ports[j].rindex = i;
  438. if (forcedStereoIn)
  439. {
  440. portName += "_2";
  441. pData->audioIn.ports[1].port = (CarlaEngineAudioPort*)pData->client->addPort(kEnginePortTypeAudio, portName, true, 1);
  442. pData->audioIn.ports[1].rindex = i;
  443. }
  444. }
  445. else if (LADSPA_IS_PORT_OUTPUT(portType))
  446. {
  447. const uint32_t j = iAudioOut++;
  448. pData->audioOut.ports[j].port = (CarlaEngineAudioPort*)pData->client->addPort(kEnginePortTypeAudio, portName, false, j);
  449. pData->audioOut.ports[j].rindex = i;
  450. if (forcedStereoOut)
  451. {
  452. portName += "_2";
  453. pData->audioOut.ports[1].port = (CarlaEngineAudioPort*)pData->client->addPort(kEnginePortTypeAudio, portName, false, 1);
  454. pData->audioOut.ports[1].rindex = i;
  455. }
  456. }
  457. else
  458. carla_stderr2("WARNING - Got a broken Port (Audio, but not input or output)");
  459. }
  460. else if (LADSPA_IS_PORT_CONTROL(portType))
  461. {
  462. const uint32_t j = iCtrl++;
  463. pData->param.data[j].index = static_cast<int32_t>(j);
  464. pData->param.data[j].rindex = static_cast<int32_t>(i);
  465. const char* const paramName(fDescriptor->PortNames[i] != nullptr ? fDescriptor->PortNames[i] : "unknown");
  466. float min, max, def, step, stepSmall, stepLarge;
  467. // min value
  468. if (LADSPA_IS_HINT_BOUNDED_BELOW(portRangeHints.HintDescriptor))
  469. min = portRangeHints.LowerBound;
  470. else
  471. min = 0.0f;
  472. // max value
  473. if (LADSPA_IS_HINT_BOUNDED_ABOVE(portRangeHints.HintDescriptor))
  474. max = portRangeHints.UpperBound;
  475. else
  476. max = 1.0f;
  477. if (LADSPA_IS_HINT_SAMPLE_RATE(portRangeHints.HintDescriptor))
  478. {
  479. min *= sampleRate;
  480. max *= sampleRate;
  481. pData->param.data[j].hints |= PARAMETER_USES_SAMPLERATE;
  482. }
  483. if (min >= max)
  484. {
  485. carla_stderr2("WARNING - Broken plugin parameter '%s': min >= max", paramName);
  486. max = min + 0.1f;
  487. }
  488. // default value
  489. if (hasPortRDF && LADSPA_PORT_HAS_DEFAULT(fRdfDescriptor->Ports[i].Hints))
  490. def = fRdfDescriptor->Ports[i].Default;
  491. else
  492. def = get_default_ladspa_port_value(portRangeHints.HintDescriptor, min, max);
  493. if (def < min)
  494. def = min;
  495. else if (def > max)
  496. def = max;
  497. if (LADSPA_IS_HINT_TOGGLED(portRangeHints.HintDescriptor))
  498. {
  499. step = max - min;
  500. stepSmall = step;
  501. stepLarge = step;
  502. pData->param.data[j].hints |= PARAMETER_IS_BOOLEAN;
  503. }
  504. else if (LADSPA_IS_HINT_INTEGER(portRangeHints.HintDescriptor))
  505. {
  506. step = 1.0f;
  507. stepSmall = 1.0f;
  508. stepLarge = 10.0f;
  509. pData->param.data[j].hints |= PARAMETER_IS_INTEGER;
  510. }
  511. else
  512. {
  513. const float range = max - min;
  514. step = range/100.0f;
  515. stepSmall = range/1000.0f;
  516. stepLarge = range/10.0f;
  517. }
  518. if (LADSPA_IS_PORT_INPUT(portType))
  519. {
  520. pData->param.data[j].type = PARAMETER_INPUT;
  521. pData->param.data[j].hints |= PARAMETER_IS_ENABLED;
  522. pData->param.data[j].hints |= PARAMETER_IS_AUTOMABLE;
  523. needsCtrlIn = true;
  524. }
  525. else if (LADSPA_IS_PORT_OUTPUT(portType))
  526. {
  527. pData->param.data[j].type = PARAMETER_OUTPUT;
  528. if (std::strcmp(paramName, "latency") == 0 || std::strcmp(paramName, "_latency") == 0)
  529. {
  530. min = 0.0f;
  531. max = sampleRate;
  532. def = 0.0f;
  533. step = 1.0f;
  534. stepSmall = 1.0f;
  535. stepLarge = 1.0f;
  536. pData->param.special[j] = PARAMETER_SPECIAL_LATENCY;
  537. CARLA_SAFE_ASSERT_INT2(fLatencyIndex == static_cast<int32_t>(j), fLatencyIndex, j);
  538. }
  539. else
  540. {
  541. pData->param.data[j].hints |= PARAMETER_IS_ENABLED;
  542. pData->param.data[j].hints |= PARAMETER_IS_AUTOMABLE;
  543. needsCtrlOut = true;
  544. }
  545. }
  546. else
  547. {
  548. carla_stderr2("WARNING - Got a broken Port (Control, but not input or output)");
  549. }
  550. // extra parameter hints
  551. if (LADSPA_IS_HINT_LOGARITHMIC(portRangeHints.HintDescriptor))
  552. pData->param.data[j].hints |= PARAMETER_IS_LOGARITHMIC;
  553. // check for scalepoints, require at least 2 to make it useful
  554. if (hasPortRDF && fRdfDescriptor->Ports[i].ScalePointCount >= 2)
  555. pData->param.data[j].hints |= PARAMETER_USES_SCALEPOINTS;
  556. pData->param.ranges[j].min = min;
  557. pData->param.ranges[j].max = max;
  558. pData->param.ranges[j].def = def;
  559. pData->param.ranges[j].step = step;
  560. pData->param.ranges[j].stepSmall = stepSmall;
  561. pData->param.ranges[j].stepLarge = stepLarge;
  562. // Start parameters in their default values
  563. fParamBuffers[j] = def;
  564. for (LinkedList<LADSPA_Handle>::Itenerator it = fHandles.begin2(); it.valid(); it.next())
  565. {
  566. LADSPA_Handle const handle(it.getValue(nullptr));
  567. CARLA_SAFE_ASSERT_CONTINUE(handle != nullptr);
  568. try {
  569. fDescriptor->connect_port(handle, i, &fParamBuffers[j]);
  570. } CARLA_SAFE_EXCEPTION("LADSPA connect_port (parameter)");
  571. }
  572. }
  573. else
  574. {
  575. // Not Audio or Control
  576. carla_stderr2("ERROR - Got a broken Port (neither Audio or Control)");
  577. for (LinkedList<LADSPA_Handle>::Itenerator it = fHandles.begin2(); it.valid(); it.next())
  578. {
  579. LADSPA_Handle const handle(it.getValue(nullptr));
  580. CARLA_SAFE_ASSERT_CONTINUE(handle != nullptr);
  581. try {
  582. fDescriptor->connect_port(handle, i, nullptr);
  583. } CARLA_SAFE_EXCEPTION("LADSPA connect_port (null)");
  584. }
  585. }
  586. }
  587. if (needsCtrlIn)
  588. {
  589. portName.clear();
  590. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  591. {
  592. portName = pData->name;
  593. portName += ":";
  594. }
  595. portName += "events-in";
  596. portName.truncate(portNameSize);
  597. pData->event.portIn = (CarlaEngineEventPort*)pData->client->addPort(kEnginePortTypeEvent, portName, true, 0);
  598. }
  599. if (needsCtrlOut)
  600. {
  601. portName.clear();
  602. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  603. {
  604. portName = pData->name;
  605. portName += ":";
  606. }
  607. portName += "events-out";
  608. portName.truncate(portNameSize);
  609. pData->event.portOut = (CarlaEngineEventPort*)pData->client->addPort(kEnginePortTypeEvent, portName, false, 0);
  610. }
  611. if (forcedStereoIn || forcedStereoOut)
  612. pData->options |= PLUGIN_OPTION_FORCE_STEREO;
  613. else
  614. pData->options &= ~PLUGIN_OPTION_FORCE_STEREO;
  615. // plugin hints
  616. pData->hints = 0x0;
  617. if (LADSPA_IS_HARD_RT_CAPABLE(fDescriptor->Properties))
  618. pData->hints |= PLUGIN_IS_RTSAFE;
  619. #ifndef BUILD_BRIDGE
  620. if (aOuts > 0 && (aIns == aOuts || aIns == 1))
  621. pData->hints |= PLUGIN_CAN_DRYWET;
  622. if (aOuts > 0)
  623. pData->hints |= PLUGIN_CAN_VOLUME;
  624. if (aOuts >= 2 && aOuts % 2 == 0)
  625. pData->hints |= PLUGIN_CAN_BALANCE;
  626. #endif
  627. // extra plugin hints
  628. pData->extraHints = 0x0;
  629. pData->extraHints |= PLUGIN_EXTRA_HINT_CAN_RUN_RACK;
  630. // check initial latency
  631. findInitialLatencyValue(aIns, aOuts);
  632. fForcedStereoIn = forcedStereoIn;
  633. fForcedStereoOut = forcedStereoOut;
  634. bufferSizeChanged(pData->engine->getBufferSize());
  635. if (pData->active)
  636. activate();
  637. carla_debug("CarlaPluginLADSPA::reload() - end");
  638. }
  639. void findInitialLatencyValue(const uint32_t aIns, const uint32_t aOuts) const
  640. {
  641. if (fLatencyIndex < 0 || fHandles.count() == 0)
  642. return;
  643. // we need to pre-run the plugin so it can update its latency control-port
  644. const LADSPA_Handle handle(fHandles.getFirst(nullptr));
  645. CARLA_SAFE_ASSERT_RETURN(handle != nullptr,);
  646. float tmpIn [(aIns > 0) ? aIns : 1][2];
  647. float tmpOut[(aOuts > 0) ? aOuts : 1][2];
  648. for (uint32_t j=0; j < aIns; ++j)
  649. {
  650. tmpIn[j][0] = 0.0f;
  651. tmpIn[j][1] = 0.0f;
  652. try {
  653. fDescriptor->connect_port(handle, pData->audioIn.ports[j].rindex, tmpIn[j]);
  654. } CARLA_SAFE_EXCEPTION("LADSPA connect_port (latency input)");
  655. }
  656. for (uint32_t j=0; j < aOuts; ++j)
  657. {
  658. tmpOut[j][0] = 0.0f;
  659. tmpOut[j][1] = 0.0f;
  660. try {
  661. fDescriptor->connect_port(handle, pData->audioOut.ports[j].rindex, tmpOut[j]);
  662. } CARLA_SAFE_EXCEPTION("LADSPA connect_port (latency output)");
  663. }
  664. if (fDescriptor->activate != nullptr)
  665. {
  666. try {
  667. fDescriptor->activate(handle);
  668. } CARLA_SAFE_EXCEPTION("LADSPA latency activate");
  669. }
  670. try {
  671. fDescriptor->run(handle, 2);
  672. } CARLA_SAFE_EXCEPTION("LADSPA latency run");
  673. if (fDescriptor->deactivate != nullptr)
  674. {
  675. try {
  676. fDescriptor->deactivate(handle);
  677. } CARLA_SAFE_EXCEPTION("LADSPA latency deactivate");
  678. }
  679. // done, let's get the value
  680. if (const uint32_t latency = getLatencyInFrames())
  681. {
  682. pData->client->setLatency(latency);
  683. #ifndef BUILD_BRIDGE
  684. pData->latency.recreateBuffers(std::max(aIns, aOuts), latency);
  685. #endif
  686. }
  687. }
  688. // -------------------------------------------------------------------
  689. // Plugin processing
  690. void activate() noexcept override
  691. {
  692. CARLA_SAFE_ASSERT_RETURN(fDescriptor != nullptr,);
  693. if (fDescriptor->activate != nullptr)
  694. {
  695. for (LinkedList<LADSPA_Handle>::Itenerator it = fHandles.begin2(); it.valid(); it.next())
  696. {
  697. LADSPA_Handle const handle(it.getValue(nullptr));
  698. CARLA_SAFE_ASSERT_CONTINUE(handle != nullptr);
  699. try {
  700. fDescriptor->activate(handle);
  701. } CARLA_SAFE_EXCEPTION("LADSPA activate");
  702. }
  703. }
  704. }
  705. void deactivate() noexcept override
  706. {
  707. CARLA_SAFE_ASSERT_RETURN(fDescriptor != nullptr,);
  708. if (fDescriptor->deactivate != nullptr)
  709. {
  710. for (LinkedList<LADSPA_Handle>::Itenerator it = fHandles.begin2(); it.valid(); it.next())
  711. {
  712. LADSPA_Handle const handle(it.getValue(nullptr));
  713. CARLA_SAFE_ASSERT_CONTINUE(handle != nullptr);
  714. try {
  715. fDescriptor->deactivate(handle);
  716. } CARLA_SAFE_EXCEPTION("LADSPA deactivate");
  717. }
  718. }
  719. }
  720. void process(const float** const audioIn, float** const audioOut, const float** const, float** const, const uint32_t frames) override
  721. {
  722. // --------------------------------------------------------------------------------------------------------
  723. // Check if active
  724. if (! pData->active)
  725. {
  726. // disable any output sound
  727. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  728. FloatVectorOperations::clear(audioOut[i], static_cast<int>(frames));
  729. return;
  730. }
  731. // --------------------------------------------------------------------------------------------------------
  732. // Check if needs reset
  733. if (pData->needsReset)
  734. {
  735. // nothing to do
  736. pData->needsReset = false;
  737. }
  738. // --------------------------------------------------------------------------------------------------------
  739. // Event Input and Processing
  740. if (pData->event.portIn != nullptr)
  741. {
  742. // ----------------------------------------------------------------------------------------------------
  743. // Event Input (System)
  744. const bool isSampleAccurate = (pData->options & PLUGIN_OPTION_FIXED_BUFFERS) == 0;
  745. uint32_t timeOffset = 0;
  746. for (uint32_t i=0, numEvents=pData->event.portIn->getEventCount(); i < numEvents; ++i)
  747. {
  748. const EngineEvent& event(pData->event.portIn->getEvent(i));
  749. if (event.time >= frames)
  750. continue;
  751. CARLA_ASSERT_INT2(event.time >= timeOffset, event.time, timeOffset);
  752. if (isSampleAccurate && event.time > timeOffset)
  753. {
  754. if (processSingle(audioIn, audioOut, event.time - timeOffset, timeOffset))
  755. timeOffset = event.time;
  756. }
  757. switch (event.type)
  758. {
  759. case kEngineEventTypeNull:
  760. break;
  761. case kEngineEventTypeControl: {
  762. const EngineControlEvent& ctrlEvent(event.ctrl);
  763. switch (ctrlEvent.type)
  764. {
  765. case kEngineControlEventTypeNull:
  766. break;
  767. case kEngineControlEventTypeParameter: {
  768. #ifndef BUILD_BRIDGE
  769. // Control backend stuff
  770. if (event.channel == pData->ctrlChannel)
  771. {
  772. float value;
  773. if (MIDI_IS_CONTROL_BREATH_CONTROLLER(ctrlEvent.param) && (pData->hints & PLUGIN_CAN_DRYWET) != 0)
  774. {
  775. value = ctrlEvent.value;
  776. setDryWet(value, false, false);
  777. pData->postponeRtEvent(kPluginPostRtEventParameterChange, PARAMETER_DRYWET, 0, value);
  778. }
  779. if (MIDI_IS_CONTROL_CHANNEL_VOLUME(ctrlEvent.param) && (pData->hints & PLUGIN_CAN_VOLUME) != 0)
  780. {
  781. value = ctrlEvent.value*127.0f/100.0f;
  782. setVolume(value, false, false);
  783. pData->postponeRtEvent(kPluginPostRtEventParameterChange, PARAMETER_VOLUME, 0, value);
  784. }
  785. if (MIDI_IS_CONTROL_BALANCE(ctrlEvent.param) && (pData->hints & PLUGIN_CAN_BALANCE) != 0)
  786. {
  787. float left, right;
  788. value = ctrlEvent.value/0.5f - 1.0f;
  789. if (value < 0.0f)
  790. {
  791. left = -1.0f;
  792. right = (value*2.0f)+1.0f;
  793. }
  794. else if (value > 0.0f)
  795. {
  796. left = (value*2.0f)-1.0f;
  797. right = 1.0f;
  798. }
  799. else
  800. {
  801. left = -1.0f;
  802. right = 1.0f;
  803. }
  804. setBalanceLeft(left, false, false);
  805. setBalanceRight(right, false, false);
  806. pData->postponeRtEvent(kPluginPostRtEventParameterChange, PARAMETER_BALANCE_LEFT, 0, left);
  807. pData->postponeRtEvent(kPluginPostRtEventParameterChange, PARAMETER_BALANCE_RIGHT, 0, right);
  808. }
  809. }
  810. #endif
  811. // Control plugin parameters
  812. for (uint32_t k=0; k < pData->param.count; ++k)
  813. {
  814. if (pData->param.data[k].midiChannel != event.channel)
  815. continue;
  816. if (pData->param.data[k].midiCC != ctrlEvent.param)
  817. continue;
  818. if (pData->param.data[k].type != PARAMETER_INPUT)
  819. continue;
  820. if ((pData->param.data[k].hints & PARAMETER_IS_AUTOMABLE) == 0)
  821. continue;
  822. float value;
  823. if (pData->param.data[k].hints & PARAMETER_IS_BOOLEAN)
  824. {
  825. value = (ctrlEvent.value < 0.5f) ? pData->param.ranges[k].min : pData->param.ranges[k].max;
  826. }
  827. else
  828. {
  829. if (pData->param.data[k].hints & PARAMETER_IS_LOGARITHMIC)
  830. value = pData->param.ranges[k].getUnnormalizedLogValue(ctrlEvent.value);
  831. else
  832. value = pData->param.ranges[k].getUnnormalizedValue(ctrlEvent.value);
  833. if (pData->param.data[k].hints & PARAMETER_IS_INTEGER)
  834. value = std::rint(value);
  835. }
  836. setParameterValue(k, value, false, false, false);
  837. pData->postponeRtEvent(kPluginPostRtEventParameterChange, static_cast<int32_t>(k), 0, value);
  838. }
  839. break;
  840. } // case kEngineControlEventTypeParameter
  841. case kEngineControlEventTypeMidiBank:
  842. case kEngineControlEventTypeMidiProgram:
  843. case kEngineControlEventTypeAllSoundOff:
  844. case kEngineControlEventTypeAllNotesOff:
  845. break;
  846. } // switch (ctrlEvent.type)
  847. break;
  848. } // case kEngineEventTypeControl
  849. case kEngineEventTypeMidi:
  850. break;
  851. } // switch (event.type)
  852. }
  853. pData->postRtEvents.trySplice();
  854. if (frames > timeOffset)
  855. processSingle(audioIn, audioOut, frames - timeOffset, timeOffset);
  856. } // End of Event Input and Processing
  857. // --------------------------------------------------------------------------------------------------------
  858. // Plugin processing (no events)
  859. else
  860. {
  861. processSingle(audioIn, audioOut, frames, 0);
  862. } // End of Plugin processing (no events)
  863. // --------------------------------------------------------------------------------------------------------
  864. // Control Output
  865. if (pData->event.portOut != nullptr)
  866. {
  867. uint8_t channel;
  868. uint16_t param;
  869. float value;
  870. for (uint32_t k=0; k < pData->param.count; ++k)
  871. {
  872. if (pData->param.data[k].type != PARAMETER_OUTPUT)
  873. continue;
  874. pData->param.ranges[k].fixValue(fParamBuffers[k]);
  875. if (pData->param.data[k].midiCC > 0)
  876. {
  877. channel = pData->param.data[k].midiChannel;
  878. param = static_cast<uint16_t>(pData->param.data[k].midiCC);
  879. value = pData->param.ranges[k].getNormalizedValue(fParamBuffers[k]);
  880. pData->event.portOut->writeControlEvent(0, channel, kEngineControlEventTypeParameter, param, value);
  881. }
  882. }
  883. } // End of Control Output
  884. }
  885. bool processSingle(const float** const audioIn, float** const audioOut, const uint32_t frames,
  886. const uint32_t timeOffset)
  887. {
  888. CARLA_SAFE_ASSERT_RETURN(frames > 0, false);
  889. if (pData->audioIn.count > 0)
  890. {
  891. CARLA_SAFE_ASSERT_RETURN(audioIn != nullptr, false);
  892. }
  893. if (pData->audioOut.count > 0)
  894. {
  895. CARLA_SAFE_ASSERT_RETURN(audioOut != nullptr, false);
  896. }
  897. // --------------------------------------------------------------------------------------------------------
  898. // Try lock, silence otherwise
  899. if (pData->engine->isOffline())
  900. {
  901. pData->singleMutex.lock();
  902. }
  903. else if (! pData->singleMutex.tryLock())
  904. {
  905. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  906. {
  907. for (uint32_t k=0; k < frames; ++k)
  908. audioOut[i][k+timeOffset] = 0.0f;
  909. }
  910. return false;
  911. }
  912. const int iframes(static_cast<int>(frames));
  913. // --------------------------------------------------------------------------------------------------------
  914. // Set audio buffers
  915. const bool customMonoOut = pData->audioOut.count == 2 && fForcedStereoOut && ! fForcedStereoIn;
  916. const bool customStereoOut = pData->audioOut.count == 2 && fForcedStereoIn && ! fForcedStereoOut;
  917. if (! customMonoOut)
  918. {
  919. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  920. FloatVectorOperations::clear(fAudioOutBuffers[i], iframes);
  921. }
  922. for (uint32_t i=0; i < pData->audioIn.count; ++i)
  923. FloatVectorOperations::copy(fAudioInBuffers[i], audioIn[i]+timeOffset, iframes);
  924. // --------------------------------------------------------------------------------------------------------
  925. // Run plugin
  926. uint instn = 0;
  927. for (LinkedList<LADSPA_Handle>::Itenerator it = fHandles.begin2(); it.valid(); it.next(), ++instn)
  928. {
  929. LADSPA_Handle const handle(it.getValue(nullptr));
  930. CARLA_SAFE_ASSERT_CONTINUE(handle != nullptr);
  931. // ----------------------------------------------------------------------------------------------------
  932. // Mixdown for forced stereo
  933. if (customMonoOut)
  934. FloatVectorOperations::clear(fAudioOutBuffers[instn], iframes);
  935. // ----------------------------------------------------------------------------------------------------
  936. // Run it
  937. try {
  938. fDescriptor->run(handle, frames);
  939. } CARLA_SAFE_EXCEPTION("LADSPA run");
  940. // ----------------------------------------------------------------------------------------------------
  941. // Mixdown for forced stereo
  942. if (customMonoOut)
  943. FloatVectorOperations::multiply(fAudioOutBuffers[instn], 0.5f, iframes);
  944. else if (customStereoOut)
  945. FloatVectorOperations::copy(fExtraStereoBuffer[instn], fAudioOutBuffers[instn], iframes);
  946. }
  947. if (customStereoOut)
  948. {
  949. FloatVectorOperations::copy(fAudioOutBuffers[0], fExtraStereoBuffer[0], iframes);
  950. FloatVectorOperations::copy(fAudioOutBuffers[1], fExtraStereoBuffer[1], iframes);
  951. }
  952. #ifndef BUILD_BRIDGE
  953. // --------------------------------------------------------------------------------------------------------
  954. // Post-processing (dry/wet, volume and balance)
  955. {
  956. const bool doDryWet = (pData->hints & PLUGIN_CAN_DRYWET) != 0 && carla_isNotEqual(pData->postProc.dryWet, 1.0f);
  957. const bool doBalance = (pData->hints & PLUGIN_CAN_BALANCE) != 0 && ! (carla_isEqual(pData->postProc.balanceLeft, -1.0f) && carla_isEqual(pData->postProc.balanceRight, 1.0f));
  958. const bool isMono = (pData->audioIn.count == 1);
  959. bool isPair;
  960. float bufValue, oldBufLeft[doBalance ? frames : 1];
  961. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  962. {
  963. // Dry/Wet
  964. if (doDryWet)
  965. {
  966. const uint32_t c = isMono ? 0 : i;
  967. for (uint32_t k=0; k < frames; ++k)
  968. {
  969. if (k < pData->latency.frames)
  970. bufValue = pData->latency.buffers[c][k];
  971. else if (pData->latency.frames < frames)
  972. bufValue = fAudioInBuffers[c][k-pData->latency.frames];
  973. else
  974. bufValue = fAudioInBuffers[c][k];
  975. fAudioOutBuffers[i][k] = (fAudioOutBuffers[i][k] * pData->postProc.dryWet) + (bufValue * (1.0f - pData->postProc.dryWet));
  976. }
  977. }
  978. // Balance
  979. if (doBalance)
  980. {
  981. isPair = (i % 2 == 0);
  982. if (isPair)
  983. {
  984. CARLA_ASSERT(i+1 < pData->audioOut.count);
  985. FloatVectorOperations::copy(oldBufLeft, fAudioOutBuffers[i], iframes);
  986. }
  987. float balRangeL = (pData->postProc.balanceLeft + 1.0f)/2.0f;
  988. float balRangeR = (pData->postProc.balanceRight + 1.0f)/2.0f;
  989. for (uint32_t k=0; k < frames; ++k)
  990. {
  991. if (isPair)
  992. {
  993. // left
  994. fAudioOutBuffers[i][k] = oldBufLeft[k] * (1.0f - balRangeL);
  995. fAudioOutBuffers[i][k] += fAudioOutBuffers[i+1][k] * (1.0f - balRangeR);
  996. }
  997. else
  998. {
  999. // right
  1000. fAudioOutBuffers[i][k] = fAudioOutBuffers[i][k] * balRangeR;
  1001. fAudioOutBuffers[i][k] += oldBufLeft[k] * balRangeL;
  1002. }
  1003. }
  1004. }
  1005. // Volume (and buffer copy)
  1006. {
  1007. for (uint32_t k=0; k < frames; ++k)
  1008. audioOut[i][k+timeOffset] = fAudioOutBuffers[i][k] * pData->postProc.volume;
  1009. }
  1010. }
  1011. } // End of Post-processing
  1012. // --------------------------------------------------------------------------------------------------------
  1013. // Save latency values for next callback
  1014. if (const uint32_t latframes = pData->latency.frames)
  1015. {
  1016. CARLA_SAFE_ASSERT(timeOffset == 0);
  1017. if (latframes <= frames)
  1018. {
  1019. for (uint32_t i=0; i < pData->audioIn.count; ++i)
  1020. FloatVectorOperations::copy(pData->latency.buffers[i], audioIn[i]+(frames-latframes), static_cast<int>(latframes));
  1021. }
  1022. else
  1023. {
  1024. const uint32_t diff = pData->latency.frames-frames;
  1025. for (uint32_t i=0, k; i<pData->audioIn.count; ++i)
  1026. {
  1027. // push back buffer by 'frames'
  1028. for (k=0; k < diff; ++k)
  1029. pData->latency.buffers[i][k] = pData->latency.buffers[i][k+frames];
  1030. // put current input at the end
  1031. for (uint32_t j=0; k < latframes; ++j, ++k)
  1032. pData->latency.buffers[i][k] = audioIn[i][j];
  1033. }
  1034. }
  1035. }
  1036. #else // BUILD_BRIDGE
  1037. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  1038. {
  1039. for (uint32_t k=0; k < frames; ++k)
  1040. audioOut[i][k+timeOffset] = fAudioOutBuffers[i][k];
  1041. }
  1042. #endif
  1043. // --------------------------------------------------------------------------------------------------------
  1044. pData->singleMutex.unlock();
  1045. return true;
  1046. }
  1047. void bufferSizeChanged(const uint32_t newBufferSize) override
  1048. {
  1049. CARLA_ASSERT_INT(newBufferSize > 0, newBufferSize);
  1050. carla_debug("CarlaPluginLADSPA::bufferSizeChanged(%i) - start", newBufferSize);
  1051. const int iBufferSize(static_cast<int>(newBufferSize));
  1052. for (uint32_t i=0; i < pData->audioIn.count; ++i)
  1053. {
  1054. if (fAudioInBuffers[i] != nullptr)
  1055. delete[] fAudioInBuffers[i];
  1056. fAudioInBuffers[i] = new float[newBufferSize];
  1057. FloatVectorOperations::clear(fAudioInBuffers[i], iBufferSize);
  1058. }
  1059. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  1060. {
  1061. if (fAudioOutBuffers[i] != nullptr)
  1062. delete[] fAudioOutBuffers[i];
  1063. fAudioOutBuffers[i] = new float[newBufferSize];
  1064. FloatVectorOperations::clear(fAudioOutBuffers[i], iBufferSize);
  1065. }
  1066. if (fExtraStereoBuffer[0] != nullptr)
  1067. {
  1068. delete[] fExtraStereoBuffer[0];
  1069. fExtraStereoBuffer[0] = nullptr;
  1070. }
  1071. if (fExtraStereoBuffer[1] != nullptr)
  1072. {
  1073. delete[] fExtraStereoBuffer[1];
  1074. fExtraStereoBuffer[1] = nullptr;
  1075. }
  1076. if (fForcedStereoIn && pData->audioOut.count == 2)
  1077. {
  1078. fExtraStereoBuffer[0] = new float[newBufferSize];
  1079. fExtraStereoBuffer[1] = new float[newBufferSize];
  1080. FloatVectorOperations::clear(fExtraStereoBuffer[0], iBufferSize);
  1081. FloatVectorOperations::clear(fExtraStereoBuffer[1], iBufferSize);
  1082. }
  1083. reconnectAudioPorts();
  1084. carla_debug("CarlaPluginLADSPA::bufferSizeChanged(%i) - end", newBufferSize);
  1085. }
  1086. void sampleRateChanged(const double newSampleRate) override
  1087. {
  1088. CARLA_ASSERT_INT(newSampleRate > 0.0, newSampleRate);
  1089. carla_stdout("CarlaPluginLADSPA::sampleRateChanged(%g) - start", newSampleRate);
  1090. if (pData->active)
  1091. deactivate();
  1092. const std::size_t instanceCount(fHandles.count());
  1093. if (fDescriptor->cleanup == nullptr)
  1094. {
  1095. for (LinkedList<LADSPA_Handle>::Itenerator it = fHandles.begin2(); it.valid(); it.next())
  1096. {
  1097. LADSPA_Handle const handle(it.getValue(nullptr));
  1098. CARLA_SAFE_ASSERT_CONTINUE(handle != nullptr);
  1099. try {
  1100. fDescriptor->cleanup(handle);
  1101. } CARLA_SAFE_EXCEPTION("LADSPA cleanup");
  1102. }
  1103. }
  1104. fHandles.clear();
  1105. for (std::size_t i=0; i<instanceCount; ++i)
  1106. addInstance();
  1107. reconnectAudioPorts();
  1108. if (pData->active)
  1109. activate();
  1110. carla_stdout("CarlaPluginLADSPA::sampleRateChanged(%g) - end", newSampleRate);
  1111. }
  1112. void reconnectAudioPorts() const noexcept
  1113. {
  1114. if (fForcedStereoIn)
  1115. {
  1116. if (LADSPA_Handle const handle = fHandles.getFirst(nullptr))
  1117. {
  1118. try {
  1119. fDescriptor->connect_port(handle, pData->audioIn.ports[0].rindex, fAudioInBuffers[0]);
  1120. } CARLA_SAFE_EXCEPTION("LADSPA connect_port (forced stereo input, first)");
  1121. }
  1122. if (LADSPA_Handle const handle = fHandles.getLast(nullptr))
  1123. {
  1124. try {
  1125. fDescriptor->connect_port(handle, pData->audioIn.ports[1].rindex, fAudioInBuffers[1]);
  1126. } CARLA_SAFE_EXCEPTION("LADSPA connect_port (forced stereo input, last)");
  1127. }
  1128. }
  1129. else
  1130. {
  1131. for (LinkedList<LADSPA_Handle>::Itenerator it = fHandles.begin2(); it.valid(); it.next())
  1132. {
  1133. LADSPA_Handle const handle(it.getValue(nullptr));
  1134. CARLA_SAFE_ASSERT_CONTINUE(handle != nullptr);
  1135. for (uint32_t i=0; i < pData->audioIn.count; ++i)
  1136. {
  1137. try {
  1138. fDescriptor->connect_port(handle, pData->audioIn.ports[i].rindex, fAudioInBuffers[i]);
  1139. } CARLA_SAFE_EXCEPTION("LADSPA connect_port (audio input)");
  1140. }
  1141. }
  1142. }
  1143. if (fForcedStereoOut)
  1144. {
  1145. if (LADSPA_Handle const handle = fHandles.getFirst(nullptr))
  1146. {
  1147. try {
  1148. fDescriptor->connect_port(handle, pData->audioOut.ports[0].rindex, fAudioOutBuffers[0]);
  1149. } CARLA_SAFE_EXCEPTION("LADSPA connect_port (forced stereo output, first)");
  1150. }
  1151. if (LADSPA_Handle const handle = fHandles.getLast(nullptr))
  1152. {
  1153. try {
  1154. fDescriptor->connect_port(handle, pData->audioOut.ports[1].rindex, fAudioOutBuffers[1]);
  1155. } CARLA_SAFE_EXCEPTION("LADSPA connect_port (forced stereo output, last)");
  1156. }
  1157. }
  1158. else
  1159. {
  1160. for (LinkedList<LADSPA_Handle>::Itenerator it = fHandles.begin2(); it.valid(); it.next())
  1161. {
  1162. LADSPA_Handle const handle(it.getValue(nullptr));
  1163. CARLA_SAFE_ASSERT_CONTINUE(handle != nullptr);
  1164. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  1165. {
  1166. try {
  1167. fDescriptor->connect_port(handle, pData->audioOut.ports[i].rindex, fAudioOutBuffers[i]);
  1168. } CARLA_SAFE_EXCEPTION("LADSPA connect_port (audio output)");
  1169. }
  1170. }
  1171. }
  1172. }
  1173. // -------------------------------------------------------------------
  1174. // Plugin buffers
  1175. void clearBuffers() noexcept override
  1176. {
  1177. carla_debug("CarlaPluginLADSPA::clearBuffers() - start");
  1178. if (fAudioInBuffers != nullptr)
  1179. {
  1180. for (uint32_t i=0; i < pData->audioIn.count; ++i)
  1181. {
  1182. if (fAudioInBuffers[i] != nullptr)
  1183. {
  1184. delete[] fAudioInBuffers[i];
  1185. fAudioInBuffers[i] = nullptr;
  1186. }
  1187. }
  1188. delete[] fAudioInBuffers;
  1189. fAudioInBuffers = nullptr;
  1190. }
  1191. if (fAudioOutBuffers != nullptr)
  1192. {
  1193. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  1194. {
  1195. if (fAudioOutBuffers[i] != nullptr)
  1196. {
  1197. delete[] fAudioOutBuffers[i];
  1198. fAudioOutBuffers[i] = nullptr;
  1199. }
  1200. }
  1201. delete[] fAudioOutBuffers;
  1202. fAudioOutBuffers = nullptr;
  1203. }
  1204. if (fExtraStereoBuffer[0] != nullptr)
  1205. {
  1206. delete[] fExtraStereoBuffer[0];
  1207. fExtraStereoBuffer[0] = nullptr;
  1208. }
  1209. if (fExtraStereoBuffer[1] != nullptr)
  1210. {
  1211. delete[] fExtraStereoBuffer[1];
  1212. fExtraStereoBuffer[1] = nullptr;
  1213. }
  1214. if (fParamBuffers != nullptr)
  1215. {
  1216. delete[] fParamBuffers;
  1217. fParamBuffers = nullptr;
  1218. }
  1219. CarlaPlugin::clearBuffers();
  1220. carla_debug("CarlaPluginLADSPA::clearBuffers() - end");
  1221. }
  1222. // -------------------------------------------------------------------
  1223. const void* getNativeDescriptor() const noexcept override
  1224. {
  1225. return fDescriptor;
  1226. }
  1227. const void* getExtraStuff() const noexcept override
  1228. {
  1229. return fRdfDescriptor;
  1230. }
  1231. // -------------------------------------------------------------------
  1232. bool init(const char* const filename, const char* name, const char* const label, const uint options,
  1233. const LADSPA_RDF_Descriptor* const rdfDescriptor)
  1234. {
  1235. CARLA_SAFE_ASSERT_RETURN(pData->engine != nullptr, false);
  1236. // ---------------------------------------------------------------
  1237. // first checks
  1238. if (pData->client != nullptr)
  1239. {
  1240. pData->engine->setLastError("Plugin client is already registered");
  1241. return false;
  1242. }
  1243. if (filename == nullptr || filename[0] == '\0')
  1244. {
  1245. pData->engine->setLastError("null filename");
  1246. return false;
  1247. }
  1248. // ---------------------------------------------------------------
  1249. // open DLL
  1250. if (! pData->libOpen(filename))
  1251. {
  1252. pData->engine->setLastError(pData->libError(filename));
  1253. return false;
  1254. }
  1255. // ---------------------------------------------------------------
  1256. // get DLL main entry
  1257. const LADSPA_Descriptor_Function descFn = pData->libSymbol<LADSPA_Descriptor_Function>("ladspa_descriptor");
  1258. if (descFn == nullptr)
  1259. {
  1260. pData->engine->setLastError("Could not find the LASDPA Descriptor in the plugin library");
  1261. return false;
  1262. }
  1263. // ---------------------------------------------------------------
  1264. // get descriptor that matches label
  1265. // if label is null, get first valid plugin
  1266. const bool nullLabel = (label == nullptr || label[0] == '\0');
  1267. for (ulong d=0;; ++d)
  1268. {
  1269. try {
  1270. fDescriptor = descFn(d);
  1271. }
  1272. catch(...) {
  1273. carla_stderr2("Caught exception when trying to get LADSPA descriptor");
  1274. fDescriptor = nullptr;
  1275. break;
  1276. }
  1277. if (fDescriptor == nullptr)
  1278. break;
  1279. if (fDescriptor->Label == nullptr || fDescriptor->Label[0] == '\0')
  1280. {
  1281. carla_stderr2("WARNING - Got an invalid label, will not use this plugin");
  1282. fDescriptor = nullptr;
  1283. break;
  1284. }
  1285. if (fDescriptor->run == nullptr)
  1286. {
  1287. carla_stderr2("WARNING - Plugin has no run, cannot use it");
  1288. fDescriptor = nullptr;
  1289. break;
  1290. }
  1291. if (nullLabel || std::strcmp(fDescriptor->Label, label) == 0)
  1292. break;
  1293. }
  1294. if (fDescriptor == nullptr)
  1295. {
  1296. pData->engine->setLastError("Could not find the requested plugin label in the plugin library");
  1297. return false;
  1298. }
  1299. // ---------------------------------------------------------------
  1300. // check for fixed buffer size requirement
  1301. fNeedsFixedBuffers = CarlaString(filename).contains("dssi-vst", true);
  1302. if (fNeedsFixedBuffers && ! pData->engine->usesConstantBufferSize())
  1303. {
  1304. pData->engine->setLastError("Cannot use this plugin under the current engine.\n"
  1305. "The plugin requires a fixed block size which is not possible right now.");
  1306. return false;
  1307. }
  1308. // ---------------------------------------------------------------
  1309. // get info
  1310. if (is_ladspa_rdf_descriptor_valid(rdfDescriptor, fDescriptor))
  1311. fRdfDescriptor = ladspa_rdf_dup(rdfDescriptor);
  1312. if (name == nullptr || name[0] == '\0')
  1313. {
  1314. /**/ if (fRdfDescriptor != nullptr && fRdfDescriptor->Title != nullptr && fRdfDescriptor->Title[0] != '\0')
  1315. name = fRdfDescriptor->Title;
  1316. else if (fDescriptor->Name != nullptr && fDescriptor->Name[0] != '\0')
  1317. name = fDescriptor->Name;
  1318. else
  1319. name = fDescriptor->Label;
  1320. }
  1321. pData->name = pData->engine->getUniquePluginName(name);
  1322. pData->filename = carla_strdup(filename);
  1323. // ---------------------------------------------------------------
  1324. // register client
  1325. pData->client = pData->engine->addClient(this);
  1326. if (pData->client == nullptr || ! pData->client->isOk())
  1327. {
  1328. pData->engine->setLastError("Failed to register plugin client");
  1329. return false;
  1330. }
  1331. // ---------------------------------------------------------------
  1332. // initialize plugin
  1333. if (! addInstance())
  1334. return false;
  1335. // ---------------------------------------------------------------
  1336. // find latency port index
  1337. for (uint32_t i=0, iCtrl=0, count=getSafePortCount(); i<count; ++i)
  1338. {
  1339. const int portType(fDescriptor->PortDescriptors[i]);
  1340. if (! LADSPA_IS_PORT_CONTROL(portType))
  1341. continue;
  1342. const uint32_t index(iCtrl++);
  1343. if (! LADSPA_IS_PORT_OUTPUT(portType))
  1344. continue;
  1345. const char* const portName(fDescriptor->PortNames[i]);
  1346. CARLA_SAFE_ASSERT_BREAK(portName != nullptr);
  1347. if (std::strcmp(portName, "latency") == 0 ||
  1348. std::strcmp(portName, "_latency") == 0)
  1349. {
  1350. fLatencyIndex = static_cast<int32_t>(index);
  1351. break;
  1352. }
  1353. }
  1354. // ---------------------------------------------------------------
  1355. // set default options
  1356. pData->options = 0x0;
  1357. /**/ if (fLatencyIndex >= 0 || fNeedsFixedBuffers)
  1358. pData->options |= PLUGIN_OPTION_FIXED_BUFFERS;
  1359. else if (options & PLUGIN_OPTION_FIXED_BUFFERS)
  1360. pData->options |= PLUGIN_OPTION_FIXED_BUFFERS;
  1361. /**/ if (pData->engine->getOptions().forceStereo)
  1362. pData->options |= PLUGIN_OPTION_FORCE_STEREO;
  1363. else if (options & PLUGIN_OPTION_FORCE_STEREO)
  1364. pData->options |= PLUGIN_OPTION_FORCE_STEREO;
  1365. return true;
  1366. }
  1367. // -------------------------------------------------------------------
  1368. private:
  1369. LinkedList<LADSPA_Handle> fHandles;
  1370. const LADSPA_Descriptor* fDescriptor;
  1371. const LADSPA_RDF_Descriptor* fRdfDescriptor;
  1372. float** fAudioInBuffers;
  1373. float** fAudioOutBuffers;
  1374. float* fExtraStereoBuffer[2]; // used only if forcedStereoIn and audioOut == 2
  1375. float* fParamBuffers;
  1376. int32_t fLatencyIndex; // -1 if invalid
  1377. bool fForcedStereoIn;
  1378. bool fForcedStereoOut;
  1379. bool fNeedsFixedBuffers;
  1380. // -------------------------------------------------------------------
  1381. bool addInstance()
  1382. {
  1383. LADSPA_Handle handle;
  1384. try {
  1385. handle = fDescriptor->instantiate(fDescriptor, static_cast<ulong>(pData->engine->getSampleRate()));
  1386. } CARLA_SAFE_EXCEPTION_RETURN_ERR("LADSPA instantiate", "Plugin failed to initialize");
  1387. for (uint32_t i=0, count=pData->param.count; i<count; ++i)
  1388. {
  1389. const int32_t rindex(pData->param.data[i].rindex);
  1390. CARLA_SAFE_ASSERT_CONTINUE(rindex >= 0);
  1391. try {
  1392. fDescriptor->connect_port(handle, static_cast<ulong>(rindex), &fParamBuffers[i]);
  1393. } CARLA_SAFE_EXCEPTION("LADSPA connect_port");
  1394. }
  1395. if (fHandles.append(handle))
  1396. return true;
  1397. try {
  1398. fDescriptor->cleanup(handle);
  1399. } CARLA_SAFE_EXCEPTION("LADSPA cleanup");
  1400. pData->engine->setLastError("Out of memory");
  1401. return false;
  1402. }
  1403. uint32_t getSafePortCount() const noexcept
  1404. {
  1405. if (fDescriptor->PortCount == 0)
  1406. return 0;
  1407. CARLA_SAFE_ASSERT_RETURN(fDescriptor->PortDescriptors != nullptr, 0);
  1408. CARLA_SAFE_ASSERT_RETURN(fDescriptor->PortRangeHints != nullptr, 0);
  1409. CARLA_SAFE_ASSERT_RETURN(fDescriptor->PortNames != nullptr, 0);
  1410. return static_cast<uint32_t>(fDescriptor->PortCount);
  1411. }
  1412. bool getSeparatedParameterNameOrUnit(const char* const paramName, char* const strBuf, const bool wantName) const noexcept
  1413. {
  1414. if (_getSeparatedParameterNameOrUnitImpl(paramName, strBuf, wantName, true))
  1415. return true;
  1416. if (_getSeparatedParameterNameOrUnitImpl(paramName, strBuf, wantName, false))
  1417. return true;
  1418. return false;
  1419. }
  1420. static bool _getSeparatedParameterNameOrUnitImpl(const char* const paramName, char* const strBuf,
  1421. const bool wantName, const bool useBracket) noexcept
  1422. {
  1423. const char* const sepBracketStart(std::strstr(paramName, useBracket ? " [" : " ("));
  1424. if (sepBracketStart == nullptr)
  1425. return false;
  1426. const char* const sepBracketEnd(std::strstr(sepBracketStart, useBracket ? "]" : ")"));
  1427. if (sepBracketEnd == nullptr)
  1428. return false;
  1429. const std::size_t unitSize(static_cast<std::size_t>(sepBracketEnd-sepBracketStart-2));
  1430. if (unitSize > 7) // very unlikely to have such big unit
  1431. return false;
  1432. const std::size_t sepIndex(std::strlen(paramName)-unitSize-3);
  1433. // just in case
  1434. if (sepIndex+2 >= STR_MAX)
  1435. return false;
  1436. if (wantName)
  1437. {
  1438. std::strncpy(strBuf, paramName, sepIndex);
  1439. strBuf[sepIndex] = '\0';
  1440. }
  1441. else
  1442. {
  1443. std::strncpy(strBuf, paramName+(sepIndex+2), unitSize);
  1444. strBuf[unitSize] = '\0';
  1445. }
  1446. return true;
  1447. }
  1448. // -------------------------------------------------------------------
  1449. CARLA_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(CarlaPluginLADSPA)
  1450. };
  1451. // -------------------------------------------------------------------------------------------------------------------
  1452. CarlaPlugin* CarlaPlugin::newLADSPA(const Initializer& init, const LADSPA_RDF_Descriptor* const rdfDescriptor)
  1453. {
  1454. carla_debug("CarlaPlugin::newLADSPA({%p, \"%s\", \"%s\", \"%s\", " P_INT64 ", %x}, %p)",
  1455. init.engine, init.filename, init.name, init.label, init.uniqueId, init.options, rdfDescriptor);
  1456. CarlaPluginLADSPA* const plugin(new CarlaPluginLADSPA(init.engine, init.id));
  1457. if (! plugin->init(init.filename, init.name, init.label, init.options, rdfDescriptor))
  1458. {
  1459. delete plugin;
  1460. return nullptr;
  1461. }
  1462. return plugin;
  1463. }
  1464. // -------------------------------------------------------------------------------------------------------------------
  1465. CARLA_BACKEND_END_NAMESPACE