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.

1707 lines
62KB

  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 FluidSynthPlugin : public CarlaPlugin
  32. {
  33. public:
  34. FluidSynthPlugin(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_FluidSynthPlugin()
  43. {
  44. carla_debug("FluidSynthPlugin::FluidSynthPlugin(%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. ~FluidSynthPlugin() override
  74. {
  75. carla_debug("FluidSynthPlugin::~FluidSynthPlugin()");
  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("FluidSynthPlugin::setCustomData(%s, \"%s\", \"%s\", %s)", type, key, value, bool2str(sendGui));
  387. if (std::strcmp(type, CUSTOM_DATA_TYPE_STRING) != 0)
  388. return carla_stderr2("FluidSynthPlugin::setCustomData(\"%s\", \"%s\", \"%s\", %s) - type is not string", type, key, value, bool2str(sendGui));
  389. if (std::strcmp(key, "midiPrograms") != 0)
  390. return carla_stderr2("FluidSynthPlugin::setCustomData(\"%s\", \"%s\", \"%s\", %s) - type is not string", type, key, value, bool2str(sendGui));
  391. StringArray midiProgramList(StringArray::fromTokens(value, ":", ""));
  392. if (midiProgramList.size() == MAX_MIDI_CHANNELS)
  393. {
  394. uint8_t channel = 0;
  395. for (String *it=midiProgramList.begin(), *end=midiProgramList.end(); it != end; ++it)
  396. {
  397. const int index(it->getIntValue());
  398. if (index >= 0 && index < static_cast<int>(pData->midiprog.count))
  399. {
  400. const uint32_t bank = pData->midiprog.data[index].bank;
  401. const uint32_t program = pData->midiprog.data[index].program;
  402. fluid_synth_program_select(fSynth, channel, fSynthId, bank, program);
  403. fCurMidiProgs[channel] = index;
  404. if (pData->ctrlChannel == static_cast<int32_t>(channel))
  405. {
  406. pData->midiprog.current = index;
  407. pData->engine->callback(ENGINE_CALLBACK_MIDI_PROGRAM_CHANGED, pData->id, index, 0, 0.0f, nullptr);
  408. }
  409. }
  410. ++channel;
  411. }
  412. CARLA_SAFE_ASSERT(channel == MAX_MIDI_CHANNELS);
  413. }
  414. CarlaPlugin::setCustomData(type, key, value, sendGui);
  415. }
  416. void setMidiProgram(const int32_t index, const bool sendGui, const bool sendOsc, const bool sendCallback) noexcept override
  417. {
  418. CARLA_SAFE_ASSERT_RETURN(fSynth != nullptr,);
  419. CARLA_SAFE_ASSERT_RETURN(index >= -1 && index < static_cast<int32_t>(pData->midiprog.count),);
  420. if (index >= 0 && pData->ctrlChannel >= 0 && pData->ctrlChannel < MAX_MIDI_CHANNELS)
  421. {
  422. const uint32_t bank = pData->midiprog.data[index].bank;
  423. const uint32_t program = pData->midiprog.data[index].program;
  424. //const ScopedSingleProcessLocker spl(this, (sendGui || sendOsc || sendCallback));
  425. try {
  426. fluid_synth_program_select(fSynth, pData->ctrlChannel, fSynthId, bank, program);
  427. } catch(...) {}
  428. fCurMidiProgs[pData->ctrlChannel] = index;
  429. }
  430. CarlaPlugin::setMidiProgram(index, sendGui, sendOsc, sendCallback);
  431. }
  432. // -------------------------------------------------------------------
  433. // Set ui stuff
  434. // nothing
  435. // -------------------------------------------------------------------
  436. // Plugin state
  437. void reload() override
  438. {
  439. CARLA_SAFE_ASSERT_RETURN(pData->engine != nullptr,);
  440. CARLA_SAFE_ASSERT_RETURN(fSynth != nullptr,);
  441. carla_debug("FluidSynthPlugin::reload() - start");
  442. const EngineProcessMode processMode(pData->engine->getProccessMode());
  443. // Safely disable plugin for reload
  444. const ScopedDisabler sd(this);
  445. if (pData->active)
  446. deactivate();
  447. clearBuffers();
  448. uint32_t aOuts, params;
  449. aOuts = kUse16Outs ? 32 : 2;
  450. params = FluidSynthParametersMax;
  451. pData->audioOut.createNew(aOuts);
  452. pData->param.createNew(params, false);
  453. const uint portNameSize(pData->engine->getMaxPortNameSize());
  454. CarlaString portName;
  455. // ---------------------------------------
  456. // Audio Outputs
  457. if (kUse16Outs)
  458. {
  459. for (uint32_t i=0; i < 32; ++i)
  460. {
  461. portName.clear();
  462. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  463. {
  464. portName = pData->name;
  465. portName += ":";
  466. }
  467. portName += "out-";
  468. if ((i+2)/2 < 9)
  469. portName += "0";
  470. portName += CarlaString((i+2)/2);
  471. if (i % 2 == 0)
  472. portName += "L";
  473. else
  474. portName += "R";
  475. portName.truncate(portNameSize);
  476. pData->audioOut.ports[i].port = (CarlaEngineAudioPort*)pData->client->addPort(kEnginePortTypeAudio, portName, false);
  477. pData->audioOut.ports[i].rindex = i;
  478. }
  479. fAudio16Buffers = new float*[aOuts];
  480. for (uint32_t i=0; i < aOuts; ++i)
  481. fAudio16Buffers[i] = nullptr;
  482. }
  483. else
  484. {
  485. // out-left
  486. portName.clear();
  487. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  488. {
  489. portName = pData->name;
  490. portName += ":";
  491. }
  492. portName += "out-left";
  493. portName.truncate(portNameSize);
  494. pData->audioOut.ports[0].port = (CarlaEngineAudioPort*)pData->client->addPort(kEnginePortTypeAudio, portName, false);
  495. pData->audioOut.ports[0].rindex = 0;
  496. // out-right
  497. portName.clear();
  498. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  499. {
  500. portName = pData->name;
  501. portName += ":";
  502. }
  503. portName += "out-right";
  504. portName.truncate(portNameSize);
  505. pData->audioOut.ports[1].port = (CarlaEngineAudioPort*)pData->client->addPort(kEnginePortTypeAudio, portName, false);
  506. pData->audioOut.ports[1].rindex = 1;
  507. }
  508. // ---------------------------------------
  509. // Event Input
  510. {
  511. portName.clear();
  512. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  513. {
  514. portName = pData->name;
  515. portName += ":";
  516. }
  517. portName += "events-in";
  518. portName.truncate(portNameSize);
  519. pData->event.portIn = (CarlaEngineEventPort*)pData->client->addPort(kEnginePortTypeEvent, portName, true);
  520. }
  521. // ---------------------------------------
  522. // Event Output
  523. {
  524. portName.clear();
  525. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  526. {
  527. portName = pData->name;
  528. portName += ":";
  529. }
  530. portName += "events-out";
  531. portName.truncate(portNameSize);
  532. pData->event.portOut = (CarlaEngineEventPort*)pData->client->addPort(kEnginePortTypeEvent, portName, false);
  533. }
  534. // ---------------------------------------
  535. // Parameters
  536. {
  537. int j;
  538. // ----------------------
  539. j = FluidSynthReverbOnOff;
  540. pData->param.data[j].type = PARAMETER_INPUT;
  541. pData->param.data[j].hints = PARAMETER_IS_ENABLED /*| PARAMETER_IS_AUTOMABLE*/ | PARAMETER_IS_BOOLEAN;
  542. pData->param.data[j].index = j;
  543. pData->param.data[j].rindex = j;
  544. pData->param.ranges[j].min = 0.0f;
  545. pData->param.ranges[j].max = 1.0f;
  546. pData->param.ranges[j].def = 1.0f;
  547. pData->param.ranges[j].step = 1.0f;
  548. pData->param.ranges[j].stepSmall = 1.0f;
  549. pData->param.ranges[j].stepLarge = 1.0f;
  550. // ----------------------
  551. j = FluidSynthReverbRoomSize;
  552. pData->param.data[j].type = PARAMETER_INPUT;
  553. pData->param.data[j].hints = PARAMETER_IS_ENABLED /*| PARAMETER_IS_AUTOMABLE*/;
  554. pData->param.data[j].index = j;
  555. pData->param.data[j].rindex = j;
  556. pData->param.ranges[j].min = 0.0f;
  557. pData->param.ranges[j].max = 1.2f;
  558. pData->param.ranges[j].def = FLUID_REVERB_DEFAULT_ROOMSIZE;
  559. pData->param.ranges[j].step = 0.01f;
  560. pData->param.ranges[j].stepSmall = 0.0001f;
  561. pData->param.ranges[j].stepLarge = 0.1f;
  562. // ----------------------
  563. j = FluidSynthReverbDamp;
  564. pData->param.data[j].type = PARAMETER_INPUT;
  565. pData->param.data[j].hints = PARAMETER_IS_ENABLED /*| PARAMETER_IS_AUTOMABLE*/;
  566. pData->param.data[j].index = j;
  567. pData->param.data[j].rindex = j;
  568. pData->param.ranges[j].min = 0.0f;
  569. pData->param.ranges[j].max = 1.0f;
  570. pData->param.ranges[j].def = FLUID_REVERB_DEFAULT_DAMP;
  571. pData->param.ranges[j].step = 0.01f;
  572. pData->param.ranges[j].stepSmall = 0.0001f;
  573. pData->param.ranges[j].stepLarge = 0.1f;
  574. // ----------------------
  575. j = FluidSynthReverbLevel;
  576. pData->param.data[j].type = PARAMETER_INPUT;
  577. pData->param.data[j].hints = PARAMETER_IS_ENABLED /*| PARAMETER_IS_AUTOMABLE*/;
  578. pData->param.data[j].index = j;
  579. pData->param.data[j].rindex = j;
  580. pData->param.data[j].midiCC = MIDI_CONTROL_REVERB_SEND_LEVEL;
  581. pData->param.ranges[j].min = 0.0f;
  582. pData->param.ranges[j].max = 1.0f;
  583. pData->param.ranges[j].def = FLUID_REVERB_DEFAULT_LEVEL;
  584. pData->param.ranges[j].step = 0.01f;
  585. pData->param.ranges[j].stepSmall = 0.0001f;
  586. pData->param.ranges[j].stepLarge = 0.1f;
  587. // ----------------------
  588. j = FluidSynthReverbWidth;
  589. pData->param.data[j].type = PARAMETER_INPUT;
  590. pData->param.data[j].hints = PARAMETER_IS_ENABLED /*| PARAMETER_IS_AUTOMABLE*/;
  591. pData->param.data[j].index = j;
  592. pData->param.data[j].rindex = j;
  593. pData->param.ranges[j].min = 0.0f;
  594. pData->param.ranges[j].max = 10.0f; // should be 100, but that sounds too much
  595. pData->param.ranges[j].def = FLUID_REVERB_DEFAULT_WIDTH;
  596. pData->param.ranges[j].step = 0.01f;
  597. pData->param.ranges[j].stepSmall = 0.0001f;
  598. pData->param.ranges[j].stepLarge = 0.1f;
  599. // ----------------------
  600. j = FluidSynthChorusOnOff;
  601. pData->param.data[j].type = PARAMETER_INPUT;
  602. pData->param.data[j].hints = PARAMETER_IS_ENABLED | PARAMETER_IS_BOOLEAN;
  603. pData->param.data[j].index = j;
  604. pData->param.data[j].rindex = j;
  605. pData->param.ranges[j].min = 0.0f;
  606. pData->param.ranges[j].max = 1.0f;
  607. pData->param.ranges[j].def = 1.0f;
  608. pData->param.ranges[j].step = 1.0f;
  609. pData->param.ranges[j].stepSmall = 1.0f;
  610. pData->param.ranges[j].stepLarge = 1.0f;
  611. // ----------------------
  612. j = FluidSynthChorusNr;
  613. pData->param.data[j].type = PARAMETER_INPUT;
  614. pData->param.data[j].hints = PARAMETER_IS_ENABLED | PARAMETER_IS_INTEGER;
  615. pData->param.data[j].index = j;
  616. pData->param.data[j].rindex = j;
  617. pData->param.ranges[j].min = 0.0f;
  618. pData->param.ranges[j].max = 99.0f;
  619. pData->param.ranges[j].def = FLUID_CHORUS_DEFAULT_N;
  620. pData->param.ranges[j].step = 1.0f;
  621. pData->param.ranges[j].stepSmall = 1.0f;
  622. pData->param.ranges[j].stepLarge = 10.0f;
  623. // ----------------------
  624. j = FluidSynthChorusLevel;
  625. pData->param.data[j].type = PARAMETER_INPUT;
  626. pData->param.data[j].hints = PARAMETER_IS_ENABLED;
  627. pData->param.data[j].index = j;
  628. pData->param.data[j].rindex = j;
  629. pData->param.ranges[j].min = 0.0f;
  630. pData->param.ranges[j].max = 10.0f;
  631. pData->param.ranges[j].def = FLUID_CHORUS_DEFAULT_LEVEL;
  632. pData->param.ranges[j].step = 0.01f;
  633. pData->param.ranges[j].stepSmall = 0.0001f;
  634. pData->param.ranges[j].stepLarge = 0.1f;
  635. // ----------------------
  636. j = FluidSynthChorusSpeedHz;
  637. pData->param.data[j].type = PARAMETER_INPUT;
  638. pData->param.data[j].hints = PARAMETER_IS_ENABLED;
  639. pData->param.data[j].index = j;
  640. pData->param.data[j].rindex = j;
  641. pData->param.ranges[j].min = 0.29f;
  642. pData->param.ranges[j].max = 5.0f;
  643. pData->param.ranges[j].def = FLUID_CHORUS_DEFAULT_SPEED;
  644. pData->param.ranges[j].step = 0.01f;
  645. pData->param.ranges[j].stepSmall = 0.0001f;
  646. pData->param.ranges[j].stepLarge = 0.1f;
  647. // ----------------------
  648. j = FluidSynthChorusDepthMs;
  649. pData->param.data[j].type = PARAMETER_INPUT;
  650. pData->param.data[j].hints = PARAMETER_IS_ENABLED;
  651. pData->param.data[j].index = j;
  652. pData->param.data[j].rindex = j;
  653. pData->param.ranges[j].min = 0.0f;
  654. pData->param.ranges[j].max = float(2048.0 * 1000.0 / pData->engine->getSampleRate()); // FIXME?
  655. pData->param.ranges[j].def = FLUID_CHORUS_DEFAULT_DEPTH;
  656. pData->param.ranges[j].step = 0.01f;
  657. pData->param.ranges[j].stepSmall = 0.0001f;
  658. pData->param.ranges[j].stepLarge = 0.1f;
  659. // ----------------------
  660. j = FluidSynthChorusType;
  661. pData->param.data[j].type = PARAMETER_INPUT;
  662. pData->param.data[j].hints = PARAMETER_IS_ENABLED | PARAMETER_IS_INTEGER | PARAMETER_USES_SCALEPOINTS;
  663. pData->param.data[j].index = j;
  664. pData->param.data[j].rindex = j;
  665. pData->param.ranges[j].min = FLUID_CHORUS_MOD_SINE;
  666. pData->param.ranges[j].max = FLUID_CHORUS_MOD_TRIANGLE;
  667. pData->param.ranges[j].def = FLUID_CHORUS_DEFAULT_TYPE;
  668. pData->param.ranges[j].step = 1.0f;
  669. pData->param.ranges[j].stepSmall = 1.0f;
  670. pData->param.ranges[j].stepLarge = 1.0f;
  671. // ----------------------
  672. j = FluidSynthPolyphony;
  673. pData->param.data[j].type = PARAMETER_INPUT;
  674. pData->param.data[j].hints = PARAMETER_IS_ENABLED | PARAMETER_IS_INTEGER;
  675. pData->param.data[j].index = j;
  676. pData->param.data[j].rindex = j;
  677. pData->param.ranges[j].min = 1.0f;
  678. pData->param.ranges[j].max = 512.0f; // max theoric is 65535
  679. pData->param.ranges[j].def = (float)fluid_synth_get_polyphony(fSynth);
  680. pData->param.ranges[j].step = 1.0f;
  681. pData->param.ranges[j].stepSmall = 1.0f;
  682. pData->param.ranges[j].stepLarge = 10.0f;
  683. // ----------------------
  684. j = FluidSynthInterpolation;
  685. pData->param.data[j].type = PARAMETER_INPUT;
  686. pData->param.data[j].hints = PARAMETER_IS_ENABLED | PARAMETER_IS_INTEGER | PARAMETER_USES_SCALEPOINTS;
  687. pData->param.data[j].index = j;
  688. pData->param.data[j].rindex = j;
  689. pData->param.ranges[j].min = FLUID_INTERP_NONE;
  690. pData->param.ranges[j].max = FLUID_INTERP_HIGHEST;
  691. pData->param.ranges[j].def = FLUID_INTERP_DEFAULT;
  692. pData->param.ranges[j].step = 1.0f;
  693. pData->param.ranges[j].stepSmall = 1.0f;
  694. pData->param.ranges[j].stepLarge = 1.0f;
  695. // ----------------------
  696. j = FluidSynthVoiceCount;
  697. pData->param.data[j].type = PARAMETER_OUTPUT;
  698. pData->param.data[j].hints = PARAMETER_IS_ENABLED | PARAMETER_IS_AUTOMABLE | PARAMETER_IS_INTEGER;
  699. pData->param.data[j].index = j;
  700. pData->param.data[j].rindex = j;
  701. pData->param.ranges[j].min = 0.0f;
  702. pData->param.ranges[j].max = 65535.0f;
  703. pData->param.ranges[j].def = 0.0f;
  704. pData->param.ranges[j].step = 1.0f;
  705. pData->param.ranges[j].stepSmall = 1.0f;
  706. pData->param.ranges[j].stepLarge = 1.0f;
  707. for (j=0; j<FluidSynthParametersMax; ++j)
  708. fParamBuffers[j] = pData->param.ranges[j].def;
  709. }
  710. // ---------------------------------------
  711. // plugin hints
  712. pData->hints = 0x0;
  713. pData->hints |= PLUGIN_IS_SYNTH;
  714. pData->hints |= PLUGIN_CAN_VOLUME;
  715. if (! kUse16Outs)
  716. pData->hints |= PLUGIN_CAN_BALANCE;
  717. // extra plugin hints
  718. pData->extraHints = 0x0;
  719. pData->extraHints |= PLUGIN_EXTRA_HINT_HAS_MIDI_IN;
  720. pData->extraHints |= PLUGIN_EXTRA_HINT_USES_MULTI_PROGS;
  721. if (kUse16Outs)
  722. pData->extraHints |= PLUGIN_EXTRA_HINT_CAN_RUN_RACK;
  723. bufferSizeChanged(pData->engine->getBufferSize());
  724. reloadPrograms(true);
  725. if (pData->active)
  726. activate();
  727. carla_debug("FluidSynthPlugin::reload() - end");
  728. }
  729. void reloadPrograms(const bool doInit) override
  730. {
  731. carla_debug("FluidSynthPlugin::reloadPrograms(%s)", bool2str(doInit));
  732. // save drum info in case we have one program for it
  733. bool hasDrums = false;
  734. uint32_t drumIndex, drumProg;
  735. drumIndex = drumProg = 0;
  736. // Delete old programs
  737. pData->midiprog.clear();
  738. // Query new programs
  739. uint32_t count = 0;
  740. if (fluid_sfont_t* const f_sfont = fluid_synth_get_sfont_by_id(fSynth, fSynthId))
  741. {
  742. fluid_preset_t f_preset;
  743. // initial check to know how many midi-programs we have
  744. f_sfont->iteration_start(f_sfont);
  745. for (; f_sfont->iteration_next(f_sfont, &f_preset);)
  746. ++count;
  747. // sound kits must always have at least 1 midi-program
  748. CARLA_SAFE_ASSERT_RETURN(count > 0,);
  749. pData->midiprog.createNew(count);
  750. // Update data
  751. int tmp;
  752. uint32_t i = 0;
  753. f_sfont->iteration_start(f_sfont);
  754. for (; f_sfont->iteration_next(f_sfont, &f_preset);)
  755. {
  756. CARLA_SAFE_ASSERT_BREAK(i < count);
  757. tmp = f_preset.get_banknum(&f_preset);
  758. pData->midiprog.data[i].bank = (tmp >= 0) ? static_cast<uint32_t>(tmp) : 0;
  759. tmp = f_preset.get_num(&f_preset);
  760. pData->midiprog.data[i].program = (tmp >= 0) ? static_cast<uint32_t>(tmp) : 0;
  761. pData->midiprog.data[i].name = carla_strdup(f_preset.get_name(&f_preset));
  762. if (pData->midiprog.data[i].bank == 128 && ! hasDrums)
  763. {
  764. hasDrums = true;
  765. drumIndex = i;
  766. drumProg = pData->midiprog.data[i].program;
  767. }
  768. ++i;
  769. }
  770. }
  771. else
  772. {
  773. // failing means 0 midi-programs, it shouldn't happen!
  774. carla_safe_assert("fluid_sfont_t* const f_sfont = fluid_synth_get_sfont_by_id(fSynth, fSynthId)", __FILE__, __LINE__);
  775. return;
  776. }
  777. #ifndef BUILD_BRIDGE
  778. // Update OSC Names
  779. if (pData->engine->isOscControlRegistered())
  780. {
  781. pData->engine->oscSend_control_set_midi_program_count(pData->id, count);
  782. for (uint32_t i=0; i < count; ++i)
  783. 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);
  784. }
  785. #endif
  786. if (doInit)
  787. {
  788. fluid_synth_program_reset(fSynth);
  789. // select first program, or 128 for ch10
  790. for (int i=0; i < MAX_MIDI_CHANNELS && i != 9; ++i)
  791. {
  792. #ifdef FLUIDSYNTH_VERSION_NEW_API
  793. fluid_synth_set_channel_type(fSynth, i, CHANNEL_TYPE_MELODIC);
  794. #endif
  795. fluid_synth_program_select(fSynth, i, fSynthId, pData->midiprog.data[0].bank, pData->midiprog.data[0].program);
  796. fCurMidiProgs[i] = 0;
  797. }
  798. if (hasDrums)
  799. {
  800. #ifdef FLUIDSYNTH_VERSION_NEW_API
  801. fluid_synth_set_channel_type(fSynth, 9, CHANNEL_TYPE_DRUM);
  802. #endif
  803. fluid_synth_program_select(fSynth, 9, fSynthId, 128, drumProg);
  804. fCurMidiProgs[9] = static_cast<int32_t>(drumIndex);
  805. }
  806. else
  807. {
  808. #ifdef FLUIDSYNTH_VERSION_NEW_API
  809. fluid_synth_set_channel_type(fSynth, 9, CHANNEL_TYPE_MELODIC);
  810. #endif
  811. fluid_synth_program_select(fSynth, 9, fSynthId, pData->midiprog.data[0].bank, pData->midiprog.data[0].program);
  812. fCurMidiProgs[9] = 0;
  813. }
  814. pData->midiprog.current = 0;
  815. }
  816. else
  817. {
  818. pData->engine->callback(ENGINE_CALLBACK_RELOAD_PROGRAMS, pData->id, 0, 0, 0.0f, nullptr);
  819. }
  820. }
  821. // -------------------------------------------------------------------
  822. // Plugin processing
  823. void process(float** const, float** const outBuffer, const uint32_t frames) override
  824. {
  825. // --------------------------------------------------------------------------------------------------------
  826. // Check if active
  827. if (! pData->active)
  828. {
  829. // disable any output sound
  830. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  831. FloatVectorOperations::clear(outBuffer[i], static_cast<int>(frames));
  832. return;
  833. }
  834. // --------------------------------------------------------------------------------------------------------
  835. // Check if needs reset
  836. if (pData->needsReset)
  837. {
  838. if (pData->options & PLUGIN_OPTION_SEND_ALL_SOUND_OFF)
  839. {
  840. for (int i=0; i < MAX_MIDI_CHANNELS; ++i)
  841. {
  842. #ifdef FLUIDSYNTH_VERSION_NEW_API
  843. fluid_synth_all_notes_off(fSynth, i);
  844. fluid_synth_all_sounds_off(fSynth, i);
  845. #else
  846. fluid_synth_cc(fSynth, i, MIDI_CONTROL_ALL_SOUND_OFF, 0);
  847. fluid_synth_cc(fSynth, i, MIDI_CONTROL_ALL_NOTES_OFF, 0);
  848. #endif
  849. }
  850. }
  851. else if (pData->ctrlChannel >= 0 && pData->ctrlChannel < MAX_MIDI_CHANNELS)
  852. {
  853. for (int i=0; i < MAX_MIDI_NOTE; ++i)
  854. fluid_synth_noteoff(fSynth, pData->ctrlChannel, i);
  855. }
  856. pData->needsReset = false;
  857. }
  858. // --------------------------------------------------------------------------------------------------------
  859. // Event Input and Processing
  860. {
  861. // ----------------------------------------------------------------------------------------------------
  862. // MIDI Input (External)
  863. if (pData->extNotes.mutex.tryLock())
  864. {
  865. for (RtLinkedList<ExternalMidiNote>::Itenerator it = pData->extNotes.data.begin(); it.valid(); it.next())
  866. {
  867. const ExternalMidiNote& note(it.getValue());
  868. CARLA_SAFE_ASSERT_CONTINUE(note.channel >= 0 && note.channel < MAX_MIDI_CHANNELS);
  869. if (note.velo > 0)
  870. fluid_synth_noteon(fSynth, note.channel, note.note, note.velo);
  871. else
  872. fluid_synth_noteoff(fSynth,note.channel, note.note);
  873. }
  874. pData->extNotes.data.clear();
  875. pData->extNotes.mutex.unlock();
  876. } // End of MIDI Input (External)
  877. // ----------------------------------------------------------------------------------------------------
  878. // Event Input (System)
  879. #ifndef BUILD_BRIDGE
  880. bool allNotesOffSent = false;
  881. #endif
  882. uint32_t time, nEvents = pData->event.portIn->getEventCount();
  883. uint32_t timeOffset = 0;
  884. uint32_t nextBankIds[MAX_MIDI_CHANNELS] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 0, 0, 0, 0, 0, 0 };
  885. if (pData->midiprog.current >= 0 && pData->midiprog.count > 0 && pData->ctrlChannel >= 0 && pData->ctrlChannel < MAX_MIDI_CHANNELS)
  886. nextBankIds[pData->ctrlChannel] = pData->midiprog.data[pData->midiprog.current].bank;
  887. for (uint32_t i=0; i < nEvents; ++i)
  888. {
  889. const EngineEvent& event(pData->event.portIn->getEvent(i));
  890. time = event.time;
  891. CARLA_SAFE_ASSERT_CONTINUE(time < frames);
  892. CARLA_SAFE_ASSERT_BREAK(time >= timeOffset);
  893. if (time > timeOffset)
  894. {
  895. if (processSingle(outBuffer, time - timeOffset, timeOffset))
  896. {
  897. timeOffset = time;
  898. if (pData->midiprog.current >= 0 && pData->midiprog.count > 0 && pData->ctrlChannel >= 0 && pData->ctrlChannel < MAX_MIDI_CHANNELS)
  899. nextBankIds[pData->ctrlChannel] = pData->midiprog.data[pData->midiprog.current].bank;
  900. }
  901. }
  902. // Control change
  903. switch (event.type)
  904. {
  905. case kEngineEventTypeNull:
  906. break;
  907. case kEngineEventTypeControl:
  908. {
  909. const EngineControlEvent& ctrlEvent = event.ctrl;
  910. switch (ctrlEvent.type)
  911. {
  912. case kEngineControlEventTypeNull:
  913. break;
  914. case kEngineControlEventTypeParameter:
  915. {
  916. #ifndef BUILD_BRIDGE
  917. // Control backend stuff
  918. if (event.channel == pData->ctrlChannel)
  919. {
  920. float value;
  921. if (MIDI_IS_CONTROL_BREATH_CONTROLLER(ctrlEvent.param) && (pData->hints & PLUGIN_CAN_DRYWET) != 0)
  922. {
  923. value = ctrlEvent.value;
  924. setDryWet(value, false, false);
  925. pData->postponeRtEvent(kPluginPostRtEventParameterChange, PARAMETER_DRYWET, 0, value);
  926. }
  927. if (MIDI_IS_CONTROL_CHANNEL_VOLUME(ctrlEvent.param) && (pData->hints & PLUGIN_CAN_VOLUME) != 0)
  928. {
  929. value = ctrlEvent.value*127.0f/100.0f;
  930. setVolume(value, false, false);
  931. pData->postponeRtEvent(kPluginPostRtEventParameterChange, PARAMETER_VOLUME, 0, value);
  932. }
  933. if (MIDI_IS_CONTROL_BALANCE(ctrlEvent.param) && (pData->hints & PLUGIN_CAN_BALANCE) != 0)
  934. {
  935. float left, right;
  936. value = ctrlEvent.value/0.5f - 1.0f;
  937. if (value < 0.0f)
  938. {
  939. left = -1.0f;
  940. right = (value*2.0f)+1.0f;
  941. }
  942. else if (value > 0.0f)
  943. {
  944. left = (value*2.0f)-1.0f;
  945. right = 1.0f;
  946. }
  947. else
  948. {
  949. left = -1.0f;
  950. right = 1.0f;
  951. }
  952. setBalanceLeft(left, false, false);
  953. setBalanceRight(right, false, false);
  954. pData->postponeRtEvent(kPluginPostRtEventParameterChange, PARAMETER_BALANCE_LEFT, 0, left);
  955. pData->postponeRtEvent(kPluginPostRtEventParameterChange, PARAMETER_BALANCE_RIGHT, 0, right);
  956. }
  957. }
  958. #endif
  959. // Control plugin parameters
  960. for (uint32_t k=0; k < pData->param.count; ++k)
  961. {
  962. if (pData->param.data[k].midiChannel != event.channel)
  963. continue;
  964. if (pData->param.data[k].midiCC != ctrlEvent.param)
  965. continue;
  966. if (pData->param.data[k].hints != PARAMETER_INPUT)
  967. continue;
  968. if ((pData->param.data[k].hints & PARAMETER_IS_AUTOMABLE) == 0)
  969. continue;
  970. float value;
  971. if (pData->param.data[k].hints & PARAMETER_IS_BOOLEAN)
  972. {
  973. value = (ctrlEvent.value < 0.5f) ? pData->param.ranges[k].min : pData->param.ranges[k].max;
  974. }
  975. else
  976. {
  977. value = pData->param.ranges[k].getUnnormalizedValue(ctrlEvent.value);
  978. if (pData->param.data[k].hints & PARAMETER_IS_INTEGER)
  979. value = std::rint(value);
  980. }
  981. setParameterValue(k, value, false, false, false);
  982. pData->postponeRtEvent(kPluginPostRtEventParameterChange, static_cast<int32_t>(k), 0, value);
  983. }
  984. if ((pData->options & PLUGIN_OPTION_SEND_CONTROL_CHANGES) != 0 && ctrlEvent.param <= 0x5F)
  985. {
  986. fluid_synth_cc(fSynth, event.channel, ctrlEvent.param, int(ctrlEvent.value*127.0f));
  987. }
  988. break;
  989. }
  990. case kEngineControlEventTypeMidiBank:
  991. if (event.channel < MAX_MIDI_CHANNELS && (pData->options & PLUGIN_OPTION_MAP_PROGRAM_CHANGES) != 0)
  992. nextBankIds[event.channel] = ctrlEvent.param;
  993. break;
  994. case kEngineControlEventTypeMidiProgram:
  995. if (event.channel < MAX_MIDI_CHANNELS && (pData->options & PLUGIN_OPTION_MAP_PROGRAM_CHANGES) != 0)
  996. {
  997. const uint32_t bankId(nextBankIds[event.channel]);
  998. const uint32_t progId(ctrlEvent.param);
  999. for (uint32_t k=0; k < pData->midiprog.count; ++k)
  1000. {
  1001. if (pData->midiprog.data[k].bank == bankId && pData->midiprog.data[k].program == progId)
  1002. {
  1003. fluid_synth_program_select(fSynth, event.channel, fSynthId, bankId, progId);
  1004. fCurMidiProgs[event.channel] = static_cast<int32_t>(k);
  1005. if (event.channel == pData->ctrlChannel)
  1006. pData->postponeRtEvent(kPluginPostRtEventMidiProgramChange, static_cast<int32_t>(k), 0, 0.0f);
  1007. break;
  1008. }
  1009. }
  1010. }
  1011. break;
  1012. case kEngineControlEventTypeAllSoundOff:
  1013. if (pData->options & PLUGIN_OPTION_SEND_ALL_SOUND_OFF)
  1014. {
  1015. #ifdef FLUIDSYNTH_VERSION_NEW_API
  1016. fluid_synth_all_sounds_off(fSynth, event.channel);
  1017. #else
  1018. fluid_synth_cc(fSynth, event.channel, MIDI_CONTROL_ALL_SOUND_OFF, 0);
  1019. #endif
  1020. }
  1021. break;
  1022. case kEngineControlEventTypeAllNotesOff:
  1023. if (pData->options & PLUGIN_OPTION_SEND_ALL_SOUND_OFF)
  1024. {
  1025. #ifndef BUILD_BRIDGE
  1026. if (event.channel == pData->ctrlChannel && ! allNotesOffSent)
  1027. {
  1028. allNotesOffSent = true;
  1029. sendMidiAllNotesOffToCallback();
  1030. }
  1031. #endif
  1032. #ifdef FLUIDSYNTH_VERSION_NEW_API
  1033. fluid_synth_all_notes_off(fSynth, event.channel);
  1034. #else
  1035. fluid_synth_cc(fSynth, event.channel, MIDI_CONTROL_ALL_NOTES_OFF, 0);
  1036. #endif
  1037. }
  1038. break;
  1039. }
  1040. break;
  1041. }
  1042. case kEngineEventTypeMidi:
  1043. {
  1044. const EngineMidiEvent& midiEvent(event.midi);
  1045. uint8_t status = uint8_t(MIDI_GET_STATUS_FROM_DATA(midiEvent.data));
  1046. uint8_t channel = event.channel;
  1047. // Fix bad note-off
  1048. if (MIDI_IS_STATUS_NOTE_ON(status) && midiEvent.data[2] == 0)
  1049. status = MIDI_STATUS_NOTE_OFF;
  1050. if (MIDI_IS_STATUS_NOTE_OFF(status))
  1051. {
  1052. const uint8_t note = midiEvent.data[1];
  1053. fluid_synth_noteoff(fSynth, channel, note);
  1054. pData->postponeRtEvent(kPluginPostRtEventNoteOff, channel, note, 0.0f);
  1055. }
  1056. else if (MIDI_IS_STATUS_NOTE_ON(status))
  1057. {
  1058. const uint8_t note = midiEvent.data[1];
  1059. const uint8_t velo = midiEvent.data[2];
  1060. fluid_synth_noteon(fSynth, channel, note, velo);
  1061. pData->postponeRtEvent(kPluginPostRtEventNoteOn, channel, note, velo);
  1062. }
  1063. else if (MIDI_IS_STATUS_POLYPHONIC_AFTERTOUCH(status) && (pData->options & PLUGIN_OPTION_SEND_NOTE_AFTERTOUCH) != 0)
  1064. {
  1065. //const uint8_t note = midiEvent.data[1];
  1066. //const uint8_t pressure = midiEvent.data[2];
  1067. // TODO, not in fluidsynth API
  1068. }
  1069. else if (MIDI_IS_STATUS_CONTROL_CHANGE(status) && (pData->options & PLUGIN_OPTION_SEND_CONTROL_CHANGES) != 0)
  1070. {
  1071. const uint8_t control = midiEvent.data[1];
  1072. const uint8_t value = midiEvent.data[2];
  1073. fluid_synth_cc(fSynth, channel, control, value);
  1074. }
  1075. else if (MIDI_IS_STATUS_CHANNEL_PRESSURE(status) && (pData->options & PLUGIN_OPTION_SEND_CHANNEL_PRESSURE) != 0)
  1076. {
  1077. const uint8_t pressure = midiEvent.data[1];
  1078. fluid_synth_channel_pressure(fSynth, channel, pressure);;
  1079. }
  1080. else if (MIDI_IS_STATUS_PITCH_WHEEL_CONTROL(status) && (pData->options & PLUGIN_OPTION_SEND_PITCHBEND) != 0)
  1081. {
  1082. const uint8_t lsb = midiEvent.data[1];
  1083. const uint8_t msb = midiEvent.data[2];
  1084. const int value = ((msb << 7) | lsb);
  1085. fluid_synth_pitch_bend(fSynth, channel, value);
  1086. }
  1087. break;
  1088. }
  1089. }
  1090. }
  1091. pData->postRtEvents.trySplice();
  1092. if (frames > timeOffset)
  1093. processSingle(outBuffer, frames - timeOffset, timeOffset);
  1094. } // End of Event Input and Processing
  1095. #ifndef BUILD_BRIDGE
  1096. // --------------------------------------------------------------------------------------------------------
  1097. // Control Output
  1098. {
  1099. uint32_t k = FluidSynthVoiceCount;
  1100. fParamBuffers[k] = float(fluid_synth_get_active_voice_count(fSynth));
  1101. pData->param.ranges[k].fixValue(fParamBuffers[k]);
  1102. if (pData->param.data[k].midiCC > 0)
  1103. {
  1104. float value(pData->param.ranges[k].getNormalizedValue(fParamBuffers[k]));
  1105. pData->event.portOut->writeControlEvent(0, pData->param.data[k].midiChannel, kEngineControlEventTypeParameter, static_cast<uint16_t>(pData->param.data[k].midiCC), value);
  1106. }
  1107. } // End of Control Output
  1108. #endif
  1109. }
  1110. bool processSingle(float** const outBuffer, const uint32_t frames, const uint32_t timeOffset)
  1111. {
  1112. CARLA_SAFE_ASSERT_RETURN(outBuffer != nullptr, false);
  1113. CARLA_SAFE_ASSERT_RETURN(frames > 0, false);
  1114. // --------------------------------------------------------------------------------------------------------
  1115. // Try lock, silence otherwise
  1116. if (pData->engine->isOffline())
  1117. {
  1118. pData->singleMutex.lock();
  1119. }
  1120. else if (! pData->singleMutex.tryLock())
  1121. {
  1122. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  1123. {
  1124. for (uint32_t k=0; k < frames; ++k)
  1125. outBuffer[i][k+timeOffset] = 0.0f;
  1126. }
  1127. return false;
  1128. }
  1129. // --------------------------------------------------------------------------------------------------------
  1130. // Fill plugin buffers and Run plugin
  1131. if (kUse16Outs)
  1132. {
  1133. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  1134. FloatVectorOperations::clear(fAudio16Buffers[i], static_cast<int>(frames));
  1135. // FIXME use '32' or '16' instead of outs
  1136. fluid_synth_process(fSynth, static_cast<int>(frames), 0, nullptr, static_cast<int>(pData->audioOut.count), fAudio16Buffers);
  1137. }
  1138. else
  1139. fluid_synth_write_float(fSynth, static_cast<int>(frames), outBuffer[0] + timeOffset, 0, 1, outBuffer[1] + timeOffset, 0, 1);
  1140. #ifndef BUILD_BRIDGE
  1141. // --------------------------------------------------------------------------------------------------------
  1142. // Post-processing (volume and balance)
  1143. {
  1144. // note - balance not possible with kUse16Outs, so we can safely skip fAudioOutBuffers
  1145. const bool doVolume = (pData->hints & PLUGIN_CAN_VOLUME) != 0 && ! carla_compareFloats(pData->postProc.volume, 1.0f);
  1146. const bool doBalance = (pData->hints & PLUGIN_CAN_BALANCE) != 0 && ! (carla_compareFloats(pData->postProc.balanceLeft, -1.0f) && carla_compareFloats(pData->postProc.balanceRight, 1.0f));
  1147. float oldBufLeft[doBalance ? frames : 1];
  1148. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  1149. {
  1150. // Balance
  1151. if (doBalance)
  1152. {
  1153. if (i % 2 == 0)
  1154. FloatVectorOperations::copy(oldBufLeft, outBuffer[i]+timeOffset, static_cast<int>(frames));
  1155. float balRangeL = (pData->postProc.balanceLeft + 1.0f)/2.0f;
  1156. float balRangeR = (pData->postProc.balanceRight + 1.0f)/2.0f;
  1157. for (uint32_t k=0; k < frames; ++k)
  1158. {
  1159. if (i % 2 == 0)
  1160. {
  1161. // left
  1162. outBuffer[i][k+timeOffset] = oldBufLeft[k] * (1.0f - balRangeL);
  1163. outBuffer[i][k+timeOffset] += outBuffer[i+1][k+timeOffset] * (1.0f - balRangeR);
  1164. }
  1165. else
  1166. {
  1167. // right
  1168. outBuffer[i][k+timeOffset] = outBuffer[i][k+timeOffset] * balRangeR;
  1169. outBuffer[i][k+timeOffset] += oldBufLeft[k] * balRangeL;
  1170. }
  1171. }
  1172. }
  1173. // Volume
  1174. if (kUse16Outs)
  1175. {
  1176. for (uint32_t k=0; k < frames; ++k)
  1177. outBuffer[i][k+timeOffset] = fAudio16Buffers[i][k] * pData->postProc.volume;
  1178. }
  1179. else if (doVolume)
  1180. {
  1181. for (uint32_t k=0; k < frames; ++k)
  1182. outBuffer[i][k+timeOffset] *= pData->postProc.volume;
  1183. }
  1184. }
  1185. } // End of Post-processing
  1186. #else
  1187. if (kUse16Outs)
  1188. {
  1189. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  1190. {
  1191. for (uint32_t k=0; k < frames; ++k)
  1192. outBuffer[i][k+timeOffset] = fAudio16Buffers[i][k];
  1193. }
  1194. }
  1195. #endif
  1196. // --------------------------------------------------------------------------------------------------------
  1197. pData->singleMutex.unlock();
  1198. return true;
  1199. }
  1200. void bufferSizeChanged(const uint32_t newBufferSize) override
  1201. {
  1202. if (! kUse16Outs)
  1203. return;
  1204. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  1205. {
  1206. if (fAudio16Buffers[i] != nullptr)
  1207. delete[] fAudio16Buffers[i];
  1208. fAudio16Buffers[i] = new float[newBufferSize];
  1209. }
  1210. }
  1211. void sampleRateChanged(const double newSampleRate) override
  1212. {
  1213. CARLA_SAFE_ASSERT_RETURN(fSettings != nullptr,);
  1214. fluid_settings_setnum(fSettings, "synth.sample-rate", newSampleRate);
  1215. #ifdef FLUIDSYNTH_VERSION_NEW_API
  1216. CARLA_SAFE_ASSERT_RETURN(fSynth != nullptr,);
  1217. fluid_synth_set_sample_rate(fSynth, float(newSampleRate));
  1218. #endif
  1219. }
  1220. // -------------------------------------------------------------------
  1221. // Plugin buffers
  1222. void clearBuffers() noexcept override
  1223. {
  1224. carla_debug("FluidSynthPlugin::clearBuffers() - start");
  1225. if (fAudio16Buffers != nullptr)
  1226. {
  1227. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  1228. {
  1229. if (fAudio16Buffers[i] != nullptr)
  1230. {
  1231. delete[] fAudio16Buffers[i];
  1232. fAudio16Buffers[i] = nullptr;
  1233. }
  1234. }
  1235. delete[] fAudio16Buffers;
  1236. fAudio16Buffers = nullptr;
  1237. }
  1238. CarlaPlugin::clearBuffers();
  1239. carla_debug("FluidSynthPlugin::clearBuffers() - end");
  1240. }
  1241. // -------------------------------------------------------------------
  1242. const void* getExtraStuff() const noexcept override
  1243. {
  1244. static const char xtrue[] = "true";
  1245. static const char xfalse[] = "false";
  1246. return kUse16Outs ? xtrue : xfalse;
  1247. }
  1248. // -------------------------------------------------------------------
  1249. bool init(const char* const filename, const char* const name, const char* const label)
  1250. {
  1251. CARLA_SAFE_ASSERT_RETURN(pData->engine != nullptr, false);
  1252. // ---------------------------------------------------------------
  1253. // first checks
  1254. if (pData->client != nullptr)
  1255. {
  1256. pData->engine->setLastError("Plugin client is already registered");
  1257. return false;
  1258. }
  1259. if (fSynth == nullptr)
  1260. {
  1261. pData->engine->setLastError("null synth");
  1262. return false;
  1263. }
  1264. if (filename == nullptr || filename[0] == '\0')
  1265. {
  1266. pData->engine->setLastError("null filename");
  1267. return false;
  1268. }
  1269. if (label == nullptr || label[0] == '\0')
  1270. {
  1271. pData->engine->setLastError("null label");
  1272. return false;
  1273. }
  1274. // ---------------------------------------------------------------
  1275. // open soundfont
  1276. const int synthId(fluid_synth_sfload(fSynth, filename, 0));
  1277. if (synthId < 0)
  1278. {
  1279. pData->engine->setLastError("Failed to load SoundFont file");
  1280. return false;
  1281. }
  1282. fSynthId = static_cast<uint>(synthId);
  1283. // ---------------------------------------------------------------
  1284. // get info
  1285. CarlaString label2(label);
  1286. if (kUse16Outs && ! label2.endsWith(" (16 outs)"))
  1287. label2 += " (16 outs)";
  1288. fLabel = label2.dup();
  1289. pData->filename = carla_strdup(filename);
  1290. if (name != nullptr && name[0] != '\0')
  1291. pData->name = pData->engine->getUniquePluginName(name);
  1292. else
  1293. pData->name = pData->engine->getUniquePluginName(label);
  1294. // ---------------------------------------------------------------
  1295. // register client
  1296. pData->client = pData->engine->addClient(this);
  1297. if (pData->client == nullptr || ! pData->client->isOk())
  1298. {
  1299. pData->engine->setLastError("Failed to register plugin client");
  1300. return false;
  1301. }
  1302. // ---------------------------------------------------------------
  1303. // set default options
  1304. pData->options = 0x0;
  1305. pData->options |= PLUGIN_OPTION_MAP_PROGRAM_CHANGES;
  1306. pData->options |= PLUGIN_OPTION_SEND_CHANNEL_PRESSURE;
  1307. pData->options |= PLUGIN_OPTION_SEND_PITCHBEND;
  1308. pData->options |= PLUGIN_OPTION_SEND_ALL_SOUND_OFF;
  1309. return true;
  1310. }
  1311. private:
  1312. enum FluidSynthInputParameters {
  1313. FluidSynthReverbOnOff = 0,
  1314. FluidSynthReverbRoomSize = 1,
  1315. FluidSynthReverbDamp = 2,
  1316. FluidSynthReverbLevel = 3,
  1317. FluidSynthReverbWidth = 4,
  1318. FluidSynthChorusOnOff = 5,
  1319. FluidSynthChorusNr = 6,
  1320. FluidSynthChorusLevel = 7,
  1321. FluidSynthChorusSpeedHz = 8,
  1322. FluidSynthChorusDepthMs = 9,
  1323. FluidSynthChorusType = 10,
  1324. FluidSynthPolyphony = 11,
  1325. FluidSynthInterpolation = 12,
  1326. FluidSynthVoiceCount = 13,
  1327. FluidSynthParametersMax = 14
  1328. };
  1329. const bool kUse16Outs;
  1330. fluid_settings_t* fSettings;
  1331. fluid_synth_t* fSynth;
  1332. uint fSynthId;
  1333. float** fAudio16Buffers;
  1334. float fParamBuffers[FluidSynthParametersMax];
  1335. int32_t fCurMidiProgs[MAX_MIDI_CHANNELS];
  1336. const char* fLabel;
  1337. CARLA_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(FluidSynthPlugin)
  1338. };
  1339. CARLA_BACKEND_END_NAMESPACE
  1340. #endif // HAVE_FLUIDSYNTH
  1341. CARLA_BACKEND_START_NAMESPACE
  1342. // -------------------------------------------------------------------------------------------------------------------
  1343. CarlaPlugin* CarlaPlugin::newFluidSynth(const Initializer& init, const bool use16Outs)
  1344. {
  1345. carla_debug("CarlaPlugin::newFluidSynth({%p, \"%s\", \"%s\", \"%s\", " P_INT64 "}, %s)", init.engine, init.filename, init.name, init.label, init.uniqueId, bool2str(use16Outs));
  1346. #ifdef HAVE_FLUIDSYNTH
  1347. if (init.engine->getProccessMode() == ENGINE_PROCESS_MODE_CONTINUOUS_RACK && use16Outs)
  1348. {
  1349. init.engine->setLastError("Carla's rack mode can only work with Stereo modules, please choose the 2-channel only SoundFont version");
  1350. return nullptr;
  1351. }
  1352. if (! fluid_is_soundfont(init.filename))
  1353. {
  1354. init.engine->setLastError("Requested file is not a valid SoundFont");
  1355. return nullptr;
  1356. }
  1357. FluidSynthPlugin* const plugin(new FluidSynthPlugin(init.engine, init.id, use16Outs));
  1358. if (! plugin->init(init.filename, init.name, init.label))
  1359. {
  1360. delete plugin;
  1361. return nullptr;
  1362. }
  1363. plugin->reload();
  1364. return plugin;
  1365. #else
  1366. init.engine->setLastError("fluidsynth support not available");
  1367. return nullptr;
  1368. // unused
  1369. (void)use16Outs;
  1370. #endif
  1371. }
  1372. CarlaPlugin* CarlaPlugin::newFileSF2(const Initializer& init, const bool use16Outs)
  1373. {
  1374. carla_debug("CarlaPlugin::newFileSF2({%p, \"%s\", \"%s\", \"%s\"}, %s)", init.engine, init.filename, init.name, init.label, bool2str(use16Outs));
  1375. #ifdef HAVE_FLUIDSYNTH
  1376. return newFluidSynth(init, use16Outs);
  1377. #else
  1378. init.engine->setLastError("SF2 support not available");
  1379. return nullptr;
  1380. // unused
  1381. (void)use16Outs;
  1382. #endif
  1383. }
  1384. // -------------------------------------------------------------------------------------------------------------------
  1385. CARLA_BACKEND_END_NAMESPACE