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.

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