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.

1178 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_SYNTH;
  308. fHints |= PLUGIN_CAN_VOLUME;
  309. fHints |= PLUGIN_CAN_BALANCE;
  310. // extra plugin hints
  311. kData->extraHints = 0x0;
  312. kData->extraHints |= PLUGIN_HINT_HAS_MIDI_IN;
  313. kData->extraHints |= PLUGIN_HINT_CAN_RUN_RACK;
  314. bufferSizeChanged(kData->engine->getBufferSize());
  315. reloadPrograms(true);
  316. if (kData->active)
  317. activate();
  318. carla_debug("LinuxSamplerPlugin::reload() - end");
  319. }
  320. void reloadPrograms(bool init) override
  321. {
  322. carla_debug("LinuxSamplerPlugin::reloadPrograms(%s)", bool2str(init));
  323. // Delete old programs
  324. kData->midiprog.clear();
  325. // Query new programs
  326. uint32_t i, count = 0; fInstrumentIds.size();
  327. // sound kits must always have at least 1 midi-program
  328. CARLA_SAFE_ASSERT(count > 0); // FIXME
  329. if (count == 0)
  330. return;
  331. kData->midiprog.createNew(count);
  332. // Update data
  333. for (i=0; i < kData->midiprog.count; ++i)
  334. {
  335. LinuxSampler::InstrumentManager::instrument_info_t info = fInstrument->GetInstrumentInfo(fInstrumentIds[i]);
  336. kData->midiprog.data[i].bank = i / 128;
  337. kData->midiprog.data[i].program = i % 128;
  338. kData->midiprog.data[i].name = carla_strdup(info.InstrumentName.c_str());
  339. }
  340. #ifndef BUILD_BRIDGE
  341. // Update OSC Names
  342. if (kData->engine->isOscControlRegistered())
  343. {
  344. kData->engine->osc_send_control_set_midi_program_count(fId, count);
  345. for (i=0; i < count; ++i)
  346. 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);
  347. }
  348. #endif
  349. if (init)
  350. {
  351. setMidiProgram(0, false, false, false);
  352. }
  353. else
  354. {
  355. kData->engine->callback(CALLBACK_RELOAD_PROGRAMS, fId, 0, 0, 0.0f, nullptr);
  356. }
  357. }
  358. // -------------------------------------------------------------------
  359. // Plugin processing
  360. void activate() override
  361. {
  362. CARLA_ASSERT(fAudioOutputDevice != nullptr);
  363. fAudioOutputDevice->Play();
  364. }
  365. void deactivate() override
  366. {
  367. CARLA_ASSERT(fAudioOutputDevice != nullptr);
  368. fAudioOutputDevice->Stop();
  369. }
  370. void process(float** const, float** const outBuffer, const uint32_t frames) override
  371. {
  372. uint32_t i, k;
  373. // --------------------------------------------------------------------------------------------------------
  374. // Check if active
  375. if (! kData->active)
  376. {
  377. // disable any output sound
  378. for (i=0; i < kData->audioOut.count; ++i)
  379. carla_zeroFloat(outBuffer[i], frames);
  380. return;
  381. }
  382. // --------------------------------------------------------------------------------------------------------
  383. // Check if needs reset
  384. if (kData->needsReset)
  385. {
  386. // TODO
  387. if (fOptions & PLUGIN_OPTION_SEND_ALL_SOUND_OFF)
  388. {
  389. for (k=0, i=MAX_MIDI_CHANNELS; k < MAX_MIDI_CHANNELS; ++k)
  390. {
  391. fMidiInputPort->DispatchControlChange(MIDI_CONTROL_ALL_SOUND_OFF, 0, k, 0);
  392. fMidiInputPort->DispatchControlChange(MIDI_CONTROL_ALL_NOTES_OFF, 0, k, 0);
  393. }
  394. }
  395. else
  396. {
  397. }
  398. kData->needsReset = false;
  399. }
  400. // --------------------------------------------------------------------------------------------------------
  401. // Event Input and Processing
  402. {
  403. // ----------------------------------------------------------------------------------------------------
  404. // MIDI Input (External)
  405. if (kData->extNotes.mutex.tryLock())
  406. {
  407. while (! kData->extNotes.data.isEmpty())
  408. {
  409. const ExternalMidiNote& note(kData->extNotes.data.getFirst(true));
  410. CARLA_ASSERT(note.channel >= 0 && note.channel < MAX_MIDI_CHANNELS);
  411. if (note.velo > 0)
  412. fMidiInputPort->DispatchNoteOn(note.note, note.velo, note.channel, 0);
  413. else
  414. fMidiInputPort->DispatchNoteOff(note.note, note.velo, note.channel, 0);
  415. }
  416. kData->extNotes.mutex.unlock();
  417. } // End of MIDI Input (External)
  418. // ----------------------------------------------------------------------------------------------------
  419. // Event Input (System)
  420. bool allNotesOffSent = false;
  421. bool sampleAccurate = (fOptions & PLUGIN_OPTION_FIXED_BUFFER) == 0;
  422. uint32_t time, nEvents = kData->event.portIn->getEventCount();
  423. uint32_t startTime = 0;
  424. uint32_t timeOffset = 0;
  425. uint32_t nextBankId = 0;
  426. if (kData->midiprog.current >= 0 && kData->midiprog.count > 0)
  427. nextBankId = kData->midiprog.data[kData->midiprog.current].bank;
  428. for (i=0; i < nEvents; ++i)
  429. {
  430. const EngineEvent& event(kData->event.portIn->getEvent(i));
  431. time = event.time;
  432. if (time >= frames)
  433. continue;
  434. CARLA_ASSERT_INT2(time >= timeOffset, time, timeOffset);
  435. if (time > timeOffset && sampleAccurate)
  436. {
  437. if (processSingle(outBuffer, time - timeOffset, timeOffset))
  438. {
  439. startTime = 0;
  440. timeOffset = time;
  441. if (kData->midiprog.current >= 0 && kData->midiprog.count > 0)
  442. nextBankId = kData->midiprog.data[kData->midiprog.current].bank;
  443. else
  444. nextBankId = 0;
  445. }
  446. else
  447. startTime += timeOffset;
  448. }
  449. // Control change
  450. switch (event.type)
  451. {
  452. case kEngineEventTypeNull:
  453. break;
  454. case kEngineEventTypeControl:
  455. {
  456. const EngineControlEvent& ctrlEvent = event.ctrl;
  457. switch (ctrlEvent.type)
  458. {
  459. case kEngineControlEventTypeNull:
  460. break;
  461. case kEngineControlEventTypeParameter:
  462. {
  463. // Control backend stuff
  464. if (event.channel == kData->ctrlChannel)
  465. {
  466. double value;
  467. if (MIDI_IS_CONTROL_BREATH_CONTROLLER(ctrlEvent.param) && (fHints & PLUGIN_CAN_DRYWET) > 0)
  468. {
  469. value = ctrlEvent.value;
  470. setDryWet(value, false, false);
  471. postponeRtEvent(kPluginPostRtEventParameterChange, PARAMETER_DRYWET, 0, value);
  472. continue;
  473. }
  474. if (MIDI_IS_CONTROL_CHANNEL_VOLUME(ctrlEvent.param) && (fHints & PLUGIN_CAN_VOLUME) > 0)
  475. {
  476. value = ctrlEvent.value*127/100;
  477. setVolume(value, false, false);
  478. postponeRtEvent(kPluginPostRtEventParameterChange, PARAMETER_VOLUME, 0, value);
  479. continue;
  480. }
  481. if (MIDI_IS_CONTROL_BALANCE(ctrlEvent.param) && (fHints & PLUGIN_CAN_BALANCE) > 0)
  482. {
  483. double left, right;
  484. value = ctrlEvent.value/0.5 - 1.0;
  485. if (value < 0.0)
  486. {
  487. left = -1.0;
  488. right = (value*2)+1.0;
  489. }
  490. else if (value > 0.0)
  491. {
  492. left = (value*2)-1.0;
  493. right = 1.0;
  494. }
  495. else
  496. {
  497. left = -1.0;
  498. right = 1.0;
  499. }
  500. setBalanceLeft(left, false, false);
  501. setBalanceRight(right, false, false);
  502. postponeRtEvent(kPluginPostRtEventParameterChange, PARAMETER_BALANCE_LEFT, 0, left);
  503. postponeRtEvent(kPluginPostRtEventParameterChange, PARAMETER_BALANCE_RIGHT, 0, right);
  504. continue;
  505. }
  506. }
  507. // Control plugin parameters
  508. for (k=0; k < kData->param.count; ++k)
  509. {
  510. if (kData->param.data[k].midiChannel != event.channel)
  511. continue;
  512. if (kData->param.data[k].midiCC != ctrlEvent.param)
  513. continue;
  514. if (kData->param.data[k].type != PARAMETER_INPUT)
  515. continue;
  516. if ((kData->param.data[k].hints & PARAMETER_IS_AUTOMABLE) == 0)
  517. continue;
  518. double value;
  519. if (kData->param.data[k].hints & PARAMETER_IS_BOOLEAN)
  520. {
  521. value = (ctrlEvent.value < 0.5f) ? kData->param.ranges[k].min : kData->param.ranges[k].max;
  522. }
  523. else
  524. {
  525. value = kData->param.ranges[i].unnormalizeValue(ctrlEvent.value);
  526. if (kData->param.data[k].hints & PARAMETER_IS_INTEGER)
  527. value = std::rint(value);
  528. }
  529. setParameterValue(k, value, false, false, false);
  530. postponeRtEvent(kPluginPostRtEventParameterChange, static_cast<int32_t>(k), 0, value);
  531. }
  532. break;
  533. }
  534. case kEngineControlEventTypeMidiBank:
  535. if (event.channel == kData->ctrlChannel && (fOptions & PLUGIN_OPTION_MAP_PROGRAM_CHANGES) != 0)
  536. nextBankId = ctrlEvent.param;
  537. break;
  538. case kEngineControlEventTypeMidiProgram:
  539. if (event.channel == kData->ctrlChannel && (fOptions & PLUGIN_OPTION_MAP_PROGRAM_CHANGES) != 0)
  540. {
  541. const uint32_t nextProgramId = ctrlEvent.param;
  542. for (k=0; k < kData->midiprog.count; ++k)
  543. {
  544. if (kData->midiprog.data[k].bank == nextBankId && kData->midiprog.data[k].program == nextProgramId)
  545. {
  546. setMidiProgram(k, false, false, false);
  547. postponeRtEvent(kPluginPostRtEventMidiProgramChange, k, 0, 0.0f);
  548. break;
  549. }
  550. }
  551. }
  552. break;
  553. case kEngineControlEventTypeAllSoundOff:
  554. if (event.channel == kData->ctrlChannel)
  555. {
  556. if (! allNotesOffSent)
  557. {
  558. sendMidiAllNotesOff();
  559. allNotesOffSent = true;
  560. }
  561. postponeRtEvent(kPluginPostRtEventParameterChange, PARAMETER_ACTIVE, 0, 0.0f);
  562. postponeRtEvent(kPluginPostRtEventParameterChange, PARAMETER_ACTIVE, 0, 1.0f);
  563. }
  564. if (fOptions & PLUGIN_OPTION_SEND_ALL_SOUND_OFF)
  565. fMidiInputPort->DispatchControlChange(MIDI_CONTROL_ALL_SOUND_OFF, 0, k, sampleAccurate ? startTime : time);
  566. break;
  567. case kEngineControlEventTypeAllNotesOff:
  568. if (event.channel == kData->ctrlChannel)
  569. {
  570. if (! allNotesOffSent)
  571. {
  572. sendMidiAllNotesOff();
  573. allNotesOffSent = true;
  574. }
  575. }
  576. if (fOptions & PLUGIN_OPTION_SEND_ALL_SOUND_OFF)
  577. fMidiInputPort->DispatchControlChange(MIDI_CONTROL_ALL_NOTES_OFF, 0, k, sampleAccurate ? startTime : time);
  578. break;
  579. }
  580. break;
  581. }
  582. case kEngineEventTypeMidi:
  583. {
  584. const EngineMidiEvent& midiEvent = event.midi;
  585. uint8_t status = MIDI_GET_STATUS_FROM_DATA(midiEvent.data);
  586. uint8_t channel = event.channel;
  587. // Fix bad note-off (per DSSI spec)
  588. if (MIDI_IS_STATUS_NOTE_ON(status) && midiEvent.data[2] == 0)
  589. status -= 0x10;
  590. int32_t fragmentPos = sampleAccurate ? startTime : time;
  591. if (MIDI_IS_STATUS_NOTE_OFF(status))
  592. {
  593. const uint8_t note = midiEvent.data[1];
  594. fMidiInputPort->DispatchNoteOff(note, 0, channel, fragmentPos);
  595. postponeRtEvent(kPluginPostRtEventNoteOff, channel, note, 0.0f);
  596. }
  597. else if (MIDI_IS_STATUS_NOTE_ON(status))
  598. {
  599. const uint8_t note = midiEvent.data[1];
  600. const uint8_t velo = midiEvent.data[2];
  601. fMidiInputPort->DispatchNoteOn(note, velo, channel, fragmentPos);
  602. postponeRtEvent(kPluginPostRtEventNoteOn, channel, note, velo);
  603. }
  604. else if (MIDI_IS_STATUS_POLYPHONIC_AFTERTOUCH(status) && (fOptions & PLUGIN_OPTION_SEND_NOTE_AFTERTOUCH) != 0)
  605. {
  606. //const uint8_t note = midiEvent.data[1];
  607. //const uint8_t pressure = midiEvent.data[2];
  608. // unsupported
  609. }
  610. else if (MIDI_IS_STATUS_CONTROL_CHANGE(status) && (fOptions & PLUGIN_OPTION_SEND_CONTROL_CHANGES) != 0)
  611. {
  612. const uint8_t control = midiEvent.data[1];
  613. const uint8_t value = midiEvent.data[2];
  614. fMidiInputPort->DispatchControlChange(control, value, channel, fragmentPos);
  615. }
  616. else if (MIDI_IS_STATUS_AFTERTOUCH(status) && (fOptions & PLUGIN_OPTION_SEND_CHANNEL_PRESSURE) != 0)
  617. {
  618. //const uint8_t pressure = midiEvent.data[1];
  619. // unsupported
  620. }
  621. else if (MIDI_IS_STATUS_PITCH_WHEEL_CONTROL(status) && (fOptions & PLUGIN_OPTION_SEND_PITCHBEND) != 0)
  622. {
  623. const uint8_t lsb = midiEvent.data[1];
  624. const uint8_t msb = midiEvent.data[2];
  625. fMidiInputPort->DispatchPitchbend(((msb << 7) | lsb) - 8192, channel, fragmentPos);
  626. }
  627. break;
  628. }
  629. }
  630. }
  631. kData->postRtEvents.trySplice();
  632. if (frames > timeOffset)
  633. processSingle(outBuffer, frames - timeOffset, timeOffset);
  634. } // End of Event Input and Processing
  635. }
  636. bool processSingle(float** const outBuffer, const uint32_t frames, const uint32_t timeOffset)
  637. {
  638. CARLA_ASSERT(outBuffer != nullptr);
  639. CARLA_ASSERT(frames > 0);
  640. if (outBuffer == nullptr)
  641. return false;
  642. if (frames == 0)
  643. return false;
  644. uint32_t i, k;
  645. // --------------------------------------------------------------------------------------------------------
  646. // Try lock, silence otherwise
  647. if (kData->engine->isOffline())
  648. {
  649. kData->singleMutex.lock();
  650. }
  651. else if (! kData->singleMutex.tryLock())
  652. {
  653. for (i=0; i < kData->audioOut.count; ++i)
  654. {
  655. for (k=0; k < frames; ++k)
  656. outBuffer[i][k+timeOffset] = 0.0f;
  657. }
  658. return false;
  659. }
  660. // --------------------------------------------------------------------------------------------------------
  661. // Run plugin
  662. fAudioOutputDevice->Channel(0)->SetBuffer(outBuffer[0] + timeOffset);
  663. fAudioOutputDevice->Channel(1)->SetBuffer(outBuffer[1] + timeOffset);
  664. // QUESTION: Need to clear it before?
  665. fAudioOutputDevice->Render(frames);
  666. // --------------------------------------------------------------------------------------------------------
  667. // Post-processing (dry/wet, volume and balance)
  668. {
  669. const bool doVolume = (fHints & PLUGIN_CAN_VOLUME) > 0 && kData->postProc.volume != 1.0f;
  670. const bool doBalance = (fHints & PLUGIN_CAN_BALANCE) > 0 && (kData->postProc.balanceLeft != -1.0f || kData->postProc.balanceRight != 1.0f);
  671. float oldBufLeft[doBalance ? frames : 1];
  672. for (i=0; i < kData->audioOut.count; ++i)
  673. {
  674. // Balance
  675. if (doBalance)
  676. {
  677. if (i % 2 == 0)
  678. carla_copyFloat(oldBufLeft, outBuffer[i], frames);
  679. float balRangeL = (kData->postProc.balanceLeft + 1.0f)/2.0f;
  680. float balRangeR = (kData->postProc.balanceRight + 1.0f)/2.0f;
  681. for (k=0; k < frames; ++k)
  682. {
  683. if (i % 2 == 0)
  684. {
  685. // left
  686. outBuffer[i][k] = oldBufLeft[k] * (1.0f - balRangeL);
  687. outBuffer[i][k] += outBuffer[i+1][k] * (1.0f - balRangeR);
  688. }
  689. else
  690. {
  691. // right
  692. outBuffer[i][k] = outBuffer[i][k] * balRangeR;
  693. outBuffer[i][k] += oldBufLeft[k] * balRangeL;
  694. }
  695. }
  696. }
  697. // Volume
  698. if (doVolume)
  699. {
  700. for (k=0; k < frames; ++k)
  701. outBuffer[i][k+timeOffset] *= kData->postProc.volume;
  702. }
  703. }
  704. } // End of Post-processing
  705. // --------------------------------------------------------------------------------------------------------
  706. kData->singleMutex.unlock();
  707. return true;
  708. }
  709. // -------------------------------------------------------------------
  710. // Plugin buffers
  711. // nothing
  712. // -------------------------------------------------------------------
  713. const void* getExtraStuff() override
  714. {
  715. return kUses16Outs ? (const void*)0x1 : nullptr;
  716. }
  717. bool init(const char* filename, const char* const name, const char* label)
  718. {
  719. CARLA_ASSERT(kData->engine != nullptr);
  720. CARLA_ASSERT(kData->client == nullptr);
  721. CARLA_ASSERT(filename != nullptr);
  722. CARLA_ASSERT(label != nullptr);
  723. // ---------------------------------------------------------------
  724. // first checks
  725. if (kData->engine == nullptr)
  726. {
  727. return false;
  728. }
  729. if (kData->client != nullptr)
  730. {
  731. kData->engine->setLastError("Plugin client is already registered");
  732. return false;
  733. }
  734. if (filename == nullptr)
  735. {
  736. kData->engine->setLastError("null filename");
  737. return false;
  738. }
  739. if (label == nullptr)
  740. {
  741. kData->engine->setLastError("null label");
  742. return false;
  743. }
  744. // ---------------------------------------------------------------
  745. // Check if file exists
  746. {
  747. QFileInfo file(filename);
  748. if (! (file.exists() && file.isFile() && file.isReadable()))
  749. {
  750. kData->engine->setLastError("Requested file is not valid or does not exist");
  751. return false;
  752. }
  753. }
  754. // ---------------------------------------------------------------
  755. // Create the LinuxSampler Engine
  756. const char* const stype = kIsGIG ? "gig" : "sfz";
  757. try {
  758. fEngine = LinuxSampler::EngineFactory::Create(stype);
  759. }
  760. catch (LinuxSampler::Exception& e)
  761. {
  762. kData->engine->setLastError(e.what());
  763. return false;
  764. }
  765. // ---------------------------------------------------------------
  766. // Get the Engine's Instrument Manager
  767. fInstrument = fEngine->GetInstrumentManager();
  768. if (fInstrument == nullptr)
  769. {
  770. kData->engine->setLastError("Failed to get LinuxSampler instrument manager");
  771. LinuxSampler::EngineFactory::Destroy(fEngine);
  772. fEngine = nullptr;
  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. fEngine = nullptr;
  785. return false;
  786. }
  787. // ---------------------------------------------------------------
  788. // Get info
  789. if (fInstrumentIds.size() == 0)
  790. {
  791. kData->engine->setLastError("Failed to find any instruments");
  792. LinuxSampler::EngineFactory::Destroy(fEngine);
  793. fEngine = nullptr;
  794. return false;
  795. }
  796. LinuxSampler::InstrumentManager::instrument_info_t info;
  797. try {
  798. info = fInstrument->GetInstrumentInfo(fInstrumentIds[0]);
  799. }
  800. catch (const LinuxSampler::InstrumentManagerException& e)
  801. {
  802. kData->engine->setLastError(e.what());
  803. LinuxSampler::EngineFactory::Destroy(fEngine);
  804. fEngine = nullptr;
  805. return false;
  806. }
  807. fRealName = info.InstrumentName.c_str();
  808. fLabel = info.Product.c_str();
  809. fMaker = info.Artists.c_str();
  810. fFilename = filename;
  811. if (name != nullptr)
  812. fName = kData->engine->getUniquePluginName(name);
  813. else
  814. fName = kData->engine->getUniquePluginName((const char*)fRealName);
  815. // ---------------------------------------------------------------
  816. // Register client
  817. kData->client = kData->engine->addClient(this);
  818. if (kData->client == nullptr || ! kData->client->isOk())
  819. {
  820. kData->engine->setLastError("Failed to register plugin client");
  821. LinuxSampler::EngineFactory::Destroy(fEngine);
  822. fEngine = nullptr;
  823. return false;
  824. }
  825. // ---------------------------------------------------------------
  826. // Init LinuxSampler stuff
  827. fSamplerChannel = fSampler->AddSamplerChannel();
  828. fSamplerChannel->SetEngineType(stype);
  829. fSamplerChannel->SetAudioOutputDevice(fAudioOutputDevice);
  830. fEngineChannel = fSamplerChannel->GetEngineChannel();
  831. fEngineChannel->Connect(fAudioOutputDevice);
  832. //fEngineChannel->PrepareLoadInstrument(filename, 0); // todo - find instrument from label
  833. //fEngineChannel->LoadInstrument();
  834. fEngineChannel->Volume(LinuxSampler::VOLUME_MAX);
  835. fMidiInputPort->Connect(fSamplerChannel->GetEngineChannel(), LinuxSampler::midi_chan_all);
  836. fInstrument->LoadInstrumentInBackground(fInstrumentIds[0], fEngineChannel);
  837. // ---------------------------------------------------------------
  838. // load plugin settings
  839. {
  840. // set default options
  841. fOptions = 0x0;
  842. fOptions |= PLUGIN_OPTION_MAP_PROGRAM_CHANGES;
  843. fOptions |= PLUGIN_OPTION_SEND_PITCHBEND;
  844. fOptions |= PLUGIN_OPTION_SEND_ALL_SOUND_OFF;
  845. // load settings
  846. kData->idStr = kIsGIG ? "GIG" : "SFZ";
  847. kData->idStr += "/";
  848. kData->idStr += label;
  849. fOptions = kData->loadSettings(fOptions, availableOptions());
  850. }
  851. return true;
  852. }
  853. // -------------------------------------------------------------------
  854. static CarlaPlugin* newLinuxSampler(const Initializer& init, bool isGIG, const bool use16Outs);
  855. private:
  856. const bool kIsGIG; // sfz if false
  857. const bool kUses16Outs;
  858. CarlaString fRealName;
  859. CarlaString fLabel;
  860. CarlaString fMaker;
  861. LinuxSampler::Sampler* fSampler;
  862. LinuxSampler::SamplerChannel* fSamplerChannel;
  863. LinuxSampler::Engine* fEngine;
  864. LinuxSampler::EngineChannel* fEngineChannel;
  865. LinuxSampler::AudioOutputDevicePlugin* fAudioOutputDevice;
  866. LinuxSampler::MidiInputDevicePlugin* fMidiInputDevice;
  867. LinuxSampler::MidiInputPort* fMidiInputPort;
  868. LinuxSampler::InstrumentManager* fInstrument;
  869. std::vector<LinuxSampler::InstrumentManager::instrument_id_t> fInstrumentIds;
  870. CARLA_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(LinuxSamplerPlugin)
  871. };
  872. CarlaPlugin* LinuxSamplerPlugin::newLinuxSampler(const Initializer& init, const bool isGIG, const bool use16Outs)
  873. {
  874. carla_debug("LinuxSamplerPlugin::newLinuxSampler({%p, \"%s\", \"%s\", \"%s\"}, %s, %s)", init.engine, init.filename, init.name, init.label, bool2str(isGIG), bool2str(use16Outs));
  875. if (init.engine->getProccessMode() == PROCESS_MODE_CONTINUOUS_RACK && use16Outs)
  876. {
  877. init.engine->setLastError("Carla's rack mode can only work with Stereo modules, please choose the 2-channel only sample-library version");
  878. return nullptr;
  879. }
  880. LinuxSamplerPlugin* const plugin(new LinuxSamplerPlugin(init.engine, init.id, isGIG, use16Outs));
  881. if (! plugin->init(init.filename, init.name, init.label))
  882. {
  883. delete plugin;
  884. return nullptr;
  885. }
  886. plugin->reload();
  887. return plugin;
  888. }
  889. CARLA_BACKEND_END_NAMESPACE
  890. #else // WANT_LINUXSAMPLER
  891. # warning linuxsampler not available (no GIG and SFZ support)
  892. #endif
  893. CARLA_BACKEND_START_NAMESPACE
  894. CarlaPlugin* CarlaPlugin::newGIG(const Initializer& init, const bool use16Outs)
  895. {
  896. carla_debug("CarlaPlugin::newGIG({%p, \"%s\", \"%s\", \"%s\"}, %s)", init.engine, init.filename, init.name, init.label, bool2str(use16Outs));
  897. #ifdef WANT_LINUXSAMPLER
  898. return LinuxSamplerPlugin::newLinuxSampler(init, true, use16Outs);
  899. #else
  900. init.engine->setLastError("linuxsampler support not available");
  901. return nullptr;
  902. #endif
  903. }
  904. CarlaPlugin* CarlaPlugin::newSFZ(const Initializer& init, const bool use16Outs)
  905. {
  906. carla_debug("CarlaPlugin::newSFZ({%p, \"%s\", \"%s\", \"%s\"}, %s)", init.engine, init.filename, init.name, init.label, bool2str(use16Outs));
  907. #ifdef WANT_LINUXSAMPLER
  908. return LinuxSamplerPlugin::newLinuxSampler(init, false, use16Outs);
  909. #else
  910. init.engine->setLastError("linuxsampler support not available");
  911. return nullptr;
  912. #endif
  913. }
  914. CARLA_BACKEND_END_NAMESPACE