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.

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