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.

1048 lines
35KB

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