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.

1472 lines
51KB

  1. /*
  2. * Carla LinuxSampler 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. /* TODO
  18. * - implement buffer size changes
  19. * - implement sample rate changes
  20. * - call outDev->ReconnectAll() after changing buffer size or sample rate
  21. * - use CARLA_SAFE_ASSERT_RETURN with err
  22. * - pianoteq-like SetNoteOnVelocityFilter drawing points widget
  23. * - voice count param
  24. */
  25. #include "CarlaPluginInternal.hpp"
  26. #include "CarlaEngine.hpp"
  27. #ifdef HAVE_LINUXSAMPLER
  28. #include "CarlaBackendUtils.hpp"
  29. #include "CarlaMathUtils.hpp"
  30. #include "juce_core.h"
  31. #include "linuxsampler/EngineFactory.h"
  32. #include <linuxsampler/Sampler.h>
  33. // -----------------------------------------------------------------------
  34. namespace LinuxSampler {
  35. using CarlaBackend::CarlaEngine;
  36. using CarlaBackend::CarlaPlugin;
  37. // -----------------------------------------------------------------------
  38. // LinuxSampler static values
  39. static const float kVolumeMax = 3.16227766f; // +10 dB
  40. static const uint kMaxStreams = 90*2; // default is not *2
  41. static const uint kMaxVoices = 64*2;
  42. // -----------------------------------------------------------------------
  43. // LinuxSampler AudioOutputDevice Plugin
  44. class AudioOutputDevicePlugin : public AudioOutputDevice
  45. {
  46. public:
  47. AudioOutputDevicePlugin(const CarlaEngine* const engine, const CarlaPlugin* const plugin, const bool uses16Outs)
  48. : AudioOutputDevice(std::map<std::string, DeviceCreationParameter*>()),
  49. kEngine(engine),
  50. kPlugin(plugin),
  51. leakDetector_AudioOutputDevicePlugin()
  52. {
  53. CARLA_ASSERT(engine != nullptr);
  54. CARLA_ASSERT(plugin != nullptr);
  55. AcquireChannels(uses16Outs ? 32 : 2);
  56. }
  57. ~AudioOutputDevicePlugin() override {}
  58. // -------------------------------------------------------------------
  59. // LinuxSampler virtual methods
  60. void Play() override {}
  61. void Stop() override {}
  62. bool IsPlaying() override
  63. {
  64. return (kEngine->isRunning() && kPlugin->isEnabled());
  65. }
  66. uint MaxSamplesPerCycle() override
  67. {
  68. return kEngine->getBufferSize();
  69. }
  70. uint SampleRate() override
  71. {
  72. return uint(kEngine->getSampleRate());
  73. }
  74. std::string Driver() override
  75. {
  76. return "AudioOutputDevicePlugin";
  77. }
  78. AudioChannel* CreateChannel(uint channelNr) override
  79. {
  80. return new AudioChannel(channelNr, nullptr, 0);
  81. }
  82. // -------------------------------------------------------------------
  83. /* */ bool isAutonomousDevice() override { return false; }
  84. static bool isAutonomousDriver() { return false; }
  85. // -------------------------------------------------------------------
  86. // Give public access to the RenderAudio call
  87. int Render(const uint samples)
  88. {
  89. return RenderAudio(samples);
  90. }
  91. // -------------------------------------------------------------------
  92. private:
  93. const CarlaEngine* const kEngine;
  94. const CarlaPlugin* const kPlugin;
  95. CARLA_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(AudioOutputDevicePlugin)
  96. };
  97. // -----------------------------------------------------------------------
  98. // LinuxSampler MidiInputPort Plugin
  99. class MidiInputPortPlugin : public MidiInputPort
  100. {
  101. public:
  102. MidiInputPortPlugin(MidiInputDevice* const device, const int portNum = 0)
  103. : MidiInputPort(device, portNum),
  104. leakDetector_MidiInputPortPlugin() {}
  105. CARLA_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(MidiInputPortPlugin)
  106. };
  107. // -----------------------------------------------------------------------
  108. // LinuxSampler MidiInputDevice Plugin
  109. class MidiInputDevicePlugin : public MidiInputDevice
  110. {
  111. public:
  112. MidiInputDevicePlugin(Sampler* const sampler)
  113. : MidiInputDevice(std::map<std::string, DeviceCreationParameter*>(), sampler),
  114. leakDetector_MidiInputDevicePlugin()
  115. {
  116. AcquirePorts(1);
  117. }
  118. ~MidiInputDevicePlugin() override
  119. {
  120. for (std::map<int,MidiInputPort*>::iterator it = Ports.begin(), end = Ports.end(); it != end; ++it)
  121. delete dynamic_cast<MidiInputPortPlugin*>(it->second);
  122. Ports.clear();
  123. }
  124. // -------------------------------------------------------------------
  125. // LinuxSampler virtual methods
  126. void Listen() override {}
  127. void StopListen() override {}
  128. std::string Driver() override
  129. {
  130. return "MidiInputDevicePlugin";
  131. }
  132. MidiInputPort* CreateMidiPort() override
  133. {
  134. return new MidiInputPortPlugin(this, int(PortCount()));
  135. }
  136. // -------------------------------------------------------------------
  137. /* */ bool isAutonomousDevice() override { return false; }
  138. static bool isAutonomousDriver() { return false; }
  139. // -------------------------------------------------------------------
  140. CARLA_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(MidiInputDevicePlugin)
  141. };
  142. } // namespace LinuxSampler
  143. // -----------------------------------------------------------------------
  144. using juce::File;
  145. using juce::SharedResourcePointer;
  146. using juce::StringArray;
  147. CARLA_BACKEND_START_NAMESPACE
  148. // -----------------------------------------------------------------------
  149. class CarlaPluginLinuxSampler : public CarlaPlugin
  150. {
  151. public:
  152. CarlaPluginLinuxSampler(CarlaEngine* const engine, const uint id, const bool isGIG, const bool use16Outs)
  153. : CarlaPlugin(engine, id),
  154. kIsGIG(isGIG),
  155. kUses16Outs(use16Outs && isGIG),
  156. kMaxChannels(isGIG ? MAX_MIDI_CHANNELS : 1),
  157. fLabel(nullptr),
  158. fMaker(nullptr),
  159. fRealName(nullptr),
  160. sSampler(),
  161. fAudioOutputDevice(engine, this, kUses16Outs),
  162. fMidiInputDevice(sSampler),
  163. fMidiInputPort(nullptr),
  164. fInstrumentIds(),
  165. fInstrumentInfo(),
  166. leakDetector_CarlaPluginLinuxSampler()
  167. {
  168. carla_debug("CarlaPluginLinuxSampler::CarlaPluginLinuxSampler(%p, %i, %s, %s)", engine, id, bool2str(isGIG), bool2str(use16Outs));
  169. // TODO - option for this
  170. sSampler->SetGlobalMaxStreams(LinuxSampler::kMaxStreams);
  171. sSampler->SetGlobalMaxVoices(LinuxSampler::kMaxVoices);
  172. carla_zeroStruct(fCurProgs, MAX_MIDI_CHANNELS);
  173. carla_zeroStruct(fSamplerChannels, MAX_MIDI_CHANNELS);
  174. carla_zeroStruct(fEngineChannels, MAX_MIDI_CHANNELS);
  175. carla_zeroFloat(fParamBuffers, LinuxSamplerParametersMax);
  176. if (use16Outs && ! isGIG)
  177. carla_stderr("Tried to use SFZ with 16 stereo outs, this doesn't make much sense so single stereo mode will be used instead");
  178. }
  179. ~CarlaPluginLinuxSampler() override
  180. {
  181. carla_debug("CarlaPluginLinuxSampler::~CarlaPluginLinuxSampler()");
  182. pData->singleMutex.lock();
  183. pData->masterMutex.lock();
  184. if (pData->client != nullptr && pData->client->isActive())
  185. pData->client->deactivate();
  186. if (pData->active)
  187. {
  188. deactivate();
  189. pData->active = false;
  190. }
  191. fMidiInputPort = nullptr;
  192. for (uint i=0; i<kMaxChannels; ++i)
  193. {
  194. if (fSamplerChannels[i] != nullptr)
  195. {
  196. if (fEngineChannels[i] != nullptr)
  197. {
  198. fEngineChannels[i]->DisconnectAudioOutputDevice();
  199. fEngineChannels[i]->DisconnectAllMidiInputPorts();
  200. fEngineChannels[i] = nullptr;
  201. }
  202. sSampler->RemoveSamplerChannel(fSamplerChannels[i]);
  203. fSamplerChannels[i] = nullptr;
  204. }
  205. }
  206. fInstrumentIds.clear();
  207. fInstrumentInfo.clear();
  208. if (fLabel != nullptr)
  209. {
  210. delete[] fLabel;
  211. fLabel = nullptr;
  212. }
  213. if (fMaker != nullptr)
  214. {
  215. delete[] fMaker;
  216. fMaker = nullptr;
  217. }
  218. if (fRealName != nullptr)
  219. {
  220. delete[] fRealName;
  221. fRealName = nullptr;
  222. }
  223. clearBuffers();
  224. }
  225. // -------------------------------------------------------------------
  226. // Information (base)
  227. PluginType getType() const noexcept override
  228. {
  229. return kIsGIG ? PLUGIN_GIG : PLUGIN_SFZ;
  230. }
  231. PluginCategory getCategory() const noexcept override
  232. {
  233. return PLUGIN_CATEGORY_SYNTH;
  234. }
  235. // -------------------------------------------------------------------
  236. // Information (count)
  237. // nothing
  238. // -------------------------------------------------------------------
  239. // Information (current data)
  240. // nothing
  241. // -------------------------------------------------------------------
  242. // Information (per-plugin data)
  243. uint getOptionsAvailable() const noexcept override
  244. {
  245. uint options = 0x0;
  246. options |= PLUGIN_OPTION_SEND_CONTROL_CHANGES;
  247. options |= PLUGIN_OPTION_SEND_CHANNEL_PRESSURE;
  248. options |= PLUGIN_OPTION_SEND_NOTE_AFTERTOUCH;
  249. options |= PLUGIN_OPTION_SEND_PITCHBEND;
  250. options |= PLUGIN_OPTION_SEND_ALL_SOUND_OFF;
  251. if (kIsGIG)
  252. options |= PLUGIN_OPTION_MAP_PROGRAM_CHANGES;
  253. return options;
  254. }
  255. float getParameterValue(const uint32_t parameterId) const noexcept override
  256. {
  257. CARLA_SAFE_ASSERT_RETURN(parameterId < pData->param.count, 0.0f);
  258. return fParamBuffers[parameterId];
  259. }
  260. void getLabel(char* const strBuf) const noexcept override
  261. {
  262. if (fLabel != nullptr)
  263. {
  264. std::strncpy(strBuf, fLabel, STR_MAX);
  265. return;
  266. }
  267. CarlaPlugin::getLabel(strBuf);
  268. }
  269. void getMaker(char* const strBuf) const noexcept override
  270. {
  271. if (fMaker != nullptr)
  272. {
  273. std::strncpy(strBuf, fMaker, STR_MAX);
  274. return;
  275. }
  276. CarlaPlugin::getMaker(strBuf);
  277. }
  278. void getCopyright(char* const strBuf) const noexcept override
  279. {
  280. getMaker(strBuf);
  281. }
  282. void getRealName(char* const strBuf) const noexcept override
  283. {
  284. if (fRealName != nullptr)
  285. {
  286. std::strncpy(strBuf, fRealName, STR_MAX);
  287. return;
  288. }
  289. CarlaPlugin::getRealName(strBuf);
  290. }
  291. void getParameterName(const uint32_t parameterId, char* const strBuf) const noexcept override
  292. {
  293. CARLA_SAFE_ASSERT_RETURN(parameterId < pData->param.count,);
  294. switch (parameterId)
  295. {
  296. case LinuxSamplerDiskStreamCount:
  297. std::strncpy(strBuf, "Disk Stream Count", STR_MAX);
  298. return;
  299. case LinuxSamplerVoiceCount:
  300. std::strncpy(strBuf, "Voice Count", STR_MAX);
  301. return;
  302. }
  303. CarlaPlugin::getParameterName(parameterId, strBuf);
  304. }
  305. // -------------------------------------------------------------------
  306. // Set data (state)
  307. void prepareForSave() override
  308. {
  309. if (kMaxChannels > 1 && fInstrumentIds.size() > 1)
  310. {
  311. char strBuf[STR_MAX+1];
  312. std::snprintf(strBuf, STR_MAX, "%i:%i:%i:%i:%i:%i:%i:%i:%i:%i:%i:%i:%i:%i:%i:%i", fCurProgs[0], fCurProgs[1], fCurProgs[2], fCurProgs[3],
  313. fCurProgs[4], fCurProgs[5], fCurProgs[6], fCurProgs[7],
  314. fCurProgs[8], fCurProgs[9], fCurProgs[10], fCurProgs[11],
  315. fCurProgs[12], fCurProgs[13], fCurProgs[14], fCurProgs[15]);
  316. CarlaPlugin::setCustomData(CUSTOM_DATA_TYPE_STRING, "programs", strBuf, false);
  317. }
  318. }
  319. // -------------------------------------------------------------------
  320. // Set data (internal stuff)
  321. void setCtrlChannel(const int8_t channel, const bool sendOsc, const bool sendCallback) noexcept override
  322. {
  323. if (channel >= 0 && channel < MAX_MIDI_CHANNELS)
  324. pData->prog.current = static_cast<int32_t>(fCurProgs[channel]);
  325. CarlaPlugin::setCtrlChannel(channel, sendOsc, sendCallback);
  326. }
  327. // -------------------------------------------------------------------
  328. // Set data (plugin-specific stuff)
  329. void setCustomData(const char* const type, const char* const key, const char* const value, const bool sendGui) override
  330. {
  331. CARLA_SAFE_ASSERT_RETURN(type != nullptr && type[0] != '\0',);
  332. CARLA_SAFE_ASSERT_RETURN(key != nullptr && key[0] != '\0',);
  333. CARLA_SAFE_ASSERT_RETURN(value != nullptr && value[0] != '\0',);
  334. carla_debug("CarlaPluginLinuxSampler::setCustomData(%s, \"%s\", \"%s\", %s)", type, key, value, bool2str(sendGui));
  335. if (std::strcmp(type, CUSTOM_DATA_TYPE_STRING) != 0)
  336. return carla_stderr2("CarlaPluginLinuxSampler::setCustomData(\"%s\", \"%s\", \"%s\", %s) - type is not string", type, key, value, bool2str(sendGui));
  337. if (std::strcmp(key, "programs") != 0)
  338. return carla_stderr2("CarlaPluginLinuxSampler::setCustomData(\"%s\", \"%s\", \"%s\", %s) - key is not programs", type, key, value, bool2str(sendGui));
  339. if (kMaxChannels > 1 && fInstrumentIds.size() > 1)
  340. {
  341. StringArray programList(StringArray::fromTokens(value, ":", ""));
  342. if (programList.size() == MAX_MIDI_CHANNELS)
  343. {
  344. uint8_t channel = 0;
  345. for (juce::String *it=programList.begin(), *end=programList.end(); it != end; ++it)
  346. {
  347. const int index(it->getIntValue());
  348. if (index >= 0)
  349. setProgramInternal(static_cast<uint>(index), channel, true, false);
  350. if (++channel >= MAX_MIDI_CHANNELS)
  351. break;
  352. }
  353. CARLA_SAFE_ASSERT(channel == MAX_MIDI_CHANNELS);
  354. }
  355. }
  356. CarlaPlugin::setCustomData(type, key, value, sendGui);
  357. }
  358. void setProgram(const int32_t index, const bool sendGui, const bool sendOsc, const bool sendCallback) noexcept override
  359. {
  360. CARLA_SAFE_ASSERT_RETURN(sendGui || sendOsc || sendCallback,); // never call this from RT
  361. CARLA_SAFE_ASSERT_RETURN(index >= -1 && index < static_cast<int32_t>(pData->prog.count),);
  362. const int8_t channel(kIsGIG ? pData->ctrlChannel : int8_t(0));
  363. if (index >= 0 && channel >= 0)
  364. setProgramInternal(static_cast<uint>(index), static_cast<uint8_t>(channel), sendCallback, false);
  365. CarlaPlugin::setProgram(index, sendGui, sendOsc, sendCallback);
  366. }
  367. void setProgramInternal(const uint32_t index, const uint8_t channel, const bool sendCallback, const bool inRtContent) noexcept
  368. {
  369. CARLA_SAFE_ASSERT_RETURN(index < pData->prog.count,);
  370. CARLA_SAFE_ASSERT_RETURN(channel < MAX_MIDI_CHANNELS,);
  371. if (fCurProgs[channel] == index)
  372. return;
  373. LinuxSampler::EngineChannel* const engineChannel(fEngineChannels[kIsGIG ? channel : 0]);
  374. CARLA_SAFE_ASSERT_RETURN(engineChannel != nullptr,);
  375. const ScopedSingleProcessLocker spl(this, !inRtContent);
  376. if (pData->engine->isOffline())
  377. {
  378. try {
  379. engineChannel->PrepareLoadInstrument(pData->filename, index);
  380. engineChannel->LoadInstrument();
  381. } CARLA_SAFE_EXCEPTION("LoadInstrument");
  382. }
  383. else
  384. {
  385. try {
  386. LinuxSampler::InstrumentManager::LoadInstrumentInBackground(fInstrumentIds[index], engineChannel);
  387. } CARLA_SAFE_EXCEPTION("LoadInstrumentInBackground");
  388. }
  389. fCurProgs[channel] = index;
  390. if (pData->ctrlChannel == channel)
  391. {
  392. const int32_t iindex(static_cast<int32_t>(index));
  393. pData->prog.current = iindex;
  394. if (inRtContent)
  395. pData->postponeRtEvent(kPluginPostRtEventProgramChange, iindex, 0, 0.0f);
  396. else if (sendCallback)
  397. pData->engine->callback(ENGINE_CALLBACK_PROGRAM_CHANGED, pData->id, iindex, 0, 0.0f, nullptr);
  398. }
  399. }
  400. // -------------------------------------------------------------------
  401. // Set ui stuff
  402. // nothing
  403. // -------------------------------------------------------------------
  404. // Plugin state
  405. void reload() override
  406. {
  407. CARLA_SAFE_ASSERT_RETURN(pData->engine != nullptr,);
  408. carla_debug("CarlaPluginLinuxSampler::reload() - start");
  409. const EngineProcessMode processMode(pData->engine->getProccessMode());
  410. // Safely disable plugin for reload
  411. const ScopedDisabler sd(this);
  412. if (pData->active)
  413. deactivate();
  414. clearBuffers();
  415. uint32_t aOuts, params;
  416. aOuts = kUses16Outs ? 32 : 2;
  417. params = LinuxSamplerParametersMax;
  418. pData->audioOut.createNew(aOuts);
  419. pData->param.createNew(params, false);
  420. const uint portNameSize(pData->engine->getMaxPortNameSize());
  421. CarlaString portName;
  422. // ---------------------------------------
  423. // Audio Outputs
  424. if (kUses16Outs)
  425. {
  426. for (uint32_t i=0; i < 32; ++i)
  427. {
  428. portName.clear();
  429. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  430. {
  431. portName = pData->name;
  432. portName += ":";
  433. }
  434. portName += "out-";
  435. if ((i+2)/2 < 9)
  436. portName += "0";
  437. portName += CarlaString((i+2)/2);
  438. if (i % 2 == 0)
  439. portName += "L";
  440. else
  441. portName += "R";
  442. portName.truncate(portNameSize);
  443. pData->audioOut.ports[i].port = (CarlaEngineAudioPort*)pData->client->addPort(kEnginePortTypeAudio, portName, false);
  444. pData->audioOut.ports[i].rindex = i;
  445. }
  446. }
  447. else
  448. {
  449. // out-left
  450. portName.clear();
  451. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  452. {
  453. portName = pData->name;
  454. portName += ":";
  455. }
  456. portName += "out-left";
  457. portName.truncate(portNameSize);
  458. pData->audioOut.ports[0].port = (CarlaEngineAudioPort*)pData->client->addPort(kEnginePortTypeAudio, portName, false);
  459. pData->audioOut.ports[0].rindex = 0;
  460. // out-right
  461. portName.clear();
  462. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  463. {
  464. portName = pData->name;
  465. portName += ":";
  466. }
  467. portName += "out-right";
  468. portName.truncate(portNameSize);
  469. pData->audioOut.ports[1].port = (CarlaEngineAudioPort*)pData->client->addPort(kEnginePortTypeAudio, portName, false);
  470. pData->audioOut.ports[1].rindex = 1;
  471. }
  472. // ---------------------------------------
  473. // Event Input
  474. {
  475. portName.clear();
  476. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  477. {
  478. portName = pData->name;
  479. portName += ":";
  480. }
  481. portName += "events-in";
  482. portName.truncate(portNameSize);
  483. pData->event.portIn = (CarlaEngineEventPort*)pData->client->addPort(kEnginePortTypeEvent, portName, true);
  484. }
  485. // ---------------------------------------
  486. // Parameters
  487. {
  488. int j;
  489. // ----------------------
  490. j = LinuxSamplerDiskStreamCount;
  491. pData->param.data[j].type = PARAMETER_OUTPUT;
  492. pData->param.data[j].hints = PARAMETER_IS_ENABLED | PARAMETER_IS_AUTOMABLE | PARAMETER_IS_INTEGER;
  493. pData->param.data[j].index = j;
  494. pData->param.data[j].rindex = j;
  495. pData->param.ranges[j].min = 0.0f;
  496. pData->param.ranges[j].max = LinuxSampler::kMaxStreams;
  497. pData->param.ranges[j].def = 0.0f;
  498. pData->param.ranges[j].step = 1.0f;
  499. pData->param.ranges[j].stepSmall = 1.0f;
  500. pData->param.ranges[j].stepLarge = 1.0f;
  501. // ----------------------
  502. j = LinuxSamplerVoiceCount;
  503. pData->param.data[j].type = PARAMETER_OUTPUT;
  504. pData->param.data[j].hints = PARAMETER_IS_ENABLED | PARAMETER_IS_AUTOMABLE | PARAMETER_IS_INTEGER;
  505. pData->param.data[j].index = j;
  506. pData->param.data[j].rindex = j;
  507. pData->param.ranges[j].min = 0.0f;
  508. pData->param.ranges[j].max = LinuxSampler::kMaxVoices;
  509. pData->param.ranges[j].def = 0.0f;
  510. pData->param.ranges[j].step = 1.0f;
  511. pData->param.ranges[j].stepSmall = 1.0f;
  512. pData->param.ranges[j].stepLarge = 1.0f;
  513. for (j=0; j<LinuxSamplerParametersMax; ++j)
  514. fParamBuffers[j] = pData->param.ranges[j].def;
  515. }
  516. // ---------------------------------------
  517. // plugin hints
  518. pData->hints = 0x0;
  519. pData->hints |= PLUGIN_IS_SYNTH;
  520. pData->hints |= PLUGIN_CAN_VOLUME;
  521. if (! kUses16Outs)
  522. pData->hints |= PLUGIN_CAN_BALANCE;
  523. // extra plugin hints
  524. pData->extraHints = 0x0;
  525. pData->extraHints |= PLUGIN_EXTRA_HINT_HAS_MIDI_IN;
  526. if (! kUses16Outs)
  527. pData->extraHints |= PLUGIN_EXTRA_HINT_CAN_RUN_RACK;
  528. if (fInstrumentIds.size() > 1)
  529. pData->extraHints |= PLUGIN_EXTRA_HINT_USES_MULTI_PROGS;
  530. bufferSizeChanged(pData->engine->getBufferSize());
  531. reloadPrograms(true);
  532. if (pData->active)
  533. activate();
  534. carla_debug("CarlaPluginLinuxSampler::reload() - end");
  535. }
  536. void reloadPrograms(bool doInit) override
  537. {
  538. carla_debug("CarlaPluginLinuxSampler::reloadPrograms(%s)", bool2str(doInit));
  539. // Delete old programs
  540. pData->prog.clear();
  541. // Query new programs
  542. const uint32_t count(static_cast<uint32_t>(fInstrumentInfo.size()));
  543. // sound kits must always have at least 1 midi-program
  544. CARLA_SAFE_ASSERT_RETURN(count > 0,);
  545. pData->prog.createNew(count);
  546. // Update data
  547. for (uint32_t i=0; i < pData->prog.count; ++i)
  548. pData->prog.names[i] = carla_strdup_safe(fInstrumentInfo[i].InstrumentName.c_str());
  549. #if defined(HAVE_LIBLO) && ! defined(BUILD_BRIDGE)
  550. // Update OSC Names
  551. if (pData->engine->isOscControlRegistered())
  552. {
  553. pData->engine->oscSend_control_set_program_count(pData->id, count);
  554. for (uint32_t i=0; i < count; ++i)
  555. pData->engine->oscSend_control_set_program_name(pData->id, i, pData->prog.names[i]);
  556. }
  557. #endif
  558. if (doInit)
  559. {
  560. for (uint i=0; i<kMaxChannels; ++i)
  561. {
  562. LinuxSampler::EngineChannel* const engineChannel(fEngineChannels[i]);
  563. CARLA_SAFE_ASSERT_CONTINUE(engineChannel != nullptr);
  564. try {
  565. LinuxSampler::InstrumentManager::LoadInstrumentInBackground(fInstrumentIds[0], engineChannel);
  566. } CARLA_SAFE_EXCEPTION("LoadInstrumentInBackground");
  567. fCurProgs[i] = 0;
  568. }
  569. pData->prog.current = 0;
  570. }
  571. else
  572. {
  573. pData->engine->callback(ENGINE_CALLBACK_RELOAD_PROGRAMS, pData->id, 0, 0, 0.0f, nullptr);
  574. }
  575. }
  576. // -------------------------------------------------------------------
  577. // Plugin processing
  578. #if 0
  579. void activate() override
  580. {
  581. for (int i=0; i < MAX_MIDI_CHANNELS; ++i)
  582. {
  583. if (fAudioOutputDevices[i] != nullptr)
  584. fAudioOutputDevices[i]->Play();
  585. }
  586. }
  587. void deactivate() override
  588. {
  589. for (int i=0; i < MAX_MIDI_CHANNELS; ++i)
  590. {
  591. if (fAudioOutputDevices[i] != nullptr)
  592. fAudioOutputDevices[i]->Stop();
  593. }
  594. }
  595. #endif
  596. void process(const float** const, float** const audioOut, const float** const, float** const, const uint32_t frames) override
  597. {
  598. // --------------------------------------------------------------------------------------------------------
  599. // Check if active
  600. if (! pData->active)
  601. {
  602. // disable any output sound
  603. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  604. FloatVectorOperations::clear(audioOut[i], static_cast<int>(frames));
  605. fParamBuffers[LinuxSamplerDiskStreamCount] = 0.0f;
  606. fParamBuffers[LinuxSamplerVoiceCount] = 0.0f;
  607. return;
  608. }
  609. // --------------------------------------------------------------------------------------------------------
  610. // Check if needs reset
  611. if (pData->needsReset)
  612. {
  613. if (pData->options & PLUGIN_OPTION_SEND_ALL_SOUND_OFF)
  614. {
  615. for (uint i=0; i < MAX_MIDI_CHANNELS; ++i)
  616. {
  617. fMidiInputPort->DispatchControlChange(MIDI_CONTROL_ALL_NOTES_OFF, 0, i);
  618. fMidiInputPort->DispatchControlChange(MIDI_CONTROL_ALL_SOUND_OFF, 0, i);
  619. }
  620. }
  621. else if (pData->ctrlChannel >= 0 && pData->ctrlChannel < MAX_MIDI_CHANNELS)
  622. {
  623. for (uint8_t i=0; i < MAX_MIDI_NOTE; ++i)
  624. fMidiInputPort->DispatchNoteOff(i, 0, uint(pData->ctrlChannel));
  625. }
  626. pData->needsReset = false;
  627. }
  628. // --------------------------------------------------------------------------------------------------------
  629. // Event Input and Processing
  630. {
  631. // ----------------------------------------------------------------------------------------------------
  632. // MIDI Input (External)
  633. if (pData->extNotes.mutex.tryLock())
  634. {
  635. for (RtLinkedList<ExternalMidiNote>::Itenerator it = pData->extNotes.data.begin(); it.valid(); it.next())
  636. {
  637. const ExternalMidiNote& note(it.getValue());
  638. CARLA_SAFE_ASSERT_CONTINUE(note.channel >= 0 && note.channel < MAX_MIDI_CHANNELS);
  639. if (note.velo > 0)
  640. fMidiInputPort->DispatchNoteOn(note.note, note.velo, static_cast<uint>(note.channel));
  641. else
  642. fMidiInputPort->DispatchNoteOff(note.note, note.velo, static_cast<uint>(note.channel));
  643. }
  644. pData->extNotes.data.clear();
  645. pData->extNotes.mutex.unlock();
  646. } // End of MIDI Input (External)
  647. // ----------------------------------------------------------------------------------------------------
  648. // Event Input (System)
  649. #ifndef BUILD_BRIDGE
  650. bool allNotesOffSent = false;
  651. #endif
  652. bool sampleAccurate = (pData->options & PLUGIN_OPTION_FIXED_BUFFERS) == 0;
  653. uint32_t startTime = 0;
  654. uint32_t timeOffset = 0;
  655. for (uint32_t i=0, numEvents=pData->event.portIn->getEventCount(); i < numEvents; ++i)
  656. {
  657. const EngineEvent& event(pData->event.portIn->getEvent(i));
  658. CARLA_SAFE_ASSERT_CONTINUE(event.time < frames);
  659. CARLA_SAFE_ASSERT_BREAK(event.time >= timeOffset);
  660. if (event.time > timeOffset && sampleAccurate)
  661. {
  662. if (processSingle(audioOut, event.time - timeOffset, timeOffset))
  663. {
  664. startTime = 0;
  665. timeOffset = event.time;
  666. }
  667. else
  668. startTime += timeOffset;
  669. }
  670. // Control change
  671. switch (event.type)
  672. {
  673. case kEngineEventTypeNull:
  674. break;
  675. case kEngineEventTypeControl:
  676. {
  677. const EngineControlEvent& ctrlEvent = event.ctrl;
  678. switch (ctrlEvent.type)
  679. {
  680. case kEngineControlEventTypeNull:
  681. break;
  682. case kEngineControlEventTypeParameter:
  683. {
  684. #ifndef BUILD_BRIDGE
  685. // Control backend stuff
  686. if (event.channel == pData->ctrlChannel)
  687. {
  688. float value;
  689. if (MIDI_IS_CONTROL_BREATH_CONTROLLER(ctrlEvent.param) && (pData->hints & PLUGIN_CAN_DRYWET) != 0)
  690. {
  691. value = ctrlEvent.value;
  692. setDryWet(value, false, false);
  693. pData->postponeRtEvent(kPluginPostRtEventParameterChange, PARAMETER_DRYWET, 0, value);
  694. }
  695. if (MIDI_IS_CONTROL_CHANNEL_VOLUME(ctrlEvent.param) && (pData->hints & PLUGIN_CAN_VOLUME) != 0)
  696. {
  697. value = ctrlEvent.value*127.0f/100.0f;
  698. setVolume(value, false, false);
  699. pData->postponeRtEvent(kPluginPostRtEventParameterChange, PARAMETER_VOLUME, 0, value);
  700. }
  701. if (MIDI_IS_CONTROL_BALANCE(ctrlEvent.param) && (pData->hints & PLUGIN_CAN_BALANCE) != 0)
  702. {
  703. float left, right;
  704. value = ctrlEvent.value/0.5f - 1.0f;
  705. if (value < 0.0f)
  706. {
  707. left = -1.0f;
  708. right = (value*2.0f)+1.0f;
  709. }
  710. else if (value > 0.0f)
  711. {
  712. left = (value*2.0f)-1.0f;
  713. right = 1.0f;
  714. }
  715. else
  716. {
  717. left = -1.0f;
  718. right = 1.0f;
  719. }
  720. setBalanceLeft(left, false, false);
  721. setBalanceRight(right, false, false);
  722. pData->postponeRtEvent(kPluginPostRtEventParameterChange, PARAMETER_BALANCE_LEFT, 0, left);
  723. pData->postponeRtEvent(kPluginPostRtEventParameterChange, PARAMETER_BALANCE_RIGHT, 0, right);
  724. }
  725. }
  726. #endif
  727. // Control plugin parameters
  728. for (uint32_t k=0; k < pData->param.count; ++k)
  729. {
  730. if (pData->param.data[k].midiChannel != event.channel)
  731. continue;
  732. if (pData->param.data[k].midiCC != ctrlEvent.param)
  733. continue;
  734. if (pData->param.data[k].hints != PARAMETER_INPUT)
  735. continue;
  736. if ((pData->param.data[k].hints & PARAMETER_IS_AUTOMABLE) == 0)
  737. continue;
  738. float value;
  739. if (pData->param.data[k].hints & PARAMETER_IS_BOOLEAN)
  740. {
  741. value = (ctrlEvent.value < 0.5f) ? pData->param.ranges[k].min : pData->param.ranges[k].max;
  742. }
  743. else
  744. {
  745. value = pData->param.ranges[k].getUnnormalizedValue(ctrlEvent.value);
  746. if (pData->param.data[k].hints & PARAMETER_IS_INTEGER)
  747. value = std::rint(value);
  748. }
  749. setParameterValue(k, value, false, false, false);
  750. pData->postponeRtEvent(kPluginPostRtEventParameterChange, static_cast<int32_t>(k), 0, value);
  751. }
  752. if ((pData->options & PLUGIN_OPTION_SEND_CONTROL_CHANGES) != 0 && ctrlEvent.param < MAX_MIDI_CONTROL)
  753. {
  754. fMidiInputPort->DispatchControlChange(uint8_t(ctrlEvent.param), uint8_t(ctrlEvent.value*127.0f), event.channel, static_cast<int32_t>(sampleAccurate ? startTime : event.time));
  755. }
  756. break;
  757. }
  758. case kEngineControlEventTypeMidiBank:
  759. break;
  760. case kEngineControlEventTypeMidiProgram:
  761. if (pData->options & PLUGIN_OPTION_MAP_PROGRAM_CHANGES)
  762. {
  763. setProgramInternal(ctrlEvent.param, event.channel, false, true);
  764. }
  765. break;
  766. case kEngineControlEventTypeAllSoundOff:
  767. if (pData->options & PLUGIN_OPTION_SEND_ALL_SOUND_OFF)
  768. {
  769. fMidiInputPort->DispatchControlChange(MIDI_CONTROL_ALL_SOUND_OFF, 0, event.channel, static_cast<int32_t>(sampleAccurate ? startTime : event.time));
  770. }
  771. break;
  772. case kEngineControlEventTypeAllNotesOff:
  773. if (pData->options & PLUGIN_OPTION_SEND_ALL_SOUND_OFF)
  774. {
  775. #ifndef BUILD_BRIDGE
  776. if (event.channel == pData->ctrlChannel && ! allNotesOffSent)
  777. {
  778. allNotesOffSent = true;
  779. sendMidiAllNotesOffToCallback();
  780. }
  781. #endif
  782. fMidiInputPort->DispatchControlChange(MIDI_CONTROL_ALL_NOTES_OFF, 0, event.channel, static_cast<int32_t>(sampleAccurate ? startTime : event.time));
  783. }
  784. break;
  785. }
  786. break;
  787. }
  788. case kEngineEventTypeMidi: {
  789. const EngineMidiEvent& midiEvent(event.midi);
  790. const uint8_t* const midiData(midiEvent.size > EngineMidiEvent::kDataSize ? midiEvent.dataExt : midiEvent.data);
  791. uint8_t status = uint8_t(MIDI_GET_STATUS_FROM_DATA(midiData));
  792. if (status == MIDI_STATUS_CHANNEL_PRESSURE && (pData->options & PLUGIN_OPTION_SEND_CHANNEL_PRESSURE) == 0)
  793. continue;
  794. if (status == MIDI_STATUS_CONTROL_CHANGE && (pData->options & PLUGIN_OPTION_SEND_CONTROL_CHANGES) == 0)
  795. continue;
  796. if (status == MIDI_STATUS_POLYPHONIC_AFTERTOUCH && (pData->options & PLUGIN_OPTION_SEND_NOTE_AFTERTOUCH) == 0)
  797. continue;
  798. if (status == MIDI_STATUS_PITCH_WHEEL_CONTROL && (pData->options & PLUGIN_OPTION_SEND_PITCHBEND) == 0)
  799. continue;
  800. // Fix bad note-off
  801. if (status == MIDI_STATUS_NOTE_ON && midiData[2] == 0)
  802. status = MIDI_STATUS_NOTE_OFF;
  803. // put back channel in data
  804. uint8_t midiData2[midiEvent.size];
  805. midiData2[0] = uint8_t(status | (event.channel & MIDI_CHANNEL_BIT));
  806. std::memcpy(midiData2+1, midiData+1, static_cast<std::size_t>(midiEvent.size-1));
  807. fMidiInputPort->DispatchRaw(midiData2, static_cast<int32_t>(sampleAccurate ? startTime : event.time));
  808. if (status == MIDI_STATUS_NOTE_ON)
  809. pData->postponeRtEvent(kPluginPostRtEventNoteOn, event.channel, midiData[1], midiData[2]);
  810. else if (status == MIDI_STATUS_NOTE_OFF)
  811. pData->postponeRtEvent(kPluginPostRtEventNoteOff, event.channel, midiData[1], 0.0f);
  812. } break;
  813. }
  814. }
  815. pData->postRtEvents.trySplice();
  816. if (frames > timeOffset)
  817. processSingle(audioOut, frames - timeOffset, timeOffset);
  818. } // End of Event Input and Processing
  819. // --------------------------------------------------------------------------------------------------------
  820. // Parameter outputs
  821. uint diskStreamCount=0, voiceCount=0;
  822. for (uint i=0; i<kMaxChannels; ++i)
  823. {
  824. LinuxSampler::EngineChannel* const engineChannel(fEngineChannels[i]);
  825. CARLA_SAFE_ASSERT_CONTINUE(engineChannel != nullptr);
  826. diskStreamCount += engineChannel->GetDiskStreamCount();
  827. /**/ voiceCount += engineChannel->GetVoiceCount();
  828. }
  829. fParamBuffers[LinuxSamplerDiskStreamCount] = static_cast<float>(diskStreamCount);
  830. fParamBuffers[LinuxSamplerVoiceCount] = static_cast<float>(voiceCount);
  831. }
  832. bool processSingle(float** const outBuffer, const uint32_t frames, const uint32_t timeOffset)
  833. {
  834. CARLA_SAFE_ASSERT_RETURN(outBuffer != nullptr, false);
  835. CARLA_SAFE_ASSERT_RETURN(frames > 0, false);
  836. // --------------------------------------------------------------------------------------------------------
  837. // Try lock, silence otherwise
  838. if (pData->engine->isOffline())
  839. {
  840. pData->singleMutex.lock();
  841. }
  842. else if (! pData->singleMutex.tryLock())
  843. {
  844. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  845. {
  846. for (uint32_t k=0; k < frames; ++k)
  847. outBuffer[i][k+timeOffset] = 0.0f;
  848. }
  849. return false;
  850. }
  851. // --------------------------------------------------------------------------------------------------------
  852. // Run plugin
  853. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  854. {
  855. if (LinuxSampler::AudioChannel* const outDev = fAudioOutputDevice.Channel(i))
  856. outDev->SetBuffer(outBuffer[i] + timeOffset);
  857. }
  858. fAudioOutputDevice.Render(frames);
  859. #ifndef BUILD_BRIDGE
  860. // --------------------------------------------------------------------------------------------------------
  861. // Post-processing (dry/wet, volume and balance)
  862. {
  863. const bool doVolume = (pData->hints & PLUGIN_CAN_VOLUME) != 0 && ! carla_compareFloats(pData->postProc.volume, 1.0f);
  864. const bool doBalance = (pData->hints & PLUGIN_CAN_BALANCE) != 0 && ! (carla_compareFloats(pData->postProc.balanceLeft, -1.0f) && carla_compareFloats(pData->postProc.balanceRight, 1.0f));
  865. float oldBufLeft[doBalance ? frames : 1];
  866. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  867. {
  868. // Balance
  869. if (doBalance)
  870. {
  871. if (i % 2 == 0)
  872. FloatVectorOperations::copy(oldBufLeft, outBuffer[i], static_cast<int>(frames));
  873. float balRangeL = (pData->postProc.balanceLeft + 1.0f)/2.0f;
  874. float balRangeR = (pData->postProc.balanceRight + 1.0f)/2.0f;
  875. for (uint32_t k=0; k < frames; ++k)
  876. {
  877. if (i % 2 == 0)
  878. {
  879. // left
  880. outBuffer[i][k] = oldBufLeft[k] * (1.0f - balRangeL);
  881. outBuffer[i][k] += outBuffer[i+1][k] * (1.0f - balRangeR);
  882. }
  883. else
  884. {
  885. // right
  886. outBuffer[i][k] = outBuffer[i][k] * balRangeR;
  887. outBuffer[i][k] += oldBufLeft[k] * balRangeL;
  888. }
  889. }
  890. }
  891. // Volume
  892. if (doVolume)
  893. {
  894. for (uint32_t k=0; k < frames; ++k)
  895. outBuffer[i][k+timeOffset] *= pData->postProc.volume;
  896. }
  897. }
  898. } // End of Post-processing
  899. #endif
  900. // --------------------------------------------------------------------------------------------------------
  901. pData->singleMutex.unlock();
  902. return true;
  903. }
  904. #ifndef CARLA_OS_WIN // FIXME, need to update linuxsampler win32 build
  905. void bufferSizeChanged(const uint32_t) override
  906. {
  907. fAudioOutputDevice.ReconnectAll();
  908. }
  909. void sampleRateChanged(const double) override
  910. {
  911. fAudioOutputDevice.ReconnectAll();
  912. }
  913. #endif
  914. // -------------------------------------------------------------------
  915. // Plugin buffers
  916. // nothing
  917. // -------------------------------------------------------------------
  918. const void* getExtraStuff() const noexcept override
  919. {
  920. static const char xtrue[] = "true";
  921. static const char xfalse[] = "false";
  922. return kUses16Outs ? xtrue : xfalse;
  923. }
  924. bool init(const char* const filename, const char* const name, const char* const label)
  925. {
  926. CARLA_SAFE_ASSERT_RETURN(pData->engine != nullptr, false);
  927. // ---------------------------------------------------------------
  928. // first checks
  929. if (pData->client != nullptr)
  930. {
  931. pData->engine->setLastError("Plugin client is already registered");
  932. return false;
  933. }
  934. if (filename == nullptr || filename[0] == '\0')
  935. {
  936. pData->engine->setLastError("null filename");
  937. return false;
  938. }
  939. // ---------------------------------------------------------------
  940. // Init LinuxSampler stuff
  941. fMidiInputPort = fMidiInputDevice.GetPort(0);
  942. if (fMidiInputPort == nullptr)
  943. {
  944. pData->engine->setLastError("Failed to get LinuxSampler midi input port");
  945. return false;
  946. }
  947. for (uint i=0; i<kMaxChannels; ++i)
  948. {
  949. LinuxSampler::SamplerChannel* const samplerChannel(sSampler->AddSamplerChannel());
  950. CARLA_SAFE_ASSERT_CONTINUE(samplerChannel != nullptr);
  951. samplerChannel->SetEngineType(kIsGIG ? "GIG" : "SFZ");
  952. samplerChannel->SetAudioOutputDevice(&fAudioOutputDevice);
  953. samplerChannel->SetMidiInputChannel(kIsGIG ? static_cast<LinuxSampler::midi_chan_t>(i) : LinuxSampler::midi_chan_all);
  954. LinuxSampler::EngineChannel* const engineChannel(samplerChannel->GetEngineChannel());
  955. CARLA_SAFE_ASSERT_CONTINUE(engineChannel != nullptr);
  956. engineChannel->Pan(0.0f);
  957. engineChannel->Volume(kIsGIG ? LinuxSampler::kVolumeMax/10.0f : LinuxSampler::kVolumeMax); // FIXME
  958. engineChannel->SetMidiInstrumentMapToDefault();
  959. engineChannel->Connect(fMidiInputPort);
  960. if (kUses16Outs)
  961. {
  962. engineChannel->SetOutputChannel(0, i*2);
  963. engineChannel->SetOutputChannel(1, i*2 +1);
  964. }
  965. else
  966. {
  967. engineChannel->SetOutputChannel(0, 0);
  968. engineChannel->SetOutputChannel(1, 1);
  969. }
  970. fSamplerChannels[i] = samplerChannel;
  971. fEngineChannels[i] = engineChannel;
  972. }
  973. if (fSamplerChannels[0] == nullptr || fEngineChannels[0] == nullptr)
  974. {
  975. pData->engine->setLastError("Failed to create LinuxSampler audio channels");
  976. return false;
  977. }
  978. // ---------------------------------------------------------------
  979. // Get Engine
  980. LinuxSampler::Engine* const engine(fEngineChannels[0]->GetEngine());
  981. if (engine == nullptr)
  982. {
  983. pData->engine->setLastError("Failed to get LinuxSampler engine via channel");
  984. return false;
  985. }
  986. // ---------------------------------------------------------------
  987. // Get the Engine's Instrument Manager
  988. LinuxSampler::InstrumentManager* const instrumentMgr(engine->GetInstrumentManager());
  989. if (instrumentMgr == nullptr)
  990. {
  991. pData->engine->setLastError("Failed to get LinuxSampler instrument manager");
  992. return false;
  993. }
  994. // ---------------------------------------------------------------
  995. // Load the Instrument via filename
  996. try {
  997. fInstrumentIds = instrumentMgr->GetInstrumentFileContent(filename);
  998. }
  999. catch (const LinuxSampler::InstrumentManagerException& e)
  1000. {
  1001. pData->engine->setLastError(e.what());
  1002. return false;
  1003. }
  1004. // ---------------------------------------------------------------
  1005. // Get info
  1006. const std::size_t numInstruments(fInstrumentIds.size());
  1007. if (numInstruments == 0)
  1008. {
  1009. pData->engine->setLastError("Failed to find any instruments");
  1010. return false;
  1011. }
  1012. for (std::size_t i=0; i<numInstruments; ++i)
  1013. {
  1014. try {
  1015. fInstrumentInfo.push_back(instrumentMgr->GetInstrumentInfo(fInstrumentIds[i]));
  1016. } CARLA_SAFE_EXCEPTION("GetInstrumentInfo");
  1017. instrumentMgr->SetMode(fInstrumentIds[i], LinuxSampler::InstrumentManager::ON_DEMAND);
  1018. }
  1019. CARLA_SAFE_ASSERT(fInstrumentInfo.size() == numInstruments);
  1020. // ---------------------------------------------------------------
  1021. CarlaString label2(label != nullptr ? label : File(filename).getFileNameWithoutExtension().toRawUTF8());
  1022. if (kUses16Outs && ! label2.endsWith(" (16 outs)"))
  1023. label2 += " (16 outs)";
  1024. fLabel = label2.dup();
  1025. fMaker = carla_strdup(fInstrumentInfo[0].Artists.c_str());
  1026. fRealName = carla_strdup(instrumentMgr->GetInstrumentName(fInstrumentIds[0]).c_str());
  1027. pData->filename = carla_strdup(filename);
  1028. if (name != nullptr && name[0] != '\0')
  1029. pData->name = pData->engine->getUniquePluginName(name);
  1030. else if (fRealName[0] != '\0')
  1031. pData->name = pData->engine->getUniquePluginName(fRealName);
  1032. else
  1033. pData->name = pData->engine->getUniquePluginName(fLabel);
  1034. // ---------------------------------------------------------------
  1035. // register client
  1036. pData->client = pData->engine->addClient(this);
  1037. if (pData->client == nullptr || ! pData->client->isOk())
  1038. {
  1039. pData->engine->setLastError("Failed to register plugin client");
  1040. return false;
  1041. }
  1042. // ---------------------------------------------------------------
  1043. // set default options
  1044. pData->options = 0x0;
  1045. pData->options |= PLUGIN_OPTION_SEND_CONTROL_CHANGES;
  1046. pData->options |= PLUGIN_OPTION_SEND_CHANNEL_PRESSURE;
  1047. pData->options |= PLUGIN_OPTION_SEND_NOTE_AFTERTOUCH;
  1048. pData->options |= PLUGIN_OPTION_SEND_PITCHBEND;
  1049. pData->options |= PLUGIN_OPTION_SEND_ALL_SOUND_OFF;
  1050. if (kIsGIG)
  1051. pData->options |= PLUGIN_OPTION_MAP_PROGRAM_CHANGES;
  1052. return true;
  1053. }
  1054. // -------------------------------------------------------------------
  1055. private:
  1056. enum LinuxSamplerParameters {
  1057. LinuxSamplerDiskStreamCount = 0,
  1058. LinuxSamplerVoiceCount = 1,
  1059. LinuxSamplerParametersMax = 2
  1060. };
  1061. const bool kIsGIG; // SFZ if false
  1062. const bool kUses16Outs;
  1063. const uint kMaxChannels; // 16 for gig, 1 for sfz
  1064. const char* fLabel;
  1065. const char* fMaker;
  1066. const char* fRealName;
  1067. uint32_t fCurProgs[MAX_MIDI_CHANNELS];
  1068. float fParamBuffers[LinuxSamplerParametersMax];
  1069. SharedResourcePointer<LinuxSampler::Sampler> sSampler;
  1070. LinuxSampler::AudioOutputDevicePlugin fAudioOutputDevice;
  1071. LinuxSampler::MidiInputDevicePlugin fMidiInputDevice;
  1072. LinuxSampler::MidiInputPort* fMidiInputPort;
  1073. LinuxSampler::SamplerChannel* fSamplerChannels[MAX_MIDI_CHANNELS];
  1074. LinuxSampler::EngineChannel* fEngineChannels[MAX_MIDI_CHANNELS];
  1075. std::vector<LinuxSampler::InstrumentManager::instrument_id_t> fInstrumentIds;
  1076. std::vector<LinuxSampler::InstrumentManager::instrument_info_t> fInstrumentInfo;
  1077. CARLA_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(CarlaPluginLinuxSampler)
  1078. };
  1079. CARLA_BACKEND_END_NAMESPACE
  1080. #endif // HAVE_LINUXSAMPLER
  1081. CARLA_BACKEND_START_NAMESPACE
  1082. // -------------------------------------------------------------------------------------------------------------------
  1083. CarlaPlugin* CarlaPlugin::newLinuxSampler(const Initializer& init, const char* const format, const bool use16Outs)
  1084. {
  1085. carla_debug("CarlaPluginLinuxSampler::newLinuxSampler({%p, \"%s\", \"%s\", \"%s\", " P_INT64 "}, %s, %s)", init.engine, init.filename, init.name, init.label, init.uniqueId, format, bool2str(use16Outs));
  1086. #ifdef HAVE_LINUXSAMPLER
  1087. CarlaString sformat(format);
  1088. sformat.toLower();
  1089. if (sformat != "gig" && sformat != "sfz")
  1090. {
  1091. init.engine->setLastError("Unsupported format requested for LinuxSampler");
  1092. return nullptr;
  1093. }
  1094. if (init.engine->getProccessMode() == ENGINE_PROCESS_MODE_CONTINUOUS_RACK && use16Outs)
  1095. {
  1096. init.engine->setLastError("Carla's rack mode can only work with Stereo modules, please choose the 2-channel only sample-library version");
  1097. return nullptr;
  1098. }
  1099. // -------------------------------------------------------------------
  1100. // Check if file exists
  1101. if (! File(init.filename).existsAsFile())
  1102. {
  1103. init.engine->setLastError("Requested file is not valid or does not exist");
  1104. return nullptr;
  1105. }
  1106. CarlaPluginLinuxSampler* const plugin(new CarlaPluginLinuxSampler(init.engine, init.id, (sformat == "gig"), use16Outs));
  1107. if (! plugin->init(init.filename, init.name, init.label))
  1108. {
  1109. delete plugin;
  1110. return nullptr;
  1111. }
  1112. plugin->reload();
  1113. return plugin;
  1114. #else
  1115. init.engine->setLastError("linuxsampler support not available");
  1116. return nullptr;
  1117. // unused
  1118. (void)format;
  1119. (void)use16Outs;
  1120. #endif
  1121. }
  1122. CarlaPlugin* CarlaPlugin::newFileGIG(const Initializer& init, const bool use16Outs)
  1123. {
  1124. carla_debug("CarlaPlugin::newFileGIG({%p, \"%s\", \"%s\", \"%s\"}, %s)", init.engine, init.filename, init.name, init.label, bool2str(use16Outs));
  1125. #ifdef HAVE_LINUXSAMPLER
  1126. return newLinuxSampler(init, "GIG", use16Outs);
  1127. #else
  1128. init.engine->setLastError("GIG support not available");
  1129. return nullptr;
  1130. // unused
  1131. (void)use16Outs;
  1132. #endif
  1133. }
  1134. CarlaPlugin* CarlaPlugin::newFileSFZ(const Initializer& init)
  1135. {
  1136. carla_debug("CarlaPlugin::newFileSFZ({%p, \"%s\", \"%s\", \"%s\"})", init.engine, init.filename, init.name, init.label);
  1137. #ifdef HAVE_LINUXSAMPLER
  1138. return newLinuxSampler(init, "SFZ", false);
  1139. #else
  1140. init.engine->setLastError("SFZ support not available");
  1141. return nullptr;
  1142. #endif
  1143. }
  1144. // -------------------------------------------------------------------------------------------------------------------
  1145. CARLA_BACKEND_END_NAMESPACE