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.

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