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.

1473 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/juce_core.h"
  31. #include <linuxsampler/Sampler.h>
  32. // -----------------------------------------------------------------------
  33. namespace LinuxSampler {
  34. using CarlaBackend::CarlaEngine;
  35. using CarlaBackend::CarlaPlugin;
  36. // -----------------------------------------------------------------------
  37. // LinuxSampler static values
  38. static const float kVolumeMax = 3.16227766f; // +10 dB
  39. static const uint kMaxStreams = 90*2; // default is not *2
  40. static const uint kMaxVoices = 64*2;
  41. // -----------------------------------------------------------------------
  42. // LinuxSampler AudioOutputDevice Plugin
  43. class AudioOutputDevicePlugin : public AudioOutputDevice
  44. {
  45. public:
  46. AudioOutputDevicePlugin(const CarlaEngine* const engine, const CarlaPlugin* const plugin, const bool uses16Outs)
  47. : AudioOutputDevice(std::map<std::string, DeviceCreationParameter*>()),
  48. kEngine(engine),
  49. kPlugin(plugin)
  50. {
  51. CARLA_ASSERT(engine != nullptr);
  52. CARLA_ASSERT(plugin != nullptr);
  53. AcquireChannels(uses16Outs ? 32 : 2);
  54. }
  55. ~AudioOutputDevicePlugin() override {}
  56. // -------------------------------------------------------------------
  57. // LinuxSampler virtual methods
  58. void Play() override {}
  59. void Stop() override {}
  60. bool IsPlaying() override
  61. {
  62. return (kEngine->isRunning() && kPlugin->isEnabled());
  63. }
  64. uint MaxSamplesPerCycle() override
  65. {
  66. return kEngine->getBufferSize();
  67. }
  68. uint SampleRate() override
  69. {
  70. return uint(kEngine->getSampleRate());
  71. }
  72. std::string Driver() override
  73. {
  74. return "AudioOutputDevicePlugin";
  75. }
  76. AudioChannel* CreateChannel(uint channelNr) override
  77. {
  78. return new AudioChannel(channelNr, nullptr, 0);
  79. }
  80. // -------------------------------------------------------------------
  81. /* */ bool isAutonomousDevice() override { return false; }
  82. static bool isAutonomousDriver() { return false; }
  83. // -------------------------------------------------------------------
  84. // Give public access to the RenderAudio call
  85. int Render(const uint samples)
  86. {
  87. return RenderAudio(samples);
  88. }
  89. // -------------------------------------------------------------------
  90. private:
  91. const CarlaEngine* const kEngine;
  92. const CarlaPlugin* const kPlugin;
  93. CARLA_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(AudioOutputDevicePlugin)
  94. };
  95. // -----------------------------------------------------------------------
  96. // LinuxSampler MidiInputPort Plugin
  97. class MidiInputPortPlugin : public MidiInputPort
  98. {
  99. public:
  100. MidiInputPortPlugin(MidiInputDevice* const device, const int portNum = 0)
  101. : MidiInputPort(device, portNum) {}
  102. CARLA_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(MidiInputPortPlugin)
  103. };
  104. // -----------------------------------------------------------------------
  105. // LinuxSampler MidiInputDevice Plugin
  106. class MidiInputDevicePlugin : public MidiInputDevice
  107. {
  108. public:
  109. MidiInputDevicePlugin(Sampler* const sampler)
  110. : MidiInputDevice(std::map<std::string, DeviceCreationParameter*>(), sampler)
  111. {
  112. AcquirePorts(1);
  113. }
  114. ~MidiInputDevicePlugin() override
  115. {
  116. for (std::map<int,MidiInputPort*>::iterator it = Ports.begin(), end = Ports.end(); it != end; ++it)
  117. delete dynamic_cast<MidiInputPortPlugin*>(it->second);
  118. Ports.clear();
  119. }
  120. // -------------------------------------------------------------------
  121. // LinuxSampler virtual methods
  122. void Listen() override {}
  123. void StopListen() override {}
  124. std::string Driver() override
  125. {
  126. return "MidiInputDevicePlugin";
  127. }
  128. MidiInputPort* CreateMidiPort() override
  129. {
  130. return new MidiInputPortPlugin(this, int(PortCount()));
  131. }
  132. // -------------------------------------------------------------------
  133. /* */ bool isAutonomousDevice() override { return false; }
  134. static bool isAutonomousDriver() { return false; }
  135. // -------------------------------------------------------------------
  136. CARLA_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(MidiInputDevicePlugin)
  137. };
  138. } // namespace LinuxSampler
  139. // -----------------------------------------------------------------------
  140. using juce::File;
  141. using juce::SharedResourcePointer;
  142. using juce::StringArray;
  143. CARLA_BACKEND_START_NAMESPACE
  144. // -------------------------------------------------------------------------------------------------------------------
  145. // Fallback data
  146. static const ExternalMidiNote kExternalMidiNoteFallback = { -1, 0, 0 };
  147. // -------------------------------------------------------------------------------------------------------------------
  148. class CarlaPluginLinuxSampler : public CarlaPlugin
  149. {
  150. public:
  151. CarlaPluginLinuxSampler(CarlaEngine* const engine, const uint id, const bool isGIG, const bool use16Outs)
  152. : CarlaPlugin(engine, id),
  153. kIsGIG(isGIG),
  154. kUses16Outs(use16Outs && isGIG),
  155. kMaxChannels(isGIG ? MAX_MIDI_CHANNELS : 1),
  156. fLabel(nullptr),
  157. fMaker(nullptr),
  158. fRealName(nullptr),
  159. sSampler(),
  160. fAudioOutputDevice(engine, this, kUses16Outs),
  161. fMidiInputDevice(sSampler),
  162. fMidiInputPort(nullptr),
  163. fInstrumentIds(),
  164. fInstrumentInfo()
  165. {
  166. carla_debug("CarlaPluginLinuxSampler::CarlaPluginLinuxSampler(%p, %i, %s, %s)", engine, id, bool2str(isGIG), bool2str(use16Outs));
  167. // TODO - option for this
  168. sSampler->SetGlobalMaxStreams(LinuxSampler::kMaxStreams);
  169. sSampler->SetGlobalMaxVoices(LinuxSampler::kMaxVoices);
  170. carla_zeroStructs(fCurProgs, MAX_MIDI_CHANNELS);
  171. carla_zeroStructs(fSamplerChannels, MAX_MIDI_CHANNELS);
  172. carla_zeroStructs(fEngineChannels, MAX_MIDI_CHANNELS);
  173. carla_zeroFloats(fParamBuffers, LinuxSamplerParametersMax);
  174. if (use16Outs && ! isGIG)
  175. carla_stderr("Tried to use SFZ with 16 stereo outs, this doesn't make much sense so single stereo mode will be used instead");
  176. }
  177. ~CarlaPluginLinuxSampler() override
  178. {
  179. carla_debug("CarlaPluginLinuxSampler::~CarlaPluginLinuxSampler()");
  180. pData->singleMutex.lock();
  181. pData->masterMutex.lock();
  182. if (pData->client != nullptr && pData->client->isActive())
  183. pData->client->deactivate();
  184. if (pData->active)
  185. {
  186. deactivate();
  187. pData->active = false;
  188. }
  189. fMidiInputPort = nullptr;
  190. for (uint i=0; i<kMaxChannels; ++i)
  191. {
  192. if (fSamplerChannels[i] != nullptr)
  193. {
  194. if (fEngineChannels[i] != nullptr)
  195. {
  196. fEngineChannels[i]->DisconnectAudioOutputDevice();
  197. fEngineChannels[i]->DisconnectAllMidiInputPorts();
  198. fEngineChannels[i] = nullptr;
  199. }
  200. sSampler->RemoveSamplerChannel(fSamplerChannels[i]);
  201. fSamplerChannels[i] = nullptr;
  202. }
  203. }
  204. fInstrumentIds.clear();
  205. fInstrumentInfo.clear();
  206. if (fLabel != nullptr)
  207. {
  208. delete[] fLabel;
  209. fLabel = nullptr;
  210. }
  211. if (fMaker != nullptr)
  212. {
  213. delete[] fMaker;
  214. fMaker = nullptr;
  215. }
  216. if (fRealName != nullptr)
  217. {
  218. delete[] fRealName;
  219. fRealName = nullptr;
  220. }
  221. clearBuffers();
  222. }
  223. // -------------------------------------------------------------------
  224. // Information (base)
  225. PluginType getType() const noexcept override
  226. {
  227. return kIsGIG ? PLUGIN_GIG : PLUGIN_SFZ;
  228. }
  229. PluginCategory getCategory() const noexcept override
  230. {
  231. return PLUGIN_CATEGORY_SYNTH;
  232. }
  233. // -------------------------------------------------------------------
  234. // Information (count)
  235. // nothing
  236. // -------------------------------------------------------------------
  237. // Information (current data)
  238. // nothing
  239. // -------------------------------------------------------------------
  240. // Information (per-plugin data)
  241. uint getOptionsAvailable() const noexcept override
  242. {
  243. uint options = 0x0;
  244. options |= PLUGIN_OPTION_SEND_CONTROL_CHANGES;
  245. options |= PLUGIN_OPTION_SEND_CHANNEL_PRESSURE;
  246. options |= PLUGIN_OPTION_SEND_NOTE_AFTERTOUCH;
  247. options |= PLUGIN_OPTION_SEND_PITCHBEND;
  248. options |= PLUGIN_OPTION_SEND_ALL_SOUND_OFF;
  249. if (kIsGIG)
  250. options |= PLUGIN_OPTION_MAP_PROGRAM_CHANGES;
  251. return options;
  252. }
  253. float getParameterValue(const uint32_t parameterId) const noexcept override
  254. {
  255. CARLA_SAFE_ASSERT_RETURN(parameterId < pData->param.count, 0.0f);
  256. return fParamBuffers[parameterId];
  257. }
  258. void getLabel(char* const strBuf) const noexcept override
  259. {
  260. if (fLabel != nullptr)
  261. {
  262. std::strncpy(strBuf, fLabel, STR_MAX);
  263. return;
  264. }
  265. CarlaPlugin::getLabel(strBuf);
  266. }
  267. void getMaker(char* const strBuf) const noexcept override
  268. {
  269. if (fMaker != nullptr)
  270. {
  271. std::strncpy(strBuf, fMaker, STR_MAX);
  272. return;
  273. }
  274. CarlaPlugin::getMaker(strBuf);
  275. }
  276. void getCopyright(char* const strBuf) const noexcept override
  277. {
  278. getMaker(strBuf);
  279. }
  280. void getRealName(char* const strBuf) const noexcept override
  281. {
  282. if (fRealName != nullptr)
  283. {
  284. std::strncpy(strBuf, fRealName, STR_MAX);
  285. return;
  286. }
  287. CarlaPlugin::getRealName(strBuf);
  288. }
  289. void getParameterName(const uint32_t parameterId, char* const strBuf) const noexcept override
  290. {
  291. CARLA_SAFE_ASSERT_RETURN(parameterId < pData->param.count,);
  292. switch (parameterId)
  293. {
  294. case LinuxSamplerDiskStreamCount:
  295. std::strncpy(strBuf, "Disk Stream Count", STR_MAX);
  296. return;
  297. case LinuxSamplerVoiceCount:
  298. std::strncpy(strBuf, "Voice Count", STR_MAX);
  299. return;
  300. }
  301. CarlaPlugin::getParameterName(parameterId, strBuf);
  302. }
  303. // -------------------------------------------------------------------
  304. // Set data (state)
  305. void prepareForSave() override
  306. {
  307. if (kMaxChannels > 1 && fInstrumentIds.size() > 1)
  308. {
  309. char strBuf[STR_MAX+1];
  310. 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],
  311. fCurProgs[4], fCurProgs[5], fCurProgs[6], fCurProgs[7],
  312. fCurProgs[8], fCurProgs[9], fCurProgs[10], fCurProgs[11],
  313. fCurProgs[12], fCurProgs[13], fCurProgs[14], fCurProgs[15]);
  314. CarlaPlugin::setCustomData(CUSTOM_DATA_TYPE_STRING, "programs", strBuf, false);
  315. }
  316. }
  317. // -------------------------------------------------------------------
  318. // Set data (internal stuff)
  319. void setCtrlChannel(const int8_t channel, const bool sendOsc, const bool sendCallback) noexcept override
  320. {
  321. if (channel >= 0 && channel < MAX_MIDI_CHANNELS)
  322. pData->prog.current = static_cast<int32_t>(fCurProgs[channel]);
  323. CarlaPlugin::setCtrlChannel(channel, sendOsc, sendCallback);
  324. }
  325. // -------------------------------------------------------------------
  326. // Set data (plugin-specific stuff)
  327. void setCustomData(const char* const type, const char* const key, const char* const value, const bool sendGui) override
  328. {
  329. CARLA_SAFE_ASSERT_RETURN(type != nullptr && type[0] != '\0',);
  330. CARLA_SAFE_ASSERT_RETURN(key != nullptr && key[0] != '\0',);
  331. CARLA_SAFE_ASSERT_RETURN(value != nullptr && value[0] != '\0',);
  332. carla_debug("CarlaPluginLinuxSampler::setCustomData(%s, \"%s\", \"%s\", %s)", type, key, value, bool2str(sendGui));
  333. if (std::strcmp(type, CUSTOM_DATA_TYPE_PROPERTY) == 0)
  334. return CarlaPlugin::setCustomData(type, key, value, 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, i);
  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, 0);
  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, 1);
  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, 0);
  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 (kMaxChannels > 1 && fInstrumentIds.size() > 1)
  527. pData->hints |= PLUGIN_USES_MULTI_PROGS;
  528. if (! kUses16Outs)
  529. pData->extraHints |= PLUGIN_EXTRA_HINT_CAN_RUN_RACK;
  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() && pData->id < pData->engine->getCurrentPluginCount())
  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.begin2(); it.valid(); it.next())
  636. {
  637. const ExternalMidiNote& note(it.getValue(kExternalMidiNoteFallback));
  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. uint32_t startTime = 0;
  653. uint32_t timeOffset = 0;
  654. for (uint32_t i=0, numEvents=pData->event.portIn->getEventCount(); i < numEvents; ++i)
  655. {
  656. const EngineEvent& event(pData->event.portIn->getEvent(i));
  657. CARLA_SAFE_ASSERT_CONTINUE(event.time < frames);
  658. CARLA_SAFE_ASSERT_BREAK(event.time >= timeOffset);
  659. if (event.time > timeOffset)
  660. {
  661. if (processSingle(audioOut, event.time - timeOffset, timeOffset))
  662. {
  663. startTime = 0;
  664. timeOffset = event.time;
  665. }
  666. else
  667. startTime += timeOffset;
  668. }
  669. // Control change
  670. switch (event.type)
  671. {
  672. case kEngineEventTypeNull:
  673. break;
  674. case kEngineEventTypeControl:
  675. {
  676. const EngineControlEvent& ctrlEvent = event.ctrl;
  677. switch (ctrlEvent.type)
  678. {
  679. case kEngineControlEventTypeNull:
  680. break;
  681. case kEngineControlEventTypeParameter:
  682. {
  683. #ifndef BUILD_BRIDGE
  684. // Control backend stuff
  685. if (event.channel == pData->ctrlChannel)
  686. {
  687. float value;
  688. if (MIDI_IS_CONTROL_BREATH_CONTROLLER(ctrlEvent.param) && (pData->hints & PLUGIN_CAN_DRYWET) != 0)
  689. {
  690. value = ctrlEvent.value;
  691. setDryWet(value, false, false);
  692. pData->postponeRtEvent(kPluginPostRtEventParameterChange, PARAMETER_DRYWET, 0, value);
  693. }
  694. if (MIDI_IS_CONTROL_CHANNEL_VOLUME(ctrlEvent.param) && (pData->hints & PLUGIN_CAN_VOLUME) != 0)
  695. {
  696. value = ctrlEvent.value*127.0f/100.0f;
  697. setVolume(value, false, false);
  698. pData->postponeRtEvent(kPluginPostRtEventParameterChange, PARAMETER_VOLUME, 0, value);
  699. }
  700. if (MIDI_IS_CONTROL_BALANCE(ctrlEvent.param) && (pData->hints & PLUGIN_CAN_BALANCE) != 0)
  701. {
  702. float left, right;
  703. value = ctrlEvent.value/0.5f - 1.0f;
  704. if (value < 0.0f)
  705. {
  706. left = -1.0f;
  707. right = (value*2.0f)+1.0f;
  708. }
  709. else if (value > 0.0f)
  710. {
  711. left = (value*2.0f)-1.0f;
  712. right = 1.0f;
  713. }
  714. else
  715. {
  716. left = -1.0f;
  717. right = 1.0f;
  718. }
  719. setBalanceLeft(left, false, false);
  720. setBalanceRight(right, false, false);
  721. pData->postponeRtEvent(kPluginPostRtEventParameterChange, PARAMETER_BALANCE_LEFT, 0, left);
  722. pData->postponeRtEvent(kPluginPostRtEventParameterChange, PARAMETER_BALANCE_RIGHT, 0, right);
  723. }
  724. }
  725. #endif
  726. // Control plugin parameters
  727. for (uint32_t k=0; k < pData->param.count; ++k)
  728. {
  729. if (pData->param.data[k].midiChannel != event.channel)
  730. continue;
  731. if (pData->param.data[k].midiCC != ctrlEvent.param)
  732. continue;
  733. if (pData->param.data[k].hints != PARAMETER_INPUT)
  734. continue;
  735. if ((pData->param.data[k].hints & PARAMETER_IS_AUTOMABLE) == 0)
  736. continue;
  737. float value;
  738. if (pData->param.data[k].hints & PARAMETER_IS_BOOLEAN)
  739. {
  740. value = (ctrlEvent.value < 0.5f) ? pData->param.ranges[k].min : pData->param.ranges[k].max;
  741. }
  742. else
  743. {
  744. value = pData->param.ranges[k].getUnnormalizedValue(ctrlEvent.value);
  745. if (pData->param.data[k].hints & PARAMETER_IS_INTEGER)
  746. value = std::rint(value);
  747. }
  748. setParameterValue(k, value, false, false, false);
  749. pData->postponeRtEvent(kPluginPostRtEventParameterChange, static_cast<int32_t>(k), 0, value);
  750. }
  751. if ((pData->options & PLUGIN_OPTION_SEND_CONTROL_CHANGES) != 0 && ctrlEvent.param < MAX_MIDI_CONTROL)
  752. {
  753. fMidiInputPort->DispatchControlChange(uint8_t(ctrlEvent.param), uint8_t(ctrlEvent.value*127.0f), event.channel, static_cast<int32_t>(startTime));
  754. }
  755. break;
  756. }
  757. case kEngineControlEventTypeMidiBank:
  758. break;
  759. case kEngineControlEventTypeMidiProgram:
  760. if (pData->options & PLUGIN_OPTION_MAP_PROGRAM_CHANGES)
  761. {
  762. setProgramInternal(ctrlEvent.param, event.channel, false, true);
  763. }
  764. break;
  765. case kEngineControlEventTypeAllSoundOff:
  766. if (pData->options & PLUGIN_OPTION_SEND_ALL_SOUND_OFF)
  767. {
  768. fMidiInputPort->DispatchControlChange(MIDI_CONTROL_ALL_SOUND_OFF, 0, event.channel, static_cast<int32_t>(startTime));
  769. }
  770. break;
  771. case kEngineControlEventTypeAllNotesOff:
  772. if (pData->options & PLUGIN_OPTION_SEND_ALL_SOUND_OFF)
  773. {
  774. #ifndef BUILD_BRIDGE
  775. if (event.channel == pData->ctrlChannel && ! allNotesOffSent)
  776. {
  777. allNotesOffSent = true;
  778. sendMidiAllNotesOffToCallback();
  779. }
  780. #endif
  781. fMidiInputPort->DispatchControlChange(MIDI_CONTROL_ALL_NOTES_OFF, 0, event.channel, static_cast<int32_t>(startTime));
  782. }
  783. break;
  784. }
  785. break;
  786. }
  787. case kEngineEventTypeMidi: {
  788. const EngineMidiEvent& midiEvent(event.midi);
  789. const uint8_t* const midiData(midiEvent.size > EngineMidiEvent::kDataSize ? midiEvent.dataExt : midiEvent.data);
  790. uint8_t status = uint8_t(MIDI_GET_STATUS_FROM_DATA(midiData));
  791. if (status == MIDI_STATUS_CHANNEL_PRESSURE && (pData->options & PLUGIN_OPTION_SEND_CHANNEL_PRESSURE) == 0)
  792. continue;
  793. if (status == MIDI_STATUS_CONTROL_CHANGE && (pData->options & PLUGIN_OPTION_SEND_CONTROL_CHANGES) == 0)
  794. continue;
  795. if (status == MIDI_STATUS_POLYPHONIC_AFTERTOUCH && (pData->options & PLUGIN_OPTION_SEND_NOTE_AFTERTOUCH) == 0)
  796. continue;
  797. if (status == MIDI_STATUS_PITCH_WHEEL_CONTROL && (pData->options & PLUGIN_OPTION_SEND_PITCHBEND) == 0)
  798. continue;
  799. // Fix bad note-off
  800. if (status == MIDI_STATUS_NOTE_ON && midiData[2] == 0)
  801. status = MIDI_STATUS_NOTE_OFF;
  802. // put back channel in data
  803. uint8_t midiData2[midiEvent.size];
  804. midiData2[0] = uint8_t(status | (event.channel & MIDI_CHANNEL_BIT));
  805. std::memcpy(midiData2+1, midiData+1, static_cast<std::size_t>(midiEvent.size-1));
  806. fMidiInputPort->DispatchRaw(midiData2, static_cast<int32_t>(startTime));
  807. if (status == MIDI_STATUS_NOTE_ON)
  808. pData->postponeRtEvent(kPluginPostRtEventNoteOn, event.channel, midiData[1], midiData[2]);
  809. else if (status == MIDI_STATUS_NOTE_OFF)
  810. pData->postponeRtEvent(kPluginPostRtEventNoteOff, event.channel, midiData[1], 0.0f);
  811. } break;
  812. }
  813. }
  814. pData->postRtEvents.trySplice();
  815. if (frames > timeOffset)
  816. processSingle(audioOut, frames - timeOffset, timeOffset);
  817. } // End of Event Input and Processing
  818. // --------------------------------------------------------------------------------------------------------
  819. // Parameter outputs
  820. uint diskStreamCount=0, voiceCount=0;
  821. for (uint i=0; i<kMaxChannels; ++i)
  822. {
  823. LinuxSampler::EngineChannel* const engineChannel(fEngineChannels[i]);
  824. CARLA_SAFE_ASSERT_CONTINUE(engineChannel != nullptr);
  825. diskStreamCount += engineChannel->GetDiskStreamCount();
  826. /**/ voiceCount += engineChannel->GetVoiceCount();
  827. }
  828. fParamBuffers[LinuxSamplerDiskStreamCount] = static_cast<float>(diskStreamCount);
  829. fParamBuffers[LinuxSamplerVoiceCount] = static_cast<float>(voiceCount);
  830. }
  831. bool processSingle(float** const outBuffer, const uint32_t frames, const uint32_t timeOffset)
  832. {
  833. CARLA_SAFE_ASSERT_RETURN(outBuffer != nullptr, false);
  834. CARLA_SAFE_ASSERT_RETURN(frames > 0, false);
  835. // --------------------------------------------------------------------------------------------------------
  836. // Try lock, silence otherwise
  837. if (pData->engine->isOffline())
  838. {
  839. pData->singleMutex.lock();
  840. }
  841. else if (! pData->singleMutex.tryLock())
  842. {
  843. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  844. {
  845. for (uint32_t k=0; k < frames; ++k)
  846. outBuffer[i][k+timeOffset] = 0.0f;
  847. }
  848. return false;
  849. }
  850. // --------------------------------------------------------------------------------------------------------
  851. // Run plugin
  852. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  853. {
  854. if (LinuxSampler::AudioChannel* const outDev = fAudioOutputDevice.Channel(i))
  855. outDev->SetBuffer(outBuffer[i] + timeOffset);
  856. }
  857. fAudioOutputDevice.Render(frames);
  858. #ifndef BUILD_BRIDGE
  859. // --------------------------------------------------------------------------------------------------------
  860. // Post-processing (dry/wet, volume and balance)
  861. {
  862. const bool doVolume = (pData->hints & PLUGIN_CAN_VOLUME) != 0 && carla_isNotEqual(pData->postProc.volume, 1.0f);
  863. const bool doBalance = (pData->hints & PLUGIN_CAN_BALANCE) != 0 && ! (carla_isEqual(pData->postProc.balanceLeft, -1.0f) && carla_isEqual(pData->postProc.balanceRight, 1.0f));
  864. float oldBufLeft[doBalance ? frames : 1];
  865. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  866. {
  867. // Balance
  868. if (doBalance)
  869. {
  870. if (i % 2 == 0)
  871. FloatVectorOperations::copy(oldBufLeft, outBuffer[i], static_cast<int>(frames));
  872. float balRangeL = (pData->postProc.balanceLeft + 1.0f)/2.0f;
  873. float balRangeR = (pData->postProc.balanceRight + 1.0f)/2.0f;
  874. for (uint32_t k=0; k < frames; ++k)
  875. {
  876. if (i % 2 == 0)
  877. {
  878. // left
  879. outBuffer[i][k] = oldBufLeft[k] * (1.0f - balRangeL);
  880. outBuffer[i][k] += outBuffer[i+1][k] * (1.0f - balRangeR);
  881. }
  882. else
  883. {
  884. // right
  885. outBuffer[i][k] = outBuffer[i][k] * balRangeR;
  886. outBuffer[i][k] += oldBufLeft[k] * balRangeL;
  887. }
  888. }
  889. }
  890. // Volume
  891. if (doVolume)
  892. {
  893. for (uint32_t k=0; k < frames; ++k)
  894. outBuffer[i][k+timeOffset] *= pData->postProc.volume;
  895. }
  896. }
  897. } // End of Post-processing
  898. #endif
  899. // --------------------------------------------------------------------------------------------------------
  900. pData->singleMutex.unlock();
  901. return true;
  902. }
  903. #ifndef CARLA_OS_WIN // FIXME, need to update linuxsampler win32 build
  904. void bufferSizeChanged(const uint32_t) override
  905. {
  906. fAudioOutputDevice.ReconnectAll();
  907. }
  908. void sampleRateChanged(const double) override
  909. {
  910. fAudioOutputDevice.ReconnectAll();
  911. }
  912. #endif
  913. // -------------------------------------------------------------------
  914. // Plugin buffers
  915. // nothing
  916. // -------------------------------------------------------------------
  917. const void* getExtraStuff() const noexcept override
  918. {
  919. static const char xtrue[] = "true";
  920. static const char xfalse[] = "false";
  921. return kUses16Outs ? xtrue : xfalse;
  922. }
  923. bool init(const char* const filename, const char* const name, const char* const label, const uint options)
  924. {
  925. CARLA_SAFE_ASSERT_RETURN(pData->engine != nullptr, false);
  926. // ---------------------------------------------------------------
  927. // first checks
  928. if (pData->client != nullptr)
  929. {
  930. pData->engine->setLastError("Plugin client is already registered");
  931. return false;
  932. }
  933. if (filename == nullptr || filename[0] == '\0')
  934. {
  935. pData->engine->setLastError("null filename");
  936. return false;
  937. }
  938. // ---------------------------------------------------------------
  939. // Init LinuxSampler stuff
  940. fMidiInputPort = fMidiInputDevice.GetPort(0);
  941. if (fMidiInputPort == nullptr)
  942. {
  943. pData->engine->setLastError("Failed to get LinuxSampler midi input port");
  944. return false;
  945. }
  946. for (uint i=0; i<kMaxChannels; ++i)
  947. {
  948. LinuxSampler::SamplerChannel* const samplerChannel(sSampler->AddSamplerChannel());
  949. CARLA_SAFE_ASSERT_CONTINUE(samplerChannel != nullptr);
  950. samplerChannel->SetEngineType(kIsGIG ? "GIG" : "SFZ");
  951. samplerChannel->SetAudioOutputDevice(&fAudioOutputDevice);
  952. samplerChannel->SetMidiInputChannel(kIsGIG ? static_cast<LinuxSampler::midi_chan_t>(i) : LinuxSampler::midi_chan_all);
  953. LinuxSampler::EngineChannel* const engineChannel(samplerChannel->GetEngineChannel());
  954. CARLA_SAFE_ASSERT_CONTINUE(engineChannel != nullptr);
  955. engineChannel->Pan(0.0f);
  956. engineChannel->Volume(kIsGIG ? LinuxSampler::kVolumeMax/10.0f : LinuxSampler::kVolumeMax); // FIXME
  957. engineChannel->SetMidiInstrumentMapToDefault();
  958. engineChannel->Connect(fMidiInputPort);
  959. if (kUses16Outs)
  960. {
  961. engineChannel->SetOutputChannel(0, i*2);
  962. engineChannel->SetOutputChannel(1, i*2 +1);
  963. }
  964. else
  965. {
  966. engineChannel->SetOutputChannel(0, 0);
  967. engineChannel->SetOutputChannel(1, 1);
  968. }
  969. fSamplerChannels[i] = samplerChannel;
  970. fEngineChannels[i] = engineChannel;
  971. }
  972. if (fSamplerChannels[0] == nullptr || fEngineChannels[0] == nullptr)
  973. {
  974. pData->engine->setLastError("Failed to create LinuxSampler audio channels");
  975. return false;
  976. }
  977. // ---------------------------------------------------------------
  978. // Get Engine
  979. LinuxSampler::Engine* const engine(fEngineChannels[0]->GetEngine());
  980. if (engine == nullptr)
  981. {
  982. pData->engine->setLastError("Failed to get LinuxSampler engine via channel");
  983. return false;
  984. }
  985. // ---------------------------------------------------------------
  986. // Get the Engine's Instrument Manager
  987. LinuxSampler::InstrumentManager* const instrumentMgr(engine->GetInstrumentManager());
  988. if (instrumentMgr == nullptr)
  989. {
  990. pData->engine->setLastError("Failed to get LinuxSampler instrument manager");
  991. return false;
  992. }
  993. // ---------------------------------------------------------------
  994. // Load the Instrument via filename
  995. try {
  996. fInstrumentIds = instrumentMgr->GetInstrumentFileContent(filename);
  997. }
  998. catch (const LinuxSampler::InstrumentManagerException& e)
  999. {
  1000. pData->engine->setLastError(e.what());
  1001. return false;
  1002. }
  1003. // ---------------------------------------------------------------
  1004. // Get info
  1005. const std::size_t numInstruments(fInstrumentIds.size());
  1006. if (numInstruments == 0)
  1007. {
  1008. pData->engine->setLastError("Failed to find any instruments");
  1009. return false;
  1010. }
  1011. for (std::size_t i=0; i<numInstruments; ++i)
  1012. {
  1013. try {
  1014. fInstrumentInfo.push_back(instrumentMgr->GetInstrumentInfo(fInstrumentIds[i]));
  1015. } CARLA_SAFE_EXCEPTION("GetInstrumentInfo");
  1016. instrumentMgr->SetMode(fInstrumentIds[i], LinuxSampler::InstrumentManager::ON_DEMAND);
  1017. }
  1018. CARLA_SAFE_ASSERT(fInstrumentInfo.size() == numInstruments);
  1019. // ---------------------------------------------------------------
  1020. CarlaString label2(label != nullptr ? label : File(filename).getFileNameWithoutExtension().toRawUTF8());
  1021. if (kUses16Outs && ! label2.endsWith(" (16 outs)"))
  1022. label2 += " (16 outs)";
  1023. fLabel = label2.dup();
  1024. fMaker = carla_strdup(fInstrumentInfo[0].Artists.c_str());
  1025. fRealName = carla_strdup(instrumentMgr->GetInstrumentName(fInstrumentIds[0]).c_str());
  1026. pData->filename = carla_strdup(filename);
  1027. if (name != nullptr && name[0] != '\0')
  1028. pData->name = pData->engine->getUniquePluginName(name);
  1029. else if (fRealName[0] != '\0')
  1030. pData->name = pData->engine->getUniquePluginName(fRealName);
  1031. else
  1032. pData->name = pData->engine->getUniquePluginName(fLabel);
  1033. // ---------------------------------------------------------------
  1034. // register client
  1035. pData->client = pData->engine->addClient(this);
  1036. if (pData->client == nullptr || ! pData->client->isOk())
  1037. {
  1038. pData->engine->setLastError("Failed to register plugin client");
  1039. return false;
  1040. }
  1041. // ---------------------------------------------------------------
  1042. // set default options
  1043. pData->options = 0x0;
  1044. pData->options |= PLUGIN_OPTION_SEND_CONTROL_CHANGES;
  1045. pData->options |= PLUGIN_OPTION_SEND_CHANNEL_PRESSURE;
  1046. pData->options |= PLUGIN_OPTION_SEND_NOTE_AFTERTOUCH;
  1047. pData->options |= PLUGIN_OPTION_SEND_PITCHBEND;
  1048. pData->options |= PLUGIN_OPTION_SEND_ALL_SOUND_OFF;
  1049. if (kIsGIG)
  1050. pData->options |= PLUGIN_OPTION_MAP_PROGRAM_CHANGES;
  1051. return true;
  1052. (void)options;
  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,"
  1097. "please choose the 2-channel only sample-library version");
  1098. return nullptr;
  1099. }
  1100. // -------------------------------------------------------------------
  1101. // Check if file exists
  1102. if (! File(init.filename).existsAsFile())
  1103. {
  1104. init.engine->setLastError("Requested file is not valid or does not exist");
  1105. return nullptr;
  1106. }
  1107. CarlaPluginLinuxSampler* const plugin(new CarlaPluginLinuxSampler(init.engine, init.id, (sformat == "gig"), use16Outs));
  1108. if (! plugin->init(init.filename, init.name, init.label, init.options))
  1109. {
  1110. delete plugin;
  1111. return nullptr;
  1112. }
  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