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.

1049 lines
35KB

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