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.

2852 lines
103KB

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