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.

1181 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. 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. double 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. continue;
  488. }
  489. if (MIDI_IS_CONTROL_CHANNEL_VOLUME(ctrlEvent.param) && (fHints & PLUGIN_CAN_VOLUME) > 0)
  490. {
  491. value = ctrlEvent.value*127/100;
  492. setVolume(value, false, false);
  493. postponeRtEvent(kPluginPostRtEventParameterChange, PARAMETER_VOLUME, 0, value);
  494. continue;
  495. }
  496. if (MIDI_IS_CONTROL_BALANCE(ctrlEvent.param) && (fHints & PLUGIN_CAN_BALANCE) > 0)
  497. {
  498. double left, right;
  499. value = ctrlEvent.value/0.5 - 1.0;
  500. if (value < 0.0)
  501. {
  502. left = -1.0;
  503. right = (value*2)+1.0;
  504. }
  505. else if (value > 0.0)
  506. {
  507. left = (value*2)-1.0;
  508. right = 1.0;
  509. }
  510. else
  511. {
  512. left = -1.0;
  513. right = 1.0;
  514. }
  515. setBalanceLeft(left, false, false);
  516. setBalanceRight(right, false, false);
  517. postponeRtEvent(kPluginPostRtEventParameterChange, PARAMETER_BALANCE_LEFT, 0, left);
  518. postponeRtEvent(kPluginPostRtEventParameterChange, PARAMETER_BALANCE_RIGHT, 0, right);
  519. continue;
  520. }
  521. }
  522. #endif
  523. // Control plugin parameters
  524. for (k=0; k < kData->param.count; ++k)
  525. {
  526. if (kData->param.data[k].midiChannel != event.channel)
  527. continue;
  528. if (kData->param.data[k].midiCC != ctrlEvent.param)
  529. continue;
  530. if (kData->param.data[k].type != PARAMETER_INPUT)
  531. continue;
  532. if ((kData->param.data[k].hints & PARAMETER_IS_AUTOMABLE) == 0)
  533. continue;
  534. double value;
  535. if (kData->param.data[k].hints & PARAMETER_IS_BOOLEAN)
  536. {
  537. value = (ctrlEvent.value < 0.5f) ? kData->param.ranges[k].min : kData->param.ranges[k].max;
  538. }
  539. else
  540. {
  541. value = kData->param.ranges[i].unnormalizeValue(ctrlEvent.value);
  542. if (kData->param.data[k].hints & PARAMETER_IS_INTEGER)
  543. value = std::rint(value);
  544. }
  545. setParameterValue(k, value, false, false, false);
  546. postponeRtEvent(kPluginPostRtEventParameterChange, static_cast<int32_t>(k), 0, value);
  547. }
  548. break;
  549. }
  550. case kEngineControlEventTypeMidiBank:
  551. if (event.channel == kData->ctrlChannel && (fOptions & PLUGIN_OPTION_MAP_PROGRAM_CHANGES) != 0)
  552. nextBankId = ctrlEvent.param;
  553. break;
  554. case kEngineControlEventTypeMidiProgram:
  555. if (event.channel == kData->ctrlChannel && (fOptions & PLUGIN_OPTION_MAP_PROGRAM_CHANGES) != 0)
  556. {
  557. const uint32_t nextProgramId = ctrlEvent.param;
  558. for (k=0; k < kData->midiprog.count; ++k)
  559. {
  560. if (kData->midiprog.data[k].bank == nextBankId && kData->midiprog.data[k].program == nextProgramId)
  561. {
  562. setMidiProgram(k, false, false, false);
  563. postponeRtEvent(kPluginPostRtEventMidiProgramChange, k, 0, 0.0f);
  564. break;
  565. }
  566. }
  567. }
  568. break;
  569. case kEngineControlEventTypeAllSoundOff:
  570. if (fOptions & PLUGIN_OPTION_SEND_ALL_SOUND_OFF)
  571. {
  572. fMidiInputPort->DispatchControlChange(MIDI_CONTROL_ALL_SOUND_OFF, 0, event.channel, sampleAccurate ? startTime : time);
  573. }
  574. break;
  575. case kEngineControlEventTypeAllNotesOff:
  576. if (fOptions & PLUGIN_OPTION_SEND_ALL_SOUND_OFF)
  577. {
  578. if (event.channel == kData->ctrlChannel && ! allNotesOffSent)
  579. {
  580. allNotesOffSent = true;
  581. sendMidiAllNotesOffToCallback();
  582. }
  583. fMidiInputPort->DispatchControlChange(MIDI_CONTROL_ALL_NOTES_OFF, 0, event.channel, sampleAccurate ? startTime : time);
  584. }
  585. break;
  586. }
  587. break;
  588. }
  589. case kEngineEventTypeMidi:
  590. {
  591. const EngineMidiEvent& midiEvent(event.midi);
  592. uint8_t status = MIDI_GET_STATUS_FROM_DATA(midiEvent.data);
  593. uint8_t channel = event.channel;
  594. // Fix bad note-off (per DSSI spec)
  595. if (MIDI_IS_STATUS_NOTE_ON(status) && midiEvent.data[2] == 0)
  596. status -= 0x10;
  597. int32_t fragmentPos = sampleAccurate ? startTime : time;
  598. if (MIDI_IS_STATUS_NOTE_OFF(status))
  599. {
  600. const uint8_t note = midiEvent.data[1];
  601. fMidiInputPort->DispatchNoteOff(note, 0, channel, fragmentPos);
  602. postponeRtEvent(kPluginPostRtEventNoteOff, channel, note, 0.0f);
  603. }
  604. else if (MIDI_IS_STATUS_NOTE_ON(status))
  605. {
  606. const uint8_t note = midiEvent.data[1];
  607. const uint8_t velo = midiEvent.data[2];
  608. fMidiInputPort->DispatchNoteOn(note, velo, channel, fragmentPos);
  609. postponeRtEvent(kPluginPostRtEventNoteOn, channel, note, velo);
  610. }
  611. else if (MIDI_IS_STATUS_POLYPHONIC_AFTERTOUCH(status) && (fOptions & PLUGIN_OPTION_SEND_NOTE_AFTERTOUCH) != 0)
  612. {
  613. //const uint8_t note = midiEvent.data[1];
  614. //const uint8_t pressure = midiEvent.data[2];
  615. // unsupported
  616. }
  617. else if (MIDI_IS_STATUS_CONTROL_CHANGE(status) && (fOptions & PLUGIN_OPTION_SEND_CONTROL_CHANGES) != 0)
  618. {
  619. const uint8_t control = midiEvent.data[1];
  620. const uint8_t value = midiEvent.data[2];
  621. fMidiInputPort->DispatchControlChange(control, value, channel, fragmentPos);
  622. }
  623. else if (MIDI_IS_STATUS_AFTERTOUCH(status) && (fOptions & PLUGIN_OPTION_SEND_CHANNEL_PRESSURE) != 0)
  624. {
  625. //const uint8_t pressure = midiEvent.data[1];
  626. // unsupported
  627. }
  628. else if (MIDI_IS_STATUS_PITCH_WHEEL_CONTROL(status) && (fOptions & PLUGIN_OPTION_SEND_PITCHBEND) != 0)
  629. {
  630. const uint8_t lsb = midiEvent.data[1];
  631. const uint8_t msb = midiEvent.data[2];
  632. fMidiInputPort->DispatchPitchbend(((msb << 7) | lsb) - 8192, channel, fragmentPos);
  633. }
  634. break;
  635. }
  636. }
  637. }
  638. kData->postRtEvents.trySplice();
  639. if (frames > timeOffset)
  640. processSingle(outBuffer, frames - timeOffset, timeOffset);
  641. } // End of Event Input and Processing
  642. }
  643. bool processSingle(float** const outBuffer, const uint32_t frames, const uint32_t timeOffset)
  644. {
  645. CARLA_ASSERT(outBuffer != nullptr);
  646. CARLA_ASSERT(frames > 0);
  647. if (outBuffer == nullptr)
  648. return false;
  649. if (frames == 0)
  650. return false;
  651. uint32_t i, k;
  652. // --------------------------------------------------------------------------------------------------------
  653. // Try lock, silence otherwise
  654. if (kData->engine->isOffline())
  655. {
  656. kData->singleMutex.lock();
  657. }
  658. else if (! kData->singleMutex.tryLock())
  659. {
  660. for (i=0; i < kData->audioOut.count; ++i)
  661. {
  662. for (k=0; k < frames; ++k)
  663. outBuffer[i][k+timeOffset] = 0.0f;
  664. }
  665. return false;
  666. }
  667. // --------------------------------------------------------------------------------------------------------
  668. // Run plugin
  669. fAudioOutputDevice->Channel(0)->SetBuffer(outBuffer[0] + timeOffset);
  670. fAudioOutputDevice->Channel(1)->SetBuffer(outBuffer[1] + timeOffset);
  671. // QUESTION: Need to clear it before?
  672. fAudioOutputDevice->Render(frames);
  673. #ifndef BUILD_BRIDGE
  674. // --------------------------------------------------------------------------------------------------------
  675. // Post-processing (dry/wet, volume and balance)
  676. {
  677. const bool doVolume = (fHints & PLUGIN_CAN_VOLUME) > 0 && kData->postProc.volume != 1.0f;
  678. const bool doBalance = (fHints & PLUGIN_CAN_BALANCE) > 0 && (kData->postProc.balanceLeft != -1.0f || kData->postProc.balanceRight != 1.0f);
  679. float oldBufLeft[doBalance ? frames : 1];
  680. for (i=0; i < kData->audioOut.count; ++i)
  681. {
  682. // Balance
  683. if (doBalance)
  684. {
  685. if (i % 2 == 0)
  686. carla_copyFloat(oldBufLeft, outBuffer[i], frames);
  687. float balRangeL = (kData->postProc.balanceLeft + 1.0f)/2.0f;
  688. float balRangeR = (kData->postProc.balanceRight + 1.0f)/2.0f;
  689. for (k=0; k < frames; ++k)
  690. {
  691. if (i % 2 == 0)
  692. {
  693. // left
  694. outBuffer[i][k] = oldBufLeft[k] * (1.0f - balRangeL);
  695. outBuffer[i][k] += outBuffer[i+1][k] * (1.0f - balRangeR);
  696. }
  697. else
  698. {
  699. // right
  700. outBuffer[i][k] = outBuffer[i][k] * balRangeR;
  701. outBuffer[i][k] += oldBufLeft[k] * balRangeL;
  702. }
  703. }
  704. }
  705. // Volume
  706. if (doVolume)
  707. {
  708. for (k=0; k < frames; ++k)
  709. outBuffer[i][k+timeOffset] *= kData->postProc.volume;
  710. }
  711. }
  712. } // End of Post-processing
  713. #endif
  714. // --------------------------------------------------------------------------------------------------------
  715. kData->singleMutex.unlock();
  716. return true;
  717. }
  718. // -------------------------------------------------------------------
  719. // Plugin buffers
  720. // nothing
  721. // -------------------------------------------------------------------
  722. const void* getExtraStuff() override
  723. {
  724. return kUses16Outs ? (const void*)0x1 : nullptr;
  725. }
  726. bool init(const char* filename, const char* const name, const char* label)
  727. {
  728. CARLA_ASSERT(kData->engine != nullptr);
  729. CARLA_ASSERT(kData->client == nullptr);
  730. CARLA_ASSERT(filename != nullptr);
  731. CARLA_ASSERT(label != nullptr);
  732. // ---------------------------------------------------------------
  733. // first checks
  734. if (kData->engine == nullptr)
  735. {
  736. return false;
  737. }
  738. if (kData->client != nullptr)
  739. {
  740. kData->engine->setLastError("Plugin client is already registered");
  741. return false;
  742. }
  743. if (filename == nullptr)
  744. {
  745. kData->engine->setLastError("null filename");
  746. return false;
  747. }
  748. if (label == nullptr)
  749. {
  750. kData->engine->setLastError("null label");
  751. return false;
  752. }
  753. // ---------------------------------------------------------------
  754. // Check if file exists
  755. {
  756. QFileInfo file(filename);
  757. if (! (file.exists() && file.isFile() && file.isReadable()))
  758. {
  759. kData->engine->setLastError("Requested file is not valid or does not exist");
  760. return false;
  761. }
  762. }
  763. // ---------------------------------------------------------------
  764. // Create the LinuxSampler Engine
  765. const char* const stype = kIsGIG ? "gig" : "sfz";
  766. try {
  767. fEngine = LinuxSampler::EngineFactory::Create(stype);
  768. }
  769. catch (LinuxSampler::Exception& e)
  770. {
  771. kData->engine->setLastError(e.what());
  772. return false;
  773. }
  774. // ---------------------------------------------------------------
  775. // Get the Engine's Instrument Manager
  776. fInstrument = fEngine->GetInstrumentManager();
  777. if (fInstrument == nullptr)
  778. {
  779. kData->engine->setLastError("Failed to get LinuxSampler instrument manager");
  780. LinuxSampler::EngineFactory::Destroy(fEngine);
  781. fEngine = nullptr;
  782. return false;
  783. }
  784. // ---------------------------------------------------------------
  785. // Load the Instrument via filename
  786. try {
  787. fInstrumentIds = fInstrument->GetInstrumentFileContent(filename);
  788. }
  789. catch (const LinuxSampler::InstrumentManagerException& e)
  790. {
  791. kData->engine->setLastError(e.what());
  792. LinuxSampler::EngineFactory::Destroy(fEngine);
  793. fEngine = nullptr;
  794. return false;
  795. }
  796. // ---------------------------------------------------------------
  797. // Get info
  798. if (fInstrumentIds.size() == 0)
  799. {
  800. kData->engine->setLastError("Failed to find any instruments");
  801. LinuxSampler::EngineFactory::Destroy(fEngine);
  802. fEngine = nullptr;
  803. return false;
  804. }
  805. LinuxSampler::InstrumentManager::instrument_info_t info;
  806. try {
  807. info = fInstrument->GetInstrumentInfo(fInstrumentIds[0]);
  808. }
  809. catch (const LinuxSampler::InstrumentManagerException& e)
  810. {
  811. kData->engine->setLastError(e.what());
  812. LinuxSampler::EngineFactory::Destroy(fEngine);
  813. fEngine = nullptr;
  814. return false;
  815. }
  816. fRealName = info.InstrumentName.c_str();
  817. fLabel = info.Product.c_str();
  818. fMaker = info.Artists.c_str();
  819. fFilename = filename;
  820. if (name != nullptr)
  821. fName = kData->engine->getUniquePluginName(name);
  822. else
  823. fName = kData->engine->getUniquePluginName((const char*)fRealName);
  824. // ---------------------------------------------------------------
  825. // Register client
  826. kData->client = kData->engine->addClient(this);
  827. if (kData->client == nullptr || ! kData->client->isOk())
  828. {
  829. kData->engine->setLastError("Failed to register plugin client");
  830. LinuxSampler::EngineFactory::Destroy(fEngine);
  831. fEngine = nullptr;
  832. return false;
  833. }
  834. // ---------------------------------------------------------------
  835. // Init LinuxSampler stuff
  836. fSamplerChannel = fSampler->AddSamplerChannel();
  837. fSamplerChannel->SetEngineType(stype);
  838. fSamplerChannel->SetAudioOutputDevice(fAudioOutputDevice);
  839. fEngineChannel = fSamplerChannel->GetEngineChannel();
  840. fEngineChannel->Connect(fAudioOutputDevice);
  841. fEngineChannel->Volume(LinuxSampler::VOLUME_MAX);
  842. fMidiInputPort->Connect(fSamplerChannel->GetEngineChannel(), LinuxSampler::midi_chan_all);
  843. // ---------------------------------------------------------------
  844. // load plugin settings
  845. {
  846. // set default options
  847. fOptions = 0x0;
  848. fOptions |= PLUGIN_OPTION_MAP_PROGRAM_CHANGES;
  849. fOptions |= PLUGIN_OPTION_SEND_PITCHBEND;
  850. fOptions |= PLUGIN_OPTION_SEND_ALL_SOUND_OFF;
  851. // load settings
  852. kData->idStr = kIsGIG ? "GIG" : "SFZ";
  853. kData->idStr += "/";
  854. kData->idStr += label;
  855. fOptions = kData->loadSettings(fOptions, availableOptions());
  856. }
  857. return true;
  858. }
  859. // -------------------------------------------------------------------
  860. static CarlaPlugin* newLinuxSampler(const Initializer& init, bool isGIG, const bool use16Outs);
  861. private:
  862. const bool kIsGIG; // sfz if false
  863. const bool kUses16Outs;
  864. CarlaString fRealName;
  865. CarlaString fLabel;
  866. CarlaString fMaker;
  867. LinuxSampler::Sampler* fSampler;
  868. LinuxSampler::SamplerChannel* fSamplerChannel;
  869. LinuxSampler::Engine* fEngine;
  870. LinuxSampler::EngineChannel* fEngineChannel;
  871. LinuxSampler::AudioOutputDevicePlugin* fAudioOutputDevice;
  872. LinuxSampler::MidiInputDevicePlugin* fMidiInputDevice;
  873. LinuxSampler::MidiInputPort* fMidiInputPort;
  874. LinuxSampler::InstrumentManager* fInstrument;
  875. std::vector<LinuxSampler::InstrumentManager::instrument_id_t> fInstrumentIds;
  876. CARLA_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(LinuxSamplerPlugin)
  877. };
  878. CarlaPlugin* LinuxSamplerPlugin::newLinuxSampler(const Initializer& init, const bool isGIG, const bool use16Outs)
  879. {
  880. carla_debug("LinuxSamplerPlugin::newLinuxSampler({%p, \"%s\", \"%s\", \"%s\"}, %s, %s)", init.engine, init.filename, init.name, init.label, bool2str(isGIG), bool2str(use16Outs));
  881. if (init.engine->getProccessMode() == PROCESS_MODE_CONTINUOUS_RACK && use16Outs)
  882. {
  883. init.engine->setLastError("Carla's rack mode can only work with Stereo modules, please choose the 2-channel only sample-library version");
  884. return nullptr;
  885. }
  886. LinuxSamplerPlugin* const plugin(new LinuxSamplerPlugin(init.engine, init.id, isGIG, use16Outs));
  887. if (! plugin->init(init.filename, init.name, init.label))
  888. {
  889. delete plugin;
  890. return nullptr;
  891. }
  892. plugin->reload();
  893. return plugin;
  894. }
  895. CARLA_BACKEND_END_NAMESPACE
  896. #else // WANT_LINUXSAMPLER
  897. # warning linuxsampler not available (no GIG and SFZ support)
  898. #endif
  899. CARLA_BACKEND_START_NAMESPACE
  900. CarlaPlugin* CarlaPlugin::newGIG(const Initializer& init, const bool use16Outs)
  901. {
  902. carla_debug("CarlaPlugin::newGIG({%p, \"%s\", \"%s\", \"%s\"}, %s)", init.engine, init.filename, init.name, init.label, bool2str(use16Outs));
  903. #ifdef WANT_LINUXSAMPLER
  904. return LinuxSamplerPlugin::newLinuxSampler(init, true, use16Outs);
  905. #else
  906. init.engine->setLastError("linuxsampler support not available");
  907. return nullptr;
  908. #endif
  909. }
  910. CarlaPlugin* CarlaPlugin::newSFZ(const Initializer& init, const bool use16Outs)
  911. {
  912. carla_debug("CarlaPlugin::newSFZ({%p, \"%s\", \"%s\", \"%s\"}, %s)", init.engine, init.filename, init.name, init.label, bool2str(use16Outs));
  913. #ifdef WANT_LINUXSAMPLER
  914. return LinuxSamplerPlugin::newLinuxSampler(init, false, use16Outs);
  915. #else
  916. init.engine->setLastError("linuxsampler support not available");
  917. return nullptr;
  918. #endif
  919. }
  920. CARLA_BACKEND_END_NAMESPACE