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.

1409 lines
47KB

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