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.

1185 lines
39KB

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