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.

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