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.

1077 lines
36KB

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