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.

2880 lines
103KB

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