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.

2814 lines
102KB

  1. /*
  2. * Carla Plugin, DSSI 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 "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. using juce::ChildProcess;
  27. using juce::ScopedPointer;
  28. using juce::String;
  29. using juce::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. pData->transientTryCounter = 0;
  534. if (fOscData.target != nullptr)
  535. {
  536. osc_send_hide(fOscData);
  537. osc_send_quit(fOscData);
  538. fOscData.clear();
  539. }
  540. fThreadUI.stopThread(static_cast<int>(pData->engine->getOptions().uiBridgesTimeout * 2));
  541. }
  542. }
  543. #endif
  544. // -------------------------------------------------------------------
  545. // Plugin state
  546. void reload() override
  547. {
  548. CARLA_SAFE_ASSERT_RETURN(pData->engine != nullptr,);
  549. CARLA_SAFE_ASSERT_RETURN(fDescriptor != nullptr,);
  550. CARLA_SAFE_ASSERT_RETURN(fDssiDescriptor != nullptr,);
  551. CARLA_SAFE_ASSERT_RETURN(fHandles.count() > 0,);
  552. carla_debug("CarlaPluginDSSI::reload() - start");
  553. const EngineProcessMode processMode(pData->engine->getProccessMode());
  554. // Safely disable plugin for reload
  555. const ScopedDisabler sd(this);
  556. if (pData->active)
  557. deactivate();
  558. clearBuffers();
  559. const float sampleRate(static_cast<float>(pData->engine->getSampleRate()));
  560. const uint32_t portCount(getSafePortCount());
  561. uint32_t aIns, aOuts, mIns, params;
  562. aIns = aOuts = mIns = params = 0;
  563. bool forcedStereoIn, forcedStereoOut;
  564. forcedStereoIn = forcedStereoOut = false;
  565. bool needsCtrlIn, needsCtrlOut;
  566. needsCtrlIn = needsCtrlOut = false;
  567. for (uint32_t i=0; i < portCount; ++i)
  568. {
  569. const LADSPA_PortDescriptor portType(fDescriptor->PortDescriptors[i]);
  570. if (LADSPA_IS_PORT_AUDIO(portType))
  571. {
  572. if (LADSPA_IS_PORT_INPUT(portType))
  573. aIns += 1;
  574. else if (LADSPA_IS_PORT_OUTPUT(portType))
  575. aOuts += 1;
  576. }
  577. else if (LADSPA_IS_PORT_CONTROL(portType))
  578. params += 1;
  579. }
  580. if (pData->options & PLUGIN_OPTION_FORCE_STEREO)
  581. {
  582. if ((aIns == 1 || aOuts == 1) && fHandles.count() == 1 && addInstance())
  583. {
  584. if (aIns == 1)
  585. {
  586. aIns = 2;
  587. forcedStereoIn = true;
  588. }
  589. if (aOuts == 1)
  590. {
  591. aOuts = 2;
  592. forcedStereoOut = true;
  593. }
  594. }
  595. }
  596. if (fDssiDescriptor->run_synth != nullptr)
  597. {
  598. mIns = 1;
  599. needsCtrlIn = true;
  600. }
  601. if (aIns > 0)
  602. {
  603. pData->audioIn.createNew(aIns);
  604. fAudioInBuffers = new float*[aIns];
  605. for (uint32_t i=0; i < aIns; ++i)
  606. fAudioInBuffers[i] = nullptr;
  607. }
  608. if (aOuts > 0)
  609. {
  610. pData->audioOut.createNew(aOuts);
  611. fAudioOutBuffers = new float*[aOuts];
  612. needsCtrlIn = true;
  613. for (uint32_t i=0; i < aOuts; ++i)
  614. fAudioOutBuffers[i] = nullptr;
  615. }
  616. if (params > 0)
  617. {
  618. pData->param.createNew(params, true);
  619. fParamBuffers = new float[params];
  620. FloatVectorOperations::clear(fParamBuffers, static_cast<int>(params));
  621. }
  622. const uint portNameSize(pData->engine->getMaxPortNameSize());
  623. CarlaString portName;
  624. for (uint32_t i=0, iAudioIn=0, iAudioOut=0, iCtrl=0; i < portCount; ++i)
  625. {
  626. const LADSPA_PortDescriptor portType = fDescriptor->PortDescriptors[i];
  627. const LADSPA_PortRangeHint portRangeHints = fDescriptor->PortRangeHints[i];
  628. if (LADSPA_IS_PORT_AUDIO(portType))
  629. {
  630. portName.clear();
  631. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  632. {
  633. portName = pData->name;
  634. portName += ":";
  635. }
  636. if (fDescriptor->PortNames[i] != nullptr && fDescriptor->PortNames[i][0] != '\0')
  637. {
  638. portName += fDescriptor->PortNames[i];
  639. }
  640. else
  641. {
  642. if (LADSPA_IS_PORT_INPUT(portType))
  643. {
  644. if (aIns > 1)
  645. {
  646. portName += "audio-in_";
  647. portName += CarlaString(iAudioIn+1);
  648. }
  649. else
  650. portName += "audio-in";
  651. }
  652. else
  653. {
  654. if (aOuts > 1)
  655. {
  656. portName += "audio-out_";
  657. portName += CarlaString(iAudioOut+1);
  658. }
  659. else
  660. portName += "audio-out";
  661. }
  662. }
  663. portName.truncate(portNameSize);
  664. if (LADSPA_IS_PORT_INPUT(portType))
  665. {
  666. const uint32_t j = iAudioIn++;
  667. pData->audioIn.ports[j].port = (CarlaEngineAudioPort*)pData->client->addPort(kEnginePortTypeAudio, portName, true, j);
  668. pData->audioIn.ports[j].rindex = i;
  669. if (forcedStereoIn)
  670. {
  671. portName += "_2";
  672. pData->audioIn.ports[1].port = (CarlaEngineAudioPort*)pData->client->addPort(kEnginePortTypeAudio, portName, true, 1);
  673. pData->audioIn.ports[1].rindex = i;
  674. }
  675. }
  676. else if (LADSPA_IS_PORT_OUTPUT(portType))
  677. {
  678. const uint32_t j = iAudioOut++;
  679. pData->audioOut.ports[j].port = (CarlaEngineAudioPort*)pData->client->addPort(kEnginePortTypeAudio, portName, false, j);
  680. pData->audioOut.ports[j].rindex = i;
  681. if (forcedStereoOut)
  682. {
  683. portName += "_2";
  684. pData->audioOut.ports[1].port = (CarlaEngineAudioPort*)pData->client->addPort(kEnginePortTypeAudio, portName, false, 1);
  685. pData->audioOut.ports[1].rindex = i;
  686. }
  687. }
  688. else
  689. carla_stderr2("WARNING - Got a broken Port (Audio, but not input or output)");
  690. }
  691. else if (LADSPA_IS_PORT_CONTROL(portType))
  692. {
  693. const uint32_t j = iCtrl++;
  694. pData->param.data[j].index = static_cast<int32_t>(j);
  695. pData->param.data[j].rindex = static_cast<int32_t>(i);
  696. const char* const paramName(fDescriptor->PortNames[i] != nullptr ? fDescriptor->PortNames[i] : "unknown");
  697. float min, max, def, step, stepSmall, stepLarge;
  698. // min value
  699. if (LADSPA_IS_HINT_BOUNDED_BELOW(portRangeHints.HintDescriptor))
  700. min = portRangeHints.LowerBound;
  701. else
  702. min = 0.0f;
  703. // max value
  704. if (LADSPA_IS_HINT_BOUNDED_ABOVE(portRangeHints.HintDescriptor))
  705. max = portRangeHints.UpperBound;
  706. else
  707. max = 1.0f;
  708. if (LADSPA_IS_HINT_SAMPLE_RATE(portRangeHints.HintDescriptor))
  709. {
  710. min *= sampleRate;
  711. max *= sampleRate;
  712. pData->param.data[j].hints |= PARAMETER_USES_SAMPLERATE;
  713. }
  714. if (min >= max)
  715. {
  716. carla_stderr2("WARNING - Broken plugin parameter '%s': min >= max", paramName);
  717. max = min + 0.1f;
  718. }
  719. // default value
  720. def = get_default_ladspa_port_value(portRangeHints.HintDescriptor, min, max);
  721. if (def < min)
  722. def = min;
  723. else if (def > max)
  724. def = max;
  725. if (LADSPA_IS_HINT_TOGGLED(portRangeHints.HintDescriptor))
  726. {
  727. step = max - min;
  728. stepSmall = step;
  729. stepLarge = step;
  730. pData->param.data[j].hints |= PARAMETER_IS_BOOLEAN;
  731. }
  732. else if (LADSPA_IS_HINT_INTEGER(portRangeHints.HintDescriptor))
  733. {
  734. step = 1.0f;
  735. stepSmall = 1.0f;
  736. stepLarge = 10.0f;
  737. pData->param.data[j].hints |= PARAMETER_IS_INTEGER;
  738. }
  739. else
  740. {
  741. const float range = max - min;
  742. step = range/100.0f;
  743. stepSmall = range/1000.0f;
  744. stepLarge = range/10.0f;
  745. }
  746. if (LADSPA_IS_PORT_INPUT(portType))
  747. {
  748. pData->param.data[j].type = PARAMETER_INPUT;
  749. pData->param.data[j].hints |= PARAMETER_IS_ENABLED;
  750. pData->param.data[j].hints |= PARAMETER_IS_AUTOMABLE;
  751. needsCtrlIn = true;
  752. // MIDI CC value
  753. if (fDssiDescriptor->get_midi_controller_for_port != nullptr)
  754. {
  755. const int ctrl = fDssiDescriptor->get_midi_controller_for_port(fHandles.getFirst(nullptr), i);
  756. if (DSSI_CONTROLLER_IS_SET(ctrl) && DSSI_IS_CC(ctrl))
  757. {
  758. const int16_t cc = DSSI_CC_NUMBER(ctrl);
  759. if (! MIDI_IS_CONTROL_BANK_SELECT(cc))
  760. pData->param.data[j].midiCC = cc;
  761. }
  762. }
  763. }
  764. else if (LADSPA_IS_PORT_OUTPUT(portType))
  765. {
  766. pData->param.data[j].type = PARAMETER_OUTPUT;
  767. if (std::strcmp(paramName, "latency") == 0 || std::strcmp(paramName, "_latency") == 0)
  768. {
  769. min = 0.0f;
  770. max = sampleRate;
  771. def = 0.0f;
  772. step = 1.0f;
  773. stepSmall = 1.0f;
  774. stepLarge = 1.0f;
  775. pData->param.special[j] = PARAMETER_SPECIAL_LATENCY;
  776. CARLA_SAFE_ASSERT_INT2(fLatencyIndex == static_cast<int32_t>(j), fLatencyIndex, j);
  777. }
  778. else
  779. {
  780. pData->param.data[j].hints |= PARAMETER_IS_ENABLED;
  781. pData->param.data[j].hints |= PARAMETER_IS_AUTOMABLE;
  782. needsCtrlOut = true;
  783. }
  784. }
  785. else
  786. {
  787. carla_stderr2("WARNING - Got a broken Port (Control, but not input or output)");
  788. }
  789. // extra parameter hints
  790. if (LADSPA_IS_HINT_LOGARITHMIC(portRangeHints.HintDescriptor))
  791. pData->param.data[j].hints |= PARAMETER_IS_LOGARITHMIC;
  792. pData->param.ranges[j].min = min;
  793. pData->param.ranges[j].max = max;
  794. pData->param.ranges[j].def = def;
  795. pData->param.ranges[j].step = step;
  796. pData->param.ranges[j].stepSmall = stepSmall;
  797. pData->param.ranges[j].stepLarge = stepLarge;
  798. // Start parameters in their default values
  799. fParamBuffers[j] = def;
  800. for (LinkedList<LADSPA_Handle>::Itenerator it = fHandles.begin2(); it.valid(); it.next())
  801. {
  802. LADSPA_Handle const handle(it.getValue(nullptr));
  803. CARLA_SAFE_ASSERT_CONTINUE(handle != nullptr);
  804. try {
  805. fDescriptor->connect_port(handle, i, &fParamBuffers[j]);
  806. } CARLA_SAFE_EXCEPTION("DSSI connect_port (parameter)");
  807. }
  808. }
  809. else
  810. {
  811. // Not Audio or Control
  812. carla_stderr2("ERROR - Got a broken Port (neither Audio or Control)");
  813. for (LinkedList<LADSPA_Handle>::Itenerator it = fHandles.begin2(); it.valid(); it.next())
  814. {
  815. LADSPA_Handle const handle(it.getValue(nullptr));
  816. CARLA_SAFE_ASSERT_CONTINUE(handle != nullptr);
  817. try {
  818. fDescriptor->connect_port(handle, i, nullptr);
  819. } CARLA_SAFE_EXCEPTION("DSSI connect_port (null)");
  820. }
  821. }
  822. }
  823. if (needsCtrlIn)
  824. {
  825. portName.clear();
  826. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  827. {
  828. portName = pData->name;
  829. portName += ":";
  830. }
  831. portName += "events-in";
  832. portName.truncate(portNameSize);
  833. pData->event.portIn = (CarlaEngineEventPort*)pData->client->addPort(kEnginePortTypeEvent, portName, true, 0);
  834. }
  835. if (needsCtrlOut)
  836. {
  837. portName.clear();
  838. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  839. {
  840. portName = pData->name;
  841. portName += ":";
  842. }
  843. portName += "events-out";
  844. portName.truncate(portNameSize);
  845. pData->event.portOut = (CarlaEngineEventPort*)pData->client->addPort(kEnginePortTypeEvent, portName, false, 0);
  846. }
  847. if (forcedStereoIn || forcedStereoOut)
  848. pData->options |= PLUGIN_OPTION_FORCE_STEREO;
  849. else
  850. pData->options &= ~PLUGIN_OPTION_FORCE_STEREO;
  851. // plugin hints
  852. pData->hints = 0x0;
  853. if (LADSPA_IS_HARD_RT_CAPABLE(fDescriptor->Properties))
  854. pData->hints |= PLUGIN_IS_RTSAFE;
  855. #ifdef HAVE_LIBLO
  856. if (fUiFilename != nullptr)
  857. pData->hints |= PLUGIN_HAS_CUSTOM_UI;
  858. #endif
  859. #ifndef BUILD_BRIDGE
  860. if (aOuts > 0 && (aIns == aOuts || aIns == 1))
  861. pData->hints |= PLUGIN_CAN_DRYWET;
  862. if (aOuts > 0)
  863. pData->hints |= PLUGIN_CAN_VOLUME;
  864. if (aOuts >= 2 && aOuts % 2 == 0)
  865. pData->hints |= PLUGIN_CAN_BALANCE;
  866. #endif
  867. // extra plugin hints
  868. pData->extraHints = 0x0;
  869. pData->extraHints |= PLUGIN_EXTRA_HINT_CAN_RUN_RACK;
  870. if (mIns > 0)
  871. pData->extraHints |= PLUGIN_EXTRA_HINT_HAS_MIDI_IN;
  872. // check initial latency
  873. findInitialLatencyValue(aIns, aOuts);
  874. fForcedStereoIn = forcedStereoIn;
  875. fForcedStereoOut = forcedStereoOut;
  876. bufferSizeChanged(pData->engine->getBufferSize());
  877. reloadPrograms(true);
  878. if (pData->active)
  879. activate();
  880. carla_debug("CarlaPluginDSSI::reload() - end");
  881. }
  882. void findInitialLatencyValue(const uint32_t aIns, const uint32_t aOuts) const
  883. {
  884. if (fLatencyIndex < 0 || fHandles.count() == 0)
  885. return;
  886. // we need to pre-run the plugin so it can update its latency control-port
  887. const LADSPA_Handle handle(fHandles.getFirst(nullptr));
  888. CARLA_SAFE_ASSERT_RETURN(handle != nullptr,);
  889. float tmpIn [(aIns > 0) ? aIns : 1][2];
  890. float tmpOut[(aOuts > 0) ? aOuts : 1][2];
  891. for (uint32_t j=0; j < aIns; ++j)
  892. {
  893. tmpIn[j][0] = 0.0f;
  894. tmpIn[j][1] = 0.0f;
  895. try {
  896. fDescriptor->connect_port(handle, pData->audioIn.ports[j].rindex, tmpIn[j]);
  897. } CARLA_SAFE_EXCEPTION("DSSI connect_port (latency input)");
  898. }
  899. for (uint32_t j=0; j < aOuts; ++j)
  900. {
  901. tmpOut[j][0] = 0.0f;
  902. tmpOut[j][1] = 0.0f;
  903. try {
  904. fDescriptor->connect_port(handle, pData->audioOut.ports[j].rindex, tmpOut[j]);
  905. } CARLA_SAFE_EXCEPTION("DSSI connect_port (latency output)");
  906. }
  907. if (fDescriptor->activate != nullptr)
  908. {
  909. try {
  910. fDescriptor->activate(handle);
  911. } CARLA_SAFE_EXCEPTION("DSSI latency activate");
  912. }
  913. try {
  914. fDescriptor->run(handle, 2);
  915. } CARLA_SAFE_EXCEPTION("DSSI latency run");
  916. if (fDescriptor->deactivate != nullptr)
  917. {
  918. try {
  919. fDescriptor->deactivate(handle);
  920. } CARLA_SAFE_EXCEPTION("DSSI latency deactivate");
  921. }
  922. // done, let's get the value
  923. if (const uint32_t latency = getLatencyInFrames())
  924. {
  925. pData->client->setLatency(latency);
  926. #ifndef BUILD_BRIDGE
  927. pData->latency.recreateBuffers(std::max(aIns, aOuts), latency);
  928. #endif
  929. }
  930. }
  931. void reloadPrograms(const bool doInit) override
  932. {
  933. carla_debug("CarlaPluginDSSI::reloadPrograms(%s)", bool2str(doInit));
  934. const LADSPA_Handle handle(fHandles.getFirst(nullptr));
  935. CARLA_SAFE_ASSERT_RETURN(handle != nullptr,);
  936. const uint32_t oldCount = pData->midiprog.count;
  937. const int32_t current = pData->midiprog.current;
  938. // Delete old programs
  939. pData->midiprog.clear();
  940. // Query new programs
  941. uint32_t newCount = 0;
  942. if (fDssiDescriptor->get_program != nullptr && fDssiDescriptor->select_program != nullptr)
  943. {
  944. for (; fDssiDescriptor->get_program(handle, newCount) != nullptr;)
  945. ++newCount;
  946. }
  947. if (newCount > 0)
  948. {
  949. pData->midiprog.createNew(newCount);
  950. // Update data
  951. for (uint32_t i=0; i < newCount; ++i)
  952. {
  953. const DSSI_Program_Descriptor* const pdesc(fDssiDescriptor->get_program(handle, i));
  954. CARLA_SAFE_ASSERT_CONTINUE(pdesc != nullptr);
  955. CARLA_SAFE_ASSERT(pdesc->Name != nullptr);
  956. pData->midiprog.data[i].bank = static_cast<uint32_t>(pdesc->Bank);
  957. pData->midiprog.data[i].program = static_cast<uint32_t>(pdesc->Program);
  958. pData->midiprog.data[i].name = carla_strdup(pdesc->Name);
  959. }
  960. }
  961. #if defined(HAVE_LIBLO) && ! defined(BUILD_BRIDGE)
  962. // Update OSC Names
  963. if (pData->engine->isOscControlRegistered() && pData->id < pData->engine->getCurrentPluginCount())
  964. {
  965. pData->engine->oscSend_control_set_midi_program_count(pData->id, newCount);
  966. for (uint32_t i=0; i < newCount; ++i)
  967. 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);
  968. }
  969. #endif
  970. if (doInit)
  971. {
  972. if (newCount > 0)
  973. setMidiProgram(0, false, false, false);
  974. }
  975. else
  976. {
  977. // Check if current program is invalid
  978. bool programChanged = false;
  979. if (newCount == oldCount+1)
  980. {
  981. // one midi program added, probably created by user
  982. pData->midiprog.current = static_cast<int32_t>(oldCount);
  983. programChanged = true;
  984. }
  985. else if (current < 0 && newCount > 0)
  986. {
  987. // programs exist now, but not before
  988. pData->midiprog.current = 0;
  989. programChanged = true;
  990. }
  991. else if (current >= 0 && newCount == 0)
  992. {
  993. // programs existed before, but not anymore
  994. pData->midiprog.current = -1;
  995. programChanged = true;
  996. }
  997. else if (current >= static_cast<int32_t>(newCount))
  998. {
  999. // current midi program > count
  1000. pData->midiprog.current = 0;
  1001. programChanged = true;
  1002. }
  1003. else
  1004. {
  1005. // no change
  1006. pData->midiprog.current = current;
  1007. }
  1008. if (programChanged)
  1009. setMidiProgram(pData->midiprog.current, true, true, true);
  1010. pData->engine->callback(ENGINE_CALLBACK_RELOAD_PROGRAMS, pData->id, 0, 0, 0.0f, nullptr);
  1011. }
  1012. }
  1013. // -------------------------------------------------------------------
  1014. // Plugin processing
  1015. void activate() noexcept override
  1016. {
  1017. CARLA_SAFE_ASSERT_RETURN(fDescriptor != nullptr,);
  1018. if (fDescriptor->activate != nullptr)
  1019. {
  1020. for (LinkedList<LADSPA_Handle>::Itenerator it = fHandles.begin2(); it.valid(); it.next())
  1021. {
  1022. LADSPA_Handle const handle(it.getValue(nullptr));
  1023. CARLA_SAFE_ASSERT_CONTINUE(handle != nullptr);
  1024. try {
  1025. fDescriptor->activate(handle);
  1026. } CARLA_SAFE_EXCEPTION("DSSI activate");
  1027. }
  1028. }
  1029. }
  1030. void deactivate() noexcept override
  1031. {
  1032. CARLA_SAFE_ASSERT_RETURN(fDescriptor != nullptr,);
  1033. if (fDescriptor->deactivate != nullptr)
  1034. {
  1035. for (LinkedList<LADSPA_Handle>::Itenerator it = fHandles.begin2(); it.valid(); it.next())
  1036. {
  1037. LADSPA_Handle const handle(it.getValue(nullptr));
  1038. CARLA_SAFE_ASSERT_CONTINUE(handle != nullptr);
  1039. try {
  1040. fDescriptor->deactivate(handle);
  1041. } CARLA_SAFE_EXCEPTION("DSSI deactivate");
  1042. }
  1043. }
  1044. }
  1045. void process(const float** const audioIn, float** const audioOut, const float** const, float** const, const uint32_t frames) override
  1046. {
  1047. // --------------------------------------------------------------------------------------------------------
  1048. // Check if active
  1049. if (! pData->active)
  1050. {
  1051. // disable any output sound
  1052. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  1053. FloatVectorOperations::clear(audioOut[i], static_cast<int>(frames));
  1054. return;
  1055. }
  1056. ulong midiEventCount = 0;
  1057. carla_zeroStructs(fMidiEvents, kPluginMaxMidiEvents);
  1058. // --------------------------------------------------------------------------------------------------------
  1059. // Check if needs reset
  1060. if (pData->needsReset)
  1061. {
  1062. if (pData->options & PLUGIN_OPTION_SEND_ALL_SOUND_OFF)
  1063. {
  1064. midiEventCount = MAX_MIDI_CHANNELS*2;
  1065. for (uchar i=0, k=MAX_MIDI_CHANNELS; i < MAX_MIDI_CHANNELS; ++i)
  1066. {
  1067. fMidiEvents[i].type = SND_SEQ_EVENT_CONTROLLER;
  1068. fMidiEvents[i].data.control.channel = i;
  1069. fMidiEvents[i].data.control.param = MIDI_CONTROL_ALL_NOTES_OFF;
  1070. fMidiEvents[k+i].type = SND_SEQ_EVENT_CONTROLLER;
  1071. fMidiEvents[k+i].data.control.channel = i;
  1072. fMidiEvents[k+i].data.control.param = MIDI_CONTROL_ALL_SOUND_OFF;
  1073. }
  1074. }
  1075. else if (pData->ctrlChannel >= 0 && pData->ctrlChannel < MAX_MIDI_CHANNELS)
  1076. {
  1077. midiEventCount = MAX_MIDI_NOTE;
  1078. for (uchar i=0; i < MAX_MIDI_NOTE; ++i)
  1079. {
  1080. fMidiEvents[i].type = SND_SEQ_EVENT_NOTEOFF;
  1081. fMidiEvents[i].data.note.channel = static_cast<uchar>(pData->ctrlChannel);
  1082. fMidiEvents[i].data.note.note = i;
  1083. }
  1084. }
  1085. pData->needsReset = false;
  1086. }
  1087. // --------------------------------------------------------------------------------------------------------
  1088. // Event Input and Processing
  1089. if (pData->event.portIn != nullptr)
  1090. {
  1091. // ----------------------------------------------------------------------------------------------------
  1092. // MIDI Input (External)
  1093. if (pData->extNotes.mutex.tryLock())
  1094. {
  1095. ExternalMidiNote note = { 0, 0, 0 };
  1096. for (; midiEventCount < kPluginMaxMidiEvents && ! pData->extNotes.data.isEmpty();)
  1097. {
  1098. note = pData->extNotes.data.getFirst(note, true);
  1099. CARLA_SAFE_ASSERT_CONTINUE(note.channel >= 0 && note.channel < MAX_MIDI_CHANNELS);
  1100. snd_seq_event_t& seqEvent(fMidiEvents[midiEventCount++]);
  1101. seqEvent.type = (note.velo > 0) ? SND_SEQ_EVENT_NOTEON : SND_SEQ_EVENT_NOTEOFF;
  1102. seqEvent.data.note.channel = static_cast<uchar>(note.channel);
  1103. seqEvent.data.note.note = note.note;
  1104. seqEvent.data.note.velocity = note.velo;
  1105. }
  1106. pData->extNotes.mutex.unlock();
  1107. } // End of MIDI Input (External)
  1108. // ----------------------------------------------------------------------------------------------------
  1109. // Event Input (System)
  1110. #ifndef BUILD_BRIDGE
  1111. bool allNotesOffSent = false;
  1112. #endif
  1113. const bool isSampleAccurate = (pData->options & PLUGIN_OPTION_FIXED_BUFFERS) == 0;
  1114. uint32_t startTime = 0;
  1115. uint32_t timeOffset = 0;
  1116. uint32_t nextBankId;
  1117. if (pData->midiprog.current >= 0 && pData->midiprog.count > 0)
  1118. nextBankId = pData->midiprog.data[pData->midiprog.current].bank;
  1119. else
  1120. nextBankId = 0;
  1121. for (uint32_t i=0, numEvents=pData->event.portIn->getEventCount(); i < numEvents; ++i)
  1122. {
  1123. const EngineEvent& event(pData->event.portIn->getEvent(i));
  1124. if (event.time >= frames)
  1125. continue;
  1126. CARLA_ASSERT_INT2(event.time >= timeOffset, event.time, timeOffset);
  1127. if (isSampleAccurate && event.time > timeOffset)
  1128. {
  1129. if (processSingle(audioIn, audioOut, event.time - timeOffset, timeOffset, midiEventCount))
  1130. {
  1131. startTime = 0;
  1132. timeOffset = event.time;
  1133. midiEventCount = 0;
  1134. if (pData->midiprog.current >= 0 && pData->midiprog.count > 0)
  1135. nextBankId = pData->midiprog.data[pData->midiprog.current].bank;
  1136. else
  1137. nextBankId = 0;
  1138. }
  1139. else
  1140. startTime += timeOffset;
  1141. }
  1142. switch (event.type)
  1143. {
  1144. case kEngineEventTypeNull:
  1145. break;
  1146. case kEngineEventTypeControl: {
  1147. const EngineControlEvent& ctrlEvent(event.ctrl);
  1148. switch (ctrlEvent.type)
  1149. {
  1150. case kEngineControlEventTypeNull:
  1151. break;
  1152. case kEngineControlEventTypeParameter: {
  1153. #ifndef BUILD_BRIDGE
  1154. // Control backend stuff
  1155. if (event.channel == pData->ctrlChannel)
  1156. {
  1157. float value;
  1158. if (MIDI_IS_CONTROL_BREATH_CONTROLLER(ctrlEvent.param) && (pData->hints & PLUGIN_CAN_DRYWET) != 0)
  1159. {
  1160. value = ctrlEvent.value;
  1161. setDryWet(value, false, false);
  1162. pData->postponeRtEvent(kPluginPostRtEventParameterChange, PARAMETER_DRYWET, 0, value);
  1163. }
  1164. if (MIDI_IS_CONTROL_CHANNEL_VOLUME(ctrlEvent.param) && (pData->hints & PLUGIN_CAN_VOLUME) != 0)
  1165. {
  1166. value = ctrlEvent.value*127.0f/100.0f;
  1167. setVolume(value, false, false);
  1168. pData->postponeRtEvent(kPluginPostRtEventParameterChange, PARAMETER_VOLUME, 0, value);
  1169. }
  1170. if (MIDI_IS_CONTROL_BALANCE(ctrlEvent.param) && (pData->hints & PLUGIN_CAN_BALANCE) != 0)
  1171. {
  1172. float left, right;
  1173. value = ctrlEvent.value/0.5f - 1.0f;
  1174. if (value < 0.0f)
  1175. {
  1176. left = -1.0f;
  1177. right = (value*2.0f)+1.0f;
  1178. }
  1179. else if (value > 0.0f)
  1180. {
  1181. left = (value*2.0f)-1.0f;
  1182. right = 1.0f;
  1183. }
  1184. else
  1185. {
  1186. left = -1.0f;
  1187. right = 1.0f;
  1188. }
  1189. setBalanceLeft(left, false, false);
  1190. setBalanceRight(right, false, false);
  1191. pData->postponeRtEvent(kPluginPostRtEventParameterChange, PARAMETER_BALANCE_LEFT, 0, left);
  1192. pData->postponeRtEvent(kPluginPostRtEventParameterChange, PARAMETER_BALANCE_RIGHT, 0, right);
  1193. }
  1194. }
  1195. #endif
  1196. // Control plugin parameters
  1197. for (uint32_t k=0; k < pData->param.count; ++k)
  1198. {
  1199. if (pData->param.data[k].midiChannel != event.channel)
  1200. continue;
  1201. if (pData->param.data[k].midiCC != ctrlEvent.param)
  1202. continue;
  1203. if (pData->param.data[k].type != PARAMETER_INPUT)
  1204. continue;
  1205. if ((pData->param.data[k].hints & PARAMETER_IS_AUTOMABLE) == 0)
  1206. continue;
  1207. float value;
  1208. if (pData->param.data[k].hints & PARAMETER_IS_BOOLEAN)
  1209. {
  1210. value = (ctrlEvent.value < 0.5f) ? pData->param.ranges[k].min : pData->param.ranges[k].max;
  1211. }
  1212. else
  1213. {
  1214. if (pData->param.data[k].hints & PARAMETER_IS_LOGARITHMIC)
  1215. value = pData->param.ranges[k].getUnnormalizedLogValue(ctrlEvent.value);
  1216. else
  1217. value = pData->param.ranges[k].getUnnormalizedValue(ctrlEvent.value);
  1218. if (pData->param.data[k].hints & PARAMETER_IS_INTEGER)
  1219. value = std::rint(value);
  1220. }
  1221. setParameterValue(k, value, false, false, false);
  1222. pData->postponeRtEvent(kPluginPostRtEventParameterChange, static_cast<int32_t>(k), 0, value);
  1223. }
  1224. if ((pData->options & PLUGIN_OPTION_SEND_CONTROL_CHANGES) != 0 && ctrlEvent.param < MAX_MIDI_CONTROL)
  1225. {
  1226. if (midiEventCount >= kPluginMaxMidiEvents)
  1227. continue;
  1228. snd_seq_event_t& seqEvent(fMidiEvents[midiEventCount++]);
  1229. seqEvent.time.tick = isSampleAccurate ? startTime : event.time;
  1230. seqEvent.type = SND_SEQ_EVENT_CONTROLLER;
  1231. seqEvent.data.control.channel = event.channel;
  1232. seqEvent.data.control.param = ctrlEvent.param;
  1233. seqEvent.data.control.value = int8_t(ctrlEvent.value*127.0f);
  1234. }
  1235. break;
  1236. } // case kEngineControlEventTypeParameter
  1237. case kEngineControlEventTypeMidiBank:
  1238. if (event.channel == pData->ctrlChannel && (pData->options & PLUGIN_OPTION_MAP_PROGRAM_CHANGES) != 0)
  1239. nextBankId = ctrlEvent.param;
  1240. break;
  1241. case kEngineControlEventTypeMidiProgram:
  1242. if (event.channel == pData->ctrlChannel && (pData->options & PLUGIN_OPTION_MAP_PROGRAM_CHANGES) != 0)
  1243. {
  1244. const uint32_t nextProgramId = ctrlEvent.param;
  1245. for (uint32_t k=0; k < pData->midiprog.count; ++k)
  1246. {
  1247. if (pData->midiprog.data[k].bank == nextBankId && pData->midiprog.data[k].program == nextProgramId)
  1248. {
  1249. const int32_t index(static_cast<int32_t>(k));
  1250. setMidiProgram(index, false, false, false);
  1251. pData->postponeRtEvent(kPluginPostRtEventMidiProgramChange, index, 0, 0.0f);
  1252. break;
  1253. }
  1254. }
  1255. }
  1256. break;
  1257. case kEngineControlEventTypeAllSoundOff:
  1258. if (pData->options & PLUGIN_OPTION_SEND_ALL_SOUND_OFF)
  1259. {
  1260. if (midiEventCount >= kPluginMaxMidiEvents)
  1261. continue;
  1262. snd_seq_event_t& seqEvent(fMidiEvents[midiEventCount++]);
  1263. seqEvent.time.tick = isSampleAccurate ? startTime : event.time;
  1264. seqEvent.type = SND_SEQ_EVENT_CONTROLLER;
  1265. seqEvent.data.control.channel = event.channel;
  1266. seqEvent.data.control.param = MIDI_CONTROL_ALL_SOUND_OFF;
  1267. }
  1268. break;
  1269. case kEngineControlEventTypeAllNotesOff:
  1270. if (pData->options & PLUGIN_OPTION_SEND_ALL_SOUND_OFF)
  1271. {
  1272. #ifndef BUILD_BRIDGE
  1273. if (event.channel == pData->ctrlChannel && ! allNotesOffSent)
  1274. {
  1275. allNotesOffSent = true;
  1276. sendMidiAllNotesOffToCallback();
  1277. }
  1278. #endif
  1279. if (midiEventCount >= kPluginMaxMidiEvents)
  1280. continue;
  1281. snd_seq_event_t& seqEvent(fMidiEvents[midiEventCount++]);
  1282. seqEvent.time.tick = isSampleAccurate ? startTime : event.time;
  1283. seqEvent.type = SND_SEQ_EVENT_CONTROLLER;
  1284. seqEvent.data.control.channel = event.channel;
  1285. seqEvent.data.control.param = MIDI_CONTROL_ALL_NOTES_OFF;
  1286. }
  1287. break;
  1288. } // switch (ctrlEvent.type)
  1289. break;
  1290. } // case kEngineEventTypeControl
  1291. case kEngineEventTypeMidi: {
  1292. if (midiEventCount >= kPluginMaxMidiEvents)
  1293. continue;
  1294. const EngineMidiEvent& midiEvent(event.midi);
  1295. if (midiEvent.size > EngineMidiEvent::kDataSize)
  1296. continue;
  1297. uint8_t status = uint8_t(MIDI_GET_STATUS_FROM_DATA(midiEvent.data));
  1298. // Fix bad note-off (per DSSI spec)
  1299. if (status == MIDI_STATUS_NOTE_ON && midiEvent.data[2] == 0)
  1300. status = MIDI_STATUS_NOTE_OFF;
  1301. snd_seq_event_t& seqEvent(fMidiEvents[midiEventCount++]);
  1302. seqEvent.time.tick = isSampleAccurate ? startTime : event.time;
  1303. switch (status)
  1304. {
  1305. case MIDI_STATUS_NOTE_OFF: {
  1306. const uint8_t note = midiEvent.data[1];
  1307. seqEvent.type = SND_SEQ_EVENT_NOTEOFF;
  1308. seqEvent.data.note.channel = event.channel;
  1309. seqEvent.data.note.note = note;
  1310. pData->postponeRtEvent(kPluginPostRtEventNoteOff, event.channel, note, 0.0f);
  1311. break;
  1312. }
  1313. case MIDI_STATUS_NOTE_ON: {
  1314. const uint8_t note = midiEvent.data[1];
  1315. const uint8_t velo = midiEvent.data[2];
  1316. seqEvent.type = SND_SEQ_EVENT_NOTEON;
  1317. seqEvent.data.note.channel = event.channel;
  1318. seqEvent.data.note.note = note;
  1319. seqEvent.data.note.velocity = velo;
  1320. pData->postponeRtEvent(kPluginPostRtEventNoteOn, event.channel, note, velo);
  1321. break;
  1322. }
  1323. case MIDI_STATUS_POLYPHONIC_AFTERTOUCH:
  1324. if (pData->options & PLUGIN_OPTION_SEND_NOTE_AFTERTOUCH)
  1325. {
  1326. const uint8_t note = midiEvent.data[1];
  1327. const uint8_t pressure = midiEvent.data[2];
  1328. seqEvent.type = SND_SEQ_EVENT_KEYPRESS;
  1329. seqEvent.data.note.channel = event.channel;
  1330. seqEvent.data.note.note = note;
  1331. seqEvent.data.note.velocity = pressure;
  1332. }
  1333. break;
  1334. case MIDI_STATUS_CONTROL_CHANGE:
  1335. if (pData->options & PLUGIN_OPTION_SEND_CONTROL_CHANGES)
  1336. {
  1337. const uint8_t control = midiEvent.data[1];
  1338. const uint8_t value = midiEvent.data[2];
  1339. seqEvent.type = SND_SEQ_EVENT_CONTROLLER;
  1340. seqEvent.data.control.channel = event.channel;
  1341. seqEvent.data.control.param = control;
  1342. seqEvent.data.control.value = value;
  1343. }
  1344. break;
  1345. case MIDI_STATUS_CHANNEL_PRESSURE:
  1346. if (pData->options & PLUGIN_OPTION_SEND_CHANNEL_PRESSURE)
  1347. {
  1348. const uint8_t pressure = midiEvent.data[1];
  1349. seqEvent.type = SND_SEQ_EVENT_CHANPRESS;
  1350. seqEvent.data.control.channel = event.channel;
  1351. seqEvent.data.control.value = pressure;
  1352. }
  1353. break;
  1354. case MIDI_STATUS_PITCH_WHEEL_CONTROL:
  1355. if (pData->options & PLUGIN_OPTION_SEND_PITCHBEND)
  1356. {
  1357. const uint8_t lsb = midiEvent.data[1];
  1358. const uint8_t msb = midiEvent.data[2];
  1359. seqEvent.type = SND_SEQ_EVENT_PITCHBEND;
  1360. seqEvent.data.control.channel = event.channel;
  1361. seqEvent.data.control.value = ((msb << 7) | lsb) - 8192;
  1362. }
  1363. break;
  1364. default:
  1365. --midiEventCount;
  1366. break;
  1367. } // switch (status)
  1368. } break;
  1369. } // switch (event.type)
  1370. }
  1371. pData->postRtEvents.trySplice();
  1372. if (frames > timeOffset)
  1373. processSingle(audioIn, audioOut, frames - timeOffset, timeOffset, midiEventCount);
  1374. } // End of Event Input and Processing
  1375. // --------------------------------------------------------------------------------------------------------
  1376. // Plugin processing (no events)
  1377. else
  1378. {
  1379. processSingle(audioIn, audioOut, frames, 0, midiEventCount);
  1380. } // End of Plugin processing (no events)
  1381. // --------------------------------------------------------------------------------------------------------
  1382. // Control Output
  1383. if (pData->event.portOut != nullptr)
  1384. {
  1385. uint8_t channel;
  1386. uint16_t param;
  1387. float value;
  1388. for (uint32_t k=0; k < pData->param.count; ++k)
  1389. {
  1390. if (pData->param.data[k].type != PARAMETER_OUTPUT)
  1391. continue;
  1392. pData->param.ranges[k].fixValue(fParamBuffers[k]);
  1393. if (pData->param.data[k].midiCC > 0)
  1394. {
  1395. channel = pData->param.data[k].midiChannel;
  1396. param = static_cast<uint16_t>(pData->param.data[k].midiCC);
  1397. value = pData->param.ranges[k].getNormalizedValue(fParamBuffers[k]);
  1398. pData->event.portOut->writeControlEvent(0, channel, kEngineControlEventTypeParameter, param, value);
  1399. }
  1400. }
  1401. } // End of Control Output
  1402. }
  1403. bool processSingle(const float** const audioIn, float** const audioOut, const uint32_t frames,
  1404. const uint32_t timeOffset, const ulong midiEventCount)
  1405. {
  1406. CARLA_SAFE_ASSERT_RETURN(frames > 0, false);
  1407. if (pData->audioIn.count > 0)
  1408. {
  1409. CARLA_SAFE_ASSERT_RETURN(audioIn != nullptr, false);
  1410. }
  1411. if (pData->audioOut.count > 0)
  1412. {
  1413. CARLA_SAFE_ASSERT_RETURN(audioOut != nullptr, false);
  1414. }
  1415. // --------------------------------------------------------------------------------------------------------
  1416. // Try lock, silence otherwise
  1417. if (pData->engine->isOffline())
  1418. {
  1419. pData->singleMutex.lock();
  1420. }
  1421. else if (! pData->singleMutex.tryLock())
  1422. {
  1423. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  1424. {
  1425. for (uint32_t k=0; k < frames; ++k)
  1426. audioOut[i][k+timeOffset] = 0.0f;
  1427. }
  1428. return false;
  1429. }
  1430. const int iframes(static_cast<int>(frames));
  1431. // --------------------------------------------------------------------------------------------------------
  1432. // Set audio buffers
  1433. const bool customMonoOut = pData->audioOut.count == 2 && fForcedStereoOut && ! fForcedStereoIn;
  1434. const bool customStereoOut = pData->audioOut.count == 2 && fForcedStereoIn && ! fForcedStereoOut;
  1435. if (! customMonoOut)
  1436. {
  1437. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  1438. FloatVectorOperations::clear(fAudioOutBuffers[i], iframes);
  1439. }
  1440. for (uint32_t i=0; i < pData->audioIn.count; ++i)
  1441. FloatVectorOperations::copy(fAudioInBuffers[i], audioIn[i]+timeOffset, iframes);
  1442. // --------------------------------------------------------------------------------------------------------
  1443. // Run plugin
  1444. uint instn = 0;
  1445. for (LinkedList<LADSPA_Handle>::Itenerator it = fHandles.begin2(); it.valid(); it.next(), ++instn)
  1446. {
  1447. LADSPA_Handle const handle(it.getValue(nullptr));
  1448. CARLA_SAFE_ASSERT_CONTINUE(handle != nullptr);
  1449. // ----------------------------------------------------------------------------------------------------
  1450. // Mixdown for forced stereo
  1451. if (customMonoOut)
  1452. FloatVectorOperations::clear(fAudioOutBuffers[instn], iframes);
  1453. // ----------------------------------------------------------------------------------------------------
  1454. // Run it
  1455. if (fDssiDescriptor->run_synth != nullptr)
  1456. {
  1457. try {
  1458. fDssiDescriptor->run_synth(handle, frames, fMidiEvents, midiEventCount);
  1459. } CARLA_SAFE_EXCEPTION("DSSI run_synth");
  1460. }
  1461. else
  1462. {
  1463. try {
  1464. fDescriptor->run(handle, frames);
  1465. } CARLA_SAFE_EXCEPTION("DSSI run");
  1466. }
  1467. // ----------------------------------------------------------------------------------------------------
  1468. // Mixdown for forced stereo
  1469. if (customMonoOut)
  1470. FloatVectorOperations::multiply(fAudioOutBuffers[instn], 0.5f, iframes);
  1471. else if (customStereoOut)
  1472. FloatVectorOperations::copy(fExtraStereoBuffer[instn], fAudioOutBuffers[instn], iframes);
  1473. }
  1474. if (customStereoOut)
  1475. {
  1476. FloatVectorOperations::copy(fAudioOutBuffers[0], fExtraStereoBuffer[0], iframes);
  1477. FloatVectorOperations::copy(fAudioOutBuffers[1], fExtraStereoBuffer[1], iframes);
  1478. }
  1479. #ifndef BUILD_BRIDGE
  1480. // --------------------------------------------------------------------------------------------------------
  1481. // Post-processing (dry/wet, volume and balance)
  1482. {
  1483. const bool doDryWet = (pData->hints & PLUGIN_CAN_DRYWET) != 0 && carla_isNotEqual(pData->postProc.dryWet, 1.0f);
  1484. const bool doBalance = (pData->hints & PLUGIN_CAN_BALANCE) != 0 && ! (carla_isEqual(pData->postProc.balanceLeft, -1.0f) && carla_isEqual(pData->postProc.balanceRight, 1.0f));
  1485. const bool isMono = (pData->audioIn.count == 1);
  1486. bool isPair;
  1487. float bufValue, oldBufLeft[doBalance ? frames : 1];
  1488. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  1489. {
  1490. // Dry/Wet
  1491. if (doDryWet)
  1492. {
  1493. const uint32_t c = isMono ? 0 : i;
  1494. for (uint32_t k=0; k < frames; ++k)
  1495. {
  1496. if (k < pData->latency.frames)
  1497. bufValue = pData->latency.buffers[c][k];
  1498. else if (pData->latency.frames < frames)
  1499. bufValue = fAudioInBuffers[c][k-pData->latency.frames];
  1500. else
  1501. bufValue = fAudioInBuffers[c][k];
  1502. fAudioOutBuffers[i][k] = (fAudioOutBuffers[i][k] * pData->postProc.dryWet) + (bufValue * (1.0f - pData->postProc.dryWet));
  1503. }
  1504. }
  1505. // Balance
  1506. if (doBalance)
  1507. {
  1508. isPair = (i % 2 == 0);
  1509. if (isPair)
  1510. {
  1511. CARLA_ASSERT(i+1 < pData->audioOut.count);
  1512. FloatVectorOperations::copy(oldBufLeft, fAudioOutBuffers[i], iframes);
  1513. }
  1514. float balRangeL = (pData->postProc.balanceLeft + 1.0f)/2.0f;
  1515. float balRangeR = (pData->postProc.balanceRight + 1.0f)/2.0f;
  1516. for (uint32_t k=0; k < frames; ++k)
  1517. {
  1518. if (isPair)
  1519. {
  1520. // left
  1521. fAudioOutBuffers[i][k] = oldBufLeft[k] * (1.0f - balRangeL);
  1522. fAudioOutBuffers[i][k] += fAudioOutBuffers[i+1][k] * (1.0f - balRangeR);
  1523. }
  1524. else
  1525. {
  1526. // right
  1527. fAudioOutBuffers[i][k] = fAudioOutBuffers[i][k] * balRangeR;
  1528. fAudioOutBuffers[i][k] += oldBufLeft[k] * balRangeL;
  1529. }
  1530. }
  1531. }
  1532. // Volume (and buffer copy)
  1533. {
  1534. for (uint32_t k=0; k < frames; ++k)
  1535. audioOut[i][k+timeOffset] = fAudioOutBuffers[i][k] * pData->postProc.volume;
  1536. }
  1537. }
  1538. } // End of Post-processing
  1539. // --------------------------------------------------------------------------------------------------------
  1540. // Save latency values for next callback
  1541. if (const uint32_t latframes = pData->latency.frames)
  1542. {
  1543. CARLA_SAFE_ASSERT(timeOffset == 0);
  1544. if (latframes <= frames)
  1545. {
  1546. for (uint32_t i=0; i < pData->audioIn.count; ++i)
  1547. FloatVectorOperations::copy(pData->latency.buffers[i], audioIn[i]+(frames-latframes), static_cast<int>(latframes));
  1548. }
  1549. else
  1550. {
  1551. const uint32_t diff = pData->latency.frames-frames;
  1552. for (uint32_t i=0, k; i<pData->audioIn.count; ++i)
  1553. {
  1554. // push back buffer by 'frames'
  1555. for (k=0; k < diff; ++k)
  1556. pData->latency.buffers[i][k] = pData->latency.buffers[i][k+frames];
  1557. // put current input at the end
  1558. for (uint32_t j=0; k < latframes; ++j, ++k)
  1559. pData->latency.buffers[i][k] = audioIn[i][j];
  1560. }
  1561. }
  1562. }
  1563. #else // BUILD_BRIDGE
  1564. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  1565. {
  1566. for (uint32_t k=0; k < frames; ++k)
  1567. audioOut[i][k+timeOffset] = fAudioOutBuffers[i][k];
  1568. }
  1569. #endif
  1570. // --------------------------------------------------------------------------------------------------------
  1571. pData->singleMutex.unlock();
  1572. return true;
  1573. }
  1574. void bufferSizeChanged(const uint32_t newBufferSize) override
  1575. {
  1576. CARLA_ASSERT_INT(newBufferSize > 0, newBufferSize);
  1577. carla_debug("CarlaPluginDSSI::bufferSizeChanged(%i) - start", newBufferSize);
  1578. const int iBufferSize(static_cast<int>(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. FloatVectorOperations::clear(fAudioInBuffers[i], iBufferSize);
  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. FloatVectorOperations::clear(fAudioOutBuffers[i], iBufferSize);
  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. FloatVectorOperations::clear(fExtraStereoBuffer[0], iBufferSize);
  1608. FloatVectorOperations::clear(fExtraStereoBuffer[1], iBufferSize);
  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. if (pData->engine->getOptions().frontendWinId != 0)
  1887. pData->transientTryCounter = 1;
  1888. carla_stdout("CarlaPluginDSSI::updateOscData() - done");
  1889. }
  1890. void handleOscMessageExiting()
  1891. {
  1892. carla_debug("CarlaPluginDSSI::handleMsgExiting()");
  1893. // hide UI
  1894. showCustomUI(false);
  1895. // tell frontend
  1896. pData->engine->callback(ENGINE_CALLBACK_UI_STATE_CHANGED, pData->id, 0, 0, 0.0f, nullptr);
  1897. }
  1898. // -------------------------------------------------------------------
  1899. // Post-poned UI Stuff
  1900. void uiParameterChange(const uint32_t index, const float value) noexcept override
  1901. {
  1902. CARLA_SAFE_ASSERT_RETURN(index < pData->param.count,);
  1903. if (fOscData.target == nullptr)
  1904. return;
  1905. osc_send_control(fOscData, pData->param.data[index].rindex, value);
  1906. }
  1907. void uiMidiProgramChange(const uint32_t index) noexcept override
  1908. {
  1909. CARLA_SAFE_ASSERT_RETURN(index < pData->midiprog.count,);
  1910. if (fOscData.target == nullptr)
  1911. return;
  1912. osc_send_program(fOscData, pData->midiprog.data[index].bank, pData->midiprog.data[index].program);
  1913. }
  1914. void uiNoteOn(const uint8_t channel, const uint8_t note, const uint8_t velo) noexcept override
  1915. {
  1916. CARLA_SAFE_ASSERT_RETURN(channel < MAX_MIDI_CHANNELS,);
  1917. CARLA_SAFE_ASSERT_RETURN(note < MAX_MIDI_NOTE,);
  1918. CARLA_SAFE_ASSERT_RETURN(velo > 0 && velo < MAX_MIDI_VALUE,);
  1919. if (fOscData.target == nullptr)
  1920. return;
  1921. #if 0
  1922. uint8_t midiData[4];
  1923. midiData[0] = 0;
  1924. midiData[1] = uint8_t(MIDI_STATUS_NOTE_ON | (channel & MIDI_CHANNEL_BIT));
  1925. midiData[2] = note;
  1926. midiData[3] = velo;
  1927. osc_send_midi(fOscData, midiData);
  1928. #endif
  1929. }
  1930. void uiNoteOff(const uint8_t channel, const uint8_t note) noexcept override
  1931. {
  1932. CARLA_SAFE_ASSERT_RETURN(channel < MAX_MIDI_CHANNELS,);
  1933. CARLA_SAFE_ASSERT_RETURN(note < MAX_MIDI_NOTE,);
  1934. if (fOscData.target == nullptr)
  1935. return;
  1936. #if 0
  1937. uint8_t midiData[4];
  1938. midiData[0] = 0;
  1939. midiData[1] = uint8_t(MIDI_STATUS_NOTE_ON | (channel & MIDI_CHANNEL_BIT));
  1940. midiData[2] = note;
  1941. midiData[3] = 0;
  1942. osc_send_midi(fOscData, midiData);
  1943. #endif
  1944. }
  1945. #endif // HAVE_LIBLO
  1946. // -------------------------------------------------------------------
  1947. const void* getNativeDescriptor() const noexcept override
  1948. {
  1949. return fDssiDescriptor;
  1950. }
  1951. #ifdef HAVE_LIBLO
  1952. uintptr_t getUiBridgeProcessId() const noexcept override
  1953. {
  1954. return fThreadUI.getProcessId();
  1955. }
  1956. const void* getExtraStuff() const noexcept override
  1957. {
  1958. return fUiFilename;
  1959. }
  1960. #endif
  1961. // -------------------------------------------------------------------
  1962. bool init(const char* const filename, const char* name, const char* const label, const uint options)
  1963. {
  1964. CARLA_SAFE_ASSERT_RETURN(pData->engine != nullptr, false);
  1965. // ---------------------------------------------------------------
  1966. // first checks
  1967. if (pData->client != nullptr)
  1968. {
  1969. pData->engine->setLastError("Plugin client is already registered");
  1970. return false;
  1971. }
  1972. if (filename == nullptr || filename[0] == '\0')
  1973. {
  1974. pData->engine->setLastError("null filename");
  1975. return false;
  1976. }
  1977. // ---------------------------------------------------------------
  1978. // open DLL
  1979. if (! pData->libOpen(filename))
  1980. {
  1981. pData->engine->setLastError(pData->libError(filename));
  1982. return false;
  1983. }
  1984. // ---------------------------------------------------------------
  1985. // get DLL main entry
  1986. const DSSI_Descriptor_Function descFn = pData->libSymbol<DSSI_Descriptor_Function>("dssi_descriptor");
  1987. if (descFn == nullptr)
  1988. {
  1989. pData->engine->setLastError("Could not find the DSSI Descriptor in the plugin library");
  1990. return false;
  1991. }
  1992. // ---------------------------------------------------------------
  1993. // get descriptor that matches label
  1994. // if label is null, get first valid plugin
  1995. const bool nullLabel = (label == nullptr || label[0] == '\0');
  1996. for (ulong d=0;; ++d)
  1997. {
  1998. try {
  1999. fDssiDescriptor = descFn(d);
  2000. }
  2001. catch(...) {
  2002. carla_stderr2("Caught exception when trying to get DSSI descriptor");
  2003. fDescriptor = nullptr;
  2004. fDssiDescriptor = nullptr;
  2005. break;
  2006. }
  2007. if (fDssiDescriptor == nullptr)
  2008. break;
  2009. fDescriptor = fDssiDescriptor->LADSPA_Plugin;
  2010. if (fDescriptor == nullptr)
  2011. {
  2012. carla_stderr2("WARNING - Missing LADSPA interface, will not use this plugin");
  2013. fDssiDescriptor = nullptr;
  2014. break;
  2015. }
  2016. if (fDescriptor->Label == nullptr || fDescriptor->Label[0] == '\0')
  2017. {
  2018. carla_stderr2("WARNING - Got an invalid label, will not use this plugin");
  2019. fDescriptor = nullptr;
  2020. fDssiDescriptor = nullptr;
  2021. break;
  2022. }
  2023. if (fDescriptor->run == nullptr)
  2024. {
  2025. carla_stderr2("WARNING - Plugin has no run, cannot use it");
  2026. fDescriptor = nullptr;
  2027. fDssiDescriptor = nullptr;
  2028. break;
  2029. }
  2030. if (nullLabel || std::strcmp(fDescriptor->Label, label) == 0)
  2031. break;
  2032. }
  2033. if (fDescriptor == nullptr || fDssiDescriptor == nullptr)
  2034. {
  2035. pData->engine->setLastError("Could not find the requested plugin label in the plugin library");
  2036. return false;
  2037. }
  2038. // ---------------------------------------------------------------
  2039. // check if uses global instance
  2040. if (fDssiDescriptor->run_synth == nullptr && fDssiDescriptor->run_multiple_synths != nullptr)
  2041. {
  2042. pData->engine->setLastError("This plugin requires run_multiple_synths which is not supported");
  2043. return false;
  2044. }
  2045. // ---------------------------------------------------------------
  2046. // check for fixed buffer size requirement
  2047. fNeedsFixedBuffers = CarlaString(filename).contains("dssi-vst", true);
  2048. if (fNeedsFixedBuffers && ! pData->engine->usesConstantBufferSize())
  2049. {
  2050. pData->engine->setLastError("Cannot use this plugin under the current engine.\n"
  2051. "The plugin requires a fixed block size which is not possible right now.");
  2052. return false;
  2053. }
  2054. // ---------------------------------------------------------------
  2055. // get info
  2056. if (name == nullptr || name[0] == '\0')
  2057. {
  2058. if (fDescriptor->Name != nullptr && fDescriptor->Name[0] != '\0')
  2059. name = fDescriptor->Name;
  2060. else
  2061. name = fDescriptor->Label;
  2062. }
  2063. pData->name = pData->engine->getUniquePluginName(name);
  2064. pData->filename = carla_strdup(filename);
  2065. // ---------------------------------------------------------------
  2066. // register client
  2067. pData->client = pData->engine->addClient(this);
  2068. if (pData->client == nullptr || ! pData->client->isOk())
  2069. {
  2070. pData->engine->setLastError("Failed to register plugin client");
  2071. return false;
  2072. }
  2073. // ---------------------------------------------------------------
  2074. // initialize plugin
  2075. if (! addInstance())
  2076. return false;
  2077. // ---------------------------------------------------------------
  2078. // find latency port index
  2079. for (uint32_t i=0, iCtrl=0, count=getSafePortCount(); i<count; ++i)
  2080. {
  2081. const int portType(fDescriptor->PortDescriptors[i]);
  2082. if (! LADSPA_IS_PORT_CONTROL(portType))
  2083. continue;
  2084. const uint32_t index(iCtrl++);
  2085. if (! LADSPA_IS_PORT_OUTPUT(portType))
  2086. continue;
  2087. const char* const portName(fDescriptor->PortNames[i]);
  2088. CARLA_SAFE_ASSERT_BREAK(portName != nullptr);
  2089. if (std::strcmp(portName, "latency") == 0 ||
  2090. std::strcmp(portName, "_latency") == 0)
  2091. {
  2092. fLatencyIndex = static_cast<int32_t>(index);
  2093. break;
  2094. }
  2095. }
  2096. // ---------------------------------------------------------------
  2097. // check for custom data extension
  2098. if (fDssiDescriptor->configure != nullptr)
  2099. {
  2100. if (char* const error = fDssiDescriptor->configure(fHandles.getFirst(nullptr), DSSI_CUSTOMDATA_EXTENSION_KEY, ""))
  2101. {
  2102. if (std::strcmp(error, "true") == 0 && fDssiDescriptor->get_custom_data != nullptr
  2103. && fDssiDescriptor->set_custom_data != nullptr)
  2104. fUsesCustomData = true;
  2105. std::free(error);
  2106. }
  2107. }
  2108. #ifdef HAVE_LIBLO
  2109. // ---------------------------------------------------------------
  2110. // check for gui
  2111. if (const char* const guiFilename = find_dssi_ui(filename, fDescriptor->Label))
  2112. {
  2113. fUiFilename = guiFilename;
  2114. fThreadUI.setData(guiFilename, fDescriptor->Label);
  2115. }
  2116. #endif
  2117. // ---------------------------------------------------------------
  2118. // set default options
  2119. pData->options = 0x0;
  2120. /**/ if (fLatencyIndex >= 0 || fNeedsFixedBuffers)
  2121. pData->options |= PLUGIN_OPTION_FIXED_BUFFERS;
  2122. else if (options & PLUGIN_OPTION_FIXED_BUFFERS)
  2123. pData->options |= PLUGIN_OPTION_FIXED_BUFFERS;
  2124. /**/ if (pData->engine->getOptions().forceStereo)
  2125. pData->options |= PLUGIN_OPTION_FORCE_STEREO;
  2126. else if (options & PLUGIN_OPTION_FORCE_STEREO)
  2127. pData->options |= PLUGIN_OPTION_FORCE_STEREO;
  2128. if (fDssiDescriptor->get_program != nullptr && fDssiDescriptor->select_program != nullptr)
  2129. pData->options |= PLUGIN_OPTION_MAP_PROGRAM_CHANGES;
  2130. if (fUsesCustomData)
  2131. pData->options |= PLUGIN_OPTION_USE_CHUNKS;
  2132. if (fDssiDescriptor->run_synth != nullptr)
  2133. {
  2134. pData->options |= PLUGIN_OPTION_SEND_CHANNEL_PRESSURE;
  2135. pData->options |= PLUGIN_OPTION_SEND_NOTE_AFTERTOUCH;
  2136. pData->options |= PLUGIN_OPTION_SEND_PITCHBEND;
  2137. pData->options |= PLUGIN_OPTION_SEND_ALL_SOUND_OFF;
  2138. if (options & PLUGIN_OPTION_SEND_CONTROL_CHANGES)
  2139. pData->options |= PLUGIN_OPTION_SEND_CONTROL_CHANGES;
  2140. }
  2141. return true;
  2142. }
  2143. // -------------------------------------------------------------------
  2144. private:
  2145. LinkedList<LADSPA_Handle> fHandles;
  2146. const LADSPA_Descriptor* fDescriptor;
  2147. const DSSI_Descriptor* fDssiDescriptor;
  2148. float** fAudioInBuffers;
  2149. float** fAudioOutBuffers;
  2150. float* fExtraStereoBuffer[2]; // used only if forcedStereoIn and audioOut == 2
  2151. float* fParamBuffers;
  2152. snd_seq_event_t fMidiEvents[kPluginMaxMidiEvents];
  2153. int32_t fLatencyIndex; // -1 if invalid
  2154. bool fForcedStereoIn;
  2155. bool fForcedStereoOut;
  2156. bool fNeedsFixedBuffers;
  2157. bool fUsesCustomData;
  2158. #ifdef HAVE_LIBLO
  2159. CarlaOscData fOscData;
  2160. CarlaThreadDSSIUI fThreadUI;
  2161. const char* fUiFilename;
  2162. #endif
  2163. // -------------------------------------------------------------------
  2164. bool addInstance()
  2165. {
  2166. LADSPA_Handle handle;
  2167. try {
  2168. handle = fDescriptor->instantiate(fDescriptor, static_cast<ulong>(pData->engine->getSampleRate()));
  2169. } CARLA_SAFE_EXCEPTION_RETURN_ERR("LADSPA instantiate", "Plugin failed to initialize");
  2170. for (uint32_t i=0, count=pData->param.count; i<count; ++i)
  2171. {
  2172. const int32_t rindex(pData->param.data[i].rindex);
  2173. CARLA_SAFE_ASSERT_CONTINUE(rindex >= 0);
  2174. try {
  2175. fDescriptor->connect_port(handle, static_cast<ulong>(rindex), &fParamBuffers[i]);
  2176. } CARLA_SAFE_EXCEPTION("LADSPA connect_port");
  2177. }
  2178. if (fHandles.append(handle))
  2179. return true;
  2180. try {
  2181. fDescriptor->cleanup(handle);
  2182. } CARLA_SAFE_EXCEPTION("LADSPA cleanup");
  2183. pData->engine->setLastError("Out of memory");
  2184. return false;
  2185. }
  2186. uint32_t getSafePortCount() const noexcept
  2187. {
  2188. if (fDescriptor->PortCount == 0)
  2189. return 0;
  2190. CARLA_SAFE_ASSERT_RETURN(fDescriptor->PortDescriptors != nullptr, 0);
  2191. CARLA_SAFE_ASSERT_RETURN(fDescriptor->PortRangeHints != nullptr, 0);
  2192. CARLA_SAFE_ASSERT_RETURN(fDescriptor->PortNames != nullptr, 0);
  2193. return static_cast<uint32_t>(fDescriptor->PortCount);
  2194. }
  2195. bool getSeparatedParameterNameOrUnit(const char* const paramName, char* const strBuf, const bool wantName) const noexcept
  2196. {
  2197. if (_getSeparatedParameterNameOrUnitImpl(paramName, strBuf, wantName, true))
  2198. return true;
  2199. if (_getSeparatedParameterNameOrUnitImpl(paramName, strBuf, wantName, false))
  2200. return true;
  2201. return false;
  2202. }
  2203. static bool _getSeparatedParameterNameOrUnitImpl(const char* const paramName, char* const strBuf,
  2204. const bool wantName, const bool useBracket) noexcept
  2205. {
  2206. const char* const sepBracketStart(std::strstr(paramName, useBracket ? " [" : " ("));
  2207. if (sepBracketStart == nullptr)
  2208. return false;
  2209. const char* const sepBracketEnd(std::strstr(sepBracketStart, useBracket ? "]" : ")"));
  2210. if (sepBracketEnd == nullptr)
  2211. return false;
  2212. const std::size_t unitSize(static_cast<std::size_t>(sepBracketEnd-sepBracketStart-2));
  2213. if (unitSize > 7) // very unlikely to have such big unit
  2214. return false;
  2215. const std::size_t sepIndex(std::strlen(paramName)-unitSize-3);
  2216. // just in case
  2217. if (sepIndex+2 >= STR_MAX)
  2218. return false;
  2219. if (wantName)
  2220. {
  2221. std::strncpy(strBuf, paramName, sepIndex);
  2222. strBuf[sepIndex] = '\0';
  2223. }
  2224. else
  2225. {
  2226. std::strncpy(strBuf, paramName+(sepIndex+2), unitSize);
  2227. strBuf[unitSize] = '\0';
  2228. }
  2229. return true;
  2230. }
  2231. // -------------------------------------------------------------------
  2232. CARLA_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(CarlaPluginDSSI)
  2233. };
  2234. // -------------------------------------------------------------------------------------------------------------------
  2235. CarlaPlugin* CarlaPlugin::newDSSI(const Initializer& init)
  2236. {
  2237. carla_debug("CarlaPlugin::newDSSI({%p, \"%s\", \"%s\", \"%s\", " P_INT64 ", %x})",
  2238. init.engine, init.filename, init.name, init.label, init.uniqueId, init.options);
  2239. CarlaPluginDSSI* const plugin(new CarlaPluginDSSI(init.engine, init.id));
  2240. if (! plugin->init(init.filename, init.name, init.label, init.options))
  2241. {
  2242. delete plugin;
  2243. return nullptr;
  2244. }
  2245. return plugin;
  2246. }
  2247. // -------------------------------------------------------------------------------------------------------------------
  2248. CARLA_BACKEND_END_NAMESPACE