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.

1727 lines
63KB

  1. /*
  2. * Carla FluidSynth Plugin
  3. * Copyright (C) 2011-2014 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 "CarlaEngine.hpp"
  19. #ifdef HAVE_FLUIDSYNTH
  20. #include "CarlaMathUtils.hpp"
  21. #include "juce_core.h"
  22. #include <fluidsynth.h>
  23. #if (FLUIDSYNTH_VERSION_MAJOR >= 1 && FLUIDSYNTH_VERSION_MINOR >= 1 && FLUIDSYNTH_VERSION_MICRO >= 4)
  24. # define FLUIDSYNTH_VERSION_NEW_API
  25. #endif
  26. #define FLUID_DEFAULT_POLYPHONY 64
  27. using juce::String;
  28. using juce::StringArray;
  29. CARLA_BACKEND_START_NAMESPACE
  30. // -----------------------------------------------------
  31. class CarlaPluginFluidSynth : public CarlaPlugin
  32. {
  33. public:
  34. CarlaPluginFluidSynth(CarlaEngine* const engine, const uint id, const bool use16Outs)
  35. : CarlaPlugin(engine, id),
  36. kUse16Outs(use16Outs),
  37. fSettings(nullptr),
  38. fSynth(nullptr),
  39. fSynthId(0),
  40. fAudio16Buffers(nullptr),
  41. fLabel(nullptr),
  42. leakDetector_CarlaPluginFluidSynth()
  43. {
  44. carla_debug("CarlaPluginFluidSynth::CarlaPluginFluidSynth(%p, %i, %s)", engine, id, bool2str(use16Outs));
  45. FloatVectorOperations::clear(fParamBuffers, FluidSynthParametersMax);
  46. carla_fill<int32_t>(fCurMidiProgs, 0, MAX_MIDI_CHANNELS);
  47. // create settings
  48. fSettings = new_fluid_settings();
  49. CARLA_SAFE_ASSERT_RETURN(fSettings != nullptr,);
  50. // define settings
  51. fluid_settings_setint(fSettings, "synth.audio-channels", use16Outs ? 16 : 1);
  52. fluid_settings_setint(fSettings, "synth.audio-groups", use16Outs ? 16 : 1);
  53. fluid_settings_setnum(fSettings, "synth.sample-rate", pData->engine->getSampleRate());
  54. //fluid_settings_setnum(fSettings, "synth.cpu-cores", 2);
  55. fluid_settings_setint(fSettings, "synth.parallel-render", 1);
  56. fluid_settings_setint(fSettings, "synth.threadsafe-api", 0);
  57. // create synth
  58. fSynth = new_fluid_synth(fSettings);
  59. CARLA_SAFE_ASSERT_RETURN(fSynth != nullptr,);
  60. #ifdef FLUIDSYNTH_VERSION_NEW_API
  61. fluid_synth_set_sample_rate(fSynth, (float)pData->engine->getSampleRate());
  62. #endif
  63. // set default values
  64. fluid_synth_set_reverb_on(fSynth, 1);
  65. fluid_synth_set_reverb(fSynth, FLUID_REVERB_DEFAULT_ROOMSIZE, FLUID_REVERB_DEFAULT_DAMP, FLUID_REVERB_DEFAULT_WIDTH, FLUID_REVERB_DEFAULT_LEVEL);
  66. fluid_synth_set_chorus_on(fSynth, 1);
  67. fluid_synth_set_chorus(fSynth, FLUID_CHORUS_DEFAULT_N, FLUID_CHORUS_DEFAULT_LEVEL, FLUID_CHORUS_DEFAULT_SPEED, FLUID_CHORUS_DEFAULT_DEPTH, FLUID_CHORUS_DEFAULT_TYPE);
  68. fluid_synth_set_polyphony(fSynth, FLUID_DEFAULT_POLYPHONY);
  69. fluid_synth_set_gain(fSynth, 1.0f);
  70. for (int i=0; i < MAX_MIDI_CHANNELS; ++i)
  71. fluid_synth_set_interp_method(fSynth, i, FLUID_INTERP_DEFAULT);
  72. }
  73. ~CarlaPluginFluidSynth() override
  74. {
  75. carla_debug("CarlaPluginFluidSynth::~CarlaPluginFluidSynth()");
  76. pData->singleMutex.lock();
  77. pData->masterMutex.lock();
  78. if (pData->client != nullptr && pData->client->isActive())
  79. pData->client->deactivate();
  80. if (pData->active)
  81. {
  82. deactivate();
  83. pData->active = false;
  84. }
  85. if (fSynth != nullptr)
  86. {
  87. delete_fluid_synth(fSynth);
  88. fSynth = nullptr;
  89. }
  90. if (fSettings != nullptr)
  91. {
  92. delete_fluid_settings(fSettings);
  93. fSettings = nullptr;
  94. }
  95. if (fLabel != nullptr)
  96. {
  97. delete[] fLabel;
  98. fLabel = nullptr;
  99. }
  100. clearBuffers();
  101. }
  102. // -------------------------------------------------------------------
  103. // Information (base)
  104. PluginType getType() const noexcept override
  105. {
  106. return PLUGIN_SF2;
  107. }
  108. PluginCategory getCategory() const noexcept override
  109. {
  110. return PLUGIN_CATEGORY_SYNTH;
  111. }
  112. // -------------------------------------------------------------------
  113. // Information (count)
  114. uint32_t getParameterScalePointCount(const uint32_t parameterId) const noexcept override
  115. {
  116. CARLA_SAFE_ASSERT_RETURN(parameterId < pData->param.count, 0);
  117. switch (parameterId)
  118. {
  119. case FluidSynthChorusType:
  120. return 2;
  121. case FluidSynthInterpolation:
  122. return 4;
  123. default:
  124. return 0;
  125. }
  126. }
  127. // -------------------------------------------------------------------
  128. // Information (current data)
  129. // nothing
  130. // -------------------------------------------------------------------
  131. // Information (per-plugin data)
  132. uint getOptionsAvailable() const noexcept override
  133. {
  134. uint options = 0x0;
  135. options |= PLUGIN_OPTION_MAP_PROGRAM_CHANGES;
  136. options |= PLUGIN_OPTION_SEND_CONTROL_CHANGES;
  137. options |= PLUGIN_OPTION_SEND_CHANNEL_PRESSURE;
  138. options |= PLUGIN_OPTION_SEND_PITCHBEND;
  139. options |= PLUGIN_OPTION_SEND_ALL_SOUND_OFF;
  140. return options;
  141. }
  142. float getParameterValue(const uint32_t parameterId) const noexcept override
  143. {
  144. CARLA_SAFE_ASSERT_RETURN(parameterId < pData->param.count, 0.0f);
  145. return fParamBuffers[parameterId];
  146. }
  147. float getParameterScalePointValue(const uint32_t parameterId, const uint32_t scalePointId) const noexcept override
  148. {
  149. CARLA_SAFE_ASSERT_RETURN(parameterId < pData->param.count, 0.0f);
  150. CARLA_SAFE_ASSERT_RETURN(scalePointId < getParameterScalePointCount(parameterId), 0.0f);
  151. switch (parameterId)
  152. {
  153. case FluidSynthChorusType:
  154. switch (scalePointId)
  155. {
  156. case 0:
  157. return FLUID_CHORUS_MOD_SINE;
  158. case 1:
  159. return FLUID_CHORUS_MOD_TRIANGLE;
  160. default:
  161. return FLUID_CHORUS_DEFAULT_TYPE;
  162. }
  163. case FluidSynthInterpolation:
  164. switch (scalePointId)
  165. {
  166. case 0:
  167. return FLUID_INTERP_NONE;
  168. case 1:
  169. return FLUID_INTERP_LINEAR;
  170. case 2:
  171. return FLUID_INTERP_4THORDER;
  172. case 3:
  173. return FLUID_INTERP_7THORDER;
  174. default:
  175. return FLUID_INTERP_DEFAULT;
  176. }
  177. default:
  178. return 0.0f;
  179. }
  180. }
  181. void getLabel(char* const strBuf) const noexcept override
  182. {
  183. if (fLabel != nullptr)
  184. {
  185. std::strncpy(strBuf, fLabel, STR_MAX);
  186. return;
  187. }
  188. CarlaPlugin::getLabel(strBuf);
  189. }
  190. void getMaker(char* const strBuf) const noexcept override
  191. {
  192. std::strncpy(strBuf, "FluidSynth SF2 engine", STR_MAX);
  193. }
  194. void getCopyright(char* const strBuf) const noexcept override
  195. {
  196. std::strncpy(strBuf, "GNU GPL v2+", STR_MAX);
  197. }
  198. void getRealName(char* const strBuf) const noexcept override
  199. {
  200. getLabel(strBuf);
  201. }
  202. void getParameterName(const uint32_t parameterId, char* const strBuf) const noexcept override
  203. {
  204. CARLA_SAFE_ASSERT_RETURN(parameterId < pData->param.count,);
  205. switch (parameterId)
  206. {
  207. case FluidSynthReverbOnOff:
  208. std::strncpy(strBuf, "Reverb On/Off", STR_MAX);
  209. return;
  210. case FluidSynthReverbRoomSize:
  211. std::strncpy(strBuf, "Reverb Room Size", STR_MAX);
  212. return;
  213. case FluidSynthReverbDamp:
  214. std::strncpy(strBuf, "Reverb Damp", STR_MAX);
  215. return;
  216. case FluidSynthReverbLevel:
  217. std::strncpy(strBuf, "Reverb Level", STR_MAX);
  218. return;
  219. case FluidSynthReverbWidth:
  220. std::strncpy(strBuf, "Reverb Width", STR_MAX);
  221. return;
  222. case FluidSynthChorusOnOff:
  223. std::strncpy(strBuf, "Chorus On/Off", STR_MAX);
  224. return;
  225. case FluidSynthChorusNr:
  226. std::strncpy(strBuf, "Chorus Voice Count", STR_MAX);
  227. return;
  228. case FluidSynthChorusLevel:
  229. std::strncpy(strBuf, "Chorus Level", STR_MAX);
  230. return;
  231. case FluidSynthChorusSpeedHz:
  232. std::strncpy(strBuf, "Chorus Speed", STR_MAX);
  233. return;
  234. case FluidSynthChorusDepthMs:
  235. std::strncpy(strBuf, "Chorus Depth", STR_MAX);
  236. return;
  237. case FluidSynthChorusType:
  238. std::strncpy(strBuf, "Chorus Type", STR_MAX);
  239. return;
  240. case FluidSynthPolyphony:
  241. std::strncpy(strBuf, "Polyphony", STR_MAX);
  242. return;
  243. case FluidSynthInterpolation:
  244. std::strncpy(strBuf, "Interpolation", STR_MAX);
  245. return;
  246. case FluidSynthVoiceCount:
  247. std::strncpy(strBuf, "Voice Count", STR_MAX);
  248. return;
  249. }
  250. CarlaPlugin::getParameterName(parameterId, strBuf);
  251. }
  252. void getParameterUnit(const uint32_t parameterId, char* const strBuf) const noexcept override
  253. {
  254. CARLA_SAFE_ASSERT_RETURN(parameterId < pData->param.count,);
  255. switch (parameterId)
  256. {
  257. case FluidSynthChorusSpeedHz:
  258. std::strncpy(strBuf, "Hz", STR_MAX);
  259. return;
  260. case FluidSynthChorusDepthMs:
  261. std::strncpy(strBuf, "ms", STR_MAX);
  262. return;
  263. }
  264. CarlaPlugin::getParameterUnit(parameterId, strBuf);
  265. }
  266. void getParameterScalePointLabel(const uint32_t parameterId, const uint32_t scalePointId, char* const strBuf) const noexcept override
  267. {
  268. CARLA_SAFE_ASSERT_RETURN(parameterId < pData->param.count,);
  269. CARLA_SAFE_ASSERT_RETURN(scalePointId < getParameterScalePointCount(parameterId),);
  270. switch (parameterId)
  271. {
  272. case FluidSynthChorusType:
  273. switch (scalePointId)
  274. {
  275. case 0:
  276. std::strncpy(strBuf, "Sine wave", STR_MAX);
  277. return;
  278. case 1:
  279. std::strncpy(strBuf, "Triangle wave", STR_MAX);
  280. return;
  281. }
  282. case FluidSynthInterpolation:
  283. switch (scalePointId)
  284. {
  285. case 0:
  286. std::strncpy(strBuf, "None", STR_MAX);
  287. return;
  288. case 1:
  289. std::strncpy(strBuf, "Straight-line", STR_MAX);
  290. return;
  291. case 2:
  292. std::strncpy(strBuf, "Fourth-order", STR_MAX);
  293. return;
  294. case 3:
  295. std::strncpy(strBuf, "Seventh-order", STR_MAX);
  296. return;
  297. }
  298. }
  299. CarlaPlugin::getParameterScalePointLabel(parameterId, scalePointId, strBuf);
  300. }
  301. // -------------------------------------------------------------------
  302. // Set data (state)
  303. void prepareForSave() override
  304. {
  305. char strBuf[STR_MAX+1];
  306. std::snprintf(strBuf, STR_MAX, "%i:%i:%i:%i:%i:%i:%i:%i:%i:%i:%i:%i:%i:%i:%i:%i", fCurMidiProgs[0], fCurMidiProgs[1], fCurMidiProgs[2], fCurMidiProgs[3],
  307. fCurMidiProgs[4], fCurMidiProgs[5], fCurMidiProgs[6], fCurMidiProgs[7],
  308. fCurMidiProgs[8], fCurMidiProgs[9], fCurMidiProgs[10], fCurMidiProgs[11],
  309. fCurMidiProgs[12], fCurMidiProgs[13], fCurMidiProgs[14], fCurMidiProgs[15]);
  310. CarlaPlugin::setCustomData(CUSTOM_DATA_TYPE_STRING, "midiPrograms", strBuf, false);
  311. }
  312. // -------------------------------------------------------------------
  313. // Set data (internal stuff)
  314. void setCtrlChannel(const int8_t channel, const bool sendOsc, const bool sendCallback) noexcept override
  315. {
  316. if (channel >= 0 && channel < MAX_MIDI_CHANNELS)
  317. pData->midiprog.current = fCurMidiProgs[channel];
  318. CarlaPlugin::setCtrlChannel(channel, sendOsc, sendCallback);
  319. }
  320. // -------------------------------------------------------------------
  321. // Set data (plugin-specific stuff)
  322. void setParameterValue(const uint32_t parameterId, const float value, const bool sendGui, const bool sendOsc, const bool sendCallback) noexcept override
  323. {
  324. CARLA_SAFE_ASSERT_RETURN(parameterId < pData->param.count,);
  325. const float fixedValue(pData->param.getFixedValue(parameterId, value));
  326. fParamBuffers[parameterId] = fixedValue;
  327. {
  328. const ScopedSingleProcessLocker spl(this, (sendGui || sendOsc || sendCallback));
  329. switch (parameterId)
  330. {
  331. case FluidSynthReverbOnOff:
  332. try {
  333. fluid_synth_set_reverb_on(fSynth, (fixedValue > 0.5f) ? 1 : 0);
  334. } catch(...) {}
  335. break;
  336. case FluidSynthReverbRoomSize:
  337. case FluidSynthReverbDamp:
  338. case FluidSynthReverbLevel:
  339. case FluidSynthReverbWidth:
  340. try {
  341. fluid_synth_set_reverb(fSynth, fParamBuffers[FluidSynthReverbRoomSize], fParamBuffers[FluidSynthReverbDamp], fParamBuffers[FluidSynthReverbWidth], fParamBuffers[FluidSynthReverbLevel]);
  342. } catch(...) {}
  343. break;
  344. case FluidSynthChorusOnOff:
  345. try {
  346. fluid_synth_set_chorus_on(fSynth, (value > 0.5f) ? 1 : 0);
  347. } catch(...) {}
  348. break;
  349. case FluidSynthChorusNr:
  350. case FluidSynthChorusLevel:
  351. case FluidSynthChorusSpeedHz:
  352. case FluidSynthChorusDepthMs:
  353. case FluidSynthChorusType:
  354. try {
  355. fluid_synth_set_chorus(fSynth, (int)fParamBuffers[FluidSynthChorusNr], fParamBuffers[FluidSynthChorusLevel], fParamBuffers[FluidSynthChorusSpeedHz], fParamBuffers[FluidSynthChorusDepthMs], (int)fParamBuffers[FluidSynthChorusType]);
  356. } catch(...) {}
  357. break;
  358. case FluidSynthPolyphony:
  359. try {
  360. fluid_synth_set_polyphony(fSynth, (int)value);
  361. } catch(...) {}
  362. break;
  363. case FluidSynthInterpolation:
  364. for (int i=0; i < MAX_MIDI_CHANNELS; ++i)
  365. {
  366. try {
  367. fluid_synth_set_interp_method(fSynth, i, (int)value);
  368. }
  369. catch(...) {
  370. break;
  371. }
  372. }
  373. break;
  374. default:
  375. break;
  376. }
  377. }
  378. CarlaPlugin::setParameterValue(parameterId, value, sendGui, sendOsc, sendCallback);
  379. }
  380. void setCustomData(const char* const type, const char* const key, const char* const value, const bool sendGui) override
  381. {
  382. CARLA_SAFE_ASSERT_RETURN(fSynth != nullptr,);
  383. CARLA_SAFE_ASSERT_RETURN(type != nullptr && type[0] != '\0',);
  384. CARLA_SAFE_ASSERT_RETURN(key != nullptr && key[0] != '\0',);
  385. CARLA_SAFE_ASSERT_RETURN(value != nullptr && value[0] != '\0',);
  386. carla_debug("CarlaPluginFluidSynth::setCustomData(%s, \"%s\", \"%s\", %s)", type, key, value, bool2str(sendGui));
  387. if (std::strcmp(type, CUSTOM_DATA_TYPE_PROPERTY) == 0)
  388. return CarlaPlugin::setCustomData(type, key, value, sendGui);
  389. if (std::strcmp(type, CUSTOM_DATA_TYPE_STRING) != 0)
  390. return carla_stderr2("CarlaPluginFluidSynth::setCustomData(\"%s\", \"%s\", \"%s\", %s) - type is not string", type, key, value, bool2str(sendGui));
  391. if (std::strcmp(key, "midiPrograms") != 0)
  392. return carla_stderr2("CarlaPluginFluidSynth::setCustomData(\"%s\", \"%s\", \"%s\", %s) - type is not string", type, key, value, bool2str(sendGui));
  393. StringArray midiProgramList(StringArray::fromTokens(value, ":", ""));
  394. if (midiProgramList.size() == MAX_MIDI_CHANNELS)
  395. {
  396. uint8_t channel = 0;
  397. for (String *it=midiProgramList.begin(), *end=midiProgramList.end(); it != end; ++it)
  398. {
  399. const int index(it->getIntValue());
  400. if (index >= 0 && index < static_cast<int>(pData->midiprog.count))
  401. {
  402. const uint32_t bank = pData->midiprog.data[index].bank;
  403. const uint32_t program = pData->midiprog.data[index].program;
  404. fluid_synth_program_select(fSynth, channel, fSynthId, bank, program);
  405. fCurMidiProgs[channel] = index;
  406. if (pData->ctrlChannel == static_cast<int32_t>(channel))
  407. {
  408. pData->midiprog.current = index;
  409. pData->engine->callback(ENGINE_CALLBACK_MIDI_PROGRAM_CHANGED, pData->id, index, 0, 0.0f, nullptr);
  410. }
  411. }
  412. ++channel;
  413. }
  414. CARLA_SAFE_ASSERT(channel == MAX_MIDI_CHANNELS);
  415. }
  416. CarlaPlugin::setCustomData(type, key, value, sendGui);
  417. }
  418. void setMidiProgram(const int32_t index, const bool sendGui, const bool sendOsc, const bool sendCallback) noexcept override
  419. {
  420. CARLA_SAFE_ASSERT_RETURN(fSynth != nullptr,);
  421. CARLA_SAFE_ASSERT_RETURN(index >= -1 && index < static_cast<int32_t>(pData->midiprog.count),);
  422. if (index >= 0 && pData->ctrlChannel >= 0 && pData->ctrlChannel < MAX_MIDI_CHANNELS)
  423. {
  424. const uint32_t bank = pData->midiprog.data[index].bank;
  425. const uint32_t program = pData->midiprog.data[index].program;
  426. //const ScopedSingleProcessLocker spl(this, (sendGui || sendOsc || sendCallback));
  427. try {
  428. fluid_synth_program_select(fSynth, pData->ctrlChannel, fSynthId, bank, program);
  429. } catch(...) {}
  430. fCurMidiProgs[pData->ctrlChannel] = index;
  431. }
  432. CarlaPlugin::setMidiProgram(index, sendGui, sendOsc, sendCallback);
  433. }
  434. // -------------------------------------------------------------------
  435. // Set ui stuff
  436. // nothing
  437. // -------------------------------------------------------------------
  438. // Plugin state
  439. void reload() override
  440. {
  441. CARLA_SAFE_ASSERT_RETURN(pData->engine != nullptr,);
  442. CARLA_SAFE_ASSERT_RETURN(fSynth != nullptr,);
  443. carla_debug("CarlaPluginFluidSynth::reload() - start");
  444. const EngineProcessMode processMode(pData->engine->getProccessMode());
  445. // Safely disable plugin for reload
  446. const ScopedDisabler sd(this);
  447. if (pData->active)
  448. deactivate();
  449. clearBuffers();
  450. uint32_t aOuts, params;
  451. aOuts = kUse16Outs ? 32 : 2;
  452. params = FluidSynthParametersMax;
  453. pData->audioOut.createNew(aOuts);
  454. pData->param.createNew(params, false);
  455. const uint portNameSize(pData->engine->getMaxPortNameSize());
  456. CarlaString portName;
  457. // ---------------------------------------
  458. // Audio Outputs
  459. if (kUse16Outs)
  460. {
  461. for (uint32_t i=0; i < 32; ++i)
  462. {
  463. portName.clear();
  464. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  465. {
  466. portName = pData->name;
  467. portName += ":";
  468. }
  469. portName += "out-";
  470. if ((i+2)/2 < 9)
  471. portName += "0";
  472. portName += CarlaString((i+2)/2);
  473. if (i % 2 == 0)
  474. portName += "L";
  475. else
  476. portName += "R";
  477. portName.truncate(portNameSize);
  478. pData->audioOut.ports[i].port = (CarlaEngineAudioPort*)pData->client->addPort(kEnginePortTypeAudio, portName, false, i);
  479. pData->audioOut.ports[i].rindex = i;
  480. }
  481. fAudio16Buffers = new float*[aOuts];
  482. for (uint32_t i=0; i < aOuts; ++i)
  483. fAudio16Buffers[i] = nullptr;
  484. }
  485. else
  486. {
  487. // out-left
  488. portName.clear();
  489. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  490. {
  491. portName = pData->name;
  492. portName += ":";
  493. }
  494. portName += "out-left";
  495. portName.truncate(portNameSize);
  496. pData->audioOut.ports[0].port = (CarlaEngineAudioPort*)pData->client->addPort(kEnginePortTypeAudio, portName, false, 0);
  497. pData->audioOut.ports[0].rindex = 0;
  498. // out-right
  499. portName.clear();
  500. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  501. {
  502. portName = pData->name;
  503. portName += ":";
  504. }
  505. portName += "out-right";
  506. portName.truncate(portNameSize);
  507. pData->audioOut.ports[1].port = (CarlaEngineAudioPort*)pData->client->addPort(kEnginePortTypeAudio, portName, false, 1);
  508. pData->audioOut.ports[1].rindex = 1;
  509. }
  510. // ---------------------------------------
  511. // Event Input
  512. {
  513. portName.clear();
  514. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  515. {
  516. portName = pData->name;
  517. portName += ":";
  518. }
  519. portName += "events-in";
  520. portName.truncate(portNameSize);
  521. pData->event.portIn = (CarlaEngineEventPort*)pData->client->addPort(kEnginePortTypeEvent, portName, true, 0);
  522. }
  523. // ---------------------------------------
  524. // Event Output
  525. {
  526. portName.clear();
  527. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  528. {
  529. portName = pData->name;
  530. portName += ":";
  531. }
  532. portName += "events-out";
  533. portName.truncate(portNameSize);
  534. pData->event.portOut = (CarlaEngineEventPort*)pData->client->addPort(kEnginePortTypeEvent, portName, false, 0);
  535. }
  536. // ---------------------------------------
  537. // Parameters
  538. {
  539. int j;
  540. // ----------------------
  541. j = FluidSynthReverbOnOff;
  542. pData->param.data[j].type = PARAMETER_INPUT;
  543. pData->param.data[j].hints = PARAMETER_IS_ENABLED /*| PARAMETER_IS_AUTOMABLE*/ | PARAMETER_IS_BOOLEAN;
  544. pData->param.data[j].index = j;
  545. pData->param.data[j].rindex = j;
  546. pData->param.ranges[j].min = 0.0f;
  547. pData->param.ranges[j].max = 1.0f;
  548. pData->param.ranges[j].def = 1.0f;
  549. pData->param.ranges[j].step = 1.0f;
  550. pData->param.ranges[j].stepSmall = 1.0f;
  551. pData->param.ranges[j].stepLarge = 1.0f;
  552. // ----------------------
  553. j = FluidSynthReverbRoomSize;
  554. pData->param.data[j].type = PARAMETER_INPUT;
  555. pData->param.data[j].hints = PARAMETER_IS_ENABLED /*| PARAMETER_IS_AUTOMABLE*/;
  556. pData->param.data[j].index = j;
  557. pData->param.data[j].rindex = j;
  558. pData->param.ranges[j].min = 0.0f;
  559. pData->param.ranges[j].max = 1.2f;
  560. pData->param.ranges[j].def = FLUID_REVERB_DEFAULT_ROOMSIZE;
  561. pData->param.ranges[j].step = 0.01f;
  562. pData->param.ranges[j].stepSmall = 0.0001f;
  563. pData->param.ranges[j].stepLarge = 0.1f;
  564. // ----------------------
  565. j = FluidSynthReverbDamp;
  566. pData->param.data[j].type = PARAMETER_INPUT;
  567. pData->param.data[j].hints = PARAMETER_IS_ENABLED /*| PARAMETER_IS_AUTOMABLE*/;
  568. pData->param.data[j].index = j;
  569. pData->param.data[j].rindex = j;
  570. pData->param.ranges[j].min = 0.0f;
  571. pData->param.ranges[j].max = 1.0f;
  572. pData->param.ranges[j].def = FLUID_REVERB_DEFAULT_DAMP;
  573. pData->param.ranges[j].step = 0.01f;
  574. pData->param.ranges[j].stepSmall = 0.0001f;
  575. pData->param.ranges[j].stepLarge = 0.1f;
  576. // ----------------------
  577. j = FluidSynthReverbLevel;
  578. pData->param.data[j].type = PARAMETER_INPUT;
  579. pData->param.data[j].hints = PARAMETER_IS_ENABLED /*| PARAMETER_IS_AUTOMABLE*/;
  580. pData->param.data[j].index = j;
  581. pData->param.data[j].rindex = j;
  582. pData->param.data[j].midiCC = MIDI_CONTROL_REVERB_SEND_LEVEL;
  583. pData->param.ranges[j].min = 0.0f;
  584. pData->param.ranges[j].max = 1.0f;
  585. pData->param.ranges[j].def = FLUID_REVERB_DEFAULT_LEVEL;
  586. pData->param.ranges[j].step = 0.01f;
  587. pData->param.ranges[j].stepSmall = 0.0001f;
  588. pData->param.ranges[j].stepLarge = 0.1f;
  589. // ----------------------
  590. j = FluidSynthReverbWidth;
  591. pData->param.data[j].type = PARAMETER_INPUT;
  592. pData->param.data[j].hints = PARAMETER_IS_ENABLED /*| PARAMETER_IS_AUTOMABLE*/;
  593. pData->param.data[j].index = j;
  594. pData->param.data[j].rindex = j;
  595. pData->param.ranges[j].min = 0.0f;
  596. pData->param.ranges[j].max = 10.0f; // should be 100, but that sounds too much
  597. pData->param.ranges[j].def = FLUID_REVERB_DEFAULT_WIDTH;
  598. pData->param.ranges[j].step = 0.01f;
  599. pData->param.ranges[j].stepSmall = 0.0001f;
  600. pData->param.ranges[j].stepLarge = 0.1f;
  601. // ----------------------
  602. j = FluidSynthChorusOnOff;
  603. pData->param.data[j].type = PARAMETER_INPUT;
  604. pData->param.data[j].hints = PARAMETER_IS_ENABLED | PARAMETER_IS_BOOLEAN;
  605. pData->param.data[j].index = j;
  606. pData->param.data[j].rindex = j;
  607. pData->param.ranges[j].min = 0.0f;
  608. pData->param.ranges[j].max = 1.0f;
  609. pData->param.ranges[j].def = 1.0f;
  610. pData->param.ranges[j].step = 1.0f;
  611. pData->param.ranges[j].stepSmall = 1.0f;
  612. pData->param.ranges[j].stepLarge = 1.0f;
  613. // ----------------------
  614. j = FluidSynthChorusNr;
  615. pData->param.data[j].type = PARAMETER_INPUT;
  616. pData->param.data[j].hints = PARAMETER_IS_ENABLED | PARAMETER_IS_INTEGER;
  617. pData->param.data[j].index = j;
  618. pData->param.data[j].rindex = j;
  619. pData->param.ranges[j].min = 0.0f;
  620. pData->param.ranges[j].max = 99.0f;
  621. pData->param.ranges[j].def = FLUID_CHORUS_DEFAULT_N;
  622. pData->param.ranges[j].step = 1.0f;
  623. pData->param.ranges[j].stepSmall = 1.0f;
  624. pData->param.ranges[j].stepLarge = 10.0f;
  625. // ----------------------
  626. j = FluidSynthChorusLevel;
  627. pData->param.data[j].type = PARAMETER_INPUT;
  628. pData->param.data[j].hints = PARAMETER_IS_ENABLED;
  629. pData->param.data[j].index = j;
  630. pData->param.data[j].rindex = j;
  631. pData->param.ranges[j].min = 0.0f;
  632. pData->param.ranges[j].max = 10.0f;
  633. pData->param.ranges[j].def = FLUID_CHORUS_DEFAULT_LEVEL;
  634. pData->param.ranges[j].step = 0.01f;
  635. pData->param.ranges[j].stepSmall = 0.0001f;
  636. pData->param.ranges[j].stepLarge = 0.1f;
  637. // ----------------------
  638. j = FluidSynthChorusSpeedHz;
  639. pData->param.data[j].type = PARAMETER_INPUT;
  640. pData->param.data[j].hints = PARAMETER_IS_ENABLED;
  641. pData->param.data[j].index = j;
  642. pData->param.data[j].rindex = j;
  643. pData->param.ranges[j].min = 0.29f;
  644. pData->param.ranges[j].max = 5.0f;
  645. pData->param.ranges[j].def = FLUID_CHORUS_DEFAULT_SPEED;
  646. pData->param.ranges[j].step = 0.01f;
  647. pData->param.ranges[j].stepSmall = 0.0001f;
  648. pData->param.ranges[j].stepLarge = 0.1f;
  649. // ----------------------
  650. j = FluidSynthChorusDepthMs;
  651. pData->param.data[j].type = PARAMETER_INPUT;
  652. pData->param.data[j].hints = PARAMETER_IS_ENABLED;
  653. pData->param.data[j].index = j;
  654. pData->param.data[j].rindex = j;
  655. pData->param.ranges[j].min = 0.0f;
  656. pData->param.ranges[j].max = float(2048.0 * 1000.0 / pData->engine->getSampleRate()); // FIXME?
  657. pData->param.ranges[j].def = FLUID_CHORUS_DEFAULT_DEPTH;
  658. pData->param.ranges[j].step = 0.01f;
  659. pData->param.ranges[j].stepSmall = 0.0001f;
  660. pData->param.ranges[j].stepLarge = 0.1f;
  661. // ----------------------
  662. j = FluidSynthChorusType;
  663. pData->param.data[j].type = PARAMETER_INPUT;
  664. pData->param.data[j].hints = PARAMETER_IS_ENABLED | PARAMETER_IS_INTEGER | PARAMETER_USES_SCALEPOINTS;
  665. pData->param.data[j].index = j;
  666. pData->param.data[j].rindex = j;
  667. pData->param.ranges[j].min = FLUID_CHORUS_MOD_SINE;
  668. pData->param.ranges[j].max = FLUID_CHORUS_MOD_TRIANGLE;
  669. pData->param.ranges[j].def = FLUID_CHORUS_DEFAULT_TYPE;
  670. pData->param.ranges[j].step = 1.0f;
  671. pData->param.ranges[j].stepSmall = 1.0f;
  672. pData->param.ranges[j].stepLarge = 1.0f;
  673. // ----------------------
  674. j = FluidSynthPolyphony;
  675. pData->param.data[j].type = PARAMETER_INPUT;
  676. pData->param.data[j].hints = PARAMETER_IS_ENABLED | PARAMETER_IS_INTEGER;
  677. pData->param.data[j].index = j;
  678. pData->param.data[j].rindex = j;
  679. pData->param.ranges[j].min = 1.0f;
  680. pData->param.ranges[j].max = 512.0f; // max theoric is 65535
  681. pData->param.ranges[j].def = (float)fluid_synth_get_polyphony(fSynth);
  682. pData->param.ranges[j].step = 1.0f;
  683. pData->param.ranges[j].stepSmall = 1.0f;
  684. pData->param.ranges[j].stepLarge = 10.0f;
  685. // ----------------------
  686. j = FluidSynthInterpolation;
  687. pData->param.data[j].type = PARAMETER_INPUT;
  688. pData->param.data[j].hints = PARAMETER_IS_ENABLED | PARAMETER_IS_INTEGER | PARAMETER_USES_SCALEPOINTS;
  689. pData->param.data[j].index = j;
  690. pData->param.data[j].rindex = j;
  691. pData->param.ranges[j].min = FLUID_INTERP_NONE;
  692. pData->param.ranges[j].max = FLUID_INTERP_HIGHEST;
  693. pData->param.ranges[j].def = FLUID_INTERP_DEFAULT;
  694. pData->param.ranges[j].step = 1.0f;
  695. pData->param.ranges[j].stepSmall = 1.0f;
  696. pData->param.ranges[j].stepLarge = 1.0f;
  697. // ----------------------
  698. j = FluidSynthVoiceCount;
  699. pData->param.data[j].type = PARAMETER_OUTPUT;
  700. pData->param.data[j].hints = PARAMETER_IS_ENABLED | PARAMETER_IS_AUTOMABLE | PARAMETER_IS_INTEGER;
  701. pData->param.data[j].index = j;
  702. pData->param.data[j].rindex = j;
  703. pData->param.ranges[j].min = 0.0f;
  704. pData->param.ranges[j].max = 65535.0f;
  705. pData->param.ranges[j].def = 0.0f;
  706. pData->param.ranges[j].step = 1.0f;
  707. pData->param.ranges[j].stepSmall = 1.0f;
  708. pData->param.ranges[j].stepLarge = 1.0f;
  709. for (j=0; j<FluidSynthParametersMax; ++j)
  710. fParamBuffers[j] = pData->param.ranges[j].def;
  711. }
  712. // ---------------------------------------
  713. // plugin hints
  714. pData->hints = 0x0;
  715. pData->hints |= PLUGIN_IS_SYNTH;
  716. pData->hints |= PLUGIN_CAN_VOLUME;
  717. pData->hints |= PLUGIN_USES_MULTI_PROGS;
  718. if (! kUse16Outs)
  719. pData->hints |= PLUGIN_CAN_BALANCE;
  720. // extra plugin hints
  721. pData->extraHints = 0x0;
  722. pData->extraHints |= PLUGIN_EXTRA_HINT_HAS_MIDI_IN;
  723. if (kUse16Outs)
  724. pData->extraHints |= PLUGIN_EXTRA_HINT_CAN_RUN_RACK;
  725. bufferSizeChanged(pData->engine->getBufferSize());
  726. reloadPrograms(true);
  727. if (pData->active)
  728. activate();
  729. carla_debug("CarlaPluginFluidSynth::reload() - end");
  730. }
  731. void reloadPrograms(const bool doInit) override
  732. {
  733. carla_debug("CarlaPluginFluidSynth::reloadPrograms(%s)", bool2str(doInit));
  734. // save drum info in case we have one program for it
  735. bool hasDrums = false;
  736. uint32_t drumIndex, drumProg;
  737. drumIndex = drumProg = 0;
  738. // Delete old programs
  739. pData->midiprog.clear();
  740. // Query new programs
  741. uint32_t count = 0;
  742. if (fluid_sfont_t* const f_sfont = fluid_synth_get_sfont_by_id(fSynth, fSynthId))
  743. {
  744. fluid_preset_t f_preset;
  745. // initial check to know how many midi-programs we have
  746. f_sfont->iteration_start(f_sfont);
  747. for (; f_sfont->iteration_next(f_sfont, &f_preset);)
  748. ++count;
  749. // sound kits must always have at least 1 midi-program
  750. CARLA_SAFE_ASSERT_RETURN(count > 0,);
  751. pData->midiprog.createNew(count);
  752. // Update data
  753. int tmp;
  754. uint32_t i = 0;
  755. f_sfont->iteration_start(f_sfont);
  756. for (; f_sfont->iteration_next(f_sfont, &f_preset);)
  757. {
  758. CARLA_SAFE_ASSERT_BREAK(i < count);
  759. tmp = f_preset.get_banknum(&f_preset);
  760. pData->midiprog.data[i].bank = (tmp >= 0) ? static_cast<uint32_t>(tmp) : 0;
  761. tmp = f_preset.get_num(&f_preset);
  762. pData->midiprog.data[i].program = (tmp >= 0) ? static_cast<uint32_t>(tmp) : 0;
  763. pData->midiprog.data[i].name = carla_strdup(f_preset.get_name(&f_preset));
  764. if (pData->midiprog.data[i].bank == 128 && ! hasDrums)
  765. {
  766. hasDrums = true;
  767. drumIndex = i;
  768. drumProg = pData->midiprog.data[i].program;
  769. }
  770. ++i;
  771. }
  772. }
  773. else
  774. {
  775. // failing means 0 midi-programs, it shouldn't happen!
  776. carla_safe_assert("fluid_sfont_t* const f_sfont = fluid_synth_get_sfont_by_id(fSynth, fSynthId)", __FILE__, __LINE__);
  777. return;
  778. }
  779. #if defined(HAVE_LIBLO) && ! defined(BUILD_BRIDGE)
  780. // Update OSC Names
  781. if (pData->engine->isOscControlRegistered() && pData->id < pData->engine->getCurrentPluginCount())
  782. {
  783. pData->engine->oscSend_control_set_midi_program_count(pData->id, count);
  784. for (uint32_t i=0; i < count; ++i)
  785. 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);
  786. }
  787. #endif
  788. if (doInit)
  789. {
  790. fluid_synth_program_reset(fSynth);
  791. // select first program, or 128 for ch10
  792. for (int i=0; i < MAX_MIDI_CHANNELS && i != 9; ++i)
  793. {
  794. #ifdef FLUIDSYNTH_VERSION_NEW_API
  795. fluid_synth_set_channel_type(fSynth, i, CHANNEL_TYPE_MELODIC);
  796. #endif
  797. fluid_synth_program_select(fSynth, i, fSynthId, pData->midiprog.data[0].bank, pData->midiprog.data[0].program);
  798. fCurMidiProgs[i] = 0;
  799. }
  800. if (hasDrums)
  801. {
  802. #ifdef FLUIDSYNTH_VERSION_NEW_API
  803. fluid_synth_set_channel_type(fSynth, 9, CHANNEL_TYPE_DRUM);
  804. #endif
  805. fluid_synth_program_select(fSynth, 9, fSynthId, 128, drumProg);
  806. fCurMidiProgs[9] = static_cast<int32_t>(drumIndex);
  807. }
  808. else
  809. {
  810. #ifdef FLUIDSYNTH_VERSION_NEW_API
  811. fluid_synth_set_channel_type(fSynth, 9, CHANNEL_TYPE_MELODIC);
  812. #endif
  813. fluid_synth_program_select(fSynth, 9, fSynthId, pData->midiprog.data[0].bank, pData->midiprog.data[0].program);
  814. fCurMidiProgs[9] = 0;
  815. }
  816. pData->midiprog.current = 0;
  817. }
  818. else
  819. {
  820. pData->engine->callback(ENGINE_CALLBACK_RELOAD_PROGRAMS, pData->id, 0, 0, 0.0f, nullptr);
  821. }
  822. }
  823. // -------------------------------------------------------------------
  824. // Plugin processing
  825. void process(const float** const, float** const audioOut, const float** const, float** const, const uint32_t frames) override
  826. {
  827. // --------------------------------------------------------------------------------------------------------
  828. // Check if active
  829. if (! pData->active)
  830. {
  831. // disable any output sound
  832. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  833. FloatVectorOperations::clear(audioOut[i], static_cast<int>(frames));
  834. return;
  835. }
  836. // --------------------------------------------------------------------------------------------------------
  837. // Check if needs reset
  838. if (pData->needsReset)
  839. {
  840. if (pData->options & PLUGIN_OPTION_SEND_ALL_SOUND_OFF)
  841. {
  842. for (int i=0; i < MAX_MIDI_CHANNELS; ++i)
  843. {
  844. #ifdef FLUIDSYNTH_VERSION_NEW_API
  845. fluid_synth_all_notes_off(fSynth, i);
  846. fluid_synth_all_sounds_off(fSynth, i);
  847. #else
  848. fluid_synth_cc(fSynth, i, MIDI_CONTROL_ALL_SOUND_OFF, 0);
  849. fluid_synth_cc(fSynth, i, MIDI_CONTROL_ALL_NOTES_OFF, 0);
  850. #endif
  851. }
  852. }
  853. else if (pData->ctrlChannel >= 0 && pData->ctrlChannel < MAX_MIDI_CHANNELS)
  854. {
  855. for (int i=0; i < MAX_MIDI_NOTE; ++i)
  856. fluid_synth_noteoff(fSynth, pData->ctrlChannel, i);
  857. }
  858. pData->needsReset = false;
  859. }
  860. // --------------------------------------------------------------------------------------------------------
  861. // Event Input and Processing
  862. {
  863. // ----------------------------------------------------------------------------------------------------
  864. // MIDI Input (External)
  865. if (pData->extNotes.mutex.tryLock())
  866. {
  867. for (RtLinkedList<ExternalMidiNote>::Itenerator it = pData->extNotes.data.begin2(); it.valid(); it.next())
  868. {
  869. const ExternalMidiNote& note(it.getValue());
  870. CARLA_SAFE_ASSERT_CONTINUE(note.channel >= 0 && note.channel < MAX_MIDI_CHANNELS);
  871. if (note.velo > 0)
  872. fluid_synth_noteon(fSynth, note.channel, note.note, note.velo);
  873. else
  874. fluid_synth_noteoff(fSynth,note.channel, note.note);
  875. }
  876. pData->extNotes.data.clear();
  877. pData->extNotes.mutex.unlock();
  878. } // End of MIDI Input (External)
  879. // ----------------------------------------------------------------------------------------------------
  880. // Event Input (System)
  881. #ifndef BUILD_BRIDGE
  882. bool allNotesOffSent = false;
  883. #endif
  884. uint32_t timeOffset = 0;
  885. uint32_t nextBankIds[MAX_MIDI_CHANNELS] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 0, 0, 0, 0, 0, 0 };
  886. if (pData->midiprog.current >= 0 && pData->midiprog.count > 0 && pData->ctrlChannel >= 0 && pData->ctrlChannel < MAX_MIDI_CHANNELS)
  887. nextBankIds[pData->ctrlChannel] = pData->midiprog.data[pData->midiprog.current].bank;
  888. for (uint32_t i=0, numEvents=pData->event.portIn->getEventCount(); i < numEvents; ++i)
  889. {
  890. const EngineEvent& event(pData->event.portIn->getEvent(i));
  891. if (event.time >= frames)
  892. continue;
  893. CARLA_ASSERT_INT2(event.time >= timeOffset, event.time, timeOffset);
  894. if (event.time > timeOffset)
  895. {
  896. if (processSingle(audioOut, event.time - timeOffset, timeOffset))
  897. {
  898. timeOffset = event.time;
  899. if (pData->midiprog.current >= 0 && pData->midiprog.count > 0 && pData->ctrlChannel >= 0 && pData->ctrlChannel < MAX_MIDI_CHANNELS)
  900. nextBankIds[pData->ctrlChannel] = pData->midiprog.data[pData->midiprog.current].bank;
  901. }
  902. }
  903. // Control change
  904. switch (event.type)
  905. {
  906. case kEngineEventTypeNull:
  907. break;
  908. case kEngineEventTypeControl:
  909. {
  910. const EngineControlEvent& ctrlEvent = event.ctrl;
  911. switch (ctrlEvent.type)
  912. {
  913. case kEngineControlEventTypeNull:
  914. break;
  915. case kEngineControlEventTypeParameter:
  916. {
  917. #ifndef BUILD_BRIDGE
  918. // Control backend stuff
  919. if (event.channel == pData->ctrlChannel)
  920. {
  921. float value;
  922. if (MIDI_IS_CONTROL_BREATH_CONTROLLER(ctrlEvent.param) && (pData->hints & PLUGIN_CAN_DRYWET) != 0)
  923. {
  924. value = ctrlEvent.value;
  925. setDryWet(value, false, false);
  926. pData->postponeRtEvent(kPluginPostRtEventParameterChange, PARAMETER_DRYWET, 0, value);
  927. }
  928. if (MIDI_IS_CONTROL_CHANNEL_VOLUME(ctrlEvent.param) && (pData->hints & PLUGIN_CAN_VOLUME) != 0)
  929. {
  930. value = ctrlEvent.value*127.0f/100.0f;
  931. setVolume(value, false, false);
  932. pData->postponeRtEvent(kPluginPostRtEventParameterChange, PARAMETER_VOLUME, 0, value);
  933. }
  934. if (MIDI_IS_CONTROL_BALANCE(ctrlEvent.param) && (pData->hints & PLUGIN_CAN_BALANCE) != 0)
  935. {
  936. float left, right;
  937. value = ctrlEvent.value/0.5f - 1.0f;
  938. if (value < 0.0f)
  939. {
  940. left = -1.0f;
  941. right = (value*2.0f)+1.0f;
  942. }
  943. else if (value > 0.0f)
  944. {
  945. left = (value*2.0f)-1.0f;
  946. right = 1.0f;
  947. }
  948. else
  949. {
  950. left = -1.0f;
  951. right = 1.0f;
  952. }
  953. setBalanceLeft(left, false, false);
  954. setBalanceRight(right, false, false);
  955. pData->postponeRtEvent(kPluginPostRtEventParameterChange, PARAMETER_BALANCE_LEFT, 0, left);
  956. pData->postponeRtEvent(kPluginPostRtEventParameterChange, PARAMETER_BALANCE_RIGHT, 0, right);
  957. }
  958. }
  959. #endif
  960. // Control plugin parameters
  961. for (uint32_t k=0; k < pData->param.count; ++k)
  962. {
  963. if (pData->param.data[k].midiChannel != event.channel)
  964. continue;
  965. if (pData->param.data[k].midiCC != ctrlEvent.param)
  966. continue;
  967. if (pData->param.data[k].hints != PARAMETER_INPUT)
  968. continue;
  969. if ((pData->param.data[k].hints & PARAMETER_IS_AUTOMABLE) == 0)
  970. continue;
  971. float value;
  972. if (pData->param.data[k].hints & PARAMETER_IS_BOOLEAN)
  973. {
  974. value = (ctrlEvent.value < 0.5f) ? pData->param.ranges[k].min : pData->param.ranges[k].max;
  975. }
  976. else
  977. {
  978. value = pData->param.ranges[k].getUnnormalizedValue(ctrlEvent.value);
  979. if (pData->param.data[k].hints & PARAMETER_IS_INTEGER)
  980. value = std::rint(value);
  981. }
  982. setParameterValue(k, value, false, false, false);
  983. pData->postponeRtEvent(kPluginPostRtEventParameterChange, static_cast<int32_t>(k), 0, value);
  984. }
  985. if ((pData->options & PLUGIN_OPTION_SEND_CONTROL_CHANGES) != 0 && ctrlEvent.param < MAX_MIDI_CONTROL)
  986. {
  987. fluid_synth_cc(fSynth, event.channel, ctrlEvent.param, int(ctrlEvent.value*127.0f));
  988. }
  989. break;
  990. }
  991. case kEngineControlEventTypeMidiBank:
  992. if (event.channel < MAX_MIDI_CHANNELS && (pData->options & PLUGIN_OPTION_MAP_PROGRAM_CHANGES) != 0)
  993. nextBankIds[event.channel] = ctrlEvent.param;
  994. break;
  995. case kEngineControlEventTypeMidiProgram:
  996. if (event.channel < MAX_MIDI_CHANNELS && (pData->options & PLUGIN_OPTION_MAP_PROGRAM_CHANGES) != 0)
  997. {
  998. const uint32_t bankId(nextBankIds[event.channel]);
  999. const uint32_t progId(ctrlEvent.param);
  1000. // TODO int32_t midiprog.find(bank, prog)
  1001. for (uint32_t k=0; k < pData->midiprog.count; ++k)
  1002. {
  1003. if (pData->midiprog.data[k].bank == bankId && pData->midiprog.data[k].program == progId)
  1004. {
  1005. fluid_synth_program_select(fSynth, event.channel, fSynthId, bankId, progId);
  1006. fCurMidiProgs[event.channel] = static_cast<int32_t>(k);
  1007. if (event.channel == pData->ctrlChannel)
  1008. pData->postponeRtEvent(kPluginPostRtEventMidiProgramChange, static_cast<int32_t>(k), 0, 0.0f);
  1009. break;
  1010. }
  1011. }
  1012. }
  1013. break;
  1014. case kEngineControlEventTypeAllSoundOff:
  1015. if (pData->options & PLUGIN_OPTION_SEND_ALL_SOUND_OFF)
  1016. {
  1017. #ifdef FLUIDSYNTH_VERSION_NEW_API
  1018. fluid_synth_all_sounds_off(fSynth, event.channel);
  1019. #else
  1020. fluid_synth_cc(fSynth, event.channel, MIDI_CONTROL_ALL_SOUND_OFF, 0);
  1021. #endif
  1022. }
  1023. break;
  1024. case kEngineControlEventTypeAllNotesOff:
  1025. if (pData->options & PLUGIN_OPTION_SEND_ALL_SOUND_OFF)
  1026. {
  1027. #ifndef BUILD_BRIDGE
  1028. if (event.channel == pData->ctrlChannel && ! allNotesOffSent)
  1029. {
  1030. allNotesOffSent = true;
  1031. sendMidiAllNotesOffToCallback();
  1032. }
  1033. #endif
  1034. #ifdef FLUIDSYNTH_VERSION_NEW_API
  1035. fluid_synth_all_notes_off(fSynth, event.channel);
  1036. #else
  1037. fluid_synth_cc(fSynth, event.channel, MIDI_CONTROL_ALL_NOTES_OFF, 0);
  1038. #endif
  1039. }
  1040. break;
  1041. }
  1042. break;
  1043. }
  1044. case kEngineEventTypeMidi: {
  1045. const EngineMidiEvent& midiEvent(event.midi);
  1046. if (midiEvent.size > EngineMidiEvent::kDataSize)
  1047. continue;
  1048. uint8_t status = uint8_t(MIDI_GET_STATUS_FROM_DATA(midiEvent.data));
  1049. // Fix bad note-off
  1050. if (status == MIDI_STATUS_NOTE_ON && midiEvent.data[2] == 0)
  1051. status = MIDI_STATUS_NOTE_OFF;
  1052. switch (status)
  1053. {
  1054. case MIDI_STATUS_NOTE_OFF: {
  1055. const uint8_t note = midiEvent.data[1];
  1056. fluid_synth_noteoff(fSynth, event.channel, note);
  1057. pData->postponeRtEvent(kPluginPostRtEventNoteOff, event.channel, note, 0.0f);
  1058. break;
  1059. }
  1060. case MIDI_STATUS_NOTE_ON: {
  1061. const uint8_t note = midiEvent.data[1];
  1062. const uint8_t velo = midiEvent.data[2];
  1063. fluid_synth_noteon(fSynth, event.channel, note, velo);
  1064. pData->postponeRtEvent(kPluginPostRtEventNoteOn, event.channel, note, velo);
  1065. break;
  1066. }
  1067. case MIDI_STATUS_POLYPHONIC_AFTERTOUCH:
  1068. if (pData->options & PLUGIN_OPTION_SEND_NOTE_AFTERTOUCH)
  1069. {
  1070. //const uint8_t note = midiEvent.data[1];
  1071. //const uint8_t pressure = midiEvent.data[2];
  1072. // not in fluidsynth API
  1073. }
  1074. break;
  1075. case MIDI_STATUS_CONTROL_CHANGE:
  1076. if (pData->options & PLUGIN_OPTION_SEND_CONTROL_CHANGES)
  1077. {
  1078. const uint8_t control = midiEvent.data[1];
  1079. const uint8_t value = midiEvent.data[2];
  1080. fluid_synth_cc(fSynth, event.channel, control, value);
  1081. }
  1082. break;
  1083. case MIDI_STATUS_CHANNEL_PRESSURE:
  1084. if (pData->options & PLUGIN_OPTION_SEND_CHANNEL_PRESSURE)
  1085. {
  1086. const uint8_t pressure = midiEvent.data[1];
  1087. fluid_synth_channel_pressure(fSynth, event.channel, pressure);;
  1088. }
  1089. break;
  1090. case MIDI_STATUS_PITCH_WHEEL_CONTROL:
  1091. if (pData->options & PLUGIN_OPTION_SEND_PITCHBEND)
  1092. {
  1093. const uint8_t lsb = midiEvent.data[1];
  1094. const uint8_t msb = midiEvent.data[2];
  1095. const int value = ((msb << 7) | lsb);
  1096. fluid_synth_pitch_bend(fSynth, event.channel, value);
  1097. }
  1098. break;
  1099. default:
  1100. continue;
  1101. break;
  1102. } // switch (status)
  1103. } break;
  1104. } // switch (event.type)
  1105. }
  1106. pData->postRtEvents.trySplice();
  1107. if (frames > timeOffset)
  1108. processSingle(audioOut, frames - timeOffset, timeOffset);
  1109. } // End of Event Input and Processing
  1110. #ifndef BUILD_BRIDGE
  1111. // --------------------------------------------------------------------------------------------------------
  1112. // Control Output
  1113. {
  1114. uint32_t k = FluidSynthVoiceCount;
  1115. fParamBuffers[k] = float(fluid_synth_get_active_voice_count(fSynth));
  1116. pData->param.ranges[k].fixValue(fParamBuffers[k]);
  1117. if (pData->param.data[k].midiCC > 0)
  1118. {
  1119. float value(pData->param.ranges[k].getNormalizedValue(fParamBuffers[k]));
  1120. pData->event.portOut->writeControlEvent(0, pData->param.data[k].midiChannel, kEngineControlEventTypeParameter, static_cast<uint16_t>(pData->param.data[k].midiCC), value);
  1121. }
  1122. } // End of Control Output
  1123. #endif
  1124. }
  1125. bool processSingle(float** const outBuffer, const uint32_t frames, const uint32_t timeOffset)
  1126. {
  1127. CARLA_SAFE_ASSERT_RETURN(outBuffer != nullptr, false);
  1128. CARLA_SAFE_ASSERT_RETURN(frames > 0, false);
  1129. // --------------------------------------------------------------------------------------------------------
  1130. // Try lock, silence otherwise
  1131. if (pData->engine->isOffline())
  1132. {
  1133. pData->singleMutex.lock();
  1134. }
  1135. else if (! pData->singleMutex.tryLock())
  1136. {
  1137. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  1138. {
  1139. for (uint32_t k=0; k < frames; ++k)
  1140. outBuffer[i][k+timeOffset] = 0.0f;
  1141. }
  1142. return false;
  1143. }
  1144. // --------------------------------------------------------------------------------------------------------
  1145. // Fill plugin buffers and Run plugin
  1146. if (kUse16Outs)
  1147. {
  1148. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  1149. FloatVectorOperations::clear(fAudio16Buffers[i], static_cast<int>(frames));
  1150. // FIXME use '32' or '16' instead of outs
  1151. fluid_synth_process(fSynth, static_cast<int>(frames), 0, nullptr, static_cast<int>(pData->audioOut.count), fAudio16Buffers);
  1152. }
  1153. else
  1154. fluid_synth_write_float(fSynth, static_cast<int>(frames), outBuffer[0] + timeOffset, 0, 1, outBuffer[1] + timeOffset, 0, 1);
  1155. #ifndef BUILD_BRIDGE
  1156. // --------------------------------------------------------------------------------------------------------
  1157. // Post-processing (volume and balance)
  1158. {
  1159. // note - balance not possible with kUse16Outs, so we can safely skip fAudioOutBuffers
  1160. const bool doVolume = (pData->hints & PLUGIN_CAN_VOLUME) != 0 && carla_isNotEqual(pData->postProc.volume, 1.0f);
  1161. const bool doBalance = (pData->hints & PLUGIN_CAN_BALANCE) != 0 && ! (carla_isEqual(pData->postProc.balanceLeft, -1.0f) && carla_isEqual(pData->postProc.balanceRight, 1.0f));
  1162. float oldBufLeft[doBalance ? frames : 1];
  1163. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  1164. {
  1165. // Balance
  1166. if (doBalance)
  1167. {
  1168. if (i % 2 == 0)
  1169. FloatVectorOperations::copy(oldBufLeft, outBuffer[i]+timeOffset, static_cast<int>(frames));
  1170. float balRangeL = (pData->postProc.balanceLeft + 1.0f)/2.0f;
  1171. float balRangeR = (pData->postProc.balanceRight + 1.0f)/2.0f;
  1172. for (uint32_t k=0; k < frames; ++k)
  1173. {
  1174. if (i % 2 == 0)
  1175. {
  1176. // left
  1177. outBuffer[i][k+timeOffset] = oldBufLeft[k] * (1.0f - balRangeL);
  1178. outBuffer[i][k+timeOffset] += outBuffer[i+1][k+timeOffset] * (1.0f - balRangeR);
  1179. }
  1180. else
  1181. {
  1182. // right
  1183. outBuffer[i][k+timeOffset] = outBuffer[i][k+timeOffset] * balRangeR;
  1184. outBuffer[i][k+timeOffset] += oldBufLeft[k] * balRangeL;
  1185. }
  1186. }
  1187. }
  1188. // Volume
  1189. if (kUse16Outs)
  1190. {
  1191. for (uint32_t k=0; k < frames; ++k)
  1192. outBuffer[i][k+timeOffset] = fAudio16Buffers[i][k] * pData->postProc.volume;
  1193. }
  1194. else if (doVolume)
  1195. {
  1196. for (uint32_t k=0; k < frames; ++k)
  1197. outBuffer[i][k+timeOffset] *= pData->postProc.volume;
  1198. }
  1199. }
  1200. } // End of Post-processing
  1201. #else
  1202. if (kUse16Outs)
  1203. {
  1204. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  1205. {
  1206. for (uint32_t k=0; k < frames; ++k)
  1207. outBuffer[i][k+timeOffset] = fAudio16Buffers[i][k];
  1208. }
  1209. }
  1210. #endif
  1211. // --------------------------------------------------------------------------------------------------------
  1212. pData->singleMutex.unlock();
  1213. return true;
  1214. }
  1215. void bufferSizeChanged(const uint32_t newBufferSize) override
  1216. {
  1217. if (! kUse16Outs)
  1218. return;
  1219. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  1220. {
  1221. if (fAudio16Buffers[i] != nullptr)
  1222. delete[] fAudio16Buffers[i];
  1223. fAudio16Buffers[i] = new float[newBufferSize];
  1224. }
  1225. }
  1226. void sampleRateChanged(const double newSampleRate) override
  1227. {
  1228. CARLA_SAFE_ASSERT_RETURN(fSettings != nullptr,);
  1229. fluid_settings_setnum(fSettings, "synth.sample-rate", newSampleRate);
  1230. #ifdef FLUIDSYNTH_VERSION_NEW_API
  1231. CARLA_SAFE_ASSERT_RETURN(fSynth != nullptr,);
  1232. fluid_synth_set_sample_rate(fSynth, float(newSampleRate));
  1233. #endif
  1234. }
  1235. // -------------------------------------------------------------------
  1236. // Plugin buffers
  1237. void clearBuffers() noexcept override
  1238. {
  1239. carla_debug("CarlaPluginFluidSynth::clearBuffers() - start");
  1240. if (fAudio16Buffers != nullptr)
  1241. {
  1242. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  1243. {
  1244. if (fAudio16Buffers[i] != nullptr)
  1245. {
  1246. delete[] fAudio16Buffers[i];
  1247. fAudio16Buffers[i] = nullptr;
  1248. }
  1249. }
  1250. delete[] fAudio16Buffers;
  1251. fAudio16Buffers = nullptr;
  1252. }
  1253. CarlaPlugin::clearBuffers();
  1254. carla_debug("CarlaPluginFluidSynth::clearBuffers() - end");
  1255. }
  1256. // -------------------------------------------------------------------
  1257. const void* getExtraStuff() const noexcept override
  1258. {
  1259. static const char xtrue[] = "true";
  1260. static const char xfalse[] = "false";
  1261. return kUse16Outs ? xtrue : xfalse;
  1262. }
  1263. // -------------------------------------------------------------------
  1264. bool init(const char* const filename, const char* const name, const char* const label)
  1265. {
  1266. CARLA_SAFE_ASSERT_RETURN(pData->engine != nullptr, false);
  1267. // ---------------------------------------------------------------
  1268. // first checks
  1269. if (pData->client != nullptr)
  1270. {
  1271. pData->engine->setLastError("Plugin client is already registered");
  1272. return false;
  1273. }
  1274. if (fSynth == nullptr)
  1275. {
  1276. pData->engine->setLastError("null synth");
  1277. return false;
  1278. }
  1279. if (filename == nullptr || filename[0] == '\0')
  1280. {
  1281. pData->engine->setLastError("null filename");
  1282. return false;
  1283. }
  1284. if (label == nullptr || label[0] == '\0')
  1285. {
  1286. pData->engine->setLastError("null label");
  1287. return false;
  1288. }
  1289. // ---------------------------------------------------------------
  1290. // open soundfont
  1291. const int synthId(fluid_synth_sfload(fSynth, filename, 0));
  1292. if (synthId < 0)
  1293. {
  1294. pData->engine->setLastError("Failed to load SoundFont file");
  1295. return false;
  1296. }
  1297. fSynthId = static_cast<uint>(synthId);
  1298. // ---------------------------------------------------------------
  1299. // get info
  1300. CarlaString label2(label);
  1301. if (kUse16Outs && ! label2.endsWith(" (16 outs)"))
  1302. label2 += " (16 outs)";
  1303. fLabel = label2.dup();
  1304. pData->filename = carla_strdup(filename);
  1305. if (name != nullptr && name[0] != '\0')
  1306. pData->name = pData->engine->getUniquePluginName(name);
  1307. else
  1308. pData->name = pData->engine->getUniquePluginName(label);
  1309. // ---------------------------------------------------------------
  1310. // register client
  1311. pData->client = pData->engine->addClient(this);
  1312. if (pData->client == nullptr || ! pData->client->isOk())
  1313. {
  1314. pData->engine->setLastError("Failed to register plugin client");
  1315. return false;
  1316. }
  1317. // ---------------------------------------------------------------
  1318. // set default options
  1319. pData->options = 0x0;
  1320. pData->options |= PLUGIN_OPTION_MAP_PROGRAM_CHANGES;
  1321. pData->options |= PLUGIN_OPTION_SEND_CHANNEL_PRESSURE;
  1322. pData->options |= PLUGIN_OPTION_SEND_PITCHBEND;
  1323. pData->options |= PLUGIN_OPTION_SEND_ALL_SOUND_OFF;
  1324. return true;
  1325. }
  1326. private:
  1327. enum FluidSynthParameters {
  1328. FluidSynthReverbOnOff = 0,
  1329. FluidSynthReverbRoomSize = 1,
  1330. FluidSynthReverbDamp = 2,
  1331. FluidSynthReverbLevel = 3,
  1332. FluidSynthReverbWidth = 4,
  1333. FluidSynthChorusOnOff = 5,
  1334. FluidSynthChorusNr = 6,
  1335. FluidSynthChorusLevel = 7,
  1336. FluidSynthChorusSpeedHz = 8,
  1337. FluidSynthChorusDepthMs = 9,
  1338. FluidSynthChorusType = 10,
  1339. FluidSynthPolyphony = 11,
  1340. FluidSynthInterpolation = 12,
  1341. FluidSynthVoiceCount = 13,
  1342. FluidSynthParametersMax = 14
  1343. };
  1344. const bool kUse16Outs;
  1345. fluid_settings_t* fSettings;
  1346. fluid_synth_t* fSynth;
  1347. uint fSynthId;
  1348. float** fAudio16Buffers;
  1349. float fParamBuffers[FluidSynthParametersMax];
  1350. int32_t fCurMidiProgs[MAX_MIDI_CHANNELS];
  1351. const char* fLabel;
  1352. CARLA_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(CarlaPluginFluidSynth)
  1353. };
  1354. CARLA_BACKEND_END_NAMESPACE
  1355. #endif // HAVE_FLUIDSYNTH
  1356. CARLA_BACKEND_START_NAMESPACE
  1357. // -------------------------------------------------------------------------------------------------------------------
  1358. CarlaPlugin* CarlaPlugin::newFluidSynth(const Initializer& init, const bool use16Outs)
  1359. {
  1360. carla_debug("CarlaPlugin::newFluidSynth({%p, \"%s\", \"%s\", \"%s\", " P_INT64 "}, %s)", init.engine, init.filename, init.name, init.label, init.uniqueId, bool2str(use16Outs));
  1361. #ifdef HAVE_FLUIDSYNTH
  1362. if (init.engine->getProccessMode() == ENGINE_PROCESS_MODE_CONTINUOUS_RACK && use16Outs)
  1363. {
  1364. init.engine->setLastError("Carla's rack mode can only work with Stereo modules, please choose the 2-channel only SoundFont version");
  1365. return nullptr;
  1366. }
  1367. if (! fluid_is_soundfont(init.filename))
  1368. {
  1369. init.engine->setLastError("Requested file is not a valid SoundFont");
  1370. return nullptr;
  1371. }
  1372. CarlaPluginFluidSynth* const plugin(new CarlaPluginFluidSynth(init.engine, init.id, use16Outs));
  1373. if (! plugin->init(init.filename, init.name, init.label))
  1374. {
  1375. delete plugin;
  1376. return nullptr;
  1377. }
  1378. return plugin;
  1379. #else
  1380. init.engine->setLastError("fluidsynth support not available");
  1381. return nullptr;
  1382. // unused
  1383. (void)use16Outs;
  1384. #endif
  1385. }
  1386. CarlaPlugin* CarlaPlugin::newFileSF2(const Initializer& init, const bool use16Outs)
  1387. {
  1388. carla_debug("CarlaPlugin::newFileSF2({%p, \"%s\", \"%s\", \"%s\"}, %s)", init.engine, init.filename, init.name, init.label, bool2str(use16Outs));
  1389. #ifdef HAVE_FLUIDSYNTH
  1390. return newFluidSynth(init, use16Outs);
  1391. #else
  1392. init.engine->setLastError("SF2 support not available");
  1393. return nullptr;
  1394. // unused
  1395. (void)use16Outs;
  1396. #endif
  1397. }
  1398. // -------------------------------------------------------------------------------------------------------------------
  1399. CARLA_BACKEND_END_NAMESPACE