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.

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