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.

1525 lines
52KB

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