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.

1026 lines
34KB

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