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.

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