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.

1183 lines
39KB

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