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.

1197 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_debug("LinuxSamplerPlugin::reload() - start");
  263. CARLA_ASSERT(pData->engine != nullptr);
  264. CARLA_ASSERT(fInstrument != nullptr);
  265. if (pData->engine == nullptr)
  266. return;
  267. if (fInstrument == nullptr)
  268. return;
  269. const ProcessMode processMode(pData->engine->getProccessMode());
  270. // Safely disable plugin for reload
  271. const ScopedDisabler sd(this);
  272. if (pData->active)
  273. deactivate();
  274. clearBuffers();
  275. uint32_t aOuts;
  276. aOuts = 2;
  277. pData->audioOut.createNew(aOuts);
  278. const int portNameSize = pData->engine->getMaxPortNameSize();
  279. CarlaString portName;
  280. // ---------------------------------------
  281. // Audio Outputs
  282. {
  283. // out-left
  284. portName.clear();
  285. if (processMode == PROCESS_MODE_SINGLE_CLIENT)
  286. {
  287. portName = fName;
  288. portName += ":";
  289. }
  290. portName += "out-left";
  291. portName.truncate(portNameSize);
  292. pData->audioOut.ports[0].port = (CarlaEngineAudioPort*)pData->client->addPort(kEnginePortTypeAudio, portName, false);
  293. pData->audioOut.ports[0].rindex = 0;
  294. // out-right
  295. portName.clear();
  296. if (processMode == PROCESS_MODE_SINGLE_CLIENT)
  297. {
  298. portName = fName;
  299. portName += ":";
  300. }
  301. portName += "out-right";
  302. portName.truncate(portNameSize);
  303. pData->audioOut.ports[1].port = (CarlaEngineAudioPort*)pData->client->addPort(kEnginePortTypeAudio, portName, false);
  304. pData->audioOut.ports[1].rindex = 1;
  305. }
  306. // ---------------------------------------
  307. // Event Input
  308. {
  309. portName.clear();
  310. if (processMode == PROCESS_MODE_SINGLE_CLIENT)
  311. {
  312. portName = fName;
  313. portName += ":";
  314. }
  315. portName += "event-in";
  316. portName.truncate(portNameSize);
  317. pData->event.portIn = (CarlaEngineEventPort*)pData->client->addPort(kEnginePortTypeEvent, portName, true);
  318. }
  319. // ---------------------------------------
  320. // plugin hints
  321. fHints = 0x0;
  322. //fHints |= PLUGIN_IS_SYNTH;
  323. fHints |= PLUGIN_CAN_VOLUME;
  324. fHints |= PLUGIN_CAN_BALANCE;
  325. // extra plugin hints
  326. pData->extraHints = 0x0;
  327. pData->extraHints |= PLUGIN_EXTRA_HINT_HAS_MIDI_IN;
  328. pData->extraHints |= PLUGIN_EXTRA_HINT_CAN_RUN_RACK;
  329. bufferSizeChanged(pData->engine->getBufferSize());
  330. reloadPrograms(true);
  331. if (pData->active)
  332. activate();
  333. carla_debug("LinuxSamplerPlugin::reload() - end");
  334. }
  335. void reloadPrograms(bool init) override
  336. {
  337. carla_debug("LinuxSamplerPlugin::reloadPrograms(%s)", bool2str(init));
  338. // Delete old programs
  339. pData->midiprog.clear();
  340. // Query new programs
  341. uint32_t i, count = fInstrumentIds.size();
  342. // sound kits must always have at least 1 midi-program
  343. CARLA_ASSERT(count > 0);
  344. if (count == 0)
  345. return;
  346. pData->midiprog.createNew(count);
  347. LinuxSampler::InstrumentManager::instrument_info_t info;
  348. for (i=0; i < pData->midiprog.count; ++i)
  349. {
  350. pData->midiprog.data[i].bank = i / 128;
  351. pData->midiprog.data[i].program = i % 128;
  352. try {
  353. info = fInstrument->GetInstrumentInfo(fInstrumentIds[i]);
  354. }
  355. catch (const LinuxSampler::InstrumentManagerException&)
  356. {
  357. continue;
  358. }
  359. pData->midiprog.data[i].name = carla_strdup(info.InstrumentName.c_str());
  360. }
  361. #ifndef BUILD_BRIDGE
  362. // Update OSC Names
  363. if (pData->engine->isOscControlRegistered())
  364. {
  365. pData->engine->oscSend_control_set_midi_program_count(fId, count);
  366. for (i=0; i < count; ++i)
  367. 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);
  368. }
  369. #endif
  370. if (init)
  371. {
  372. setMidiProgram(0, false, false, false);
  373. }
  374. else
  375. {
  376. pData->engine->callback(CALLBACK_RELOAD_PROGRAMS, fId, 0, 0, 0.0f, nullptr);
  377. }
  378. }
  379. // -------------------------------------------------------------------
  380. // Plugin processing
  381. void activate() override
  382. {
  383. CARLA_ASSERT(fAudioOutputDevice != nullptr);
  384. fAudioOutputDevice->Play();
  385. }
  386. void deactivate() override
  387. {
  388. CARLA_ASSERT(fAudioOutputDevice != nullptr);
  389. fAudioOutputDevice->Stop();
  390. }
  391. void process(float** const, float** const outBuffer, const uint32_t frames) override
  392. {
  393. uint32_t i, k;
  394. // --------------------------------------------------------------------------------------------------------
  395. // Check if active
  396. if (! pData->active)
  397. {
  398. // disable any output sound
  399. for (i=0; i < pData->audioOut.count; ++i)
  400. FloatVectorOperations::clear(outBuffer[i], frames);
  401. return;
  402. }
  403. // --------------------------------------------------------------------------------------------------------
  404. // Check if needs reset
  405. if (pData->needsReset)
  406. {
  407. if (fOptions & PLUGIN_OPTION_SEND_ALL_SOUND_OFF)
  408. {
  409. for (k=0, i=MAX_MIDI_CHANNELS; k < MAX_MIDI_CHANNELS; ++k)
  410. {
  411. fMidiInputPort->DispatchControlChange(MIDI_CONTROL_ALL_NOTES_OFF, 0, k);
  412. fMidiInputPort->DispatchControlChange(MIDI_CONTROL_ALL_SOUND_OFF, 0, k);
  413. }
  414. }
  415. else if (pData->ctrlChannel >= 0 && pData->ctrlChannel < MAX_MIDI_CHANNELS)
  416. {
  417. for (k=0; k < MAX_MIDI_NOTE; ++k)
  418. fMidiInputPort->DispatchNoteOff(k, 0, pData->ctrlChannel);
  419. }
  420. pData->needsReset = false;
  421. }
  422. // --------------------------------------------------------------------------------------------------------
  423. // Event Input and Processing
  424. {
  425. // ----------------------------------------------------------------------------------------------------
  426. // MIDI Input (External)
  427. if (pData->extNotes.mutex.tryLock())
  428. {
  429. while (! pData->extNotes.data.isEmpty())
  430. {
  431. const ExternalMidiNote& note(pData->extNotes.data.getFirst(true));
  432. CARLA_ASSERT(note.channel >= 0 && note.channel < MAX_MIDI_CHANNELS);
  433. if (note.velo > 0)
  434. fMidiInputPort->DispatchNoteOn(note.note, note.velo, note.channel, 0);
  435. else
  436. fMidiInputPort->DispatchNoteOff(note.note, note.velo, note.channel, 0);
  437. }
  438. pData->extNotes.mutex.unlock();
  439. } // End of MIDI Input (External)
  440. // ----------------------------------------------------------------------------------------------------
  441. // Event Input (System)
  442. bool allNotesOffSent = false;
  443. bool sampleAccurate = (fOptions & PLUGIN_OPTION_FIXED_BUFFERS) == 0;
  444. uint32_t time, nEvents = pData->event.portIn->getEventCount();
  445. uint32_t startTime = 0;
  446. uint32_t timeOffset = 0;
  447. uint32_t nextBankId = 0;
  448. if (pData->midiprog.current >= 0 && pData->midiprog.count > 0)
  449. nextBankId = pData->midiprog.data[pData->midiprog.current].bank;
  450. for (i=0; i < nEvents; ++i)
  451. {
  452. const EngineEvent& event(pData->event.portIn->getEvent(i));
  453. time = event.time;
  454. if (time >= frames)
  455. continue;
  456. CARLA_ASSERT_INT2(time >= timeOffset, time, timeOffset);
  457. if (time > timeOffset && sampleAccurate)
  458. {
  459. if (processSingle(outBuffer, time - timeOffset, timeOffset))
  460. {
  461. startTime = 0;
  462. timeOffset = time;
  463. if (pData->midiprog.current >= 0 && pData->midiprog.count > 0)
  464. nextBankId = pData->midiprog.data[pData->midiprog.current].bank;
  465. else
  466. nextBankId = 0;
  467. }
  468. else
  469. startTime += timeOffset;
  470. }
  471. // Control change
  472. switch (event.type)
  473. {
  474. case kEngineEventTypeNull:
  475. break;
  476. case kEngineEventTypeControl:
  477. {
  478. const EngineControlEvent& ctrlEvent = event.ctrl;
  479. switch (ctrlEvent.type)
  480. {
  481. case kEngineControlEventTypeNull:
  482. break;
  483. case kEngineControlEventTypeParameter:
  484. {
  485. #ifndef BUILD_BRIDGE
  486. // Control backend stuff
  487. if (event.channel == pData->ctrlChannel)
  488. {
  489. float value;
  490. if (MIDI_IS_CONTROL_BREATH_CONTROLLER(ctrlEvent.param) && (fHints & PLUGIN_CAN_DRYWET) > 0)
  491. {
  492. value = ctrlEvent.value;
  493. setDryWet(value, false, false);
  494. pData->postponeRtEvent(kPluginPostRtEventParameterChange, PARAMETER_DRYWET, 0, value);
  495. }
  496. if (MIDI_IS_CONTROL_CHANNEL_VOLUME(ctrlEvent.param) && (fHints & PLUGIN_CAN_VOLUME) > 0)
  497. {
  498. value = ctrlEvent.value*127.0f/100.0f;
  499. setVolume(value, false, false);
  500. pData->postponeRtEvent(kPluginPostRtEventParameterChange, PARAMETER_VOLUME, 0, value);
  501. }
  502. if (MIDI_IS_CONTROL_BALANCE(ctrlEvent.param) && (fHints & PLUGIN_CAN_BALANCE) > 0)
  503. {
  504. float left, right;
  505. value = ctrlEvent.value/0.5f - 1.0f;
  506. if (value < 0.0f)
  507. {
  508. left = -1.0f;
  509. right = (value*2.0f)+1.0f;
  510. }
  511. else if (value > 0.0f)
  512. {
  513. left = (value*2.0f)-1.0f;
  514. right = 1.0f;
  515. }
  516. else
  517. {
  518. left = -1.0f;
  519. right = 1.0f;
  520. }
  521. setBalanceLeft(left, false, false);
  522. setBalanceRight(right, false, false);
  523. pData->postponeRtEvent(kPluginPostRtEventParameterChange, PARAMETER_BALANCE_LEFT, 0, left);
  524. pData->postponeRtEvent(kPluginPostRtEventParameterChange, PARAMETER_BALANCE_RIGHT, 0, right);
  525. }
  526. }
  527. #endif
  528. // Control plugin parameters
  529. for (k=0; k < pData->param.count; ++k)
  530. {
  531. if (pData->param.data[k].midiChannel != event.channel)
  532. continue;
  533. if (pData->param.data[k].midiCC != ctrlEvent.param)
  534. continue;
  535. if (pData->param.data[k].type != PARAMETER_INPUT)
  536. continue;
  537. if ((pData->param.data[k].hints & PARAMETER_IS_AUTOMABLE) == 0)
  538. continue;
  539. double value;
  540. if (pData->param.data[k].hints & PARAMETER_IS_BOOLEAN)
  541. {
  542. value = (ctrlEvent.value < 0.5f) ? pData->param.ranges[k].min : pData->param.ranges[k].max;
  543. }
  544. else
  545. {
  546. value = pData->param.ranges[k].getUnnormalizedValue(ctrlEvent.value);
  547. if (pData->param.data[k].hints & PARAMETER_IS_INTEGER)
  548. value = std::rint(value);
  549. }
  550. setParameterValue(k, value, false, false, false);
  551. pData->postponeRtEvent(kPluginPostRtEventParameterChange, static_cast<int32_t>(k), 0, value);
  552. }
  553. if ((fOptions & PLUGIN_OPTION_SEND_CONTROL_CHANGES) != 0 && ctrlEvent.param <= 0x5F)
  554. {
  555. fMidiInputPort->DispatchControlChange(ctrlEvent.param, ctrlEvent.value*127.0f, event.channel, sampleAccurate ? startTime : time);
  556. }
  557. break;
  558. }
  559. case kEngineControlEventTypeMidiBank:
  560. if (event.channel == pData->ctrlChannel && (fOptions & PLUGIN_OPTION_MAP_PROGRAM_CHANGES) != 0)
  561. nextBankId = ctrlEvent.param;
  562. break;
  563. case kEngineControlEventTypeMidiProgram:
  564. if (event.channel == pData->ctrlChannel && (fOptions & PLUGIN_OPTION_MAP_PROGRAM_CHANGES) != 0)
  565. {
  566. const uint32_t nextProgramId = ctrlEvent.param;
  567. for (k=0; k < pData->midiprog.count; ++k)
  568. {
  569. if (pData->midiprog.data[k].bank == nextBankId && pData->midiprog.data[k].program == nextProgramId)
  570. {
  571. setMidiProgram(k, false, false, false);
  572. pData->postponeRtEvent(kPluginPostRtEventMidiProgramChange, k, 0, 0.0f);
  573. break;
  574. }
  575. }
  576. }
  577. break;
  578. case kEngineControlEventTypeAllSoundOff:
  579. if (fOptions & PLUGIN_OPTION_SEND_ALL_SOUND_OFF)
  580. {
  581. fMidiInputPort->DispatchControlChange(MIDI_CONTROL_ALL_SOUND_OFF, 0, event.channel, sampleAccurate ? startTime : time);
  582. }
  583. break;
  584. case kEngineControlEventTypeAllNotesOff:
  585. if (fOptions & PLUGIN_OPTION_SEND_ALL_SOUND_OFF)
  586. {
  587. if (event.channel == pData->ctrlChannel && ! allNotesOffSent)
  588. {
  589. allNotesOffSent = true;
  590. sendMidiAllNotesOffToCallback();
  591. }
  592. fMidiInputPort->DispatchControlChange(MIDI_CONTROL_ALL_NOTES_OFF, 0, event.channel, sampleAccurate ? startTime : time);
  593. }
  594. break;
  595. }
  596. break;
  597. }
  598. case kEngineEventTypeMidi:
  599. {
  600. const EngineMidiEvent& midiEvent(event.midi);
  601. uint8_t status = MIDI_GET_STATUS_FROM_DATA(midiEvent.data);
  602. uint8_t channel = event.channel;
  603. // Fix bad note-off (per DSSI spec)
  604. if (MIDI_IS_STATUS_NOTE_ON(status) && midiEvent.data[2] == 0)
  605. status -= 0x10;
  606. int32_t fragmentPos = sampleAccurate ? startTime : time;
  607. if (MIDI_IS_STATUS_NOTE_OFF(status))
  608. {
  609. const uint8_t note = midiEvent.data[1];
  610. fMidiInputPort->DispatchNoteOff(note, 0, channel, fragmentPos);
  611. pData->postponeRtEvent(kPluginPostRtEventNoteOff, channel, note, 0.0f);
  612. }
  613. else if (MIDI_IS_STATUS_NOTE_ON(status))
  614. {
  615. const uint8_t note = midiEvent.data[1];
  616. const uint8_t velo = midiEvent.data[2];
  617. fMidiInputPort->DispatchNoteOn(note, velo, channel, fragmentPos);
  618. pData->postponeRtEvent(kPluginPostRtEventNoteOn, channel, note, velo);
  619. }
  620. else if (MIDI_IS_STATUS_POLYPHONIC_AFTERTOUCH(status) && (fOptions & PLUGIN_OPTION_SEND_NOTE_AFTERTOUCH) != 0)
  621. {
  622. //const uint8_t note = midiEvent.data[1];
  623. //const uint8_t pressure = midiEvent.data[2];
  624. // unsupported
  625. }
  626. else if (MIDI_IS_STATUS_CONTROL_CHANGE(status) && (fOptions & PLUGIN_OPTION_SEND_CONTROL_CHANGES) != 0)
  627. {
  628. const uint8_t control = midiEvent.data[1];
  629. const uint8_t value = midiEvent.data[2];
  630. fMidiInputPort->DispatchControlChange(control, value, channel, fragmentPos);
  631. }
  632. else if (MIDI_IS_STATUS_CHANNEL_PRESSURE(status) && (fOptions & PLUGIN_OPTION_SEND_CHANNEL_PRESSURE) != 0)
  633. {
  634. //const uint8_t pressure = midiEvent.data[1];
  635. // unsupported
  636. }
  637. else if (MIDI_IS_STATUS_PITCH_WHEEL_CONTROL(status) && (fOptions & PLUGIN_OPTION_SEND_PITCHBEND) != 0)
  638. {
  639. const uint8_t lsb = midiEvent.data[1];
  640. const uint8_t msb = midiEvent.data[2];
  641. fMidiInputPort->DispatchPitchbend(((msb << 7) | lsb) - 8192, channel, fragmentPos);
  642. }
  643. break;
  644. }
  645. }
  646. }
  647. pData->postRtEvents.trySplice();
  648. if (frames > timeOffset)
  649. processSingle(outBuffer, frames - timeOffset, timeOffset);
  650. } // End of Event Input and Processing
  651. }
  652. bool processSingle(float** const outBuffer, const uint32_t frames, const uint32_t timeOffset)
  653. {
  654. CARLA_ASSERT(outBuffer != nullptr);
  655. CARLA_ASSERT(frames > 0);
  656. if (outBuffer == nullptr)
  657. return false;
  658. if (frames == 0)
  659. return false;
  660. uint32_t i, k;
  661. // --------------------------------------------------------------------------------------------------------
  662. // Try lock, silence otherwise
  663. if (pData->engine->isOffline())
  664. {
  665. pData->singleMutex.lock();
  666. }
  667. else if (! pData->singleMutex.tryLock())
  668. {
  669. for (i=0; i < pData->audioOut.count; ++i)
  670. {
  671. for (k=0; k < frames; ++k)
  672. outBuffer[i][k+timeOffset] = 0.0f;
  673. }
  674. return false;
  675. }
  676. // --------------------------------------------------------------------------------------------------------
  677. // Run plugin
  678. fAudioOutputDevice->Channel(0)->SetBuffer(outBuffer[0] + timeOffset);
  679. fAudioOutputDevice->Channel(1)->SetBuffer(outBuffer[1] + timeOffset);
  680. // QUESTION: Need to clear it before?
  681. fAudioOutputDevice->Render(frames);
  682. #ifndef BUILD_BRIDGE
  683. // --------------------------------------------------------------------------------------------------------
  684. // Post-processing (dry/wet, volume and balance)
  685. {
  686. const bool doVolume = (fHints & PLUGIN_CAN_VOLUME) > 0 && pData->postProc.volume != 1.0f;
  687. const bool doBalance = (fHints & PLUGIN_CAN_BALANCE) > 0 && (pData->postProc.balanceLeft != -1.0f || pData->postProc.balanceRight != 1.0f);
  688. float oldBufLeft[doBalance ? frames : 1];
  689. for (i=0; i < pData->audioOut.count; ++i)
  690. {
  691. // Balance
  692. if (doBalance)
  693. {
  694. if (i % 2 == 0)
  695. FloatVectorOperations::copy(oldBufLeft, outBuffer[i], frames);
  696. float balRangeL = (pData->postProc.balanceLeft + 1.0f)/2.0f;
  697. float balRangeR = (pData->postProc.balanceRight + 1.0f)/2.0f;
  698. for (k=0; k < frames; ++k)
  699. {
  700. if (i % 2 == 0)
  701. {
  702. // left
  703. outBuffer[i][k] = oldBufLeft[k] * (1.0f - balRangeL);
  704. outBuffer[i][k] += outBuffer[i+1][k] * (1.0f - balRangeR);
  705. }
  706. else
  707. {
  708. // right
  709. outBuffer[i][k] = outBuffer[i][k] * balRangeR;
  710. outBuffer[i][k] += oldBufLeft[k] * balRangeL;
  711. }
  712. }
  713. }
  714. // Volume
  715. if (doVolume)
  716. {
  717. for (k=0; k < frames; ++k)
  718. outBuffer[i][k+timeOffset] *= pData->postProc.volume;
  719. }
  720. }
  721. } // End of Post-processing
  722. #endif
  723. // --------------------------------------------------------------------------------------------------------
  724. pData->singleMutex.unlock();
  725. return true;
  726. }
  727. // -------------------------------------------------------------------
  728. // Plugin buffers
  729. // nothing
  730. // -------------------------------------------------------------------
  731. const void* getExtraStuff() const noexcept override
  732. {
  733. return kUses16Outs ? (const void*)0x1 : nullptr;
  734. }
  735. bool init(const char* filename, const char* const name, const char* label)
  736. {
  737. CARLA_ASSERT(pData->engine != nullptr);
  738. CARLA_ASSERT(pData->client == nullptr);
  739. CARLA_ASSERT(filename != nullptr);
  740. CARLA_ASSERT(label != nullptr);
  741. // ---------------------------------------------------------------
  742. // first checks
  743. if (pData->engine == nullptr)
  744. {
  745. return false;
  746. }
  747. if (pData->client != nullptr)
  748. {
  749. pData->engine->setLastError("Plugin client is already registered");
  750. return false;
  751. }
  752. if (filename == nullptr)
  753. {
  754. pData->engine->setLastError("null filename");
  755. return false;
  756. }
  757. if (label == nullptr)
  758. {
  759. pData->engine->setLastError("null label");
  760. return false;
  761. }
  762. // ---------------------------------------------------------------
  763. // Check if file exists
  764. {
  765. // QFileInfo file(filename);
  766. //
  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