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.

2815 lines
102KB

  1. /*
  2. * Carla Plugin, DSSI 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 "CarlaEngineUtils.hpp"
  19. #include "CarlaDssiUtils.hpp"
  20. #include "CarlaMathUtils.hpp"
  21. #ifdef HAVE_LIBLO
  22. # include "CarlaOscUtils.hpp"
  23. # include "CarlaPipeUtils.hpp"
  24. # include "CarlaThread.hpp"
  25. #endif
  26. #include "water/threads/ChildProcess.h"
  27. using water::ChildProcess;
  28. using water::String;
  29. using water::StringArray;
  30. #define CARLA_PLUGIN_DSSI_OSC_CHECK_OSC_TYPES(/* argc, types, */ argcToCompare, typesToCompare) \
  31. /* check argument count */ \
  32. if (argc != argcToCompare) \
  33. { \
  34. carla_stderr("CarlaPluginDSSI::%s() - argument count mismatch: %i != %i", __FUNCTION__, argc, argcToCompare); \
  35. return; \
  36. } \
  37. if (argc > 0) \
  38. { \
  39. /* check for nullness */ \
  40. if (types == nullptr || typesToCompare == nullptr) \
  41. { \
  42. carla_stderr("CarlaPluginDSSI::%s() - argument types are null", __FUNCTION__); \
  43. return; \
  44. } \
  45. /* check argument types */ \
  46. if (std::strcmp(types, typesToCompare) != 0) \
  47. { \
  48. carla_stderr("CarlaPluginDSSI::%s() - argument types mismatch: '%s' != '%s'", __FUNCTION__, types, typesToCompare); \
  49. return; \
  50. } \
  51. }
  52. CARLA_BACKEND_START_NAMESPACE
  53. // -------------------------------------------------------------------
  54. // Fallback data
  55. static const CustomData kCustomDataFallback = { nullptr, nullptr, nullptr };
  56. #ifdef HAVE_LIBLO
  57. // -------------------------------------------------------------------
  58. class CarlaThreadDSSIUI : public CarlaThread
  59. {
  60. public:
  61. CarlaThreadDSSIUI(CarlaEngine* const engine, CarlaPlugin* const plugin, const CarlaOscData& oscData) noexcept
  62. : CarlaThread("CarlaThreadDSSIUI"),
  63. kEngine(engine),
  64. kPlugin(plugin),
  65. fBinary(),
  66. fLabel(),
  67. fOscData(oscData),
  68. fProcess() {}
  69. void setData(const char* const binary, const char* const label) noexcept
  70. {
  71. CARLA_SAFE_ASSERT_RETURN(binary != nullptr && binary[0] != '\0',);
  72. CARLA_SAFE_ASSERT_RETURN(label != nullptr /*&& label[0] != '\0'*/,);
  73. CARLA_SAFE_ASSERT(! isThreadRunning());
  74. fBinary = binary;
  75. fLabel = label;
  76. if (fLabel.isEmpty())
  77. fLabel = "\"\"";
  78. }
  79. uintptr_t getProcessId() const noexcept
  80. {
  81. CARLA_SAFE_ASSERT_RETURN(fProcess != nullptr, 0);
  82. return (uintptr_t)fProcess->getPID();
  83. }
  84. void run()
  85. {
  86. carla_stdout("DSSI UI thread started");
  87. if (fProcess == nullptr)
  88. {
  89. fProcess = new ChildProcess();
  90. }
  91. else if (fProcess->isRunning())
  92. {
  93. carla_stderr("CarlaThreadDSSI::run() - already running, giving up...");
  94. fProcess->kill();
  95. fProcess = nullptr;
  96. kEngine->callback(CarlaBackend::ENGINE_CALLBACK_UI_STATE_CHANGED, kPlugin->getId(), 0, 0, 0.0f, nullptr);
  97. return;
  98. }
  99. String name(kPlugin->getName());
  100. String filename(kPlugin->getFilename());
  101. if (name.isEmpty())
  102. name = "(none)";
  103. if (filename.isEmpty())
  104. filename = "\"\"";
  105. StringArray arguments;
  106. // binary
  107. arguments.add(fBinary.buffer());
  108. // osc-url
  109. arguments.add(String(kEngine->getOscServerPathUDP()) + String("/") + String(kPlugin->getId()));
  110. // filename
  111. arguments.add(filename);
  112. // label
  113. arguments.add(fLabel.buffer());
  114. // ui-title
  115. arguments.add(name + String(" (GUI)"));
  116. bool started;
  117. {
  118. #ifdef CARLA_OS_LINUX
  119. /*
  120. * If the frontend uses winId parent, set LD_PRELOAD to auto-map the DSSI UI.
  121. * If not, unset LD_PRELOAD.
  122. */
  123. const uintptr_t winId(kEngine->getOptions().frontendWinId);
  124. // for CARLA_ENGINE_OPTION_FRONTEND_WIN_ID
  125. char winIdStr[STR_MAX+1];
  126. winIdStr[STR_MAX] = '\0';
  127. // for LD_PRELOAD
  128. CarlaString ldPreloadValue;
  129. if (winId != 0)
  130. {
  131. std::snprintf(winIdStr, STR_MAX, P_UINTPTR, winId);
  132. ldPreloadValue = (CarlaString(kEngine->getOptions().binaryDir)
  133. + "/libcarla_interposer-x11.so");
  134. }
  135. else
  136. {
  137. winIdStr[0] = '\0';
  138. }
  139. const ScopedEngineEnvironmentLocker _seel(kEngine);
  140. const ScopedEnvVar _sev1("CARLA_ENGINE_OPTION_FRONTEND_WIN_ID", winIdStr[0] != '\0' ? winIdStr : nullptr);
  141. const ScopedEnvVar _sev2("LD_PRELOAD", ldPreloadValue.isNotEmpty() ? ldPreloadValue.buffer() : nullptr);
  142. #endif // CARLA_OS_LINUX
  143. // start the DSSI UI application
  144. carla_stdout("starting DSSI UI...");
  145. started = fProcess->start(arguments);
  146. }
  147. if (! started)
  148. {
  149. carla_stdout("failed!");
  150. fProcess = nullptr;
  151. return;
  152. }
  153. if (waitForOscGuiShow())
  154. {
  155. for (; fProcess->isRunning() && ! shouldThreadExit();)
  156. carla_sleep(1);
  157. // we only get here if UI was closed or thread asked to exit
  158. if (fProcess->isRunning() && shouldThreadExit())
  159. {
  160. fProcess->waitForProcessToFinish(static_cast<int>(kEngine->getOptions().uiBridgesTimeout));
  161. if (fProcess->isRunning())
  162. {
  163. carla_stdout("CarlaThreadDSSIUI::run() - UI refused to close, force kill now");
  164. fProcess->kill();
  165. }
  166. else
  167. {
  168. carla_stdout("CarlaThreadDSSIUI::run() - UI auto-closed successfully");
  169. }
  170. }
  171. else if (fProcess->getExitCode() != 0 /*|| fProcess->exitStatus() == QProcess::CrashExit*/)
  172. carla_stderr("CarlaThreadDSSIUI::run() - UI crashed while running");
  173. else
  174. carla_stdout("CarlaThreadDSSIUI::run() - UI closed cleanly");
  175. }
  176. else
  177. {
  178. fProcess->kill();
  179. carla_stdout("CarlaThreadDSSIUI::run() - GUI timeout");
  180. }
  181. fProcess = nullptr;
  182. kEngine->callback(CarlaBackend::ENGINE_CALLBACK_UI_STATE_CHANGED, kPlugin->getId(), 0, 0, 0.0f, nullptr);
  183. carla_stdout("DSSI UI thread finished");
  184. }
  185. private:
  186. CarlaEngine* const kEngine;
  187. CarlaPlugin* const kPlugin;
  188. CarlaString fBinary;
  189. CarlaString fLabel;
  190. const CarlaOscData& fOscData;
  191. ScopedPointer<ChildProcess> fProcess;
  192. bool waitForOscGuiShow()
  193. {
  194. carla_stdout("CarlaThreadDSSIUI::waitForOscGuiShow()");
  195. const uint uiBridgesTimeout = kEngine->getOptions().uiBridgesTimeout;
  196. // wait for UI 'update' call
  197. for (uint i=0; i < uiBridgesTimeout/100; ++i)
  198. {
  199. if (fOscData.target != nullptr)
  200. {
  201. carla_stdout("CarlaThreadDSSIUI::waitForOscGuiShow() - got response, asking UI to show itself now");
  202. osc_send_show(fOscData);
  203. return true;
  204. }
  205. if (fProcess != nullptr && fProcess->isRunning() && ! shouldThreadExit())
  206. carla_msleep(100);
  207. else
  208. return false;
  209. }
  210. carla_stdout("CarlaThreadDSSIUI::waitForOscGuiShow() - Timeout while waiting for UI to respond"
  211. "(waited %u msecs)", uiBridgesTimeout);
  212. return false;
  213. }
  214. CARLA_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(CarlaThreadDSSIUI)
  215. };
  216. #endif
  217. // -----------------------------------------------------
  218. class CarlaPluginDSSI : public CarlaPlugin
  219. {
  220. public:
  221. CarlaPluginDSSI(CarlaEngine* const engine, const uint id) noexcept
  222. : CarlaPlugin(engine, id),
  223. fHandles(),
  224. fDescriptor(nullptr),
  225. fDssiDescriptor(nullptr),
  226. fAudioInBuffers(nullptr),
  227. fAudioOutBuffers(nullptr),
  228. fExtraStereoBuffer(),
  229. fParamBuffers(nullptr),
  230. fLatencyIndex(-1),
  231. fForcedStereoIn(false),
  232. fForcedStereoOut(false),
  233. fNeedsFixedBuffers(false),
  234. fUsesCustomData(false)
  235. #ifdef HAVE_LIBLO
  236. , fOscData(),
  237. fThreadUI(engine, this, fOscData),
  238. fUiFilename(nullptr)
  239. #endif
  240. {
  241. carla_debug("CarlaPluginDSSI::CarlaPluginDSSI(%p, %i)", engine, id);
  242. carla_zeroPointers(fExtraStereoBuffer, 2);
  243. }
  244. ~CarlaPluginDSSI() noexcept override
  245. {
  246. carla_debug("CarlaPluginDSSI::~CarlaPluginDSSI()");
  247. #ifdef HAVE_LIBLO
  248. // close UI
  249. if (fUiFilename != nullptr)
  250. {
  251. showCustomUI(false);
  252. delete[] fUiFilename;
  253. fUiFilename = nullptr;
  254. }
  255. #endif
  256. pData->singleMutex.lock();
  257. pData->masterMutex.lock();
  258. if (pData->client != nullptr && pData->client->isActive())
  259. pData->client->deactivate();
  260. if (pData->active)
  261. {
  262. deactivate();
  263. pData->active = false;
  264. }
  265. if (fDescriptor != nullptr)
  266. {
  267. if (fDescriptor->cleanup != nullptr)
  268. {
  269. for (LinkedList<LADSPA_Handle>::Itenerator it = fHandles.begin2(); it.valid(); it.next())
  270. {
  271. LADSPA_Handle const handle(it.getValue(nullptr));
  272. CARLA_SAFE_ASSERT_CONTINUE(handle != nullptr);
  273. try {
  274. fDescriptor->cleanup(handle);
  275. } CARLA_SAFE_EXCEPTION("LADSPA cleanup");
  276. }
  277. }
  278. fHandles.clear();
  279. fDescriptor = nullptr;
  280. fDssiDescriptor = nullptr;
  281. }
  282. clearBuffers();
  283. }
  284. // -------------------------------------------------------------------
  285. // Information (base)
  286. PluginType getType() const noexcept override
  287. {
  288. return PLUGIN_DSSI;
  289. }
  290. PluginCategory getCategory() const noexcept override
  291. {
  292. CARLA_SAFE_ASSERT_RETURN(fDssiDescriptor != nullptr, PLUGIN_CATEGORY_NONE);
  293. if (pData->audioIn.count == 0 && pData->audioOut.count > 0 && fDssiDescriptor->run_synth != nullptr)
  294. return PLUGIN_CATEGORY_SYNTH;
  295. return CarlaPlugin::getCategory();
  296. }
  297. int64_t getUniqueId() const noexcept override
  298. {
  299. CARLA_SAFE_ASSERT_RETURN(fDescriptor != nullptr, 0);
  300. return static_cast<int64_t>(fDescriptor->UniqueID);
  301. }
  302. uint32_t getLatencyInFrames() const noexcept override
  303. {
  304. if (fLatencyIndex < 0 || fParamBuffers == nullptr)
  305. return 0;
  306. const float latency(fParamBuffers[fLatencyIndex]);
  307. CARLA_SAFE_ASSERT_RETURN(latency >= 0.0f, 0);
  308. return static_cast<uint32_t>(latency);
  309. }
  310. // -------------------------------------------------------------------
  311. // Information (count)
  312. // nothing
  313. // -------------------------------------------------------------------
  314. // Information (current data)
  315. std::size_t getChunkData(void** const dataPtr) noexcept override
  316. {
  317. CARLA_SAFE_ASSERT_RETURN(fUsesCustomData, 0);
  318. CARLA_SAFE_ASSERT_RETURN(pData->options & PLUGIN_OPTION_USE_CHUNKS, 0);
  319. CARLA_SAFE_ASSERT_RETURN(fDssiDescriptor != nullptr, 0);
  320. CARLA_SAFE_ASSERT_RETURN(fDssiDescriptor->get_custom_data != nullptr, 0);
  321. CARLA_SAFE_ASSERT_RETURN(fHandles.count() > 0, 0);
  322. CARLA_SAFE_ASSERT_RETURN(dataPtr != nullptr, 0);
  323. *dataPtr = nullptr;
  324. int ret = 0;
  325. ulong dataSize = 0;
  326. try {
  327. ret = fDssiDescriptor->get_custom_data(fHandles.getFirst(nullptr), dataPtr, &dataSize);
  328. } CARLA_SAFE_EXCEPTION_RETURN("CarlaPluginDSSI::getChunkData", 0);
  329. return (ret != 0) ? dataSize : 0;
  330. }
  331. // -------------------------------------------------------------------
  332. // Information (per-plugin data)
  333. uint getOptionsAvailable() const noexcept override
  334. {
  335. CARLA_SAFE_ASSERT_RETURN(fDssiDescriptor != nullptr, 0x0);
  336. uint options = 0x0;
  337. // can't disable fixed buffers if using latency
  338. if (fLatencyIndex == -1 && ! fNeedsFixedBuffers)
  339. options |= PLUGIN_OPTION_FIXED_BUFFERS;
  340. // can't disable forced stereo if enabled in the engine
  341. if (pData->engine->getOptions().forceStereo)
  342. pass();
  343. // if inputs or outputs are just 1, then yes we can force stereo
  344. else if (pData->audioIn.count == 1 || pData->audioOut.count == 1 || fForcedStereoIn || fForcedStereoOut)
  345. options |= PLUGIN_OPTION_FORCE_STEREO;
  346. if (fDssiDescriptor->get_program != nullptr && fDssiDescriptor->select_program != nullptr)
  347. options |= PLUGIN_OPTION_MAP_PROGRAM_CHANGES;
  348. if (fUsesCustomData)
  349. options |= PLUGIN_OPTION_USE_CHUNKS;
  350. if (fDssiDescriptor->run_synth != nullptr)
  351. {
  352. options |= PLUGIN_OPTION_SEND_CONTROL_CHANGES;
  353. options |= PLUGIN_OPTION_SEND_CHANNEL_PRESSURE;
  354. options |= PLUGIN_OPTION_SEND_NOTE_AFTERTOUCH;
  355. options |= PLUGIN_OPTION_SEND_PITCHBEND;
  356. options |= PLUGIN_OPTION_SEND_ALL_SOUND_OFF;
  357. }
  358. return options;
  359. }
  360. float getParameterValue(const uint32_t parameterId) const noexcept override
  361. {
  362. CARLA_SAFE_ASSERT_RETURN(fParamBuffers != nullptr, 0.0f);
  363. CARLA_SAFE_ASSERT_RETURN(parameterId < pData->param.count, 0.0f);
  364. // bad plugins might have set output values out of bounds
  365. if (pData->param.data[parameterId].type == PARAMETER_OUTPUT)
  366. return pData->param.ranges[parameterId].getFixedValue(fParamBuffers[parameterId]);
  367. // not output, should be fine
  368. return fParamBuffers[parameterId];
  369. }
  370. void getLabel(char* const strBuf) const noexcept override
  371. {
  372. CARLA_SAFE_ASSERT_RETURN(fDescriptor != nullptr, nullStrBuf(strBuf));
  373. CARLA_SAFE_ASSERT_RETURN(fDescriptor->Label != nullptr, nullStrBuf(strBuf));
  374. std::strncpy(strBuf, fDescriptor->Label, STR_MAX);
  375. }
  376. void getMaker(char* const strBuf) const noexcept override
  377. {
  378. CARLA_SAFE_ASSERT_RETURN(fDescriptor != nullptr, nullStrBuf(strBuf));
  379. CARLA_SAFE_ASSERT_RETURN(fDescriptor->Maker != nullptr, nullStrBuf(strBuf));
  380. std::strncpy(strBuf, fDescriptor->Maker, STR_MAX);
  381. }
  382. void getCopyright(char* const strBuf) const noexcept override
  383. {
  384. CARLA_SAFE_ASSERT_RETURN(fDescriptor != nullptr, nullStrBuf(strBuf));
  385. CARLA_SAFE_ASSERT_RETURN(fDescriptor->Copyright != nullptr, nullStrBuf(strBuf));
  386. std::strncpy(strBuf, fDescriptor->Copyright, STR_MAX);
  387. }
  388. void getRealName(char* const strBuf) const noexcept override
  389. {
  390. CARLA_SAFE_ASSERT_RETURN(fDescriptor != nullptr, nullStrBuf(strBuf));
  391. CARLA_SAFE_ASSERT_RETURN(fDescriptor->Name != nullptr, nullStrBuf(strBuf));
  392. std::strncpy(strBuf, fDescriptor->Name, STR_MAX);
  393. }
  394. void getParameterName(const uint32_t parameterId, char* const strBuf) const noexcept override
  395. {
  396. CARLA_SAFE_ASSERT_RETURN(fDescriptor != nullptr, nullStrBuf(strBuf));
  397. CARLA_SAFE_ASSERT_RETURN(parameterId < pData->param.count, nullStrBuf(strBuf));
  398. const int32_t rindex(pData->param.data[parameterId].rindex);
  399. CARLA_SAFE_ASSERT_RETURN(rindex >= 0, nullStrBuf(strBuf));
  400. CARLA_SAFE_ASSERT_RETURN(rindex < static_cast<int32_t>(fDescriptor->PortCount), nullStrBuf(strBuf));
  401. CARLA_SAFE_ASSERT_RETURN(fDescriptor->PortNames[rindex] != nullptr, nullStrBuf(strBuf));
  402. if (getSeparatedParameterNameOrUnit(fDescriptor->PortNames[rindex], strBuf, true))
  403. return;
  404. std::strncpy(strBuf, fDescriptor->PortNames[rindex], STR_MAX);
  405. }
  406. void getParameterUnit(const uint32_t parameterId, char* const strBuf) const noexcept override
  407. {
  408. CARLA_SAFE_ASSERT_RETURN(parameterId < pData->param.count, nullStrBuf(strBuf));
  409. const int32_t rindex(pData->param.data[parameterId].rindex);
  410. CARLA_SAFE_ASSERT_RETURN(rindex >= 0, nullStrBuf(strBuf));
  411. CARLA_SAFE_ASSERT_RETURN(rindex < static_cast<int32_t>(fDescriptor->PortCount), nullStrBuf(strBuf));
  412. CARLA_SAFE_ASSERT_RETURN(fDescriptor->PortNames[rindex] != nullptr, nullStrBuf(strBuf));
  413. if (getSeparatedParameterNameOrUnit(fDescriptor->PortNames[rindex], strBuf, false))
  414. return;
  415. nullStrBuf(strBuf);
  416. }
  417. // -------------------------------------------------------------------
  418. // Set data (state)
  419. // nothing
  420. // -------------------------------------------------------------------
  421. // Set data (internal stuff)
  422. void setId(const uint newId) noexcept override
  423. {
  424. CarlaPlugin::setId(newId);
  425. // UI osc-url uses Id, so we need to close it when it changes
  426. // FIXME - must be RT safe
  427. showCustomUI(false);
  428. }
  429. // -------------------------------------------------------------------
  430. // Set data (plugin-specific stuff)
  431. void setParameterValue(const uint32_t parameterId, const float value, const bool sendGui, const bool sendOsc, const bool sendCallback) noexcept override
  432. {
  433. CARLA_SAFE_ASSERT_RETURN(fParamBuffers != nullptr,);
  434. CARLA_SAFE_ASSERT_RETURN(parameterId < pData->param.count,);
  435. const float fixedValue(pData->param.getFixedValue(parameterId, value));
  436. fParamBuffers[parameterId] = fixedValue;
  437. CarlaPlugin::setParameterValue(parameterId, fixedValue, sendGui, sendOsc, sendCallback);
  438. }
  439. void setCustomData(const char* const type, const char* const key, const char* const value, const bool sendGui) override
  440. {
  441. CARLA_SAFE_ASSERT_RETURN(fDssiDescriptor != nullptr,);
  442. CARLA_SAFE_ASSERT_RETURN(type != nullptr && type[0] != '\0',);
  443. CARLA_SAFE_ASSERT_RETURN(key != nullptr && key[0] != '\0',);
  444. CARLA_SAFE_ASSERT_RETURN(value != nullptr,);
  445. carla_debug("CarlaPluginDSSI::setCustomData(%s, %s, %s, %s)", type, key, value, bool2str(sendGui));
  446. if (std::strcmp(type, CUSTOM_DATA_TYPE_PROPERTY) == 0)
  447. return CarlaPlugin::setCustomData(type, key, value, sendGui);
  448. if (std::strcmp(type, CUSTOM_DATA_TYPE_STRING) != 0)
  449. return carla_stderr2("CarlaPluginDSSI::setCustomData(\"%s\", \"%s\", \"%s\", %s) - type is not string",
  450. type, key, value, bool2str(sendGui));
  451. if (fDssiDescriptor->configure != nullptr && fHandles.count() > 0)
  452. {
  453. for (LinkedList<LADSPA_Handle>::Itenerator it = fHandles.begin2(); it.valid(); it.next())
  454. {
  455. LADSPA_Handle const handle(it.getValue(nullptr));
  456. CARLA_SAFE_ASSERT_CONTINUE(handle != nullptr);
  457. try {
  458. fDssiDescriptor->configure(handle, key, value);
  459. } CARLA_SAFE_EXCEPTION("DSSI setCustomData");
  460. }
  461. }
  462. #ifdef HAVE_LIBLO
  463. if (sendGui && fOscData.target != nullptr)
  464. osc_send_configure(fOscData, key, value);
  465. #endif
  466. if (std::strcmp(key, "reloadprograms") == 0 || std::strcmp(key, "load") == 0 || std::strncmp(key, "patches", 7) == 0)
  467. {
  468. const ScopedSingleProcessLocker spl(this, true);
  469. reloadPrograms(false);
  470. }
  471. CarlaPlugin::setCustomData(type, key, value, sendGui);
  472. }
  473. void setChunkData(const void* const data, const std::size_t dataSize) override
  474. {
  475. CARLA_SAFE_ASSERT_RETURN(fUsesCustomData,);
  476. CARLA_SAFE_ASSERT_RETURN(pData->options & PLUGIN_OPTION_USE_CHUNKS,);
  477. CARLA_SAFE_ASSERT_RETURN(fDssiDescriptor != nullptr,);
  478. CARLA_SAFE_ASSERT_RETURN(fDssiDescriptor->set_custom_data != nullptr,);
  479. CARLA_SAFE_ASSERT_RETURN(data != nullptr,);
  480. CARLA_SAFE_ASSERT_RETURN(dataSize > 0,);
  481. if (fHandles.count() > 0)
  482. {
  483. const ScopedSingleProcessLocker spl(this, true);
  484. for (LinkedList<LADSPA_Handle>::Itenerator it = fHandles.begin2(); it.valid(); it.next())
  485. {
  486. LADSPA_Handle const handle(it.getValue(nullptr));
  487. CARLA_SAFE_ASSERT_CONTINUE(handle != nullptr);
  488. try {
  489. fDssiDescriptor->set_custom_data(handle, const_cast<void*>(data), static_cast<ulong>(dataSize));
  490. } CARLA_SAFE_EXCEPTION("CarlaPluginDSSI::setChunkData");
  491. }
  492. }
  493. #if defined(HAVE_LIBLO) && ! defined(BUILD_BRIDGE)
  494. const bool sendOsc(pData->engine->isOscControlRegistered());
  495. #else
  496. const bool sendOsc(false);
  497. #endif
  498. pData->updateParameterValues(this, sendOsc, true, false);
  499. }
  500. void setMidiProgram(const int32_t index, const bool sendGui, const bool sendOsc, const bool sendCallback) noexcept override
  501. {
  502. CARLA_SAFE_ASSERT_RETURN(fDssiDescriptor != nullptr,);
  503. CARLA_SAFE_ASSERT_RETURN(fDssiDescriptor->select_program != nullptr,);
  504. CARLA_SAFE_ASSERT_RETURN(index >= -1 && index < static_cast<int32_t>(pData->midiprog.count),);
  505. if (index >= 0 && fHandles.count() > 0)
  506. {
  507. const uint32_t bank(pData->midiprog.data[index].bank);
  508. const uint32_t program(pData->midiprog.data[index].program);
  509. const ScopedSingleProcessLocker spl(this, (sendGui || sendOsc || sendCallback));
  510. for (LinkedList<LADSPA_Handle>::Itenerator it = fHandles.begin2(); it.valid(); it.next())
  511. {
  512. LADSPA_Handle const handle(it.getValue(nullptr));
  513. CARLA_SAFE_ASSERT_CONTINUE(handle != nullptr);
  514. try {
  515. fDssiDescriptor->select_program(handle, bank, program);
  516. } CARLA_SAFE_EXCEPTION("DSSI setMidiProgram")
  517. }
  518. }
  519. CarlaPlugin::setMidiProgram(index, sendGui, sendOsc, sendCallback);
  520. }
  521. #ifdef HAVE_LIBLO
  522. // -------------------------------------------------------------------
  523. // Set ui stuff
  524. void showCustomUI(const bool yesNo) override
  525. {
  526. if (yesNo)
  527. {
  528. fOscData.clear();
  529. fThreadUI.startThread();
  530. }
  531. else
  532. {
  533. #ifndef BUILD_BRIDGE
  534. pData->transientTryCounter = 0;
  535. #endif
  536. if (fOscData.target != nullptr)
  537. {
  538. osc_send_hide(fOscData);
  539. osc_send_quit(fOscData);
  540. fOscData.clear();
  541. }
  542. fThreadUI.stopThread(static_cast<int>(pData->engine->getOptions().uiBridgesTimeout * 2));
  543. }
  544. }
  545. #endif
  546. // -------------------------------------------------------------------
  547. // Plugin state
  548. void reload() override
  549. {
  550. CARLA_SAFE_ASSERT_RETURN(pData->engine != nullptr,);
  551. CARLA_SAFE_ASSERT_RETURN(fDescriptor != nullptr,);
  552. CARLA_SAFE_ASSERT_RETURN(fDssiDescriptor != nullptr,);
  553. CARLA_SAFE_ASSERT_RETURN(fHandles.count() > 0,);
  554. carla_debug("CarlaPluginDSSI::reload() - start");
  555. const EngineProcessMode processMode(pData->engine->getProccessMode());
  556. // Safely disable plugin for reload
  557. const ScopedDisabler sd(this);
  558. if (pData->active)
  559. deactivate();
  560. clearBuffers();
  561. const float sampleRate(static_cast<float>(pData->engine->getSampleRate()));
  562. const uint32_t portCount(getSafePortCount());
  563. uint32_t aIns, aOuts, mIns, params;
  564. aIns = aOuts = mIns = params = 0;
  565. bool forcedStereoIn, forcedStereoOut;
  566. forcedStereoIn = forcedStereoOut = false;
  567. bool needsCtrlIn, needsCtrlOut;
  568. needsCtrlIn = needsCtrlOut = false;
  569. for (uint32_t i=0; i < portCount; ++i)
  570. {
  571. const LADSPA_PortDescriptor portType(fDescriptor->PortDescriptors[i]);
  572. if (LADSPA_IS_PORT_AUDIO(portType))
  573. {
  574. if (LADSPA_IS_PORT_INPUT(portType))
  575. aIns += 1;
  576. else if (LADSPA_IS_PORT_OUTPUT(portType))
  577. aOuts += 1;
  578. }
  579. else if (LADSPA_IS_PORT_CONTROL(portType))
  580. params += 1;
  581. }
  582. if (pData->options & PLUGIN_OPTION_FORCE_STEREO)
  583. {
  584. if ((aIns == 1 || aOuts == 1) && fHandles.count() == 1 && addInstance())
  585. {
  586. if (aIns == 1)
  587. {
  588. aIns = 2;
  589. forcedStereoIn = true;
  590. }
  591. if (aOuts == 1)
  592. {
  593. aOuts = 2;
  594. forcedStereoOut = true;
  595. }
  596. }
  597. }
  598. if (fDssiDescriptor->run_synth != nullptr)
  599. {
  600. mIns = 1;
  601. needsCtrlIn = true;
  602. }
  603. if (aIns > 0)
  604. {
  605. pData->audioIn.createNew(aIns);
  606. fAudioInBuffers = new float*[aIns];
  607. for (uint32_t i=0; i < aIns; ++i)
  608. fAudioInBuffers[i] = nullptr;
  609. }
  610. if (aOuts > 0)
  611. {
  612. pData->audioOut.createNew(aOuts);
  613. fAudioOutBuffers = new float*[aOuts];
  614. needsCtrlIn = true;
  615. for (uint32_t i=0; i < aOuts; ++i)
  616. fAudioOutBuffers[i] = nullptr;
  617. }
  618. if (params > 0)
  619. {
  620. pData->param.createNew(params, true);
  621. fParamBuffers = new float[params];
  622. carla_zeroFloats(fParamBuffers, params);
  623. }
  624. const uint portNameSize(pData->engine->getMaxPortNameSize());
  625. CarlaString portName;
  626. for (uint32_t i=0, iAudioIn=0, iAudioOut=0, iCtrl=0; i < portCount; ++i)
  627. {
  628. const LADSPA_PortDescriptor portType = fDescriptor->PortDescriptors[i];
  629. const LADSPA_PortRangeHint portRangeHints = fDescriptor->PortRangeHints[i];
  630. if (LADSPA_IS_PORT_AUDIO(portType))
  631. {
  632. portName.clear();
  633. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  634. {
  635. portName = pData->name;
  636. portName += ":";
  637. }
  638. if (fDescriptor->PortNames[i] != nullptr && fDescriptor->PortNames[i][0] != '\0')
  639. {
  640. portName += fDescriptor->PortNames[i];
  641. }
  642. else
  643. {
  644. if (LADSPA_IS_PORT_INPUT(portType))
  645. {
  646. if (aIns > 1)
  647. {
  648. portName += "audio-in_";
  649. portName += CarlaString(iAudioIn+1);
  650. }
  651. else
  652. portName += "audio-in";
  653. }
  654. else
  655. {
  656. if (aOuts > 1)
  657. {
  658. portName += "audio-out_";
  659. portName += CarlaString(iAudioOut+1);
  660. }
  661. else
  662. portName += "audio-out";
  663. }
  664. }
  665. portName.truncate(portNameSize);
  666. if (LADSPA_IS_PORT_INPUT(portType))
  667. {
  668. const uint32_t j = iAudioIn++;
  669. pData->audioIn.ports[j].port = (CarlaEngineAudioPort*)pData->client->addPort(kEnginePortTypeAudio, portName, true, j);
  670. pData->audioIn.ports[j].rindex = i;
  671. if (forcedStereoIn)
  672. {
  673. portName += "_2";
  674. pData->audioIn.ports[1].port = (CarlaEngineAudioPort*)pData->client->addPort(kEnginePortTypeAudio, portName, true, 1);
  675. pData->audioIn.ports[1].rindex = i;
  676. }
  677. }
  678. else if (LADSPA_IS_PORT_OUTPUT(portType))
  679. {
  680. const uint32_t j = iAudioOut++;
  681. pData->audioOut.ports[j].port = (CarlaEngineAudioPort*)pData->client->addPort(kEnginePortTypeAudio, portName, false, j);
  682. pData->audioOut.ports[j].rindex = i;
  683. if (forcedStereoOut)
  684. {
  685. portName += "_2";
  686. pData->audioOut.ports[1].port = (CarlaEngineAudioPort*)pData->client->addPort(kEnginePortTypeAudio, portName, false, 1);
  687. pData->audioOut.ports[1].rindex = i;
  688. }
  689. }
  690. else
  691. carla_stderr2("WARNING - Got a broken Port (Audio, but not input or output)");
  692. }
  693. else if (LADSPA_IS_PORT_CONTROL(portType))
  694. {
  695. const uint32_t j = iCtrl++;
  696. pData->param.data[j].index = static_cast<int32_t>(j);
  697. pData->param.data[j].rindex = static_cast<int32_t>(i);
  698. const char* const paramName(fDescriptor->PortNames[i] != nullptr ? fDescriptor->PortNames[i] : "unknown");
  699. float min, max, def, step, stepSmall, stepLarge;
  700. // min value
  701. if (LADSPA_IS_HINT_BOUNDED_BELOW(portRangeHints.HintDescriptor))
  702. min = portRangeHints.LowerBound;
  703. else
  704. min = 0.0f;
  705. // max value
  706. if (LADSPA_IS_HINT_BOUNDED_ABOVE(portRangeHints.HintDescriptor))
  707. max = portRangeHints.UpperBound;
  708. else
  709. max = 1.0f;
  710. if (LADSPA_IS_HINT_SAMPLE_RATE(portRangeHints.HintDescriptor))
  711. {
  712. min *= sampleRate;
  713. max *= sampleRate;
  714. pData->param.data[j].hints |= PARAMETER_USES_SAMPLERATE;
  715. }
  716. if (min >= max)
  717. {
  718. carla_stderr2("WARNING - Broken plugin parameter '%s': min >= max", paramName);
  719. max = min + 0.1f;
  720. }
  721. // default value
  722. def = get_default_ladspa_port_value(portRangeHints.HintDescriptor, min, max);
  723. if (def < min)
  724. def = min;
  725. else if (def > max)
  726. def = max;
  727. if (LADSPA_IS_HINT_TOGGLED(portRangeHints.HintDescriptor))
  728. {
  729. step = max - min;
  730. stepSmall = step;
  731. stepLarge = step;
  732. pData->param.data[j].hints |= PARAMETER_IS_BOOLEAN;
  733. }
  734. else if (LADSPA_IS_HINT_INTEGER(portRangeHints.HintDescriptor))
  735. {
  736. step = 1.0f;
  737. stepSmall = 1.0f;
  738. stepLarge = 10.0f;
  739. pData->param.data[j].hints |= PARAMETER_IS_INTEGER;
  740. }
  741. else
  742. {
  743. const float range = max - min;
  744. step = range/100.0f;
  745. stepSmall = range/1000.0f;
  746. stepLarge = range/10.0f;
  747. }
  748. if (LADSPA_IS_PORT_INPUT(portType))
  749. {
  750. pData->param.data[j].type = PARAMETER_INPUT;
  751. pData->param.data[j].hints |= PARAMETER_IS_ENABLED;
  752. pData->param.data[j].hints |= PARAMETER_IS_AUTOMABLE;
  753. needsCtrlIn = true;
  754. // MIDI CC value
  755. if (fDssiDescriptor->get_midi_controller_for_port != nullptr)
  756. {
  757. const int ctrl = fDssiDescriptor->get_midi_controller_for_port(fHandles.getFirst(nullptr), i);
  758. if (DSSI_CONTROLLER_IS_SET(ctrl) && DSSI_IS_CC(ctrl))
  759. {
  760. const int16_t cc = DSSI_CC_NUMBER(ctrl);
  761. if (! MIDI_IS_CONTROL_BANK_SELECT(cc))
  762. pData->param.data[j].midiCC = cc;
  763. }
  764. }
  765. }
  766. else if (LADSPA_IS_PORT_OUTPUT(portType))
  767. {
  768. pData->param.data[j].type = PARAMETER_OUTPUT;
  769. if (std::strcmp(paramName, "latency") == 0 || std::strcmp(paramName, "_latency") == 0)
  770. {
  771. min = 0.0f;
  772. max = sampleRate;
  773. def = 0.0f;
  774. step = 1.0f;
  775. stepSmall = 1.0f;
  776. stepLarge = 1.0f;
  777. pData->param.special[j] = PARAMETER_SPECIAL_LATENCY;
  778. CARLA_SAFE_ASSERT_INT2(fLatencyIndex == static_cast<int32_t>(j), fLatencyIndex, j);
  779. }
  780. else
  781. {
  782. pData->param.data[j].hints |= PARAMETER_IS_ENABLED;
  783. pData->param.data[j].hints |= PARAMETER_IS_AUTOMABLE;
  784. needsCtrlOut = true;
  785. }
  786. }
  787. else
  788. {
  789. carla_stderr2("WARNING - Got a broken Port (Control, but not input or output)");
  790. }
  791. // extra parameter hints
  792. if (LADSPA_IS_HINT_LOGARITHMIC(portRangeHints.HintDescriptor))
  793. pData->param.data[j].hints |= PARAMETER_IS_LOGARITHMIC;
  794. pData->param.ranges[j].min = min;
  795. pData->param.ranges[j].max = max;
  796. pData->param.ranges[j].def = def;
  797. pData->param.ranges[j].step = step;
  798. pData->param.ranges[j].stepSmall = stepSmall;
  799. pData->param.ranges[j].stepLarge = stepLarge;
  800. // Start parameters in their default values
  801. fParamBuffers[j] = def;
  802. for (LinkedList<LADSPA_Handle>::Itenerator it = fHandles.begin2(); it.valid(); it.next())
  803. {
  804. LADSPA_Handle const handle(it.getValue(nullptr));
  805. CARLA_SAFE_ASSERT_CONTINUE(handle != nullptr);
  806. try {
  807. fDescriptor->connect_port(handle, i, &fParamBuffers[j]);
  808. } CARLA_SAFE_EXCEPTION("DSSI connect_port (parameter)");
  809. }
  810. }
  811. else
  812. {
  813. // Not Audio or Control
  814. carla_stderr2("ERROR - Got a broken Port (neither Audio or Control)");
  815. for (LinkedList<LADSPA_Handle>::Itenerator it = fHandles.begin2(); it.valid(); it.next())
  816. {
  817. LADSPA_Handle const handle(it.getValue(nullptr));
  818. CARLA_SAFE_ASSERT_CONTINUE(handle != nullptr);
  819. try {
  820. fDescriptor->connect_port(handle, i, nullptr);
  821. } CARLA_SAFE_EXCEPTION("DSSI connect_port (null)");
  822. }
  823. }
  824. }
  825. if (needsCtrlIn)
  826. {
  827. portName.clear();
  828. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  829. {
  830. portName = pData->name;
  831. portName += ":";
  832. }
  833. portName += "events-in";
  834. portName.truncate(portNameSize);
  835. pData->event.portIn = (CarlaEngineEventPort*)pData->client->addPort(kEnginePortTypeEvent, portName, true, 0);
  836. }
  837. if (needsCtrlOut)
  838. {
  839. portName.clear();
  840. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  841. {
  842. portName = pData->name;
  843. portName += ":";
  844. }
  845. portName += "events-out";
  846. portName.truncate(portNameSize);
  847. pData->event.portOut = (CarlaEngineEventPort*)pData->client->addPort(kEnginePortTypeEvent, portName, false, 0);
  848. }
  849. if (forcedStereoIn || forcedStereoOut)
  850. pData->options |= PLUGIN_OPTION_FORCE_STEREO;
  851. else
  852. pData->options &= ~PLUGIN_OPTION_FORCE_STEREO;
  853. // plugin hints
  854. pData->hints = 0x0;
  855. if (LADSPA_IS_HARD_RT_CAPABLE(fDescriptor->Properties))
  856. pData->hints |= PLUGIN_IS_RTSAFE;
  857. #ifdef HAVE_LIBLO
  858. if (fUiFilename != nullptr)
  859. pData->hints |= PLUGIN_HAS_CUSTOM_UI;
  860. #endif
  861. #ifndef BUILD_BRIDGE
  862. if (aOuts > 0 && (aIns == aOuts || aIns == 1))
  863. pData->hints |= PLUGIN_CAN_DRYWET;
  864. if (aOuts > 0)
  865. pData->hints |= PLUGIN_CAN_VOLUME;
  866. if (aOuts >= 2 && aOuts % 2 == 0)
  867. pData->hints |= PLUGIN_CAN_BALANCE;
  868. #endif
  869. // extra plugin hints
  870. pData->extraHints = 0x0;
  871. pData->extraHints |= PLUGIN_EXTRA_HINT_CAN_RUN_RACK;
  872. if (mIns > 0)
  873. pData->extraHints |= PLUGIN_EXTRA_HINT_HAS_MIDI_IN;
  874. // check initial latency
  875. findInitialLatencyValue(aIns, aOuts);
  876. fForcedStereoIn = forcedStereoIn;
  877. fForcedStereoOut = forcedStereoOut;
  878. bufferSizeChanged(pData->engine->getBufferSize());
  879. reloadPrograms(true);
  880. if (pData->active)
  881. activate();
  882. carla_debug("CarlaPluginDSSI::reload() - end");
  883. }
  884. void findInitialLatencyValue(const uint32_t aIns, const uint32_t aOuts) const
  885. {
  886. if (fLatencyIndex < 0 || fHandles.count() == 0)
  887. return;
  888. // we need to pre-run the plugin so it can update its latency control-port
  889. const LADSPA_Handle handle(fHandles.getFirst(nullptr));
  890. CARLA_SAFE_ASSERT_RETURN(handle != nullptr,);
  891. float tmpIn [(aIns > 0) ? aIns : 1][2];
  892. float tmpOut[(aOuts > 0) ? aOuts : 1][2];
  893. for (uint32_t j=0; j < aIns; ++j)
  894. {
  895. tmpIn[j][0] = 0.0f;
  896. tmpIn[j][1] = 0.0f;
  897. try {
  898. fDescriptor->connect_port(handle, pData->audioIn.ports[j].rindex, tmpIn[j]);
  899. } CARLA_SAFE_EXCEPTION("DSSI connect_port (latency input)");
  900. }
  901. for (uint32_t j=0; j < aOuts; ++j)
  902. {
  903. tmpOut[j][0] = 0.0f;
  904. tmpOut[j][1] = 0.0f;
  905. try {
  906. fDescriptor->connect_port(handle, pData->audioOut.ports[j].rindex, tmpOut[j]);
  907. } CARLA_SAFE_EXCEPTION("DSSI connect_port (latency output)");
  908. }
  909. if (fDescriptor->activate != nullptr)
  910. {
  911. try {
  912. fDescriptor->activate(handle);
  913. } CARLA_SAFE_EXCEPTION("DSSI latency activate");
  914. }
  915. try {
  916. fDescriptor->run(handle, 2);
  917. } CARLA_SAFE_EXCEPTION("DSSI latency run");
  918. if (fDescriptor->deactivate != nullptr)
  919. {
  920. try {
  921. fDescriptor->deactivate(handle);
  922. } CARLA_SAFE_EXCEPTION("DSSI latency deactivate");
  923. }
  924. // done, let's get the value
  925. if (const uint32_t latency = getLatencyInFrames())
  926. {
  927. pData->client->setLatency(latency);
  928. #ifndef BUILD_BRIDGE
  929. pData->latency.recreateBuffers(std::max(aIns, aOuts), latency);
  930. #endif
  931. }
  932. }
  933. void reloadPrograms(const bool doInit) override
  934. {
  935. carla_debug("CarlaPluginDSSI::reloadPrograms(%s)", bool2str(doInit));
  936. const LADSPA_Handle handle(fHandles.getFirst(nullptr));
  937. CARLA_SAFE_ASSERT_RETURN(handle != nullptr,);
  938. const uint32_t oldCount = pData->midiprog.count;
  939. const int32_t current = pData->midiprog.current;
  940. // Delete old programs
  941. pData->midiprog.clear();
  942. // Query new programs
  943. uint32_t newCount = 0;
  944. if (fDssiDescriptor->get_program != nullptr && fDssiDescriptor->select_program != nullptr)
  945. {
  946. for (; fDssiDescriptor->get_program(handle, newCount) != nullptr;)
  947. ++newCount;
  948. }
  949. if (newCount > 0)
  950. {
  951. pData->midiprog.createNew(newCount);
  952. // Update data
  953. for (uint32_t i=0; i < newCount; ++i)
  954. {
  955. const DSSI_Program_Descriptor* const pdesc(fDssiDescriptor->get_program(handle, i));
  956. CARLA_SAFE_ASSERT_CONTINUE(pdesc != nullptr);
  957. CARLA_SAFE_ASSERT(pdesc->Name != nullptr);
  958. pData->midiprog.data[i].bank = static_cast<uint32_t>(pdesc->Bank);
  959. pData->midiprog.data[i].program = static_cast<uint32_t>(pdesc->Program);
  960. pData->midiprog.data[i].name = carla_strdup(pdesc->Name);
  961. }
  962. }
  963. #if defined(HAVE_LIBLO) && ! defined(BUILD_BRIDGE)
  964. // Update OSC Names
  965. if (pData->engine->isOscControlRegistered() && pData->id < pData->engine->getCurrentPluginCount())
  966. {
  967. pData->engine->oscSend_control_set_midi_program_count(pData->id, newCount);
  968. for (uint32_t i=0; i < newCount; ++i)
  969. pData->engine->oscSend_control_set_midi_program_data(pData->id, i, pData->midiprog.data[i].bank, pData->midiprog.data[i].program, pData->midiprog.data[i].name);
  970. }
  971. #endif
  972. if (doInit)
  973. {
  974. if (newCount > 0)
  975. setMidiProgram(0, false, false, false);
  976. }
  977. else
  978. {
  979. // Check if current program is invalid
  980. bool programChanged = false;
  981. if (newCount == oldCount+1)
  982. {
  983. // one midi program added, probably created by user
  984. pData->midiprog.current = static_cast<int32_t>(oldCount);
  985. programChanged = true;
  986. }
  987. else if (current < 0 && newCount > 0)
  988. {
  989. // programs exist now, but not before
  990. pData->midiprog.current = 0;
  991. programChanged = true;
  992. }
  993. else if (current >= 0 && newCount == 0)
  994. {
  995. // programs existed before, but not anymore
  996. pData->midiprog.current = -1;
  997. programChanged = true;
  998. }
  999. else if (current >= static_cast<int32_t>(newCount))
  1000. {
  1001. // current midi program > count
  1002. pData->midiprog.current = 0;
  1003. programChanged = true;
  1004. }
  1005. else
  1006. {
  1007. // no change
  1008. pData->midiprog.current = current;
  1009. }
  1010. if (programChanged)
  1011. setMidiProgram(pData->midiprog.current, true, true, true);
  1012. pData->engine->callback(ENGINE_CALLBACK_RELOAD_PROGRAMS, pData->id, 0, 0, 0.0f, nullptr);
  1013. }
  1014. }
  1015. // -------------------------------------------------------------------
  1016. // Plugin processing
  1017. void activate() noexcept override
  1018. {
  1019. CARLA_SAFE_ASSERT_RETURN(fDescriptor != nullptr,);
  1020. if (fDescriptor->activate != nullptr)
  1021. {
  1022. for (LinkedList<LADSPA_Handle>::Itenerator it = fHandles.begin2(); it.valid(); it.next())
  1023. {
  1024. LADSPA_Handle const handle(it.getValue(nullptr));
  1025. CARLA_SAFE_ASSERT_CONTINUE(handle != nullptr);
  1026. try {
  1027. fDescriptor->activate(handle);
  1028. } CARLA_SAFE_EXCEPTION("DSSI activate");
  1029. }
  1030. }
  1031. }
  1032. void deactivate() noexcept override
  1033. {
  1034. CARLA_SAFE_ASSERT_RETURN(fDescriptor != nullptr,);
  1035. if (fDescriptor->deactivate != nullptr)
  1036. {
  1037. for (LinkedList<LADSPA_Handle>::Itenerator it = fHandles.begin2(); it.valid(); it.next())
  1038. {
  1039. LADSPA_Handle const handle(it.getValue(nullptr));
  1040. CARLA_SAFE_ASSERT_CONTINUE(handle != nullptr);
  1041. try {
  1042. fDescriptor->deactivate(handle);
  1043. } CARLA_SAFE_EXCEPTION("DSSI deactivate");
  1044. }
  1045. }
  1046. }
  1047. void process(const float** const audioIn, float** const audioOut, const float** const, float** const, const uint32_t frames) override
  1048. {
  1049. // --------------------------------------------------------------------------------------------------------
  1050. // Check if active
  1051. if (! pData->active)
  1052. {
  1053. // disable any output sound
  1054. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  1055. carla_zeroFloats(audioOut[i], frames);
  1056. return;
  1057. }
  1058. ulong midiEventCount = 0;
  1059. carla_zeroStructs(fMidiEvents, kPluginMaxMidiEvents);
  1060. // --------------------------------------------------------------------------------------------------------
  1061. // Check if needs reset
  1062. if (pData->needsReset)
  1063. {
  1064. if (pData->options & PLUGIN_OPTION_SEND_ALL_SOUND_OFF)
  1065. {
  1066. midiEventCount = MAX_MIDI_CHANNELS*2;
  1067. for (uchar i=0, k=MAX_MIDI_CHANNELS; i < MAX_MIDI_CHANNELS; ++i)
  1068. {
  1069. fMidiEvents[i].type = SND_SEQ_EVENT_CONTROLLER;
  1070. fMidiEvents[i].data.control.channel = i;
  1071. fMidiEvents[i].data.control.param = MIDI_CONTROL_ALL_NOTES_OFF;
  1072. fMidiEvents[k+i].type = SND_SEQ_EVENT_CONTROLLER;
  1073. fMidiEvents[k+i].data.control.channel = i;
  1074. fMidiEvents[k+i].data.control.param = MIDI_CONTROL_ALL_SOUND_OFF;
  1075. }
  1076. }
  1077. else if (pData->ctrlChannel >= 0 && pData->ctrlChannel < MAX_MIDI_CHANNELS)
  1078. {
  1079. midiEventCount = MAX_MIDI_NOTE;
  1080. for (uchar i=0; i < MAX_MIDI_NOTE; ++i)
  1081. {
  1082. fMidiEvents[i].type = SND_SEQ_EVENT_NOTEOFF;
  1083. fMidiEvents[i].data.note.channel = static_cast<uchar>(pData->ctrlChannel);
  1084. fMidiEvents[i].data.note.note = i;
  1085. }
  1086. }
  1087. pData->needsReset = false;
  1088. }
  1089. // --------------------------------------------------------------------------------------------------------
  1090. // Event Input and Processing
  1091. if (pData->event.portIn != nullptr)
  1092. {
  1093. // ----------------------------------------------------------------------------------------------------
  1094. // MIDI Input (External)
  1095. if (pData->extNotes.mutex.tryLock())
  1096. {
  1097. ExternalMidiNote note = { 0, 0, 0 };
  1098. for (; midiEventCount < kPluginMaxMidiEvents && ! pData->extNotes.data.isEmpty();)
  1099. {
  1100. note = pData->extNotes.data.getFirst(note, true);
  1101. CARLA_SAFE_ASSERT_CONTINUE(note.channel >= 0 && note.channel < MAX_MIDI_CHANNELS);
  1102. snd_seq_event_t& seqEvent(fMidiEvents[midiEventCount++]);
  1103. seqEvent.type = (note.velo > 0) ? SND_SEQ_EVENT_NOTEON : SND_SEQ_EVENT_NOTEOFF;
  1104. seqEvent.data.note.channel = static_cast<uchar>(note.channel);
  1105. seqEvent.data.note.note = note.note;
  1106. seqEvent.data.note.velocity = note.velo;
  1107. }
  1108. pData->extNotes.mutex.unlock();
  1109. } // End of MIDI Input (External)
  1110. // ----------------------------------------------------------------------------------------------------
  1111. // Event Input (System)
  1112. #ifndef BUILD_BRIDGE
  1113. bool allNotesOffSent = false;
  1114. #endif
  1115. const bool isSampleAccurate = (pData->options & PLUGIN_OPTION_FIXED_BUFFERS) == 0;
  1116. uint32_t startTime = 0;
  1117. uint32_t timeOffset = 0;
  1118. uint32_t nextBankId;
  1119. if (pData->midiprog.current >= 0 && pData->midiprog.count > 0)
  1120. nextBankId = pData->midiprog.data[pData->midiprog.current].bank;
  1121. else
  1122. nextBankId = 0;
  1123. for (uint32_t i=0, numEvents=pData->event.portIn->getEventCount(); i < numEvents; ++i)
  1124. {
  1125. const EngineEvent& event(pData->event.portIn->getEvent(i));
  1126. if (event.time >= frames)
  1127. continue;
  1128. CARLA_ASSERT_INT2(event.time >= timeOffset, event.time, timeOffset);
  1129. if (isSampleAccurate && event.time > timeOffset)
  1130. {
  1131. if (processSingle(audioIn, audioOut, event.time - timeOffset, timeOffset, midiEventCount))
  1132. {
  1133. startTime = 0;
  1134. timeOffset = event.time;
  1135. midiEventCount = 0;
  1136. if (pData->midiprog.current >= 0 && pData->midiprog.count > 0)
  1137. nextBankId = pData->midiprog.data[pData->midiprog.current].bank;
  1138. else
  1139. nextBankId = 0;
  1140. }
  1141. else
  1142. startTime += timeOffset;
  1143. }
  1144. switch (event.type)
  1145. {
  1146. case kEngineEventTypeNull:
  1147. break;
  1148. case kEngineEventTypeControl: {
  1149. const EngineControlEvent& ctrlEvent(event.ctrl);
  1150. switch (ctrlEvent.type)
  1151. {
  1152. case kEngineControlEventTypeNull:
  1153. break;
  1154. case kEngineControlEventTypeParameter: {
  1155. #ifndef BUILD_BRIDGE
  1156. // Control backend stuff
  1157. if (event.channel == pData->ctrlChannel)
  1158. {
  1159. float value;
  1160. if (MIDI_IS_CONTROL_BREATH_CONTROLLER(ctrlEvent.param) && (pData->hints & PLUGIN_CAN_DRYWET) != 0)
  1161. {
  1162. value = ctrlEvent.value;
  1163. setDryWet(value, false, false);
  1164. pData->postponeRtEvent(kPluginPostRtEventParameterChange, PARAMETER_DRYWET, 0, value);
  1165. }
  1166. if (MIDI_IS_CONTROL_CHANNEL_VOLUME(ctrlEvent.param) && (pData->hints & PLUGIN_CAN_VOLUME) != 0)
  1167. {
  1168. value = ctrlEvent.value*127.0f/100.0f;
  1169. setVolume(value, false, false);
  1170. pData->postponeRtEvent(kPluginPostRtEventParameterChange, PARAMETER_VOLUME, 0, value);
  1171. }
  1172. if (MIDI_IS_CONTROL_BALANCE(ctrlEvent.param) && (pData->hints & PLUGIN_CAN_BALANCE) != 0)
  1173. {
  1174. float left, right;
  1175. value = ctrlEvent.value/0.5f - 1.0f;
  1176. if (value < 0.0f)
  1177. {
  1178. left = -1.0f;
  1179. right = (value*2.0f)+1.0f;
  1180. }
  1181. else if (value > 0.0f)
  1182. {
  1183. left = (value*2.0f)-1.0f;
  1184. right = 1.0f;
  1185. }
  1186. else
  1187. {
  1188. left = -1.0f;
  1189. right = 1.0f;
  1190. }
  1191. setBalanceLeft(left, false, false);
  1192. setBalanceRight(right, false, false);
  1193. pData->postponeRtEvent(kPluginPostRtEventParameterChange, PARAMETER_BALANCE_LEFT, 0, left);
  1194. pData->postponeRtEvent(kPluginPostRtEventParameterChange, PARAMETER_BALANCE_RIGHT, 0, right);
  1195. }
  1196. }
  1197. #endif
  1198. // Control plugin parameters
  1199. for (uint32_t k=0; k < pData->param.count; ++k)
  1200. {
  1201. if (pData->param.data[k].midiChannel != event.channel)
  1202. continue;
  1203. if (pData->param.data[k].midiCC != ctrlEvent.param)
  1204. continue;
  1205. if (pData->param.data[k].type != PARAMETER_INPUT)
  1206. continue;
  1207. if ((pData->param.data[k].hints & PARAMETER_IS_AUTOMABLE) == 0)
  1208. continue;
  1209. float value;
  1210. if (pData->param.data[k].hints & PARAMETER_IS_BOOLEAN)
  1211. {
  1212. value = (ctrlEvent.value < 0.5f) ? pData->param.ranges[k].min : pData->param.ranges[k].max;
  1213. }
  1214. else
  1215. {
  1216. if (pData->param.data[k].hints & PARAMETER_IS_LOGARITHMIC)
  1217. value = pData->param.ranges[k].getUnnormalizedLogValue(ctrlEvent.value);
  1218. else
  1219. value = pData->param.ranges[k].getUnnormalizedValue(ctrlEvent.value);
  1220. if (pData->param.data[k].hints & PARAMETER_IS_INTEGER)
  1221. value = std::rint(value);
  1222. }
  1223. setParameterValue(k, value, false, false, false);
  1224. pData->postponeRtEvent(kPluginPostRtEventParameterChange, static_cast<int32_t>(k), 0, value);
  1225. }
  1226. if ((pData->options & PLUGIN_OPTION_SEND_CONTROL_CHANGES) != 0 && ctrlEvent.param < MAX_MIDI_CONTROL)
  1227. {
  1228. if (midiEventCount >= kPluginMaxMidiEvents)
  1229. continue;
  1230. snd_seq_event_t& seqEvent(fMidiEvents[midiEventCount++]);
  1231. seqEvent.time.tick = isSampleAccurate ? startTime : event.time;
  1232. seqEvent.type = SND_SEQ_EVENT_CONTROLLER;
  1233. seqEvent.data.control.channel = event.channel;
  1234. seqEvent.data.control.param = ctrlEvent.param;
  1235. seqEvent.data.control.value = int8_t(ctrlEvent.value*127.0f);
  1236. }
  1237. break;
  1238. } // case kEngineControlEventTypeParameter
  1239. case kEngineControlEventTypeMidiBank:
  1240. if (event.channel == pData->ctrlChannel && (pData->options & PLUGIN_OPTION_MAP_PROGRAM_CHANGES) != 0)
  1241. nextBankId = ctrlEvent.param;
  1242. break;
  1243. case kEngineControlEventTypeMidiProgram:
  1244. if (event.channel == pData->ctrlChannel && (pData->options & PLUGIN_OPTION_MAP_PROGRAM_CHANGES) != 0)
  1245. {
  1246. const uint32_t nextProgramId = ctrlEvent.param;
  1247. for (uint32_t k=0; k < pData->midiprog.count; ++k)
  1248. {
  1249. if (pData->midiprog.data[k].bank == nextBankId && pData->midiprog.data[k].program == nextProgramId)
  1250. {
  1251. const int32_t index(static_cast<int32_t>(k));
  1252. setMidiProgram(index, false, false, false);
  1253. pData->postponeRtEvent(kPluginPostRtEventMidiProgramChange, index, 0, 0.0f);
  1254. break;
  1255. }
  1256. }
  1257. }
  1258. break;
  1259. case kEngineControlEventTypeAllSoundOff:
  1260. if (pData->options & PLUGIN_OPTION_SEND_ALL_SOUND_OFF)
  1261. {
  1262. if (midiEventCount >= kPluginMaxMidiEvents)
  1263. continue;
  1264. snd_seq_event_t& seqEvent(fMidiEvents[midiEventCount++]);
  1265. seqEvent.time.tick = isSampleAccurate ? startTime : event.time;
  1266. seqEvent.type = SND_SEQ_EVENT_CONTROLLER;
  1267. seqEvent.data.control.channel = event.channel;
  1268. seqEvent.data.control.param = MIDI_CONTROL_ALL_SOUND_OFF;
  1269. }
  1270. break;
  1271. case kEngineControlEventTypeAllNotesOff:
  1272. if (pData->options & PLUGIN_OPTION_SEND_ALL_SOUND_OFF)
  1273. {
  1274. #ifndef BUILD_BRIDGE
  1275. if (event.channel == pData->ctrlChannel && ! allNotesOffSent)
  1276. {
  1277. allNotesOffSent = true;
  1278. sendMidiAllNotesOffToCallback();
  1279. }
  1280. #endif
  1281. if (midiEventCount >= kPluginMaxMidiEvents)
  1282. continue;
  1283. snd_seq_event_t& seqEvent(fMidiEvents[midiEventCount++]);
  1284. seqEvent.time.tick = isSampleAccurate ? startTime : event.time;
  1285. seqEvent.type = SND_SEQ_EVENT_CONTROLLER;
  1286. seqEvent.data.control.channel = event.channel;
  1287. seqEvent.data.control.param = MIDI_CONTROL_ALL_NOTES_OFF;
  1288. }
  1289. break;
  1290. } // switch (ctrlEvent.type)
  1291. break;
  1292. } // case kEngineEventTypeControl
  1293. case kEngineEventTypeMidi: {
  1294. if (midiEventCount >= kPluginMaxMidiEvents)
  1295. continue;
  1296. const EngineMidiEvent& midiEvent(event.midi);
  1297. if (midiEvent.size > EngineMidiEvent::kDataSize)
  1298. continue;
  1299. uint8_t status = uint8_t(MIDI_GET_STATUS_FROM_DATA(midiEvent.data));
  1300. // Fix bad note-off (per DSSI spec)
  1301. if (status == MIDI_STATUS_NOTE_ON && midiEvent.data[2] == 0)
  1302. status = MIDI_STATUS_NOTE_OFF;
  1303. snd_seq_event_t& seqEvent(fMidiEvents[midiEventCount++]);
  1304. seqEvent.time.tick = isSampleAccurate ? startTime : event.time;
  1305. switch (status)
  1306. {
  1307. case MIDI_STATUS_NOTE_OFF: {
  1308. const uint8_t note = midiEvent.data[1];
  1309. seqEvent.type = SND_SEQ_EVENT_NOTEOFF;
  1310. seqEvent.data.note.channel = event.channel;
  1311. seqEvent.data.note.note = note;
  1312. pData->postponeRtEvent(kPluginPostRtEventNoteOff, event.channel, note, 0.0f);
  1313. break;
  1314. }
  1315. case MIDI_STATUS_NOTE_ON: {
  1316. const uint8_t note = midiEvent.data[1];
  1317. const uint8_t velo = midiEvent.data[2];
  1318. seqEvent.type = SND_SEQ_EVENT_NOTEON;
  1319. seqEvent.data.note.channel = event.channel;
  1320. seqEvent.data.note.note = note;
  1321. seqEvent.data.note.velocity = velo;
  1322. pData->postponeRtEvent(kPluginPostRtEventNoteOn, event.channel, note, velo);
  1323. break;
  1324. }
  1325. case MIDI_STATUS_POLYPHONIC_AFTERTOUCH:
  1326. if (pData->options & PLUGIN_OPTION_SEND_NOTE_AFTERTOUCH)
  1327. {
  1328. const uint8_t note = midiEvent.data[1];
  1329. const uint8_t pressure = midiEvent.data[2];
  1330. seqEvent.type = SND_SEQ_EVENT_KEYPRESS;
  1331. seqEvent.data.note.channel = event.channel;
  1332. seqEvent.data.note.note = note;
  1333. seqEvent.data.note.velocity = pressure;
  1334. }
  1335. break;
  1336. case MIDI_STATUS_CONTROL_CHANGE:
  1337. if (pData->options & PLUGIN_OPTION_SEND_CONTROL_CHANGES)
  1338. {
  1339. const uint8_t control = midiEvent.data[1];
  1340. const uint8_t value = midiEvent.data[2];
  1341. seqEvent.type = SND_SEQ_EVENT_CONTROLLER;
  1342. seqEvent.data.control.channel = event.channel;
  1343. seqEvent.data.control.param = control;
  1344. seqEvent.data.control.value = value;
  1345. }
  1346. break;
  1347. case MIDI_STATUS_CHANNEL_PRESSURE:
  1348. if (pData->options & PLUGIN_OPTION_SEND_CHANNEL_PRESSURE)
  1349. {
  1350. const uint8_t pressure = midiEvent.data[1];
  1351. seqEvent.type = SND_SEQ_EVENT_CHANPRESS;
  1352. seqEvent.data.control.channel = event.channel;
  1353. seqEvent.data.control.value = pressure;
  1354. }
  1355. break;
  1356. case MIDI_STATUS_PITCH_WHEEL_CONTROL:
  1357. if (pData->options & PLUGIN_OPTION_SEND_PITCHBEND)
  1358. {
  1359. const uint8_t lsb = midiEvent.data[1];
  1360. const uint8_t msb = midiEvent.data[2];
  1361. seqEvent.type = SND_SEQ_EVENT_PITCHBEND;
  1362. seqEvent.data.control.channel = event.channel;
  1363. seqEvent.data.control.value = ((msb << 7) | lsb) - 8192;
  1364. }
  1365. break;
  1366. default:
  1367. --midiEventCount;
  1368. break;
  1369. } // switch (status)
  1370. } break;
  1371. } // switch (event.type)
  1372. }
  1373. pData->postRtEvents.trySplice();
  1374. if (frames > timeOffset)
  1375. processSingle(audioIn, audioOut, frames - timeOffset, timeOffset, midiEventCount);
  1376. } // End of Event Input and Processing
  1377. // --------------------------------------------------------------------------------------------------------
  1378. // Plugin processing (no events)
  1379. else
  1380. {
  1381. processSingle(audioIn, audioOut, frames, 0, midiEventCount);
  1382. } // End of Plugin processing (no events)
  1383. // --------------------------------------------------------------------------------------------------------
  1384. // Control Output
  1385. if (pData->event.portOut != nullptr)
  1386. {
  1387. uint8_t channel;
  1388. uint16_t param;
  1389. float value;
  1390. for (uint32_t k=0; k < pData->param.count; ++k)
  1391. {
  1392. if (pData->param.data[k].type != PARAMETER_OUTPUT)
  1393. continue;
  1394. pData->param.ranges[k].fixValue(fParamBuffers[k]);
  1395. if (pData->param.data[k].midiCC > 0)
  1396. {
  1397. channel = pData->param.data[k].midiChannel;
  1398. param = static_cast<uint16_t>(pData->param.data[k].midiCC);
  1399. value = pData->param.ranges[k].getNormalizedValue(fParamBuffers[k]);
  1400. pData->event.portOut->writeControlEvent(0, channel, kEngineControlEventTypeParameter, param, value);
  1401. }
  1402. }
  1403. } // End of Control Output
  1404. }
  1405. bool processSingle(const float** const audioIn, float** const audioOut, const uint32_t frames,
  1406. const uint32_t timeOffset, const ulong midiEventCount)
  1407. {
  1408. CARLA_SAFE_ASSERT_RETURN(frames > 0, false);
  1409. if (pData->audioIn.count > 0)
  1410. {
  1411. CARLA_SAFE_ASSERT_RETURN(audioIn != nullptr, false);
  1412. }
  1413. if (pData->audioOut.count > 0)
  1414. {
  1415. CARLA_SAFE_ASSERT_RETURN(audioOut != nullptr, false);
  1416. }
  1417. // --------------------------------------------------------------------------------------------------------
  1418. // Try lock, silence otherwise
  1419. if (pData->engine->isOffline())
  1420. {
  1421. pData->singleMutex.lock();
  1422. }
  1423. else if (! pData->singleMutex.tryLock())
  1424. {
  1425. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  1426. {
  1427. for (uint32_t k=0; k < frames; ++k)
  1428. audioOut[i][k+timeOffset] = 0.0f;
  1429. }
  1430. return false;
  1431. }
  1432. // --------------------------------------------------------------------------------------------------------
  1433. // Set audio buffers
  1434. const bool customMonoOut = pData->audioOut.count == 2 && fForcedStereoOut && ! fForcedStereoIn;
  1435. const bool customStereoOut = pData->audioOut.count == 2 && fForcedStereoIn && ! fForcedStereoOut;
  1436. if (! customMonoOut)
  1437. {
  1438. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  1439. carla_zeroFloats(fAudioOutBuffers[i], frames);
  1440. }
  1441. for (uint32_t i=0; i < pData->audioIn.count; ++i)
  1442. carla_copyFloats(fAudioInBuffers[i], audioIn[i]+timeOffset, frames);
  1443. // --------------------------------------------------------------------------------------------------------
  1444. // Run plugin
  1445. uint instn = 0;
  1446. for (LinkedList<LADSPA_Handle>::Itenerator it = fHandles.begin2(); it.valid(); it.next(), ++instn)
  1447. {
  1448. LADSPA_Handle const handle(it.getValue(nullptr));
  1449. CARLA_SAFE_ASSERT_CONTINUE(handle != nullptr);
  1450. // ----------------------------------------------------------------------------------------------------
  1451. // Mixdown for forced stereo
  1452. if (customMonoOut)
  1453. carla_zeroFloats(fAudioOutBuffers[instn], frames);
  1454. // ----------------------------------------------------------------------------------------------------
  1455. // Run it
  1456. if (fDssiDescriptor->run_synth != nullptr)
  1457. {
  1458. try {
  1459. fDssiDescriptor->run_synth(handle, frames, fMidiEvents, midiEventCount);
  1460. } CARLA_SAFE_EXCEPTION("DSSI run_synth");
  1461. }
  1462. else
  1463. {
  1464. try {
  1465. fDescriptor->run(handle, frames);
  1466. } CARLA_SAFE_EXCEPTION("DSSI run");
  1467. }
  1468. // ----------------------------------------------------------------------------------------------------
  1469. // Mixdown for forced stereo
  1470. if (customMonoOut)
  1471. carla_multiply(fAudioOutBuffers[instn], 0.5f, frames);
  1472. else if (customStereoOut)
  1473. carla_copyFloats(fExtraStereoBuffer[instn], fAudioOutBuffers[instn], frames);
  1474. }
  1475. if (customStereoOut)
  1476. {
  1477. carla_copyFloats(fAudioOutBuffers[0], fExtraStereoBuffer[0], frames);
  1478. carla_copyFloats(fAudioOutBuffers[1], fExtraStereoBuffer[1], frames);
  1479. }
  1480. #ifndef BUILD_BRIDGE
  1481. // --------------------------------------------------------------------------------------------------------
  1482. // Post-processing (dry/wet, volume and balance)
  1483. {
  1484. const bool doDryWet = (pData->hints & PLUGIN_CAN_DRYWET) != 0 && carla_isNotEqual(pData->postProc.dryWet, 1.0f);
  1485. const bool doBalance = (pData->hints & PLUGIN_CAN_BALANCE) != 0 && ! (carla_isEqual(pData->postProc.balanceLeft, -1.0f) && carla_isEqual(pData->postProc.balanceRight, 1.0f));
  1486. const bool isMono = (pData->audioIn.count == 1);
  1487. bool isPair;
  1488. float bufValue, oldBufLeft[doBalance ? frames : 1];
  1489. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  1490. {
  1491. // Dry/Wet
  1492. if (doDryWet)
  1493. {
  1494. const uint32_t c = isMono ? 0 : i;
  1495. for (uint32_t k=0; k < frames; ++k)
  1496. {
  1497. if (k < pData->latency.frames)
  1498. bufValue = pData->latency.buffers[c][k];
  1499. else if (pData->latency.frames < frames)
  1500. bufValue = fAudioInBuffers[c][k-pData->latency.frames];
  1501. else
  1502. bufValue = fAudioInBuffers[c][k];
  1503. fAudioOutBuffers[i][k] = (fAudioOutBuffers[i][k] * pData->postProc.dryWet) + (bufValue * (1.0f - pData->postProc.dryWet));
  1504. }
  1505. }
  1506. // Balance
  1507. if (doBalance)
  1508. {
  1509. isPair = (i % 2 == 0);
  1510. if (isPair)
  1511. {
  1512. CARLA_ASSERT(i+1 < pData->audioOut.count);
  1513. carla_copyFloats(oldBufLeft, fAudioOutBuffers[i], frames);
  1514. }
  1515. float balRangeL = (pData->postProc.balanceLeft + 1.0f)/2.0f;
  1516. float balRangeR = (pData->postProc.balanceRight + 1.0f)/2.0f;
  1517. for (uint32_t k=0; k < frames; ++k)
  1518. {
  1519. if (isPair)
  1520. {
  1521. // left
  1522. fAudioOutBuffers[i][k] = oldBufLeft[k] * (1.0f - balRangeL);
  1523. fAudioOutBuffers[i][k] += fAudioOutBuffers[i+1][k] * (1.0f - balRangeR);
  1524. }
  1525. else
  1526. {
  1527. // right
  1528. fAudioOutBuffers[i][k] = fAudioOutBuffers[i][k] * balRangeR;
  1529. fAudioOutBuffers[i][k] += oldBufLeft[k] * balRangeL;
  1530. }
  1531. }
  1532. }
  1533. // Volume (and buffer copy)
  1534. {
  1535. for (uint32_t k=0; k < frames; ++k)
  1536. audioOut[i][k+timeOffset] = fAudioOutBuffers[i][k] * pData->postProc.volume;
  1537. }
  1538. }
  1539. } // End of Post-processing
  1540. // --------------------------------------------------------------------------------------------------------
  1541. // Save latency values for next callback
  1542. if (const uint32_t latframes = pData->latency.frames)
  1543. {
  1544. CARLA_SAFE_ASSERT(timeOffset == 0);
  1545. if (latframes <= frames)
  1546. {
  1547. for (uint32_t i=0; i < pData->audioIn.count; ++i)
  1548. carla_copyFloats(pData->latency.buffers[i], audioIn[i]+(frames-latframes), latframes);
  1549. }
  1550. else
  1551. {
  1552. const uint32_t diff = pData->latency.frames-frames;
  1553. for (uint32_t i=0, k; i<pData->audioIn.count; ++i)
  1554. {
  1555. // push back buffer by 'frames'
  1556. for (k=0; k < diff; ++k)
  1557. pData->latency.buffers[i][k] = pData->latency.buffers[i][k+frames];
  1558. // put current input at the end
  1559. for (uint32_t j=0; k < latframes; ++j, ++k)
  1560. pData->latency.buffers[i][k] = audioIn[i][j];
  1561. }
  1562. }
  1563. }
  1564. #else // BUILD_BRIDGE
  1565. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  1566. {
  1567. for (uint32_t k=0; k < frames; ++k)
  1568. audioOut[i][k+timeOffset] = fAudioOutBuffers[i][k];
  1569. }
  1570. #endif
  1571. // --------------------------------------------------------------------------------------------------------
  1572. pData->singleMutex.unlock();
  1573. return true;
  1574. }
  1575. void bufferSizeChanged(const uint32_t newBufferSize) override
  1576. {
  1577. CARLA_ASSERT_INT(newBufferSize > 0, newBufferSize);
  1578. carla_debug("CarlaPluginDSSI::bufferSizeChanged(%i) - start", newBufferSize);
  1579. for (uint32_t i=0; i < pData->audioIn.count; ++i)
  1580. {
  1581. if (fAudioInBuffers[i] != nullptr)
  1582. delete[] fAudioInBuffers[i];
  1583. fAudioInBuffers[i] = new float[newBufferSize];
  1584. carla_zeroFloats(fAudioInBuffers[i], newBufferSize);
  1585. }
  1586. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  1587. {
  1588. if (fAudioOutBuffers[i] != nullptr)
  1589. delete[] fAudioOutBuffers[i];
  1590. fAudioOutBuffers[i] = new float[newBufferSize];
  1591. carla_zeroFloats(fAudioOutBuffers[i], newBufferSize);
  1592. }
  1593. if (fExtraStereoBuffer[0] != nullptr)
  1594. {
  1595. delete[] fExtraStereoBuffer[0];
  1596. fExtraStereoBuffer[0] = nullptr;
  1597. }
  1598. if (fExtraStereoBuffer[1] != nullptr)
  1599. {
  1600. delete[] fExtraStereoBuffer[1];
  1601. fExtraStereoBuffer[1] = nullptr;
  1602. }
  1603. if (fForcedStereoIn && pData->audioOut.count == 2)
  1604. {
  1605. fExtraStereoBuffer[0] = new float[newBufferSize];
  1606. fExtraStereoBuffer[1] = new float[newBufferSize];
  1607. carla_zeroFloats(fExtraStereoBuffer[0], newBufferSize);
  1608. carla_zeroFloats(fExtraStereoBuffer[1], newBufferSize);
  1609. }
  1610. reconnectAudioPorts();
  1611. carla_debug("CarlaPluginDSSI::bufferSizeChanged(%i) - end", newBufferSize);
  1612. }
  1613. void sampleRateChanged(const double newSampleRate) override
  1614. {
  1615. CARLA_ASSERT_INT(newSampleRate > 0.0, newSampleRate);
  1616. carla_debug("CarlaPluginDSSI::sampleRateChanged(%g) - start", newSampleRate);
  1617. // TODO - handle UI stuff
  1618. if (pData->active)
  1619. deactivate();
  1620. const std::size_t instanceCount(fHandles.count());
  1621. if (fDescriptor->cleanup == nullptr)
  1622. {
  1623. for (LinkedList<LADSPA_Handle>::Itenerator it = fHandles.begin2(); it.valid(); it.next())
  1624. {
  1625. LADSPA_Handle const handle(it.getValue(nullptr));
  1626. CARLA_SAFE_ASSERT_CONTINUE(handle != nullptr);
  1627. try {
  1628. fDescriptor->cleanup(handle);
  1629. } CARLA_SAFE_EXCEPTION("LADSPA cleanup");
  1630. }
  1631. }
  1632. fHandles.clear();
  1633. for (std::size_t i=0; i<instanceCount; ++i)
  1634. addInstance();
  1635. reconnectAudioPorts();
  1636. if (pData->active)
  1637. activate();
  1638. carla_debug("CarlaPluginDSSI::sampleRateChanged(%g) - end", newSampleRate);
  1639. }
  1640. void reconnectAudioPorts() const noexcept
  1641. {
  1642. if (fForcedStereoIn)
  1643. {
  1644. if (LADSPA_Handle const handle = fHandles.getFirst(nullptr))
  1645. {
  1646. try {
  1647. fDescriptor->connect_port(handle, pData->audioIn.ports[0].rindex, fAudioInBuffers[0]);
  1648. } CARLA_SAFE_EXCEPTION("DSSI connect_port (forced stereo input, first)");
  1649. }
  1650. if (LADSPA_Handle const handle = fHandles.getLast(nullptr))
  1651. {
  1652. try {
  1653. fDescriptor->connect_port(handle, pData->audioIn.ports[1].rindex, fAudioInBuffers[1]);
  1654. } CARLA_SAFE_EXCEPTION("DSSI connect_port (forced stereo input, last)");
  1655. }
  1656. }
  1657. else
  1658. {
  1659. for (LinkedList<LADSPA_Handle>::Itenerator it = fHandles.begin2(); it.valid(); it.next())
  1660. {
  1661. LADSPA_Handle const handle(it.getValue(nullptr));
  1662. CARLA_SAFE_ASSERT_CONTINUE(handle != nullptr);
  1663. for (uint32_t i=0; i < pData->audioIn.count; ++i)
  1664. {
  1665. try {
  1666. fDescriptor->connect_port(handle, pData->audioIn.ports[i].rindex, fAudioInBuffers[i]);
  1667. } CARLA_SAFE_EXCEPTION("DSSI connect_port (audio input)");
  1668. }
  1669. }
  1670. }
  1671. if (fForcedStereoOut)
  1672. {
  1673. if (LADSPA_Handle const handle = fHandles.getFirst(nullptr))
  1674. {
  1675. try {
  1676. fDescriptor->connect_port(handle, pData->audioOut.ports[0].rindex, fAudioOutBuffers[0]);
  1677. } CARLA_SAFE_EXCEPTION("DSSI connect_port (forced stereo output, first)");
  1678. }
  1679. if (LADSPA_Handle const handle = fHandles.getLast(nullptr))
  1680. {
  1681. try {
  1682. fDescriptor->connect_port(handle, pData->audioOut.ports[1].rindex, fAudioOutBuffers[1]);
  1683. } CARLA_SAFE_EXCEPTION("DSSI connect_port (forced stereo output, last)");
  1684. }
  1685. }
  1686. else
  1687. {
  1688. for (LinkedList<LADSPA_Handle>::Itenerator it = fHandles.begin2(); it.valid(); it.next())
  1689. {
  1690. LADSPA_Handle const handle(it.getValue(nullptr));
  1691. CARLA_SAFE_ASSERT_CONTINUE(handle != nullptr);
  1692. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  1693. {
  1694. try {
  1695. fDescriptor->connect_port(handle, pData->audioOut.ports[i].rindex, fAudioOutBuffers[i]);
  1696. } CARLA_SAFE_EXCEPTION("DSSI connect_port (audio output)");
  1697. }
  1698. }
  1699. }
  1700. }
  1701. // -------------------------------------------------------------------
  1702. // Plugin buffers
  1703. void clearBuffers() noexcept override
  1704. {
  1705. carla_debug("CarlaPluginDSSI::clearBuffers() - start");
  1706. if (fAudioInBuffers != nullptr)
  1707. {
  1708. for (uint32_t i=0; i < pData->audioIn.count; ++i)
  1709. {
  1710. if (fAudioInBuffers[i] != nullptr)
  1711. {
  1712. delete[] fAudioInBuffers[i];
  1713. fAudioInBuffers[i] = nullptr;
  1714. }
  1715. }
  1716. delete[] fAudioInBuffers;
  1717. fAudioInBuffers = nullptr;
  1718. }
  1719. if (fAudioOutBuffers != nullptr)
  1720. {
  1721. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  1722. {
  1723. if (fAudioOutBuffers[i] != nullptr)
  1724. {
  1725. delete[] fAudioOutBuffers[i];
  1726. fAudioOutBuffers[i] = nullptr;
  1727. }
  1728. }
  1729. delete[] fAudioOutBuffers;
  1730. fAudioOutBuffers = nullptr;
  1731. }
  1732. if (fExtraStereoBuffer[0] != nullptr)
  1733. {
  1734. delete[] fExtraStereoBuffer[0];
  1735. fExtraStereoBuffer[0] = nullptr;
  1736. }
  1737. if (fExtraStereoBuffer[1] != nullptr)
  1738. {
  1739. delete[] fExtraStereoBuffer[1];
  1740. fExtraStereoBuffer[1] = nullptr;
  1741. }
  1742. if (fParamBuffers != nullptr)
  1743. {
  1744. delete[] fParamBuffers;
  1745. fParamBuffers = nullptr;
  1746. }
  1747. CarlaPlugin::clearBuffers();
  1748. carla_debug("CarlaPluginDSSI::clearBuffers() - end");
  1749. }
  1750. #ifdef HAVE_LIBLO
  1751. // -------------------------------------------------------------------
  1752. // OSC stuff
  1753. void handleOscMessage(const char* const method, const int argc, const void* const argvx, const char* const types, const lo_message msg) override
  1754. {
  1755. const lo_address source(lo_message_get_source(msg));
  1756. CARLA_SAFE_ASSERT_RETURN(source != nullptr,);
  1757. // protocol for DSSI UIs *must* be UDP
  1758. CARLA_SAFE_ASSERT_RETURN(lo_address_get_protocol(source) == LO_UDP,);
  1759. if (fOscData.source == nullptr)
  1760. {
  1761. // if no UI is registered yet only "configure" and "update" messages are valid
  1762. CARLA_SAFE_ASSERT_RETURN(std::strcmp(method, "configure") == 0 || std::strcmp(method, "update") == 0,)
  1763. }
  1764. else
  1765. {
  1766. // make sure message source is the DSSI UI
  1767. const char* const msghost = lo_address_get_hostname(source);
  1768. const char* const msgport = lo_address_get_port(source);
  1769. const char* const ourhost = lo_address_get_hostname(fOscData.source);
  1770. const char* const ourport = lo_address_get_port(fOscData.source);
  1771. CARLA_SAFE_ASSERT_RETURN(std::strcmp(msghost, ourhost) == 0,);
  1772. CARLA_SAFE_ASSERT_RETURN(std::strcmp(msgport, ourport) == 0,);
  1773. }
  1774. const lo_arg* const* const argv(static_cast<const lo_arg* const* const>(argvx));
  1775. if (std::strcmp(method, "configure") == 0)
  1776. return handleOscMessageConfigure(argc, argv, types);
  1777. if (std::strcmp(method, "control") == 0)
  1778. return handleOscMessageControl(argc, argv, types);
  1779. if (std::strcmp(method, "program") == 0)
  1780. return handleOscMessageProgram(argc, argv, types);
  1781. if (std::strcmp(method, "midi") == 0)
  1782. return handleOscMessageMIDI(argc, argv, types);
  1783. if (std::strcmp(method, "update") == 0)
  1784. return handleOscMessageUpdate(argc, argv, types, lo_message_get_source(msg));
  1785. if (std::strcmp(method, "exiting") == 0)
  1786. return handleOscMessageExiting();
  1787. carla_stdout("CarlaPluginDSSI::handleOscMessage() - unknown method '%s'", method);
  1788. }
  1789. void handleOscMessageConfigure(const int argc, const lo_arg* const* const argv, const char* const types)
  1790. {
  1791. carla_debug("CarlaPluginDSSI::handleMsgConfigure()");
  1792. CARLA_PLUGIN_DSSI_OSC_CHECK_OSC_TYPES(2, "ss");
  1793. const char* const key = (const char*)&argv[0]->s;
  1794. const char* const value = (const char*)&argv[1]->s;
  1795. setCustomData(CUSTOM_DATA_TYPE_STRING, key, value, false);
  1796. }
  1797. void handleOscMessageControl(const int argc, const lo_arg* const* const argv, const char* const types)
  1798. {
  1799. carla_debug("CarlaPluginDSSI::handleMsgControl()");
  1800. CARLA_PLUGIN_DSSI_OSC_CHECK_OSC_TYPES(2, "if");
  1801. const int32_t rindex = argv[0]->i;
  1802. const float value = argv[1]->f;
  1803. setParameterValueByRealIndex(rindex, value, false, true, true);
  1804. }
  1805. void handleOscMessageProgram(const int argc, const lo_arg* const* const argv, const char* const types)
  1806. {
  1807. carla_debug("CarlaPluginDSSI::handleMsgProgram()");
  1808. CARLA_PLUGIN_DSSI_OSC_CHECK_OSC_TYPES(2, "ii");
  1809. const int32_t bank = argv[0]->i;
  1810. const int32_t program = argv[1]->i;
  1811. CARLA_SAFE_ASSERT_RETURN(bank >= 0,);
  1812. CARLA_SAFE_ASSERT_RETURN(program >= 0,);
  1813. setMidiProgramById(static_cast<uint32_t>(bank), static_cast<uint32_t>(program), false, true, true);
  1814. }
  1815. void handleOscMessageMIDI(const int argc, const lo_arg* const* const argv, const char* const types)
  1816. {
  1817. carla_debug("CarlaPluginDSSI::handleMsgMidi()");
  1818. CARLA_PLUGIN_DSSI_OSC_CHECK_OSC_TYPES(1, "m");
  1819. if (getMidiInCount() == 0)
  1820. {
  1821. carla_stderr("CarlaPluginDSSI::handleMsgMidi() - received midi when plugin has no midi inputs");
  1822. return;
  1823. }
  1824. const uint8_t* const data = argv[0]->m;
  1825. uint8_t status = data[1];
  1826. uint8_t channel = status & 0x0F;
  1827. // Fix bad note-off
  1828. if (MIDI_IS_STATUS_NOTE_ON(status) && data[3] == 0)
  1829. status = MIDI_STATUS_NOTE_OFF;
  1830. if (MIDI_IS_STATUS_NOTE_OFF(status))
  1831. {
  1832. const uint8_t note = data[2];
  1833. CARLA_SAFE_ASSERT_RETURN(note < MAX_MIDI_NOTE,);
  1834. sendMidiSingleNote(channel, note, 0, false, true, true);
  1835. }
  1836. else if (MIDI_IS_STATUS_NOTE_ON(status))
  1837. {
  1838. const uint8_t note = data[2];
  1839. const uint8_t velo = data[3];
  1840. CARLA_SAFE_ASSERT_RETURN(note < MAX_MIDI_NOTE,);
  1841. CARLA_SAFE_ASSERT_RETURN(velo < MAX_MIDI_VALUE,);
  1842. sendMidiSingleNote(channel, note, velo, false, true, true);
  1843. }
  1844. }
  1845. void handleOscMessageUpdate(const int argc, const lo_arg* const* const argv, const char* const types, const lo_address source)
  1846. {
  1847. carla_debug("CarlaPluginDSSI::handleMsgUpdate()");
  1848. CARLA_PLUGIN_DSSI_OSC_CHECK_OSC_TYPES(1, "s");
  1849. const char* const url = (const char*)&argv[0]->s;
  1850. // FIXME - remove debug prints later
  1851. carla_stdout("CarlaPluginDSSI::updateOscData(%p, \"%s\")", source, url);
  1852. fOscData.clear();
  1853. const int proto = lo_address_get_protocol(source);
  1854. {
  1855. const char* host = lo_address_get_hostname(source);
  1856. const char* port = lo_address_get_port(source);
  1857. fOscData.source = lo_address_new_with_proto(proto, host, port);
  1858. carla_stdout("CarlaPlugin::updateOscData() - source: host \"%s\", port \"%s\"", host, port);
  1859. }
  1860. {
  1861. char* host = lo_url_get_hostname(url);
  1862. char* port = lo_url_get_port(url);
  1863. fOscData.path = carla_strdup_free(lo_url_get_path(url));
  1864. fOscData.target = lo_address_new_with_proto(proto, host, port);
  1865. carla_stdout("CarlaPlugin::updateOscData() - target: host \"%s\", port \"%s\", path \"%s\"", host, port, fOscData.path);
  1866. std::free(host);
  1867. std::free(port);
  1868. }
  1869. osc_send_sample_rate(fOscData, static_cast<float>(pData->engine->getSampleRate()));
  1870. for (LinkedList<CustomData>::Itenerator it = pData->custom.begin2(); it.valid(); it.next())
  1871. {
  1872. const CustomData& customData(it.getValue(kCustomDataFallback));
  1873. CARLA_SAFE_ASSERT_CONTINUE(customData.isValid());
  1874. if (std::strcmp(customData.type, CUSTOM_DATA_TYPE_STRING) == 0)
  1875. osc_send_configure(fOscData, customData.key, customData.value);
  1876. }
  1877. if (pData->prog.current >= 0)
  1878. osc_send_program(fOscData, static_cast<uint32_t>(pData->prog.current));
  1879. if (pData->midiprog.current >= 0)
  1880. {
  1881. const MidiProgramData& curMidiProg(pData->midiprog.getCurrent());
  1882. osc_send_program(fOscData, curMidiProg.bank, curMidiProg.program);
  1883. }
  1884. for (uint32_t i=0; i < pData->param.count; ++i)
  1885. osc_send_control(fOscData, pData->param.data[i].rindex, getParameterValue(i));
  1886. #ifndef BUILD_BRIDGE
  1887. if (pData->engine->getOptions().frontendWinId != 0)
  1888. pData->transientTryCounter = 1;
  1889. #endif
  1890. carla_stdout("CarlaPluginDSSI::updateOscData() - done");
  1891. }
  1892. void handleOscMessageExiting()
  1893. {
  1894. carla_debug("CarlaPluginDSSI::handleMsgExiting()");
  1895. // hide UI
  1896. showCustomUI(false);
  1897. // tell frontend
  1898. pData->engine->callback(ENGINE_CALLBACK_UI_STATE_CHANGED, pData->id, 0, 0, 0.0f, nullptr);
  1899. }
  1900. // -------------------------------------------------------------------
  1901. // Post-poned UI Stuff
  1902. void uiParameterChange(const uint32_t index, const float value) noexcept override
  1903. {
  1904. CARLA_SAFE_ASSERT_RETURN(index < pData->param.count,);
  1905. if (fOscData.target == nullptr)
  1906. return;
  1907. osc_send_control(fOscData, pData->param.data[index].rindex, value);
  1908. }
  1909. void uiMidiProgramChange(const uint32_t index) noexcept override
  1910. {
  1911. CARLA_SAFE_ASSERT_RETURN(index < pData->midiprog.count,);
  1912. if (fOscData.target == nullptr)
  1913. return;
  1914. osc_send_program(fOscData, pData->midiprog.data[index].bank, pData->midiprog.data[index].program);
  1915. }
  1916. void uiNoteOn(const uint8_t channel, const uint8_t note, const uint8_t velo) noexcept override
  1917. {
  1918. CARLA_SAFE_ASSERT_RETURN(channel < MAX_MIDI_CHANNELS,);
  1919. CARLA_SAFE_ASSERT_RETURN(note < MAX_MIDI_NOTE,);
  1920. CARLA_SAFE_ASSERT_RETURN(velo > 0 && velo < MAX_MIDI_VALUE,);
  1921. if (fOscData.target == nullptr)
  1922. return;
  1923. #if 0
  1924. uint8_t midiData[4];
  1925. midiData[0] = 0;
  1926. midiData[1] = uint8_t(MIDI_STATUS_NOTE_ON | (channel & MIDI_CHANNEL_BIT));
  1927. midiData[2] = note;
  1928. midiData[3] = velo;
  1929. osc_send_midi(fOscData, midiData);
  1930. #endif
  1931. }
  1932. void uiNoteOff(const uint8_t channel, const uint8_t note) noexcept override
  1933. {
  1934. CARLA_SAFE_ASSERT_RETURN(channel < MAX_MIDI_CHANNELS,);
  1935. CARLA_SAFE_ASSERT_RETURN(note < MAX_MIDI_NOTE,);
  1936. if (fOscData.target == nullptr)
  1937. return;
  1938. #if 0
  1939. uint8_t midiData[4];
  1940. midiData[0] = 0;
  1941. midiData[1] = uint8_t(MIDI_STATUS_NOTE_ON | (channel & MIDI_CHANNEL_BIT));
  1942. midiData[2] = note;
  1943. midiData[3] = 0;
  1944. osc_send_midi(fOscData, midiData);
  1945. #endif
  1946. }
  1947. #endif // HAVE_LIBLO
  1948. // -------------------------------------------------------------------
  1949. const void* getNativeDescriptor() const noexcept override
  1950. {
  1951. return fDssiDescriptor;
  1952. }
  1953. #ifdef HAVE_LIBLO
  1954. uintptr_t getUiBridgeProcessId() const noexcept override
  1955. {
  1956. return fThreadUI.getProcessId();
  1957. }
  1958. const void* getExtraStuff() const noexcept override
  1959. {
  1960. return fUiFilename;
  1961. }
  1962. #endif
  1963. // -------------------------------------------------------------------
  1964. bool init(const char* const filename, const char* name, const char* const label, const uint options)
  1965. {
  1966. CARLA_SAFE_ASSERT_RETURN(pData->engine != nullptr, false);
  1967. // ---------------------------------------------------------------
  1968. // first checks
  1969. if (pData->client != nullptr)
  1970. {
  1971. pData->engine->setLastError("Plugin client is already registered");
  1972. return false;
  1973. }
  1974. if (filename == nullptr || filename[0] == '\0')
  1975. {
  1976. pData->engine->setLastError("null filename");
  1977. return false;
  1978. }
  1979. // ---------------------------------------------------------------
  1980. // open DLL
  1981. if (! pData->libOpen(filename))
  1982. {
  1983. pData->engine->setLastError(pData->libError(filename));
  1984. return false;
  1985. }
  1986. // ---------------------------------------------------------------
  1987. // get DLL main entry
  1988. const DSSI_Descriptor_Function descFn = pData->libSymbol<DSSI_Descriptor_Function>("dssi_descriptor");
  1989. if (descFn == nullptr)
  1990. {
  1991. pData->engine->setLastError("Could not find the DSSI Descriptor in the plugin library");
  1992. return false;
  1993. }
  1994. // ---------------------------------------------------------------
  1995. // get descriptor that matches label
  1996. // if label is null, get first valid plugin
  1997. const bool nullLabel = (label == nullptr || label[0] == '\0');
  1998. for (ulong d=0;; ++d)
  1999. {
  2000. try {
  2001. fDssiDescriptor = descFn(d);
  2002. }
  2003. catch(...) {
  2004. carla_stderr2("Caught exception when trying to get DSSI descriptor");
  2005. fDescriptor = nullptr;
  2006. fDssiDescriptor = nullptr;
  2007. break;
  2008. }
  2009. if (fDssiDescriptor == nullptr)
  2010. break;
  2011. fDescriptor = fDssiDescriptor->LADSPA_Plugin;
  2012. if (fDescriptor == nullptr)
  2013. {
  2014. carla_stderr2("WARNING - Missing LADSPA interface, will not use this plugin");
  2015. fDssiDescriptor = nullptr;
  2016. break;
  2017. }
  2018. if (fDescriptor->Label == nullptr || fDescriptor->Label[0] == '\0')
  2019. {
  2020. carla_stderr2("WARNING - Got an invalid label, will not use this plugin");
  2021. fDescriptor = nullptr;
  2022. fDssiDescriptor = nullptr;
  2023. break;
  2024. }
  2025. if (fDescriptor->run == nullptr)
  2026. {
  2027. carla_stderr2("WARNING - Plugin has no run, cannot use it");
  2028. fDescriptor = nullptr;
  2029. fDssiDescriptor = nullptr;
  2030. break;
  2031. }
  2032. if (nullLabel || std::strcmp(fDescriptor->Label, label) == 0)
  2033. break;
  2034. }
  2035. if (fDescriptor == nullptr || fDssiDescriptor == nullptr)
  2036. {
  2037. pData->engine->setLastError("Could not find the requested plugin label in the plugin library");
  2038. return false;
  2039. }
  2040. // ---------------------------------------------------------------
  2041. // check if uses global instance
  2042. if (fDssiDescriptor->run_synth == nullptr && fDssiDescriptor->run_multiple_synths != nullptr)
  2043. {
  2044. pData->engine->setLastError("This plugin requires run_multiple_synths which is not supported");
  2045. return false;
  2046. }
  2047. // ---------------------------------------------------------------
  2048. // check for fixed buffer size requirement
  2049. fNeedsFixedBuffers = CarlaString(filename).contains("dssi-vst", true);
  2050. if (fNeedsFixedBuffers && ! pData->engine->usesConstantBufferSize())
  2051. {
  2052. pData->engine->setLastError("Cannot use this plugin under the current engine.\n"
  2053. "The plugin requires a fixed block size which is not possible right now.");
  2054. return false;
  2055. }
  2056. // ---------------------------------------------------------------
  2057. // get info
  2058. if (name == nullptr || name[0] == '\0')
  2059. {
  2060. if (fDescriptor->Name != nullptr && fDescriptor->Name[0] != '\0')
  2061. name = fDescriptor->Name;
  2062. else
  2063. name = fDescriptor->Label;
  2064. }
  2065. pData->name = pData->engine->getUniquePluginName(name);
  2066. pData->filename = carla_strdup(filename);
  2067. // ---------------------------------------------------------------
  2068. // register client
  2069. pData->client = pData->engine->addClient(this);
  2070. if (pData->client == nullptr || ! pData->client->isOk())
  2071. {
  2072. pData->engine->setLastError("Failed to register plugin client");
  2073. return false;
  2074. }
  2075. // ---------------------------------------------------------------
  2076. // initialize plugin
  2077. if (! addInstance())
  2078. return false;
  2079. // ---------------------------------------------------------------
  2080. // find latency port index
  2081. for (uint32_t i=0, iCtrl=0, count=getSafePortCount(); i<count; ++i)
  2082. {
  2083. const int portType(fDescriptor->PortDescriptors[i]);
  2084. if (! LADSPA_IS_PORT_CONTROL(portType))
  2085. continue;
  2086. const uint32_t index(iCtrl++);
  2087. if (! LADSPA_IS_PORT_OUTPUT(portType))
  2088. continue;
  2089. const char* const portName(fDescriptor->PortNames[i]);
  2090. CARLA_SAFE_ASSERT_BREAK(portName != nullptr);
  2091. if (std::strcmp(portName, "latency") == 0 ||
  2092. std::strcmp(portName, "_latency") == 0)
  2093. {
  2094. fLatencyIndex = static_cast<int32_t>(index);
  2095. break;
  2096. }
  2097. }
  2098. // ---------------------------------------------------------------
  2099. // check for custom data extension
  2100. if (fDssiDescriptor->configure != nullptr)
  2101. {
  2102. if (char* const error = fDssiDescriptor->configure(fHandles.getFirst(nullptr), DSSI_CUSTOMDATA_EXTENSION_KEY, ""))
  2103. {
  2104. if (std::strcmp(error, "true") == 0 && fDssiDescriptor->get_custom_data != nullptr
  2105. && fDssiDescriptor->set_custom_data != nullptr)
  2106. fUsesCustomData = true;
  2107. std::free(error);
  2108. }
  2109. }
  2110. #ifdef HAVE_LIBLO
  2111. // ---------------------------------------------------------------
  2112. // check for gui
  2113. if (const char* const guiFilename = find_dssi_ui(filename, fDescriptor->Label))
  2114. {
  2115. fUiFilename = guiFilename;
  2116. fThreadUI.setData(guiFilename, fDescriptor->Label);
  2117. }
  2118. #endif
  2119. // ---------------------------------------------------------------
  2120. // set default options
  2121. pData->options = 0x0;
  2122. /**/ if (fLatencyIndex >= 0 || fNeedsFixedBuffers)
  2123. pData->options |= PLUGIN_OPTION_FIXED_BUFFERS;
  2124. else if (options & PLUGIN_OPTION_FIXED_BUFFERS)
  2125. pData->options |= PLUGIN_OPTION_FIXED_BUFFERS;
  2126. /**/ if (pData->engine->getOptions().forceStereo)
  2127. pData->options |= PLUGIN_OPTION_FORCE_STEREO;
  2128. else if (options & PLUGIN_OPTION_FORCE_STEREO)
  2129. pData->options |= PLUGIN_OPTION_FORCE_STEREO;
  2130. if (fDssiDescriptor->get_program != nullptr && fDssiDescriptor->select_program != nullptr)
  2131. pData->options |= PLUGIN_OPTION_MAP_PROGRAM_CHANGES;
  2132. if (fUsesCustomData)
  2133. pData->options |= PLUGIN_OPTION_USE_CHUNKS;
  2134. if (fDssiDescriptor->run_synth != nullptr)
  2135. {
  2136. pData->options |= PLUGIN_OPTION_SEND_CHANNEL_PRESSURE;
  2137. pData->options |= PLUGIN_OPTION_SEND_NOTE_AFTERTOUCH;
  2138. pData->options |= PLUGIN_OPTION_SEND_PITCHBEND;
  2139. pData->options |= PLUGIN_OPTION_SEND_ALL_SOUND_OFF;
  2140. if (options & PLUGIN_OPTION_SEND_CONTROL_CHANGES)
  2141. pData->options |= PLUGIN_OPTION_SEND_CONTROL_CHANGES;
  2142. }
  2143. return true;
  2144. }
  2145. // -------------------------------------------------------------------
  2146. private:
  2147. LinkedList<LADSPA_Handle> fHandles;
  2148. const LADSPA_Descriptor* fDescriptor;
  2149. const DSSI_Descriptor* fDssiDescriptor;
  2150. float** fAudioInBuffers;
  2151. float** fAudioOutBuffers;
  2152. float* fExtraStereoBuffer[2]; // used only if forcedStereoIn and audioOut == 2
  2153. float* fParamBuffers;
  2154. snd_seq_event_t fMidiEvents[kPluginMaxMidiEvents];
  2155. int32_t fLatencyIndex; // -1 if invalid
  2156. bool fForcedStereoIn;
  2157. bool fForcedStereoOut;
  2158. bool fNeedsFixedBuffers;
  2159. bool fUsesCustomData;
  2160. #ifdef HAVE_LIBLO
  2161. CarlaOscData fOscData;
  2162. CarlaThreadDSSIUI fThreadUI;
  2163. const char* fUiFilename;
  2164. #endif
  2165. // -------------------------------------------------------------------
  2166. bool addInstance()
  2167. {
  2168. LADSPA_Handle handle;
  2169. try {
  2170. handle = fDescriptor->instantiate(fDescriptor, static_cast<ulong>(pData->engine->getSampleRate()));
  2171. } CARLA_SAFE_EXCEPTION_RETURN_ERR("LADSPA instantiate", "Plugin failed to initialize");
  2172. for (uint32_t i=0, count=pData->param.count; i<count; ++i)
  2173. {
  2174. const int32_t rindex(pData->param.data[i].rindex);
  2175. CARLA_SAFE_ASSERT_CONTINUE(rindex >= 0);
  2176. try {
  2177. fDescriptor->connect_port(handle, static_cast<ulong>(rindex), &fParamBuffers[i]);
  2178. } CARLA_SAFE_EXCEPTION("LADSPA connect_port");
  2179. }
  2180. if (fHandles.append(handle))
  2181. return true;
  2182. try {
  2183. fDescriptor->cleanup(handle);
  2184. } CARLA_SAFE_EXCEPTION("LADSPA cleanup");
  2185. pData->engine->setLastError("Out of memory");
  2186. return false;
  2187. }
  2188. uint32_t getSafePortCount() const noexcept
  2189. {
  2190. if (fDescriptor->PortCount == 0)
  2191. return 0;
  2192. CARLA_SAFE_ASSERT_RETURN(fDescriptor->PortDescriptors != nullptr, 0);
  2193. CARLA_SAFE_ASSERT_RETURN(fDescriptor->PortRangeHints != nullptr, 0);
  2194. CARLA_SAFE_ASSERT_RETURN(fDescriptor->PortNames != nullptr, 0);
  2195. return static_cast<uint32_t>(fDescriptor->PortCount);
  2196. }
  2197. bool getSeparatedParameterNameOrUnit(const char* const paramName, char* const strBuf, const bool wantName) const noexcept
  2198. {
  2199. if (_getSeparatedParameterNameOrUnitImpl(paramName, strBuf, wantName, true))
  2200. return true;
  2201. if (_getSeparatedParameterNameOrUnitImpl(paramName, strBuf, wantName, false))
  2202. return true;
  2203. return false;
  2204. }
  2205. static bool _getSeparatedParameterNameOrUnitImpl(const char* const paramName, char* const strBuf,
  2206. const bool wantName, const bool useBracket) noexcept
  2207. {
  2208. const char* const sepBracketStart(std::strstr(paramName, useBracket ? " [" : " ("));
  2209. if (sepBracketStart == nullptr)
  2210. return false;
  2211. const char* const sepBracketEnd(std::strstr(sepBracketStart, useBracket ? "]" : ")"));
  2212. if (sepBracketEnd == nullptr)
  2213. return false;
  2214. const std::size_t unitSize(static_cast<std::size_t>(sepBracketEnd-sepBracketStart-2));
  2215. if (unitSize > 7) // very unlikely to have such big unit
  2216. return false;
  2217. const std::size_t sepIndex(std::strlen(paramName)-unitSize-3);
  2218. // just in case
  2219. if (sepIndex+2 >= STR_MAX)
  2220. return false;
  2221. if (wantName)
  2222. {
  2223. std::strncpy(strBuf, paramName, sepIndex);
  2224. strBuf[sepIndex] = '\0';
  2225. }
  2226. else
  2227. {
  2228. std::strncpy(strBuf, paramName+(sepIndex+2), unitSize);
  2229. strBuf[unitSize] = '\0';
  2230. }
  2231. return true;
  2232. }
  2233. // -------------------------------------------------------------------
  2234. CARLA_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(CarlaPluginDSSI)
  2235. };
  2236. // -------------------------------------------------------------------------------------------------------------------
  2237. CarlaPlugin* CarlaPlugin::newDSSI(const Initializer& init)
  2238. {
  2239. carla_debug("CarlaPlugin::newDSSI({%p, \"%s\", \"%s\", \"%s\", " P_INT64 ", %x})",
  2240. init.engine, init.filename, init.name, init.label, init.uniqueId, init.options);
  2241. CarlaPluginDSSI* const plugin(new CarlaPluginDSSI(init.engine, init.id));
  2242. if (! plugin->init(init.filename, init.name, init.label, init.options))
  2243. {
  2244. delete plugin;
  2245. return nullptr;
  2246. }
  2247. return plugin;
  2248. }
  2249. // -------------------------------------------------------------------------------------------------------------------
  2250. CARLA_BACKEND_END_NAMESPACE