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.

1548 lines
53KB

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