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. // 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. namespace LinuxSampler {
  27. using CarlaBackend::CarlaEngine;
  28. using CarlaBackend::CarlaPlugin;
  29. // -----------------------------------------------------------------------
  30. // LinuxSampler static values
  31. static const float VOLUME_MAX = 3.16227766f; // +10 dB
  32. static const float VOLUME_MIN = 0.0f; // -inf dB
  33. // -----------------------------------------------------------------------
  34. // LinuxSampler AudioOutputDevice Plugin
  35. class AudioOutputDevicePlugin : public AudioOutputDevice
  36. {
  37. public:
  38. AudioOutputDevicePlugin(CarlaBackend::CarlaEngine* const engine, CarlaBackend::CarlaPlugin* const plugin)
  39. : AudioOutputDevice(std::map<String, DeviceCreationParameter*>()),
  40. fEngine(engine),
  41. fPlugin(plugin)
  42. {
  43. CARLA_ASSERT(engine != nullptr);
  44. CARLA_ASSERT(plugin != nullptr);
  45. }
  46. // -------------------------------------------------------------------
  47. // LinuxSampler virtual methods
  48. void Play() override
  49. {
  50. }
  51. bool IsPlaying() override
  52. {
  53. return (fEngine->isRunning() && fPlugin->isEnabled());
  54. }
  55. void Stop() override
  56. {
  57. }
  58. uint MaxSamplesPerCycle() override
  59. {
  60. return fEngine->getBufferSize();
  61. }
  62. uint SampleRate() override
  63. {
  64. return fEngine->getSampleRate();
  65. }
  66. String Driver() override
  67. {
  68. return "AudioOutputDevicePlugin";
  69. }
  70. AudioChannel* CreateChannel(uint channelNr) override
  71. {
  72. return new AudioChannel(channelNr, nullptr, 0);
  73. }
  74. // -------------------------------------------------------------------
  75. // Give public access to the RenderAudio call
  76. int Render(const uint samples)
  77. {
  78. return RenderAudio(samples);
  79. }
  80. private:
  81. CarlaEngine* const fEngine;
  82. CarlaPlugin* const fPlugin;
  83. };
  84. // -----------------------------------------------------------------------
  85. // LinuxSampler MidiInputDevice Plugin
  86. class MidiInputDevicePlugin : public MidiInputDevice
  87. {
  88. public:
  89. MidiInputDevicePlugin(Sampler* const sampler)
  90. : MidiInputDevice(std::map<String, DeviceCreationParameter*>(), sampler)
  91. {
  92. }
  93. // -------------------------------------------------------------------
  94. // LinuxSampler virtual methods
  95. void Listen() override
  96. {
  97. }
  98. void StopListen() override
  99. {
  100. }
  101. String Driver() override
  102. {
  103. return "MidiInputDevicePlugin";
  104. }
  105. MidiInputPort* CreateMidiPort() override
  106. {
  107. return new MidiInputPortPlugin(this, Ports.size());
  108. }
  109. // -------------------------------------------------------------------
  110. // Properly delete port (destructor is protected)
  111. void DeleteMidiPort(MidiInputPort* const port)
  112. {
  113. delete (MidiInputPortPlugin*)port;
  114. }
  115. // -------------------------------------------------------------------
  116. // MIDI Port implementation for this plugin MIDI input driver
  117. // (Constructor and destructor are protected)
  118. class MidiInputPortPlugin : public MidiInputPort
  119. {
  120. protected:
  121. MidiInputPortPlugin(MidiInputDevicePlugin* const device, const int portNumber)
  122. : MidiInputPort(device, portNumber) {}
  123. friend class MidiInputDevicePlugin;
  124. };
  125. };
  126. } // namespace LinuxSampler
  127. // -----------------------------------------------------------------------
  128. CARLA_BACKEND_START_NAMESPACE
  129. #if 0
  130. }
  131. #endif
  132. class LinuxSamplerPlugin : public CarlaPlugin
  133. {
  134. public:
  135. LinuxSamplerPlugin(CarlaEngine* const engine, const unsigned short id, const bool isGIG, const bool use16Outs)
  136. : CarlaPlugin(engine, id),
  137. kIsGIG(isGIG),
  138. kUses16Outs(use16Outs),
  139. fSampler(new LinuxSampler::Sampler()),
  140. fSamplerChannel(nullptr),
  141. fEngine(nullptr),
  142. fEngineChannel(nullptr),
  143. fAudioOutputDevice(new LinuxSampler::AudioOutputDevicePlugin(engine, this)),
  144. fMidiInputDevice(new LinuxSampler::MidiInputDevicePlugin(fSampler)),
  145. fMidiInputPort(fMidiInputDevice->CreateMidiPort()),
  146. fInstrument(nullptr)
  147. {
  148. carla_debug("LinuxSamplerPlugin::LinuxSamplerPlugin(%p, %i, %s)", engine, id, bool2str(isGIG));
  149. }
  150. ~LinuxSamplerPlugin() override
  151. {
  152. carla_debug("LinuxSamplerPlugin::~LinuxSamplerPlugin()");
  153. pData->singleMutex.lock();
  154. pData->masterMutex.lock();
  155. if (pData->client != nullptr && pData->client->isActive())
  156. pData->client->deactivate();
  157. if (pData->active)
  158. {
  159. deactivate();
  160. pData->active = false;
  161. }
  162. if (fEngine != nullptr)
  163. {
  164. if (fSamplerChannel != nullptr)
  165. {
  166. fMidiInputPort->Disconnect(fSamplerChannel->GetEngineChannel());
  167. fEngineChannel->DisconnectAudioOutputDevice();
  168. fSampler->RemoveSamplerChannel(fSamplerChannel);
  169. }
  170. LinuxSampler::EngineFactory::Destroy(fEngine);
  171. }
  172. // destructor is private
  173. fMidiInputDevice->DeleteMidiPort(fMidiInputPort);
  174. delete fMidiInputDevice;
  175. delete fAudioOutputDevice;
  176. delete fSampler;
  177. fInstrumentIds.clear();
  178. clearBuffers();
  179. }
  180. // -------------------------------------------------------------------
  181. // Information (base)
  182. PluginType getType() const noexcept override
  183. {
  184. return kIsGIG ? PLUGIN_GIG : PLUGIN_SFZ;
  185. }
  186. PluginCategory getCategory() const override
  187. {
  188. return PLUGIN_CATEGORY_SYNTH;
  189. }
  190. // -------------------------------------------------------------------
  191. // Information (count)
  192. // nothing
  193. // -------------------------------------------------------------------
  194. // Information (current data)
  195. // nothing
  196. // -------------------------------------------------------------------
  197. // Information (per-plugin data)
  198. unsigned int getAvailableOptions() const override
  199. {
  200. unsigned int options = 0x0;
  201. options |= PLUGIN_OPTION_MAP_PROGRAM_CHANGES;
  202. options |= PLUGIN_OPTION_SEND_CONTROL_CHANGES;
  203. options |= PLUGIN_OPTION_SEND_PITCHBEND;
  204. options |= PLUGIN_OPTION_SEND_ALL_SOUND_OFF;
  205. return options;
  206. }
  207. void getLabel(char* const strBuf) const override
  208. {
  209. std::strncpy(strBuf, (const char*)fLabel, STR_MAX);
  210. }
  211. void getMaker(char* const strBuf) const override
  212. {
  213. std::strncpy(strBuf, (const char*)fMaker, STR_MAX);
  214. }
  215. void getCopyright(char* const strBuf) const override
  216. {
  217. getMaker(strBuf);
  218. }
  219. void getRealName(char* const strBuf) const override
  220. {
  221. std::strncpy(strBuf, (const char*)fRealName, STR_MAX);
  222. }
  223. // -------------------------------------------------------------------
  224. // Set data (state)
  225. // nothing
  226. // -------------------------------------------------------------------
  227. // Set data (internal stuff)
  228. // nothing
  229. // -------------------------------------------------------------------
  230. // Set data (plugin-specific stuff)
  231. void setMidiProgram(int32_t index, const bool sendGui, const bool sendOsc, const bool sendCallback) override
  232. {
  233. CARLA_ASSERT(index >= -1 && index < static_cast<int32_t>(pData->midiprog.count));
  234. if (index < -1)
  235. index = -1;
  236. else if (index > static_cast<int32_t>(pData->midiprog.count))
  237. return;
  238. if (pData->ctrlChannel < 0 || pData->ctrlChannel >= 16)
  239. return;
  240. if (index >= 0)
  241. {
  242. const uint32_t bank = pData->midiprog.data[index].bank;
  243. const uint32_t program = pData->midiprog.data[index].program;
  244. const uint32_t rIndex = bank*128 + program;
  245. const ScopedSingleProcessLocker spl(this, (sendGui || sendOsc || sendCallback));
  246. if (pData->engine->isOffline())
  247. {
  248. fEngineChannel->PrepareLoadInstrument((const char*)fFilename, rIndex);
  249. fEngineChannel->LoadInstrument();
  250. }
  251. else
  252. {
  253. fInstrument->LoadInstrumentInBackground(fInstrumentIds[rIndex], fEngineChannel);
  254. }
  255. }
  256. CarlaPlugin::setMidiProgram(index, sendGui, sendOsc, sendCallback);
  257. }
  258. // -------------------------------------------------------------------
  259. // Plugin state
  260. void reload() override
  261. {
  262. CARLA_SAFE_ASSERT_RETURN(pData->engine != nullptr,);
  263. CARLA_SAFE_ASSERT_RETURN(fInstrument != nullptr,);
  264. carla_debug("LinuxSamplerPlugin::reload() - start");
  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_EXTRA_HINT_HAS_MIDI_IN;
  324. pData->extraHints |= PLUGIN_EXTRA_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. FloatVectorOperations::clear(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_BUFFERS) == 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. FloatVectorOperations::copy(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. //
  763. // if (! (file.exists() && file.isFile() && file.isReadable()))
  764. // {
  765. // pData->engine->setLastError("Requested file is not valid or does not exist");
  766. // return false;
  767. // }
  768. }
  769. // ---------------------------------------------------------------
  770. // Create the LinuxSampler Engine
  771. const char* const stype = kIsGIG ? "gig" : "sfz";
  772. try {
  773. fEngine = LinuxSampler::EngineFactory::Create(stype);
  774. }
  775. catch (LinuxSampler::Exception& e)
  776. {
  777. pData->engine->setLastError(e.what());
  778. return false;
  779. }
  780. // ---------------------------------------------------------------
  781. // Get the Engine's Instrument Manager
  782. fInstrument = fEngine->GetInstrumentManager();
  783. if (fInstrument == nullptr)
  784. {
  785. pData->engine->setLastError("Failed to get LinuxSampler instrument manager");
  786. LinuxSampler::EngineFactory::Destroy(fEngine);
  787. fEngine = nullptr;
  788. return false;
  789. }
  790. // ---------------------------------------------------------------
  791. // Load the Instrument via filename
  792. try {
  793. fInstrumentIds = fInstrument->GetInstrumentFileContent(filename);
  794. }
  795. catch (const LinuxSampler::InstrumentManagerException& e)
  796. {
  797. pData->engine->setLastError(e.what());
  798. LinuxSampler::EngineFactory::Destroy(fEngine);
  799. fEngine = nullptr;
  800. return false;
  801. }
  802. // ---------------------------------------------------------------
  803. // Get info
  804. if (fInstrumentIds.size() == 0)
  805. {
  806. pData->engine->setLastError("Failed to find any instruments");
  807. LinuxSampler::EngineFactory::Destroy(fEngine);
  808. fEngine = nullptr;
  809. return false;
  810. }
  811. LinuxSampler::InstrumentManager::instrument_info_t info;
  812. try {
  813. info = fInstrument->GetInstrumentInfo(fInstrumentIds[0]);
  814. }
  815. catch (const LinuxSampler::InstrumentManagerException& e)
  816. {
  817. pData->engine->setLastError(e.what());
  818. LinuxSampler::EngineFactory::Destroy(fEngine);
  819. fEngine = nullptr;
  820. return false;
  821. }
  822. fRealName = info.InstrumentName.c_str();
  823. fLabel = info.Product.c_str();
  824. fMaker = info.Artists.c_str();
  825. fFilename = filename;
  826. if (kUses16Outs && ! fLabel.endsWith(" (16 outs)"))
  827. fLabel += " (16 outs)";
  828. if (name != nullptr)
  829. fName = pData->engine->getUniquePluginName(name);
  830. else
  831. fName = pData->engine->getUniquePluginName((const char*)fRealName);
  832. // ---------------------------------------------------------------
  833. // Register client
  834. pData->client = pData->engine->addClient(this);
  835. if (pData->client == nullptr || ! pData->client->isOk())
  836. {
  837. pData->engine->setLastError("Failed to register plugin client");
  838. LinuxSampler::EngineFactory::Destroy(fEngine);
  839. fEngine = nullptr;
  840. return false;
  841. }
  842. // ---------------------------------------------------------------
  843. // Init LinuxSampler stuff
  844. fSamplerChannel = fSampler->AddSamplerChannel();
  845. fSamplerChannel->SetEngineType(stype);
  846. fSamplerChannel->SetAudioOutputDevice(fAudioOutputDevice);
  847. fEngineChannel = fSamplerChannel->GetEngineChannel();
  848. fEngineChannel->Connect(fAudioOutputDevice);
  849. fEngineChannel->Volume(LinuxSampler::VOLUME_MAX);
  850. fMidiInputPort->Connect(fSamplerChannel->GetEngineChannel(), LinuxSampler::midi_chan_all);
  851. // ---------------------------------------------------------------
  852. // load plugin settings
  853. {
  854. // set default options
  855. fOptions = 0x0;
  856. fOptions |= PLUGIN_OPTION_MAP_PROGRAM_CHANGES;
  857. fOptions |= PLUGIN_OPTION_SEND_PITCHBEND;
  858. fOptions |= PLUGIN_OPTION_SEND_ALL_SOUND_OFF;
  859. // load settings
  860. pData->idStr = kIsGIG ? "GIG" : "SFZ";
  861. pData->idStr += "/";
  862. pData->idStr += label;
  863. fOptions = pData->loadSettings(fOptions, getAvailableOptions());
  864. }
  865. return true;
  866. }
  867. // -------------------------------------------------------------------
  868. static CarlaPlugin* newLinuxSampler(const Initializer& init, bool isGIG, const bool use16Outs);
  869. private:
  870. const bool kIsGIG; // sfz if false
  871. const bool kUses16Outs;
  872. CarlaString fRealName;
  873. CarlaString fLabel;
  874. CarlaString fMaker;
  875. LinuxSampler::Sampler* fSampler;
  876. LinuxSampler::SamplerChannel* fSamplerChannel;
  877. LinuxSampler::Engine* fEngine;
  878. LinuxSampler::EngineChannel* fEngineChannel;
  879. LinuxSampler::AudioOutputDevicePlugin* fAudioOutputDevice;
  880. LinuxSampler::MidiInputDevicePlugin* fMidiInputDevice;
  881. LinuxSampler::MidiInputPort* fMidiInputPort;
  882. LinuxSampler::InstrumentManager* fInstrument;
  883. std::vector<LinuxSampler::InstrumentManager::instrument_id_t> fInstrumentIds;
  884. CARLA_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(LinuxSamplerPlugin)
  885. };
  886. CarlaPlugin* LinuxSamplerPlugin::newLinuxSampler(const Initializer& init, const bool isGIG, const bool use16Outs)
  887. {
  888. carla_debug("LinuxSamplerPlugin::newLinuxSampler({%p, \"%s\", \"%s\", \"%s\"}, %s, %s)", init.engine, init.filename, init.name, init.label, bool2str(isGIG), bool2str(use16Outs));
  889. if (init.engine->getProccessMode() == PROCESS_MODE_CONTINUOUS_RACK && use16Outs)
  890. {
  891. init.engine->setLastError("Carla's rack mode can only work with Stereo modules, please choose the 2-channel only sample-library version");
  892. return nullptr;
  893. }
  894. LinuxSamplerPlugin* const plugin(new LinuxSamplerPlugin(init.engine, init.id, isGIG, use16Outs));
  895. if (! plugin->init(init.filename, init.name, init.label))
  896. {
  897. delete plugin;
  898. return nullptr;
  899. }
  900. plugin->reload();
  901. return plugin;
  902. }
  903. CARLA_BACKEND_END_NAMESPACE
  904. #else // WANT_LINUXSAMPLER
  905. # warning linuxsampler not available (no GIG and SFZ support)
  906. #endif
  907. CARLA_BACKEND_START_NAMESPACE
  908. CarlaPlugin* CarlaPlugin::newGIG(const Initializer& init, const bool use16Outs)
  909. {
  910. carla_debug("CarlaPlugin::newGIG({%p, \"%s\", \"%s\", \"%s\"}, %s)", init.engine, init.filename, init.name, init.label, bool2str(use16Outs));
  911. #ifdef WANT_LINUXSAMPLER
  912. return LinuxSamplerPlugin::newLinuxSampler(init, true, use16Outs);
  913. #else
  914. init.engine->setLastError("linuxsampler support not available");
  915. return nullptr;
  916. #endif
  917. }
  918. CarlaPlugin* CarlaPlugin::newSFZ(const Initializer& init, const bool use16Outs)
  919. {
  920. carla_debug("CarlaPlugin::newSFZ({%p, \"%s\", \"%s\", \"%s\"}, %s)", init.engine, init.filename, init.name, init.label, bool2str(use16Outs));
  921. #ifdef WANT_LINUXSAMPLER
  922. return LinuxSamplerPlugin::newLinuxSampler(init, false, use16Outs);
  923. #else
  924. init.engine->setLastError("linuxsampler support not available");
  925. return nullptr;
  926. #endif
  927. }
  928. CARLA_BACKEND_END_NAMESPACE