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.

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