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.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_zeroStructs(fCurProgs, MAX_MIDI_CHANNELS);
  173. carla_zeroStructs(fSamplerChannels, MAX_MIDI_CHANNELS);
  174. carla_zeroStructs(fEngineChannels, MAX_MIDI_CHANNELS);
  175. carla_zeroFloats(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_PROPERTY) == 0)
  336. return CarlaPlugin::setCustomData(type, key, value, sendGui);
  337. if (std::strcmp(type, CUSTOM_DATA_TYPE_STRING) != 0)
  338. return carla_stderr2("CarlaPluginLinuxSampler::setCustomData(\"%s\", \"%s\", \"%s\", %s) - type is not string", type, key, value, bool2str(sendGui));
  339. if (std::strcmp(key, "programs") != 0)
  340. return carla_stderr2("CarlaPluginLinuxSampler::setCustomData(\"%s\", \"%s\", \"%s\", %s) - key is not programs", type, key, value, bool2str(sendGui));
  341. if (kMaxChannels > 1 && fInstrumentIds.size() > 1)
  342. {
  343. StringArray programList(StringArray::fromTokens(value, ":", ""));
  344. if (programList.size() == MAX_MIDI_CHANNELS)
  345. {
  346. uint8_t channel = 0;
  347. for (juce::String *it=programList.begin(), *end=programList.end(); it != end; ++it)
  348. {
  349. const int index(it->getIntValue());
  350. if (index >= 0)
  351. setProgramInternal(static_cast<uint>(index), channel, true, false);
  352. if (++channel >= MAX_MIDI_CHANNELS)
  353. break;
  354. }
  355. CARLA_SAFE_ASSERT(channel == MAX_MIDI_CHANNELS);
  356. }
  357. }
  358. CarlaPlugin::setCustomData(type, key, value, sendGui);
  359. }
  360. void setProgram(const int32_t index, const bool sendGui, const bool sendOsc, const bool sendCallback) noexcept override
  361. {
  362. CARLA_SAFE_ASSERT_RETURN(sendGui || sendOsc || sendCallback,); // never call this from RT
  363. CARLA_SAFE_ASSERT_RETURN(index >= -1 && index < static_cast<int32_t>(pData->prog.count),);
  364. const int8_t channel(kIsGIG ? pData->ctrlChannel : int8_t(0));
  365. if (index >= 0 && channel >= 0)
  366. setProgramInternal(static_cast<uint>(index), static_cast<uint8_t>(channel), sendCallback, false);
  367. CarlaPlugin::setProgram(index, sendGui, sendOsc, sendCallback);
  368. }
  369. void setProgramInternal(const uint32_t index, const uint8_t channel, const bool sendCallback, const bool inRtContent) noexcept
  370. {
  371. CARLA_SAFE_ASSERT_RETURN(index < pData->prog.count,);
  372. CARLA_SAFE_ASSERT_RETURN(channel < MAX_MIDI_CHANNELS,);
  373. if (fCurProgs[channel] == index)
  374. return;
  375. LinuxSampler::EngineChannel* const engineChannel(fEngineChannels[kIsGIG ? channel : 0]);
  376. CARLA_SAFE_ASSERT_RETURN(engineChannel != nullptr,);
  377. const ScopedSingleProcessLocker spl(this, !inRtContent);
  378. if (pData->engine->isOffline())
  379. {
  380. try {
  381. engineChannel->PrepareLoadInstrument(pData->filename, index);
  382. engineChannel->LoadInstrument();
  383. } CARLA_SAFE_EXCEPTION("LoadInstrument");
  384. }
  385. else
  386. {
  387. try {
  388. LinuxSampler::InstrumentManager::LoadInstrumentInBackground(fInstrumentIds[index], engineChannel);
  389. } CARLA_SAFE_EXCEPTION("LoadInstrumentInBackground");
  390. }
  391. fCurProgs[channel] = index;
  392. if (pData->ctrlChannel == channel)
  393. {
  394. const int32_t iindex(static_cast<int32_t>(index));
  395. pData->prog.current = iindex;
  396. if (inRtContent)
  397. pData->postponeRtEvent(kPluginPostRtEventProgramChange, iindex, 0, 0.0f);
  398. else if (sendCallback)
  399. pData->engine->callback(ENGINE_CALLBACK_PROGRAM_CHANGED, pData->id, iindex, 0, 0.0f, nullptr);
  400. }
  401. }
  402. // -------------------------------------------------------------------
  403. // Set ui stuff
  404. // nothing
  405. // -------------------------------------------------------------------
  406. // Plugin state
  407. void reload() override
  408. {
  409. CARLA_SAFE_ASSERT_RETURN(pData->engine != nullptr,);
  410. carla_debug("CarlaPluginLinuxSampler::reload() - start");
  411. const EngineProcessMode processMode(pData->engine->getProccessMode());
  412. // Safely disable plugin for reload
  413. const ScopedDisabler sd(this);
  414. if (pData->active)
  415. deactivate();
  416. clearBuffers();
  417. uint32_t aOuts, params;
  418. aOuts = kUses16Outs ? 32 : 2;
  419. params = LinuxSamplerParametersMax;
  420. pData->audioOut.createNew(aOuts);
  421. pData->param.createNew(params, false);
  422. const uint portNameSize(pData->engine->getMaxPortNameSize());
  423. CarlaString portName;
  424. // ---------------------------------------
  425. // Audio Outputs
  426. if (kUses16Outs)
  427. {
  428. for (uint32_t i=0; i < 32; ++i)
  429. {
  430. portName.clear();
  431. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  432. {
  433. portName = pData->name;
  434. portName += ":";
  435. }
  436. portName += "out-";
  437. if ((i+2)/2 < 9)
  438. portName += "0";
  439. portName += CarlaString((i+2)/2);
  440. if (i % 2 == 0)
  441. portName += "L";
  442. else
  443. portName += "R";
  444. portName.truncate(portNameSize);
  445. pData->audioOut.ports[i].port = (CarlaEngineAudioPort*)pData->client->addPort(kEnginePortTypeAudio, portName, false, i);
  446. pData->audioOut.ports[i].rindex = i;
  447. }
  448. }
  449. else
  450. {
  451. // out-left
  452. portName.clear();
  453. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  454. {
  455. portName = pData->name;
  456. portName += ":";
  457. }
  458. portName += "out-left";
  459. portName.truncate(portNameSize);
  460. pData->audioOut.ports[0].port = (CarlaEngineAudioPort*)pData->client->addPort(kEnginePortTypeAudio, portName, false, 0);
  461. pData->audioOut.ports[0].rindex = 0;
  462. // out-right
  463. portName.clear();
  464. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  465. {
  466. portName = pData->name;
  467. portName += ":";
  468. }
  469. portName += "out-right";
  470. portName.truncate(portNameSize);
  471. pData->audioOut.ports[1].port = (CarlaEngineAudioPort*)pData->client->addPort(kEnginePortTypeAudio, portName, false, 1);
  472. pData->audioOut.ports[1].rindex = 1;
  473. }
  474. // ---------------------------------------
  475. // Event Input
  476. {
  477. portName.clear();
  478. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  479. {
  480. portName = pData->name;
  481. portName += ":";
  482. }
  483. portName += "events-in";
  484. portName.truncate(portNameSize);
  485. pData->event.portIn = (CarlaEngineEventPort*)pData->client->addPort(kEnginePortTypeEvent, portName, true, 0);
  486. }
  487. // ---------------------------------------
  488. // Parameters
  489. {
  490. int j;
  491. // ----------------------
  492. j = LinuxSamplerDiskStreamCount;
  493. pData->param.data[j].type = PARAMETER_OUTPUT;
  494. pData->param.data[j].hints = PARAMETER_IS_ENABLED | PARAMETER_IS_AUTOMABLE | PARAMETER_IS_INTEGER;
  495. pData->param.data[j].index = j;
  496. pData->param.data[j].rindex = j;
  497. pData->param.ranges[j].min = 0.0f;
  498. pData->param.ranges[j].max = LinuxSampler::kMaxStreams;
  499. pData->param.ranges[j].def = 0.0f;
  500. pData->param.ranges[j].step = 1.0f;
  501. pData->param.ranges[j].stepSmall = 1.0f;
  502. pData->param.ranges[j].stepLarge = 1.0f;
  503. // ----------------------
  504. j = LinuxSamplerVoiceCount;
  505. pData->param.data[j].type = PARAMETER_OUTPUT;
  506. pData->param.data[j].hints = PARAMETER_IS_ENABLED | PARAMETER_IS_AUTOMABLE | PARAMETER_IS_INTEGER;
  507. pData->param.data[j].index = j;
  508. pData->param.data[j].rindex = j;
  509. pData->param.ranges[j].min = 0.0f;
  510. pData->param.ranges[j].max = LinuxSampler::kMaxVoices;
  511. pData->param.ranges[j].def = 0.0f;
  512. pData->param.ranges[j].step = 1.0f;
  513. pData->param.ranges[j].stepSmall = 1.0f;
  514. pData->param.ranges[j].stepLarge = 1.0f;
  515. for (j=0; j<LinuxSamplerParametersMax; ++j)
  516. fParamBuffers[j] = pData->param.ranges[j].def;
  517. }
  518. // ---------------------------------------
  519. // plugin hints
  520. pData->hints = 0x0;
  521. pData->hints |= PLUGIN_IS_SYNTH;
  522. pData->hints |= PLUGIN_CAN_VOLUME;
  523. if (! kUses16Outs)
  524. pData->hints |= PLUGIN_CAN_BALANCE;
  525. // extra plugin hints
  526. pData->extraHints = 0x0;
  527. pData->extraHints |= PLUGIN_EXTRA_HINT_HAS_MIDI_IN;
  528. if (kMaxChannels > 1 && fInstrumentIds.size() > 1)
  529. pData->hints |= PLUGIN_USES_MULTI_PROGS;
  530. if (! kUses16Outs)
  531. pData->extraHints |= PLUGIN_EXTRA_HINT_CAN_RUN_RACK;
  532. bufferSizeChanged(pData->engine->getBufferSize());
  533. reloadPrograms(true);
  534. if (pData->active)
  535. activate();
  536. carla_debug("CarlaPluginLinuxSampler::reload() - end");
  537. }
  538. void reloadPrograms(bool doInit) override
  539. {
  540. carla_debug("CarlaPluginLinuxSampler::reloadPrograms(%s)", bool2str(doInit));
  541. // Delete old programs
  542. pData->prog.clear();
  543. // Query new programs
  544. const uint32_t count(static_cast<uint32_t>(fInstrumentInfo.size()));
  545. // sound kits must always have at least 1 midi-program
  546. CARLA_SAFE_ASSERT_RETURN(count > 0,);
  547. pData->prog.createNew(count);
  548. // Update data
  549. for (uint32_t i=0; i < pData->prog.count; ++i)
  550. pData->prog.names[i] = carla_strdup_safe(fInstrumentInfo[i].InstrumentName.c_str());
  551. #if defined(HAVE_LIBLO) && ! defined(BUILD_BRIDGE)
  552. // Update OSC Names
  553. if (pData->engine->isOscControlRegistered() && pData->id < pData->engine->getCurrentPluginCount())
  554. {
  555. pData->engine->oscSend_control_set_program_count(pData->id, count);
  556. for (uint32_t i=0; i < count; ++i)
  557. pData->engine->oscSend_control_set_program_name(pData->id, i, pData->prog.names[i]);
  558. }
  559. #endif
  560. if (doInit)
  561. {
  562. for (uint i=0; i<kMaxChannels; ++i)
  563. {
  564. LinuxSampler::EngineChannel* const engineChannel(fEngineChannels[i]);
  565. CARLA_SAFE_ASSERT_CONTINUE(engineChannel != nullptr);
  566. try {
  567. LinuxSampler::InstrumentManager::LoadInstrumentInBackground(fInstrumentIds[0], engineChannel);
  568. } CARLA_SAFE_EXCEPTION("LoadInstrumentInBackground");
  569. fCurProgs[i] = 0;
  570. }
  571. pData->prog.current = 0;
  572. }
  573. else
  574. {
  575. pData->engine->callback(ENGINE_CALLBACK_RELOAD_PROGRAMS, pData->id, 0, 0, 0.0f, nullptr);
  576. }
  577. }
  578. // -------------------------------------------------------------------
  579. // Plugin processing
  580. #if 0
  581. void activate() override
  582. {
  583. for (int i=0; i < MAX_MIDI_CHANNELS; ++i)
  584. {
  585. if (fAudioOutputDevices[i] != nullptr)
  586. fAudioOutputDevices[i]->Play();
  587. }
  588. }
  589. void deactivate() override
  590. {
  591. for (int i=0; i < MAX_MIDI_CHANNELS; ++i)
  592. {
  593. if (fAudioOutputDevices[i] != nullptr)
  594. fAudioOutputDevices[i]->Stop();
  595. }
  596. }
  597. #endif
  598. void process(const float** const, float** const audioOut, const float** const, float** const, const uint32_t frames) override
  599. {
  600. // --------------------------------------------------------------------------------------------------------
  601. // Check if active
  602. if (! pData->active)
  603. {
  604. // disable any output sound
  605. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  606. FloatVectorOperations::clear(audioOut[i], static_cast<int>(frames));
  607. fParamBuffers[LinuxSamplerDiskStreamCount] = 0.0f;
  608. fParamBuffers[LinuxSamplerVoiceCount] = 0.0f;
  609. return;
  610. }
  611. // --------------------------------------------------------------------------------------------------------
  612. // Check if needs reset
  613. if (pData->needsReset)
  614. {
  615. if (pData->options & PLUGIN_OPTION_SEND_ALL_SOUND_OFF)
  616. {
  617. for (uint i=0; i < MAX_MIDI_CHANNELS; ++i)
  618. {
  619. fMidiInputPort->DispatchControlChange(MIDI_CONTROL_ALL_NOTES_OFF, 0, i);
  620. fMidiInputPort->DispatchControlChange(MIDI_CONTROL_ALL_SOUND_OFF, 0, i);
  621. }
  622. }
  623. else if (pData->ctrlChannel >= 0 && pData->ctrlChannel < MAX_MIDI_CHANNELS)
  624. {
  625. for (uint8_t i=0; i < MAX_MIDI_NOTE; ++i)
  626. fMidiInputPort->DispatchNoteOff(i, 0, uint(pData->ctrlChannel));
  627. }
  628. pData->needsReset = false;
  629. }
  630. // --------------------------------------------------------------------------------------------------------
  631. // Event Input and Processing
  632. {
  633. // ----------------------------------------------------------------------------------------------------
  634. // MIDI Input (External)
  635. if (pData->extNotes.mutex.tryLock())
  636. {
  637. for (RtLinkedList<ExternalMidiNote>::Itenerator it = pData->extNotes.data.begin2(); it.valid(); it.next())
  638. {
  639. const ExternalMidiNote& note(it.getValue());
  640. CARLA_SAFE_ASSERT_CONTINUE(note.channel >= 0 && note.channel < MAX_MIDI_CHANNELS);
  641. if (note.velo > 0)
  642. fMidiInputPort->DispatchNoteOn(note.note, note.velo, static_cast<uint>(note.channel));
  643. else
  644. fMidiInputPort->DispatchNoteOff(note.note, note.velo, static_cast<uint>(note.channel));
  645. }
  646. pData->extNotes.data.clear();
  647. pData->extNotes.mutex.unlock();
  648. } // End of MIDI Input (External)
  649. // ----------------------------------------------------------------------------------------------------
  650. // Event Input (System)
  651. #ifndef BUILD_BRIDGE
  652. bool allNotesOffSent = false;
  653. #endif
  654. bool sampleAccurate = (pData->options & PLUGIN_OPTION_FIXED_BUFFERS) == 0;
  655. uint32_t startTime = 0;
  656. uint32_t timeOffset = 0;
  657. for (uint32_t i=0, numEvents=pData->event.portIn->getEventCount(); i < numEvents; ++i)
  658. {
  659. const EngineEvent& event(pData->event.portIn->getEvent(i));
  660. CARLA_SAFE_ASSERT_CONTINUE(event.time < frames);
  661. CARLA_SAFE_ASSERT_BREAK(event.time >= timeOffset);
  662. if (event.time > timeOffset && sampleAccurate)
  663. {
  664. if (processSingle(audioOut, event.time - timeOffset, timeOffset))
  665. {
  666. startTime = 0;
  667. timeOffset = event.time;
  668. }
  669. else
  670. startTime += timeOffset;
  671. }
  672. // Control change
  673. switch (event.type)
  674. {
  675. case kEngineEventTypeNull:
  676. break;
  677. case kEngineEventTypeControl:
  678. {
  679. const EngineControlEvent& ctrlEvent = event.ctrl;
  680. switch (ctrlEvent.type)
  681. {
  682. case kEngineControlEventTypeNull:
  683. break;
  684. case kEngineControlEventTypeParameter:
  685. {
  686. #ifndef BUILD_BRIDGE
  687. // Control backend stuff
  688. if (event.channel == pData->ctrlChannel)
  689. {
  690. float value;
  691. if (MIDI_IS_CONTROL_BREATH_CONTROLLER(ctrlEvent.param) && (pData->hints & PLUGIN_CAN_DRYWET) != 0)
  692. {
  693. value = ctrlEvent.value;
  694. setDryWet(value, false, false);
  695. pData->postponeRtEvent(kPluginPostRtEventParameterChange, PARAMETER_DRYWET, 0, value);
  696. }
  697. if (MIDI_IS_CONTROL_CHANNEL_VOLUME(ctrlEvent.param) && (pData->hints & PLUGIN_CAN_VOLUME) != 0)
  698. {
  699. value = ctrlEvent.value*127.0f/100.0f;
  700. setVolume(value, false, false);
  701. pData->postponeRtEvent(kPluginPostRtEventParameterChange, PARAMETER_VOLUME, 0, value);
  702. }
  703. if (MIDI_IS_CONTROL_BALANCE(ctrlEvent.param) && (pData->hints & PLUGIN_CAN_BALANCE) != 0)
  704. {
  705. float left, right;
  706. value = ctrlEvent.value/0.5f - 1.0f;
  707. if (value < 0.0f)
  708. {
  709. left = -1.0f;
  710. right = (value*2.0f)+1.0f;
  711. }
  712. else if (value > 0.0f)
  713. {
  714. left = (value*2.0f)-1.0f;
  715. right = 1.0f;
  716. }
  717. else
  718. {
  719. left = -1.0f;
  720. right = 1.0f;
  721. }
  722. setBalanceLeft(left, false, false);
  723. setBalanceRight(right, false, false);
  724. pData->postponeRtEvent(kPluginPostRtEventParameterChange, PARAMETER_BALANCE_LEFT, 0, left);
  725. pData->postponeRtEvent(kPluginPostRtEventParameterChange, PARAMETER_BALANCE_RIGHT, 0, right);
  726. }
  727. }
  728. #endif
  729. // Control plugin parameters
  730. for (uint32_t k=0; k < pData->param.count; ++k)
  731. {
  732. if (pData->param.data[k].midiChannel != event.channel)
  733. continue;
  734. if (pData->param.data[k].midiCC != ctrlEvent.param)
  735. continue;
  736. if (pData->param.data[k].hints != PARAMETER_INPUT)
  737. continue;
  738. if ((pData->param.data[k].hints & PARAMETER_IS_AUTOMABLE) == 0)
  739. continue;
  740. float value;
  741. if (pData->param.data[k].hints & PARAMETER_IS_BOOLEAN)
  742. {
  743. value = (ctrlEvent.value < 0.5f) ? pData->param.ranges[k].min : pData->param.ranges[k].max;
  744. }
  745. else
  746. {
  747. value = pData->param.ranges[k].getUnnormalizedValue(ctrlEvent.value);
  748. if (pData->param.data[k].hints & PARAMETER_IS_INTEGER)
  749. value = std::rint(value);
  750. }
  751. setParameterValue(k, value, false, false, false);
  752. pData->postponeRtEvent(kPluginPostRtEventParameterChange, static_cast<int32_t>(k), 0, value);
  753. }
  754. if ((pData->options & PLUGIN_OPTION_SEND_CONTROL_CHANGES) != 0 && ctrlEvent.param < MAX_MIDI_CONTROL)
  755. {
  756. fMidiInputPort->DispatchControlChange(uint8_t(ctrlEvent.param), uint8_t(ctrlEvent.value*127.0f), event.channel, static_cast<int32_t>(sampleAccurate ? startTime : event.time));
  757. }
  758. break;
  759. }
  760. case kEngineControlEventTypeMidiBank:
  761. break;
  762. case kEngineControlEventTypeMidiProgram:
  763. if (pData->options & PLUGIN_OPTION_MAP_PROGRAM_CHANGES)
  764. {
  765. setProgramInternal(ctrlEvent.param, event.channel, false, true);
  766. }
  767. break;
  768. case kEngineControlEventTypeAllSoundOff:
  769. if (pData->options & PLUGIN_OPTION_SEND_ALL_SOUND_OFF)
  770. {
  771. fMidiInputPort->DispatchControlChange(MIDI_CONTROL_ALL_SOUND_OFF, 0, event.channel, static_cast<int32_t>(sampleAccurate ? startTime : event.time));
  772. }
  773. break;
  774. case kEngineControlEventTypeAllNotesOff:
  775. if (pData->options & PLUGIN_OPTION_SEND_ALL_SOUND_OFF)
  776. {
  777. #ifndef BUILD_BRIDGE
  778. if (event.channel == pData->ctrlChannel && ! allNotesOffSent)
  779. {
  780. allNotesOffSent = true;
  781. sendMidiAllNotesOffToCallback();
  782. }
  783. #endif
  784. fMidiInputPort->DispatchControlChange(MIDI_CONTROL_ALL_NOTES_OFF, 0, event.channel, static_cast<int32_t>(sampleAccurate ? startTime : event.time));
  785. }
  786. break;
  787. }
  788. break;
  789. }
  790. case kEngineEventTypeMidi: {
  791. const EngineMidiEvent& midiEvent(event.midi);
  792. const uint8_t* const midiData(midiEvent.size > EngineMidiEvent::kDataSize ? midiEvent.dataExt : midiEvent.data);
  793. uint8_t status = uint8_t(MIDI_GET_STATUS_FROM_DATA(midiData));
  794. if (status == MIDI_STATUS_CHANNEL_PRESSURE && (pData->options & PLUGIN_OPTION_SEND_CHANNEL_PRESSURE) == 0)
  795. continue;
  796. if (status == MIDI_STATUS_CONTROL_CHANGE && (pData->options & PLUGIN_OPTION_SEND_CONTROL_CHANGES) == 0)
  797. continue;
  798. if (status == MIDI_STATUS_POLYPHONIC_AFTERTOUCH && (pData->options & PLUGIN_OPTION_SEND_NOTE_AFTERTOUCH) == 0)
  799. continue;
  800. if (status == MIDI_STATUS_PITCH_WHEEL_CONTROL && (pData->options & PLUGIN_OPTION_SEND_PITCHBEND) == 0)
  801. continue;
  802. // Fix bad note-off
  803. if (status == MIDI_STATUS_NOTE_ON && midiData[2] == 0)
  804. status = MIDI_STATUS_NOTE_OFF;
  805. // put back channel in data
  806. uint8_t midiData2[midiEvent.size];
  807. midiData2[0] = uint8_t(status | (event.channel & MIDI_CHANNEL_BIT));
  808. std::memcpy(midiData2+1, midiData+1, static_cast<std::size_t>(midiEvent.size-1));
  809. fMidiInputPort->DispatchRaw(midiData2, static_cast<int32_t>(sampleAccurate ? startTime : event.time));
  810. if (status == MIDI_STATUS_NOTE_ON)
  811. pData->postponeRtEvent(kPluginPostRtEventNoteOn, event.channel, midiData[1], midiData[2]);
  812. else if (status == MIDI_STATUS_NOTE_OFF)
  813. pData->postponeRtEvent(kPluginPostRtEventNoteOff, event.channel, midiData[1], 0.0f);
  814. } break;
  815. }
  816. }
  817. pData->postRtEvents.trySplice();
  818. if (frames > timeOffset)
  819. processSingle(audioOut, frames - timeOffset, timeOffset);
  820. } // End of Event Input and Processing
  821. // --------------------------------------------------------------------------------------------------------
  822. // Parameter outputs
  823. uint diskStreamCount=0, voiceCount=0;
  824. for (uint i=0; i<kMaxChannels; ++i)
  825. {
  826. LinuxSampler::EngineChannel* const engineChannel(fEngineChannels[i]);
  827. CARLA_SAFE_ASSERT_CONTINUE(engineChannel != nullptr);
  828. diskStreamCount += engineChannel->GetDiskStreamCount();
  829. /**/ voiceCount += engineChannel->GetVoiceCount();
  830. }
  831. fParamBuffers[LinuxSamplerDiskStreamCount] = static_cast<float>(diskStreamCount);
  832. fParamBuffers[LinuxSamplerVoiceCount] = static_cast<float>(voiceCount);
  833. }
  834. bool processSingle(float** const outBuffer, const uint32_t frames, const uint32_t timeOffset)
  835. {
  836. CARLA_SAFE_ASSERT_RETURN(outBuffer != nullptr, false);
  837. CARLA_SAFE_ASSERT_RETURN(frames > 0, false);
  838. // --------------------------------------------------------------------------------------------------------
  839. // Try lock, silence otherwise
  840. if (pData->engine->isOffline())
  841. {
  842. pData->singleMutex.lock();
  843. }
  844. else if (! pData->singleMutex.tryLock())
  845. {
  846. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  847. {
  848. for (uint32_t k=0; k < frames; ++k)
  849. outBuffer[i][k+timeOffset] = 0.0f;
  850. }
  851. return false;
  852. }
  853. // --------------------------------------------------------------------------------------------------------
  854. // Run plugin
  855. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  856. {
  857. if (LinuxSampler::AudioChannel* const outDev = fAudioOutputDevice.Channel(i))
  858. outDev->SetBuffer(outBuffer[i] + timeOffset);
  859. }
  860. fAudioOutputDevice.Render(frames);
  861. #ifndef BUILD_BRIDGE
  862. // --------------------------------------------------------------------------------------------------------
  863. // Post-processing (dry/wet, volume and balance)
  864. {
  865. const bool doVolume = (pData->hints & PLUGIN_CAN_VOLUME) != 0 && carla_isNotEqual(pData->postProc.volume, 1.0f);
  866. const bool doBalance = (pData->hints & PLUGIN_CAN_BALANCE) != 0 && ! (carla_isEqual(pData->postProc.balanceLeft, -1.0f) && carla_isEqual(pData->postProc.balanceRight, 1.0f));
  867. float oldBufLeft[doBalance ? frames : 1];
  868. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  869. {
  870. // Balance
  871. if (doBalance)
  872. {
  873. if (i % 2 == 0)
  874. FloatVectorOperations::copy(oldBufLeft, outBuffer[i], static_cast<int>(frames));
  875. float balRangeL = (pData->postProc.balanceLeft + 1.0f)/2.0f;
  876. float balRangeR = (pData->postProc.balanceRight + 1.0f)/2.0f;
  877. for (uint32_t k=0; k < frames; ++k)
  878. {
  879. if (i % 2 == 0)
  880. {
  881. // left
  882. outBuffer[i][k] = oldBufLeft[k] * (1.0f - balRangeL);
  883. outBuffer[i][k] += outBuffer[i+1][k] * (1.0f - balRangeR);
  884. }
  885. else
  886. {
  887. // right
  888. outBuffer[i][k] = outBuffer[i][k] * balRangeR;
  889. outBuffer[i][k] += oldBufLeft[k] * balRangeL;
  890. }
  891. }
  892. }
  893. // Volume
  894. if (doVolume)
  895. {
  896. for (uint32_t k=0; k < frames; ++k)
  897. outBuffer[i][k+timeOffset] *= pData->postProc.volume;
  898. }
  899. }
  900. } // End of Post-processing
  901. #endif
  902. // --------------------------------------------------------------------------------------------------------
  903. pData->singleMutex.unlock();
  904. return true;
  905. }
  906. #ifndef CARLA_OS_WIN // FIXME, need to update linuxsampler win32 build
  907. void bufferSizeChanged(const uint32_t) override
  908. {
  909. fAudioOutputDevice.ReconnectAll();
  910. }
  911. void sampleRateChanged(const double) override
  912. {
  913. fAudioOutputDevice.ReconnectAll();
  914. }
  915. #endif
  916. // -------------------------------------------------------------------
  917. // Plugin buffers
  918. // nothing
  919. // -------------------------------------------------------------------
  920. const void* getExtraStuff() const noexcept override
  921. {
  922. static const char xtrue[] = "true";
  923. static const char xfalse[] = "false";
  924. return kUses16Outs ? xtrue : xfalse;
  925. }
  926. bool init(const char* const filename, const char* const name, const char* const label)
  927. {
  928. CARLA_SAFE_ASSERT_RETURN(pData->engine != nullptr, false);
  929. // ---------------------------------------------------------------
  930. // first checks
  931. if (pData->client != nullptr)
  932. {
  933. pData->engine->setLastError("Plugin client is already registered");
  934. return false;
  935. }
  936. if (filename == nullptr || filename[0] == '\0')
  937. {
  938. pData->engine->setLastError("null filename");
  939. return false;
  940. }
  941. // ---------------------------------------------------------------
  942. // Init LinuxSampler stuff
  943. fMidiInputPort = fMidiInputDevice.GetPort(0);
  944. if (fMidiInputPort == nullptr)
  945. {
  946. pData->engine->setLastError("Failed to get LinuxSampler midi input port");
  947. return false;
  948. }
  949. for (uint i=0; i<kMaxChannels; ++i)
  950. {
  951. LinuxSampler::SamplerChannel* const samplerChannel(sSampler->AddSamplerChannel());
  952. CARLA_SAFE_ASSERT_CONTINUE(samplerChannel != nullptr);
  953. samplerChannel->SetEngineType(kIsGIG ? "GIG" : "SFZ");
  954. samplerChannel->SetAudioOutputDevice(&fAudioOutputDevice);
  955. samplerChannel->SetMidiInputChannel(kIsGIG ? static_cast<LinuxSampler::midi_chan_t>(i) : LinuxSampler::midi_chan_all);
  956. LinuxSampler::EngineChannel* const engineChannel(samplerChannel->GetEngineChannel());
  957. CARLA_SAFE_ASSERT_CONTINUE(engineChannel != nullptr);
  958. engineChannel->Pan(0.0f);
  959. engineChannel->Volume(kIsGIG ? LinuxSampler::kVolumeMax/10.0f : LinuxSampler::kVolumeMax); // FIXME
  960. engineChannel->SetMidiInstrumentMapToDefault();
  961. engineChannel->Connect(fMidiInputPort);
  962. if (kUses16Outs)
  963. {
  964. engineChannel->SetOutputChannel(0, i*2);
  965. engineChannel->SetOutputChannel(1, i*2 +1);
  966. }
  967. else
  968. {
  969. engineChannel->SetOutputChannel(0, 0);
  970. engineChannel->SetOutputChannel(1, 1);
  971. }
  972. fSamplerChannels[i] = samplerChannel;
  973. fEngineChannels[i] = engineChannel;
  974. }
  975. if (fSamplerChannels[0] == nullptr || fEngineChannels[0] == nullptr)
  976. {
  977. pData->engine->setLastError("Failed to create LinuxSampler audio channels");
  978. return false;
  979. }
  980. // ---------------------------------------------------------------
  981. // Get Engine
  982. LinuxSampler::Engine* const engine(fEngineChannels[0]->GetEngine());
  983. if (engine == nullptr)
  984. {
  985. pData->engine->setLastError("Failed to get LinuxSampler engine via channel");
  986. return false;
  987. }
  988. // ---------------------------------------------------------------
  989. // Get the Engine's Instrument Manager
  990. LinuxSampler::InstrumentManager* const instrumentMgr(engine->GetInstrumentManager());
  991. if (instrumentMgr == nullptr)
  992. {
  993. pData->engine->setLastError("Failed to get LinuxSampler instrument manager");
  994. return false;
  995. }
  996. // ---------------------------------------------------------------
  997. // Load the Instrument via filename
  998. try {
  999. fInstrumentIds = instrumentMgr->GetInstrumentFileContent(filename);
  1000. }
  1001. catch (const LinuxSampler::InstrumentManagerException& e)
  1002. {
  1003. pData->engine->setLastError(e.what());
  1004. return false;
  1005. }
  1006. // ---------------------------------------------------------------
  1007. // Get info
  1008. const std::size_t numInstruments(fInstrumentIds.size());
  1009. if (numInstruments == 0)
  1010. {
  1011. pData->engine->setLastError("Failed to find any instruments");
  1012. return false;
  1013. }
  1014. for (std::size_t i=0; i<numInstruments; ++i)
  1015. {
  1016. try {
  1017. fInstrumentInfo.push_back(instrumentMgr->GetInstrumentInfo(fInstrumentIds[i]));
  1018. } CARLA_SAFE_EXCEPTION("GetInstrumentInfo");
  1019. instrumentMgr->SetMode(fInstrumentIds[i], LinuxSampler::InstrumentManager::ON_DEMAND);
  1020. }
  1021. CARLA_SAFE_ASSERT(fInstrumentInfo.size() == numInstruments);
  1022. // ---------------------------------------------------------------
  1023. CarlaString label2(label != nullptr ? label : File(filename).getFileNameWithoutExtension().toRawUTF8());
  1024. if (kUses16Outs && ! label2.endsWith(" (16 outs)"))
  1025. label2 += " (16 outs)";
  1026. fLabel = label2.dup();
  1027. fMaker = carla_strdup(fInstrumentInfo[0].Artists.c_str());
  1028. fRealName = carla_strdup(instrumentMgr->GetInstrumentName(fInstrumentIds[0]).c_str());
  1029. pData->filename = carla_strdup(filename);
  1030. if (name != nullptr && name[0] != '\0')
  1031. pData->name = pData->engine->getUniquePluginName(name);
  1032. else if (fRealName[0] != '\0')
  1033. pData->name = pData->engine->getUniquePluginName(fRealName);
  1034. else
  1035. pData->name = pData->engine->getUniquePluginName(fLabel);
  1036. // ---------------------------------------------------------------
  1037. // register client
  1038. pData->client = pData->engine->addClient(this);
  1039. if (pData->client == nullptr || ! pData->client->isOk())
  1040. {
  1041. pData->engine->setLastError("Failed to register plugin client");
  1042. return false;
  1043. }
  1044. // ---------------------------------------------------------------
  1045. // set default options
  1046. pData->options = 0x0;
  1047. pData->options |= PLUGIN_OPTION_SEND_CONTROL_CHANGES;
  1048. pData->options |= PLUGIN_OPTION_SEND_CHANNEL_PRESSURE;
  1049. pData->options |= PLUGIN_OPTION_SEND_NOTE_AFTERTOUCH;
  1050. pData->options |= PLUGIN_OPTION_SEND_PITCHBEND;
  1051. pData->options |= PLUGIN_OPTION_SEND_ALL_SOUND_OFF;
  1052. if (kIsGIG)
  1053. pData->options |= PLUGIN_OPTION_MAP_PROGRAM_CHANGES;
  1054. return true;
  1055. }
  1056. // -------------------------------------------------------------------
  1057. private:
  1058. enum LinuxSamplerParameters {
  1059. LinuxSamplerDiskStreamCount = 0,
  1060. LinuxSamplerVoiceCount = 1,
  1061. LinuxSamplerParametersMax = 2
  1062. };
  1063. const bool kIsGIG; // SFZ if false
  1064. const bool kUses16Outs;
  1065. const uint kMaxChannels; // 16 for gig, 1 for sfz
  1066. const char* fLabel;
  1067. const char* fMaker;
  1068. const char* fRealName;
  1069. uint32_t fCurProgs[MAX_MIDI_CHANNELS];
  1070. float fParamBuffers[LinuxSamplerParametersMax];
  1071. SharedResourcePointer<LinuxSampler::Sampler> sSampler;
  1072. LinuxSampler::AudioOutputDevicePlugin fAudioOutputDevice;
  1073. LinuxSampler::MidiInputDevicePlugin fMidiInputDevice;
  1074. LinuxSampler::MidiInputPort* fMidiInputPort;
  1075. LinuxSampler::SamplerChannel* fSamplerChannels[MAX_MIDI_CHANNELS];
  1076. LinuxSampler::EngineChannel* fEngineChannels[MAX_MIDI_CHANNELS];
  1077. std::vector<LinuxSampler::InstrumentManager::instrument_id_t> fInstrumentIds;
  1078. std::vector<LinuxSampler::InstrumentManager::instrument_info_t> fInstrumentInfo;
  1079. CARLA_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(CarlaPluginLinuxSampler)
  1080. };
  1081. CARLA_BACKEND_END_NAMESPACE
  1082. #endif // HAVE_LINUXSAMPLER
  1083. CARLA_BACKEND_START_NAMESPACE
  1084. // -------------------------------------------------------------------------------------------------------------------
  1085. CarlaPlugin* CarlaPlugin::newLinuxSampler(const Initializer& init, const char* const format, const bool use16Outs)
  1086. {
  1087. 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));
  1088. #ifdef HAVE_LINUXSAMPLER
  1089. CarlaString sformat(format);
  1090. sformat.toLower();
  1091. if (sformat != "gig" && sformat != "sfz")
  1092. {
  1093. init.engine->setLastError("Unsupported format requested for LinuxSampler");
  1094. return nullptr;
  1095. }
  1096. if (init.engine->getProccessMode() == ENGINE_PROCESS_MODE_CONTINUOUS_RACK && use16Outs)
  1097. {
  1098. init.engine->setLastError("Carla's rack mode can only work with Stereo modules, please choose the 2-channel only sample-library version");
  1099. return nullptr;
  1100. }
  1101. // -------------------------------------------------------------------
  1102. // Check if file exists
  1103. if (! File(init.filename).existsAsFile())
  1104. {
  1105. init.engine->setLastError("Requested file is not valid or does not exist");
  1106. return nullptr;
  1107. }
  1108. CarlaPluginLinuxSampler* const plugin(new CarlaPluginLinuxSampler(init.engine, init.id, (sformat == "gig"), use16Outs));
  1109. if (! plugin->init(init.filename, init.name, init.label))
  1110. {
  1111. delete plugin;
  1112. return nullptr;
  1113. }
  1114. return plugin;
  1115. #else
  1116. init.engine->setLastError("linuxsampler support not available");
  1117. return nullptr;
  1118. // unused
  1119. (void)format;
  1120. (void)use16Outs;
  1121. #endif
  1122. }
  1123. CarlaPlugin* CarlaPlugin::newFileGIG(const Initializer& init, const bool use16Outs)
  1124. {
  1125. carla_debug("CarlaPlugin::newFileGIG({%p, \"%s\", \"%s\", \"%s\"}, %s)", init.engine, init.filename, init.name, init.label, bool2str(use16Outs));
  1126. #ifdef HAVE_LINUXSAMPLER
  1127. return newLinuxSampler(init, "GIG", use16Outs);
  1128. #else
  1129. init.engine->setLastError("GIG support not available");
  1130. return nullptr;
  1131. // unused
  1132. (void)use16Outs;
  1133. #endif
  1134. }
  1135. CarlaPlugin* CarlaPlugin::newFileSFZ(const Initializer& init)
  1136. {
  1137. carla_debug("CarlaPlugin::newFileSFZ({%p, \"%s\", \"%s\", \"%s\"})", init.engine, init.filename, init.name, init.label);
  1138. #ifdef HAVE_LINUXSAMPLER
  1139. return newLinuxSampler(init, "SFZ", false);
  1140. #else
  1141. init.engine->setLastError("SFZ support not available");
  1142. return nullptr;
  1143. #endif
  1144. }
  1145. // -------------------------------------------------------------------------------------------------------------------
  1146. CARLA_BACKEND_END_NAMESPACE