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.

2821 lines
102KB

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