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.

1139 lines
37KB

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