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.

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