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.

1174 lines
38KB

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