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.

1142 lines
38KB

  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 GPL.txt file
  16. */
  17. #include "CarlaPluginInternal.hpp"
  18. #ifdef WANT_LINUXSAMPLER
  19. #include "linuxsampler/EngineFactory.h"
  20. #include <linuxsampler/Sampler.h>
  21. #include <QtCore/QFileInfo>
  22. // TODO - setMidiProgram()
  23. namespace LinuxSampler {
  24. // -----------------------------------------------------------------------
  25. // LinuxSampler static values
  26. static const float VOLUME_MAX = 3.16227766f; // +10 dB
  27. static const float VOLUME_MIN = 0.0f; // -inf dB
  28. // -----------------------------------------------------------------------
  29. // LinuxSampler AudioOutputDevice Plugin
  30. class AudioOutputDevicePlugin : public AudioOutputDevice
  31. {
  32. public:
  33. AudioOutputDevicePlugin(CarlaBackend::CarlaEngine* const engine, CarlaBackend::CarlaPlugin* const plugin)
  34. : AudioOutputDevice(std::map<String, DeviceCreationParameter*>()),
  35. kEngine(engine),
  36. kPlugin(plugin)
  37. {
  38. CARLA_ASSERT(engine != nullptr);
  39. CARLA_ASSERT(plugin != nullptr);
  40. }
  41. // -------------------------------------------------------------------
  42. // LinuxSampler virtual methods
  43. void Play() override
  44. {
  45. }
  46. bool IsPlaying() override
  47. {
  48. return (kEngine->isRunning() && kPlugin->enabled());
  49. }
  50. void Stop() override
  51. {
  52. }
  53. uint MaxSamplesPerCycle() override
  54. {
  55. return kEngine->getBufferSize();
  56. }
  57. uint SampleRate() override
  58. {
  59. return kEngine->getSampleRate();
  60. }
  61. String Driver() override
  62. {
  63. return "AudioOutputDevicePlugin";
  64. }
  65. AudioChannel* CreateChannel(uint channelNr) override
  66. {
  67. return new AudioChannel(channelNr, nullptr, 0);
  68. }
  69. // -------------------------------------------------------------------
  70. // Give public access to the RenderAudio call
  71. int Render(const uint samples)
  72. {
  73. return RenderAudio(samples);
  74. }
  75. private:
  76. CarlaBackend::CarlaEngine* const kEngine;
  77. CarlaBackend::CarlaPlugin* const kPlugin;
  78. };
  79. // -----------------------------------------------------------------------
  80. // LinuxSampler MidiInputDevice Plugin
  81. class MidiInputDevicePlugin : public MidiInputDevice
  82. {
  83. public:
  84. MidiInputDevicePlugin(Sampler* const sampler)
  85. : MidiInputDevice(std::map<String, DeviceCreationParameter*>(), sampler)
  86. {
  87. }
  88. // -------------------------------------------------------------------
  89. // LinuxSampler virtual methods
  90. void Listen() override
  91. {
  92. }
  93. void StopListen() override
  94. {
  95. }
  96. String Driver() override
  97. {
  98. return "MidiInputDevicePlugin";
  99. }
  100. MidiInputPort* CreateMidiPort() override
  101. {
  102. return new MidiInputPortPlugin(this, Ports.size());
  103. }
  104. // -------------------------------------------------------------------
  105. // Properly delete port (destructor is protected)
  106. void DeleteMidiPort(MidiInputPort* const port)
  107. {
  108. delete (MidiInputPortPlugin*)port;
  109. }
  110. // -------------------------------------------------------------------
  111. // MIDI Port implementation for this plugin MIDI input driver
  112. // (Constructor and destructor are protected)
  113. class MidiInputPortPlugin : public MidiInputPort
  114. {
  115. protected:
  116. MidiInputPortPlugin(MidiInputDevicePlugin* const device, const int portNumber)
  117. : MidiInputPort(device, portNumber) {}
  118. friend class MidiInputDevicePlugin;
  119. };
  120. };
  121. } // namespace LinuxSampler
  122. // -----------------------------------------------------------------------
  123. CARLA_BACKEND_START_NAMESPACE
  124. #if 0
  125. }
  126. #endif
  127. class LinuxSamplerPlugin : public CarlaPlugin
  128. {
  129. public:
  130. LinuxSamplerPlugin(CarlaEngine* const engine, const unsigned short id, const bool isGIG, const bool use16Outs)
  131. : CarlaPlugin(engine, id),
  132. kIsGIG(isGIG),
  133. kUses16Outs(use16Outs),
  134. fSampler(nullptr),
  135. fSamplerChannel(nullptr),
  136. fEngine(nullptr),
  137. fEngineChannel(nullptr),
  138. fAudioOutputDevice(nullptr),
  139. fMidiInputDevice(nullptr),
  140. fMidiInputPort(nullptr),
  141. fInstrument(nullptr)
  142. {
  143. carla_debug("LinuxSamplerPlugin::LinuxSamplerPlugin(%p, %i, %s)", engine, id, bool2str(isGIG));
  144. fSampler = new LinuxSampler::Sampler;
  145. fAudioOutputDevice = new LinuxSampler::AudioOutputDevicePlugin(engine, this);
  146. fMidiInputDevice = new LinuxSampler::MidiInputDevicePlugin(fSampler);
  147. fMidiInputPort = fMidiInputDevice->CreateMidiPort();
  148. }
  149. ~LinuxSamplerPlugin() override
  150. {
  151. carla_debug("LinuxSamplerPlugin::~LinuxSamplerPlugin()");
  152. kData->singleMutex.lock();
  153. kData->masterMutex.lock();
  154. if (kData->active/*Before*/)
  155. fAudioOutputDevice->Stop();
  156. if (fEngine != nullptr)
  157. {
  158. if (fSamplerChannel != nullptr)
  159. {
  160. fMidiInputPort->Disconnect(fSamplerChannel->GetEngineChannel());
  161. fEngineChannel->DisconnectAudioOutputDevice();
  162. fSampler->RemoveSamplerChannel(fSamplerChannel);
  163. }
  164. LinuxSampler::EngineFactory::Destroy(fEngine);
  165. }
  166. // destructor is private
  167. fMidiInputDevice->DeleteMidiPort(fMidiInputPort);
  168. delete fMidiInputDevice;
  169. delete fAudioOutputDevice;
  170. delete fSampler;
  171. fInstrumentIds.clear();
  172. }
  173. // -------------------------------------------------------------------
  174. // Information (base)
  175. PluginType type() const override
  176. {
  177. return kIsGIG ? PLUGIN_GIG : PLUGIN_SFZ;
  178. }
  179. PluginCategory category() override
  180. {
  181. return PLUGIN_CATEGORY_SYNTH;
  182. }
  183. // -------------------------------------------------------------------
  184. // Information (per-plugin data)
  185. unsigned int availableOptions() override
  186. {
  187. unsigned int options = 0x0;
  188. options |= PLUGIN_OPTION_MAP_PROGRAM_CHANGES;
  189. options |= PLUGIN_OPTION_SEND_CONTROL_CHANGES;
  190. options |= PLUGIN_OPTION_SEND_PITCHBEND;
  191. options |= PLUGIN_OPTION_SEND_ALL_SOUND_OFF;
  192. return options;
  193. }
  194. void getLabel(char* const strBuf) override
  195. {
  196. std::strncpy(strBuf, (const char*)fLabel, STR_MAX);
  197. }
  198. void getMaker(char* const strBuf) override
  199. {
  200. std::strncpy(strBuf, (const char*)fMaker, STR_MAX);
  201. }
  202. void getCopyright(char* const strBuf) override
  203. {
  204. getMaker(strBuf);
  205. }
  206. void getRealName(char* const strBuf) override
  207. {
  208. std::strncpy(strBuf, (const char*)fRealName, STR_MAX);
  209. }
  210. // -------------------------------------------------------------------
  211. // Set data (plugin-specific stuff)
  212. void setMidiProgram(int32_t index, const bool sendGui, const bool sendOsc, const bool sendCallback) override
  213. {
  214. CARLA_ASSERT(index >= -1 && index < static_cast<int32_t>(kData->midiprog.count));
  215. if (index < -1)
  216. index = -1;
  217. else if (index > static_cast<int32_t>(kData->midiprog.count))
  218. return;
  219. if (kData->ctrlChannel < 0 || kData->ctrlChannel >= 16)
  220. return;
  221. if (index >= 0)
  222. {
  223. // TODO
  224. //const uint32_t bank = kData->midiprog.data[index].bank;
  225. //const uint32_t program = kData->midiprog.data[index].program;
  226. //const ScopedProcessLocker spl(this);
  227. //fluid_synth_program_select(fSynth, kData->ctrlChannel, fSynthId, bank, program);
  228. }
  229. CarlaPlugin::setMidiProgram(index, sendGui, sendOsc, sendCallback);
  230. }
  231. // -------------------------------------------------------------------
  232. // Plugin state
  233. void reload() override
  234. {
  235. carla_debug("LinuxSamplerPlugin::reload() - start");
  236. CARLA_ASSERT(kData->engine != nullptr);
  237. CARLA_ASSERT(fInstrument != nullptr);
  238. if (kData->engine == nullptr)
  239. return;
  240. if (fInstrument == nullptr)
  241. return;
  242. const ProcessMode processMode(kData->engine->getProccessMode());
  243. // Safely disable plugin for reload
  244. const ScopedDisabler sd(this);
  245. if (kData->active)
  246. deactivate();
  247. clearBuffers();
  248. uint32_t aOuts;
  249. aOuts = 2;
  250. kData->audioOut.createNew(aOuts);
  251. const int portNameSize = kData->engine->maxPortNameSize();
  252. CarlaString portName;
  253. // ---------------------------------------
  254. // Audio Outputs
  255. {
  256. // out-left
  257. portName.clear();
  258. if (processMode == PROCESS_MODE_SINGLE_CLIENT)
  259. {
  260. portName = fName;
  261. portName += ":";
  262. }
  263. portName += "out-left";
  264. portName.truncate(portNameSize);
  265. kData->audioOut.ports[0].port = (CarlaEngineAudioPort*)kData->client->addPort(kEnginePortTypeAudio, portName, false);
  266. kData->audioOut.ports[0].rindex = 0;
  267. // out-right
  268. portName.clear();
  269. if (processMode == PROCESS_MODE_SINGLE_CLIENT)
  270. {
  271. portName = fName;
  272. portName += ":";
  273. }
  274. portName += "out-right";
  275. portName.truncate(portNameSize);
  276. kData->audioOut.ports[1].port = (CarlaEngineAudioPort*)kData->client->addPort(kEnginePortTypeAudio, portName, false);
  277. kData->audioOut.ports[1].rindex = 1;
  278. }
  279. // ---------------------------------------
  280. // Event Input
  281. {
  282. portName.clear();
  283. if (processMode == PROCESS_MODE_SINGLE_CLIENT)
  284. {
  285. portName = fName;
  286. portName += ":";
  287. }
  288. portName += "event-in";
  289. portName.truncate(portNameSize);
  290. kData->event.portIn = (CarlaEngineEventPort*)kData->client->addPort(kEnginePortTypeEvent, portName, true);
  291. }
  292. // ---------------------------------------
  293. // plugin hints
  294. fHints = 0x0;
  295. fHints |= PLUGIN_IS_RTSAFE;
  296. fHints |= PLUGIN_IS_SYNTH;
  297. fHints |= PLUGIN_CAN_VOLUME;
  298. fHints |= PLUGIN_CAN_BALANCE;
  299. // extra plugin hints
  300. kData->extraHints = 0x0;
  301. kData->extraHints |= PLUGIN_HINT_HAS_MIDI_IN;
  302. kData->extraHints |= PLUGIN_HINT_CAN_RUN_RACK;
  303. bufferSizeChanged(kData->engine->getBufferSize());
  304. reloadPrograms(true);
  305. if (kData->active)
  306. activate();
  307. carla_debug("LinuxSamplerPlugin::reload() - end");
  308. }
  309. void reloadPrograms(bool init) override
  310. {
  311. carla_debug("LinuxSamplerPlugin::reloadPrograms(%s)", bool2str(init));
  312. // Delete old programs
  313. kData->midiprog.clear();
  314. // Query new programs
  315. uint32_t i, count = 0; fInstrumentIds.size();
  316. // sound kits must always have at least 1 midi-program
  317. CARLA_SAFE_ASSERT(count > 0); // FIXME
  318. if (count == 0)
  319. return;
  320. kData->midiprog.createNew(count);
  321. // Update data
  322. for (i=0; i < kData->midiprog.count; ++i)
  323. {
  324. LinuxSampler::InstrumentManager::instrument_info_t info = fInstrument->GetInstrumentInfo(fInstrumentIds[i]);
  325. kData->midiprog.data[i].bank = i / 128;
  326. kData->midiprog.data[i].program = i % 128;
  327. kData->midiprog.data[i].name = carla_strdup(info.InstrumentName.c_str());
  328. }
  329. #ifndef BUILD_BRIDGE
  330. // Update OSC Names
  331. if (kData->engine->isOscControlRegistered())
  332. {
  333. kData->engine->osc_send_control_set_midi_program_count(fId, count);
  334. for (i=0; i < count; ++i)
  335. kData->engine->osc_send_control_set_midi_program_data(fId, i, kData->midiprog.data[i].bank, kData->midiprog.data[i].program, kData->midiprog.data[i].name);
  336. }
  337. #endif
  338. if (init)
  339. {
  340. setMidiProgram(0, false, false, false);
  341. }
  342. else
  343. {
  344. kData->engine->callback(CALLBACK_RELOAD_PROGRAMS, fId, 0, 0, 0.0f, nullptr);
  345. }
  346. }
  347. // -------------------------------------------------------------------
  348. // Plugin processing
  349. void activate() override
  350. {
  351. CARLA_ASSERT(fAudioOutputDevice != nullptr);
  352. fAudioOutputDevice->Play();
  353. }
  354. void deactivate() override
  355. {
  356. CARLA_ASSERT(fAudioOutputDevice != nullptr);
  357. fAudioOutputDevice->Stop();
  358. }
  359. void process(float** const, float** const outBuffer, const uint32_t frames) override
  360. {
  361. uint32_t i, k;
  362. // --------------------------------------------------------------------------------------------------------
  363. // Check if active
  364. if (! kData->active)
  365. {
  366. // disable any output sound
  367. for (i=0; i < kData->audioOut.count; ++i)
  368. carla_zeroFloat(outBuffer[i], frames);
  369. return;
  370. }
  371. // --------------------------------------------------------------------------------------------------------
  372. // Check if needs reset
  373. if (kData->needsReset)
  374. {
  375. // TODO
  376. if (fOptions & PLUGIN_OPTION_SEND_ALL_SOUND_OFF)
  377. {
  378. for (k=0, i=MAX_MIDI_CHANNELS; k < MAX_MIDI_CHANNELS; ++k)
  379. {
  380. fMidiInputPort->DispatchControlChange(MIDI_CONTROL_ALL_SOUND_OFF, 0, k, 0);
  381. fMidiInputPort->DispatchControlChange(MIDI_CONTROL_ALL_NOTES_OFF, 0, k, 0);
  382. }
  383. }
  384. else
  385. {
  386. }
  387. kData->needsReset = false;
  388. }
  389. // --------------------------------------------------------------------------------------------------------
  390. // Event Input and Processing
  391. {
  392. // ----------------------------------------------------------------------------------------------------
  393. // MIDI Input (External)
  394. if (kData->extNotes.mutex.tryLock())
  395. {
  396. while (! kData->extNotes.data.isEmpty())
  397. {
  398. const ExternalMidiNote& note(kData->extNotes.data.getFirst(true));
  399. CARLA_ASSERT(note.channel >= 0 && note.channel < MAX_MIDI_CHANNELS);
  400. if (note.velo > 0)
  401. fMidiInputPort->DispatchNoteOn(note.note, note.velo, note.channel, 0);
  402. else
  403. fMidiInputPort->DispatchNoteOff(note.note, note.velo, note.channel, 0);
  404. }
  405. kData->extNotes.mutex.unlock();
  406. } // End of MIDI Input (External)
  407. // ----------------------------------------------------------------------------------------------------
  408. // Event Input (System)
  409. bool allNotesOffSent = false;
  410. bool sampleAccurate = (fOptions & PLUGIN_OPTION_FIXED_BUFFER) == 0;
  411. uint32_t time, nEvents = kData->event.portIn->getEventCount();
  412. uint32_t startTime = 0;
  413. uint32_t timeOffset = 0;
  414. uint32_t nextBankId = 0;
  415. if (kData->midiprog.current >= 0 && kData->midiprog.count > 0)
  416. nextBankId = kData->midiprog.data[kData->midiprog.current].bank;
  417. for (i=0; i < nEvents; ++i)
  418. {
  419. const EngineEvent& event = kData->event.portIn->getEvent(i);
  420. time = event.time;
  421. if (time >= frames)
  422. continue;
  423. CARLA_ASSERT_INT2(time >= timeOffset, time, timeOffset);
  424. if (time > timeOffset && sampleAccurate)
  425. {
  426. if (processSingle(outBuffer, time - timeOffset, timeOffset))
  427. {
  428. startTime = 0;
  429. timeOffset = time;
  430. if (kData->midiprog.current >= 0 && kData->midiprog.count > 0)
  431. nextBankId = kData->midiprog.data[kData->midiprog.current].bank;
  432. else
  433. nextBankId = 0;
  434. }
  435. else
  436. startTime += timeOffset;
  437. }
  438. // Control change
  439. switch (event.type)
  440. {
  441. case kEngineEventTypeNull:
  442. break;
  443. case kEngineEventTypeControl:
  444. {
  445. const EngineControlEvent& ctrlEvent = event.ctrl;
  446. switch (ctrlEvent.type)
  447. {
  448. case kEngineControlEventTypeNull:
  449. break;
  450. case kEngineControlEventTypeParameter:
  451. {
  452. // Control backend stuff
  453. if (event.channel == kData->ctrlChannel)
  454. {
  455. double value;
  456. if (MIDI_IS_CONTROL_BREATH_CONTROLLER(ctrlEvent.param) && (fHints & PLUGIN_CAN_DRYWET) > 0)
  457. {
  458. value = ctrlEvent.value;
  459. setDryWet(value, false, false);
  460. postponeRtEvent(kPluginPostRtEventParameterChange, PARAMETER_DRYWET, 0, value);
  461. continue;
  462. }
  463. if (MIDI_IS_CONTROL_CHANNEL_VOLUME(ctrlEvent.param) && (fHints & PLUGIN_CAN_VOLUME) > 0)
  464. {
  465. value = ctrlEvent.value*127/100;
  466. setVolume(value, false, false);
  467. postponeRtEvent(kPluginPostRtEventParameterChange, PARAMETER_VOLUME, 0, value);
  468. continue;
  469. }
  470. if (MIDI_IS_CONTROL_BALANCE(ctrlEvent.param) && (fHints & PLUGIN_CAN_BALANCE) > 0)
  471. {
  472. double left, right;
  473. value = ctrlEvent.value/0.5 - 1.0;
  474. if (value < 0.0)
  475. {
  476. left = -1.0;
  477. right = (value*2)+1.0;
  478. }
  479. else if (value > 0.0)
  480. {
  481. left = (value*2)-1.0;
  482. right = 1.0;
  483. }
  484. else
  485. {
  486. left = -1.0;
  487. right = 1.0;
  488. }
  489. setBalanceLeft(left, false, false);
  490. setBalanceRight(right, false, false);
  491. postponeRtEvent(kPluginPostRtEventParameterChange, PARAMETER_BALANCE_LEFT, 0, left);
  492. postponeRtEvent(kPluginPostRtEventParameterChange, PARAMETER_BALANCE_RIGHT, 0, right);
  493. continue;
  494. }
  495. }
  496. // Control plugin parameters
  497. for (k=0; k < kData->param.count; ++k)
  498. {
  499. if (kData->param.data[k].midiChannel != event.channel)
  500. continue;
  501. if (kData->param.data[k].midiCC != ctrlEvent.param)
  502. continue;
  503. if (kData->param.data[k].type != PARAMETER_INPUT)
  504. continue;
  505. if ((kData->param.data[k].hints & PARAMETER_IS_AUTOMABLE) == 0)
  506. continue;
  507. double value;
  508. if (kData->param.data[k].hints & PARAMETER_IS_BOOLEAN)
  509. {
  510. value = (ctrlEvent.value < 0.5f) ? kData->param.ranges[k].min : kData->param.ranges[k].max;
  511. }
  512. else
  513. {
  514. value = kData->param.ranges[i].unnormalizeValue(ctrlEvent.value);
  515. if (kData->param.data[k].hints & PARAMETER_IS_INTEGER)
  516. value = std::rint(value);
  517. }
  518. setParameterValue(k, value, false, false, false);
  519. postponeRtEvent(kPluginPostRtEventParameterChange, static_cast<int32_t>(k), 0, value);
  520. }
  521. break;
  522. }
  523. case kEngineControlEventTypeMidiBank:
  524. if (event.channel == kData->ctrlChannel && (fOptions & PLUGIN_OPTION_MAP_PROGRAM_CHANGES) != 0)
  525. nextBankId = ctrlEvent.param;
  526. break;
  527. case kEngineControlEventTypeMidiProgram:
  528. if (event.channel == kData->ctrlChannel && (fOptions & PLUGIN_OPTION_MAP_PROGRAM_CHANGES) != 0)
  529. {
  530. const uint32_t nextProgramId = ctrlEvent.param;
  531. for (k=0; k < kData->midiprog.count; ++k)
  532. {
  533. if (kData->midiprog.data[k].bank == nextBankId && kData->midiprog.data[k].program == nextProgramId)
  534. {
  535. setMidiProgram(k, false, false, false);
  536. postponeRtEvent(kPluginPostRtEventMidiProgramChange, k, 0, 0.0f);
  537. break;
  538. }
  539. }
  540. }
  541. break;
  542. case kEngineControlEventTypeAllSoundOff:
  543. if (event.channel == kData->ctrlChannel)
  544. {
  545. if (! allNotesOffSent)
  546. {
  547. sendMidiAllNotesOff();
  548. allNotesOffSent = true;
  549. }
  550. postponeRtEvent(kPluginPostRtEventParameterChange, PARAMETER_ACTIVE, 0, 0.0f);
  551. postponeRtEvent(kPluginPostRtEventParameterChange, PARAMETER_ACTIVE, 0, 1.0f);
  552. }
  553. if (fOptions & PLUGIN_OPTION_SEND_ALL_SOUND_OFF)
  554. fMidiInputPort->DispatchControlChange(MIDI_CONTROL_ALL_SOUND_OFF, 0, k, sampleAccurate ? startTime : time);
  555. break;
  556. case kEngineControlEventTypeAllNotesOff:
  557. if (event.channel == kData->ctrlChannel)
  558. {
  559. if (! allNotesOffSent)
  560. {
  561. sendMidiAllNotesOff();
  562. allNotesOffSent = true;
  563. }
  564. }
  565. if (fOptions & PLUGIN_OPTION_SEND_ALL_SOUND_OFF)
  566. fMidiInputPort->DispatchControlChange(MIDI_CONTROL_ALL_NOTES_OFF, 0, k, sampleAccurate ? startTime : time);
  567. break;
  568. }
  569. break;
  570. }
  571. case kEngineEventTypeMidi:
  572. {
  573. const EngineMidiEvent& midiEvent = event.midi;
  574. uint8_t status = MIDI_GET_STATUS_FROM_DATA(midiEvent.data);
  575. uint8_t channel = event.channel;
  576. // Fix bad note-off (per DSSI spec)
  577. if (MIDI_IS_STATUS_NOTE_ON(status) && midiEvent.data[2] == 0)
  578. status -= 0x10;
  579. int32_t fragmentPos = sampleAccurate ? startTime : time;
  580. if (MIDI_IS_STATUS_NOTE_OFF(status))
  581. {
  582. const uint8_t note = midiEvent.data[1];
  583. fMidiInputPort->DispatchNoteOff(note, 0, channel, fragmentPos);
  584. postponeRtEvent(kPluginPostRtEventNoteOff, channel, note, 0.0f);
  585. }
  586. else if (MIDI_IS_STATUS_NOTE_ON(status))
  587. {
  588. const uint8_t note = midiEvent.data[1];
  589. const uint8_t velo = midiEvent.data[2];
  590. fMidiInputPort->DispatchNoteOn(note, velo, channel, fragmentPos);
  591. postponeRtEvent(kPluginPostRtEventNoteOn, channel, note, velo);
  592. }
  593. else if (MIDI_IS_STATUS_POLYPHONIC_AFTERTOUCH(status) && (fOptions & PLUGIN_OPTION_SEND_NOTE_AFTERTOUCH) != 0)
  594. {
  595. //const uint8_t note = midiEvent.data[1];
  596. //const uint8_t pressure = midiEvent.data[2];
  597. // unsupported
  598. }
  599. else if (MIDI_IS_STATUS_CONTROL_CHANGE(status) && (fOptions & PLUGIN_OPTION_SEND_CONTROL_CHANGES) != 0)
  600. {
  601. const uint8_t control = midiEvent.data[1];
  602. const uint8_t value = midiEvent.data[2];
  603. fMidiInputPort->DispatchControlChange(control, value, channel, fragmentPos);
  604. }
  605. else if (MIDI_IS_STATUS_AFTERTOUCH(status) && (fOptions & PLUGIN_OPTION_SEND_CHANNEL_PRESSURE) != 0)
  606. {
  607. //const uint8_t pressure = midiEvent.data[1];
  608. // unsupported
  609. }
  610. else if (MIDI_IS_STATUS_PITCH_WHEEL_CONTROL(status) && (fOptions & PLUGIN_OPTION_SEND_PITCHBEND) != 0)
  611. {
  612. const uint8_t lsb = midiEvent.data[1];
  613. const uint8_t msb = midiEvent.data[2];
  614. fMidiInputPort->DispatchPitchbend(((msb << 7) | lsb) - 8192, channel, fragmentPos);
  615. }
  616. break;
  617. }
  618. }
  619. }
  620. kData->postRtEvents.trySplice();
  621. if (frames > timeOffset)
  622. processSingle(outBuffer, frames - timeOffset, timeOffset);
  623. } // End of Event Input and Processing
  624. }
  625. bool processSingle(float** const outBuffer, const uint32_t frames, const uint32_t timeOffset)
  626. {
  627. CARLA_ASSERT(outBuffer != nullptr);
  628. CARLA_ASSERT(frames > 0);
  629. if (outBuffer == nullptr)
  630. return false;
  631. if (frames == 0)
  632. return false;
  633. uint32_t i, k;
  634. // --------------------------------------------------------------------------------------------------------
  635. // Try lock, silence otherwise
  636. if (kData->engine->isOffline())
  637. {
  638. kData->singleMutex.lock();
  639. }
  640. else if (! kData->singleMutex.tryLock())
  641. {
  642. for (i=0; i < kData->audioOut.count; ++i)
  643. {
  644. for (k=0; k < frames; ++k)
  645. outBuffer[i][k+timeOffset] = 0.0f;
  646. }
  647. return false;
  648. }
  649. // --------------------------------------------------------------------------------------------------------
  650. // Run plugin
  651. fAudioOutputDevice->Channel(0)->SetBuffer(outBuffer[0] + timeOffset);
  652. fAudioOutputDevice->Channel(1)->SetBuffer(outBuffer[1] + timeOffset);
  653. // QUESTION: Need to clear it before?
  654. fAudioOutputDevice->Render(frames);
  655. // --------------------------------------------------------------------------------------------------------
  656. // Post-processing (dry/wet, volume and balance)
  657. {
  658. const bool doVolume = (fHints & PLUGIN_CAN_VOLUME) > 0 && kData->postProc.volume != 1.0f;
  659. const bool doBalance = (fHints & PLUGIN_CAN_BALANCE) > 0 && (kData->postProc.balanceLeft != -1.0f || kData->postProc.balanceRight != 1.0f);
  660. float oldBufLeft[doBalance ? frames : 1];
  661. for (i=0; i < kData->audioOut.count; ++i)
  662. {
  663. // Balance
  664. if (doBalance)
  665. {
  666. if (i % 2 == 0)
  667. carla_copyFloat(oldBufLeft, outBuffer[i], frames);
  668. float balRangeL = (kData->postProc.balanceLeft + 1.0f)/2.0f;
  669. float balRangeR = (kData->postProc.balanceRight + 1.0f)/2.0f;
  670. for (k=0; k < frames; ++k)
  671. {
  672. if (i % 2 == 0)
  673. {
  674. // left
  675. outBuffer[i][k] = oldBufLeft[k] * (1.0f - balRangeL);
  676. outBuffer[i][k] += outBuffer[i+1][k] * (1.0f - balRangeR);
  677. }
  678. else
  679. {
  680. // right
  681. outBuffer[i][k] = outBuffer[i][k] * balRangeR;
  682. outBuffer[i][k] += oldBufLeft[k] * balRangeL;
  683. }
  684. }
  685. }
  686. // Volume
  687. if (doVolume)
  688. {
  689. for (k=0; k < frames; ++k)
  690. outBuffer[i][k+timeOffset] *= kData->postProc.volume;
  691. }
  692. }
  693. } // End of Post-processing
  694. // --------------------------------------------------------------------------------------------------------
  695. kData->singleMutex.unlock();
  696. return true;
  697. }
  698. // -------------------------------------------------------------------
  699. const void* getExtraStuff() override
  700. {
  701. return kUses16Outs ? (const void*)0x1 : nullptr;
  702. }
  703. bool init(const char* filename, const char* const name, const char* label)
  704. {
  705. CARLA_ASSERT(kData->engine != nullptr);
  706. CARLA_ASSERT(kData->client == nullptr);
  707. CARLA_ASSERT(filename != nullptr);
  708. CARLA_ASSERT(label != nullptr);
  709. // ---------------------------------------------------------------
  710. // first checks
  711. if (kData->engine == nullptr)
  712. {
  713. return false;
  714. }
  715. if (kData->client != nullptr)
  716. {
  717. kData->engine->setLastError("Plugin client is already registered");
  718. return false;
  719. }
  720. if (filename == nullptr)
  721. {
  722. kData->engine->setLastError("null filename");
  723. return false;
  724. }
  725. if (label == nullptr)
  726. {
  727. kData->engine->setLastError("null label");
  728. return false;
  729. }
  730. // ---------------------------------------------------------------
  731. // Check if file exists
  732. {
  733. QFileInfo file(filename);
  734. if (! (file.exists() && file.isFile() && file.isReadable()))
  735. {
  736. kData->engine->setLastError("Requested file is not valid or does not exist");
  737. return false;
  738. }
  739. }
  740. // ---------------------------------------------------------------
  741. // Create the LinuxSampler Engine
  742. const char* const stype = kIsGIG ? "gig" : "sfz";
  743. try {
  744. fEngine = LinuxSampler::EngineFactory::Create(stype);
  745. }
  746. catch (LinuxSampler::Exception& e)
  747. {
  748. kData->engine->setLastError(e.what());
  749. return false;
  750. }
  751. // ---------------------------------------------------------------
  752. // Get the Engine's Instrument Manager
  753. fInstrument = fEngine->GetInstrumentManager();
  754. if (fInstrument == nullptr)
  755. {
  756. kData->engine->setLastError("Failed to get LinuxSampler instrument manager");
  757. LinuxSampler::EngineFactory::Destroy(fEngine);
  758. return false;
  759. }
  760. // ---------------------------------------------------------------
  761. // Load the Instrument via filename
  762. try {
  763. fInstrumentIds = fInstrument->GetInstrumentFileContent(filename);
  764. }
  765. catch (const LinuxSampler::InstrumentManagerException& e)
  766. {
  767. kData->engine->setLastError(e.what());
  768. LinuxSampler::EngineFactory::Destroy(fEngine);
  769. return false;
  770. }
  771. // ---------------------------------------------------------------
  772. // Get info
  773. if (fInstrumentIds.size() == 0)
  774. {
  775. kData->engine->setLastError("Failed to find any instruments");
  776. LinuxSampler::EngineFactory::Destroy(fEngine);
  777. return false;
  778. }
  779. LinuxSampler::InstrumentManager::instrument_info_t info;
  780. try {
  781. info = fInstrument->GetInstrumentInfo(fInstrumentIds[0]);
  782. }
  783. catch (const LinuxSampler::InstrumentManagerException& e)
  784. {
  785. kData->engine->setLastError(e.what());
  786. LinuxSampler::EngineFactory::Destroy(fEngine);
  787. return false;
  788. }
  789. fRealName = info.InstrumentName.c_str();
  790. fLabel = info.Product.c_str();
  791. fMaker = info.Artists.c_str();
  792. fFilename = filename;
  793. if (name != nullptr)
  794. fName = kData->engine->getNewUniquePluginName(name);
  795. else
  796. fName = kData->engine->getNewUniquePluginName((const char*)fRealName);
  797. // ---------------------------------------------------------------
  798. // Register client
  799. kData->client = kData->engine->addClient(this);
  800. if (kData->client == nullptr || ! kData->client->isOk())
  801. {
  802. kData->engine->setLastError("Failed to register plugin client");
  803. LinuxSampler::EngineFactory::Destroy(fEngine);
  804. return false;
  805. }
  806. // ---------------------------------------------------------------
  807. // Init LinuxSampler stuff
  808. fSamplerChannel = fSampler->AddSamplerChannel();
  809. fSamplerChannel->SetEngineType(stype);
  810. fSamplerChannel->SetAudioOutputDevice(fAudioOutputDevice);
  811. fEngineChannel = fSamplerChannel->GetEngineChannel();
  812. fEngineChannel->Connect(fAudioOutputDevice);
  813. fEngineChannel->PrepareLoadInstrument(filename, 0); // todo - find instrument from label
  814. fEngineChannel->LoadInstrument();
  815. fEngineChannel->Volume(LinuxSampler::VOLUME_MAX);
  816. fMidiInputPort->Connect(fSamplerChannel->GetEngineChannel(), LinuxSampler::midi_chan_all);
  817. // ---------------------------------------------------------------
  818. // load plugin settings
  819. {
  820. // set default options
  821. fOptions = 0x0;
  822. fOptions |= PLUGIN_OPTION_MAP_PROGRAM_CHANGES;
  823. fOptions |= PLUGIN_OPTION_SEND_PITCHBEND;
  824. fOptions |= PLUGIN_OPTION_SEND_ALL_SOUND_OFF;
  825. // load settings
  826. kData->idStr = kIsGIG ? "GIG" : "SFZ";
  827. kData->idStr += "/";
  828. kData->idStr += label;
  829. fOptions = kData->loadSettings(fOptions, availableOptions());
  830. }
  831. return true;
  832. }
  833. // -------------------------------------------------------------------
  834. static CarlaPlugin* newLinuxSampler(const Initializer& init, bool isGIG, const bool use16Outs);
  835. private:
  836. const bool kIsGIG; // sfz if false
  837. const bool kUses16Outs;
  838. CarlaString fRealName;
  839. CarlaString fLabel;
  840. CarlaString fMaker;
  841. LinuxSampler::Sampler* fSampler;
  842. LinuxSampler::SamplerChannel* fSamplerChannel;
  843. LinuxSampler::Engine* fEngine;
  844. LinuxSampler::EngineChannel* fEngineChannel;
  845. LinuxSampler::AudioOutputDevicePlugin* fAudioOutputDevice;
  846. LinuxSampler::MidiInputDevicePlugin* fMidiInputDevice;
  847. LinuxSampler::MidiInputPort* fMidiInputPort;
  848. LinuxSampler::InstrumentManager* fInstrument;
  849. std::vector<LinuxSampler::InstrumentManager::instrument_id_t> fInstrumentIds;
  850. CARLA_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(LinuxSamplerPlugin)
  851. };
  852. CarlaPlugin* LinuxSamplerPlugin::newLinuxSampler(const Initializer& init, const bool isGIG, const bool use16Outs)
  853. {
  854. carla_debug("LinuxSamplerPlugin::newLinuxSampler({%p, \"%s\", \"%s\", \"%s\"}, %s, %s)", init.engine, init.filename, init.name, init.label, bool2str(isGIG), bool2str(use16Outs));
  855. LinuxSamplerPlugin* const plugin(new LinuxSamplerPlugin(init.engine, init.id, isGIG, use16Outs));
  856. if (! plugin->init(init.filename, init.name, init.label))
  857. {
  858. delete plugin;
  859. return nullptr;
  860. }
  861. plugin->reload();
  862. return plugin;
  863. }
  864. CARLA_BACKEND_END_NAMESPACE
  865. #else // WANT_LINUXSAMPLER
  866. # warning linuxsampler not available (no GIG and SFZ support)
  867. #endif
  868. CARLA_BACKEND_START_NAMESPACE
  869. CarlaPlugin* CarlaPlugin::newGIG(const Initializer& init, const bool use16Outs)
  870. {
  871. carla_debug("CarlaPlugin::newGIG({%p, \"%s\", \"%s\", \"%s\"}, %s)", init.engine, init.filename, init.name, init.label, bool2str(use16Outs));
  872. #ifdef WANT_LINUXSAMPLER
  873. return LinuxSamplerPlugin::newLinuxSampler(init, true, use16Outs);
  874. #else
  875. init.engine->setLastError("linuxsampler support not available");
  876. return nullptr;
  877. #endif
  878. }
  879. CarlaPlugin* CarlaPlugin::newSFZ(const Initializer& init, const bool use16Outs)
  880. {
  881. carla_debug("CarlaPlugin::newSFZ({%p, \"%s\", \"%s\", \"%s\"}, %s)", init.engine, init.filename, init.name, init.label, bool2str(use16Outs));
  882. #ifdef WANT_LINUXSAMPLER
  883. return LinuxSamplerPlugin::newLinuxSampler(init, false, use16Outs);
  884. #else
  885. init.engine->setLastError("linuxsampler support not available");
  886. return nullptr;
  887. #endif
  888. }
  889. CARLA_BACKEND_END_NAMESPACE