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.

1190 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 (uint)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, (int)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 int id, const char* const format, const bool use16Outs)
  131. : CarlaPlugin(engine, id),
  132. fFormat(carla_strdup(format)),
  133. fUses16Outs(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. if (fFormat != nullptr)
  174. {
  175. delete[] fFormat;
  176. fFormat = nullptr;
  177. }
  178. clearBuffers();
  179. }
  180. // -------------------------------------------------------------------
  181. // Information (base)
  182. PluginType getType() const noexcept override
  183. {
  184. return getPluginTypeFromString(fFormat);
  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 getOptionsAvailable() 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(pData->filename, 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 EngineProcessMode 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 == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  282. {
  283. portName = pData->name;
  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 == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  293. {
  294. portName = pData->name;
  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 == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  307. {
  308. portName = pData->name;
  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. pData->hints = 0x0;
  318. //pData->hints |= PLUGIN_IS_SYNTH;
  319. pData->hints |= PLUGIN_CAN_VOLUME;
  320. pData->hints |= 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 = (uint32_t)fInstrumentIds.size();
  338. // sound kits must always have at least 1 midi-program
  339. CARLA_SAFE_ASSERT_RETURN(count > 0,);
  340. pData->midiprog.createNew(count);
  341. LinuxSampler::InstrumentManager::instrument_info_t info;
  342. for (i=0; i < pData->midiprog.count; ++i)
  343. {
  344. pData->midiprog.data[i].bank = i / 128;
  345. pData->midiprog.data[i].program = i % 128;
  346. try {
  347. info = fInstrument->GetInstrumentInfo(fInstrumentIds[i]);
  348. }
  349. catch (const LinuxSampler::InstrumentManagerException&)
  350. {
  351. continue;
  352. }
  353. pData->midiprog.data[i].name = carla_strdup(info.InstrumentName.c_str());
  354. }
  355. #ifndef BUILD_BRIDGE
  356. // Update OSC Names
  357. if (pData->engine->isOscControlRegistered())
  358. {
  359. pData->engine->oscSend_control_set_midi_program_count(pData->id, count);
  360. for (i=0; i < count; ++i)
  361. pData->engine->oscSend_control_set_midi_program_data(pData->id, i, pData->midiprog.data[i].bank, pData->midiprog.data[i].program, pData->midiprog.data[i].name);
  362. }
  363. #endif
  364. if (init)
  365. {
  366. setMidiProgram(0, false, false, false);
  367. }
  368. else
  369. {
  370. pData->engine->callback(ENGINE_CALLBACK_RELOAD_PROGRAMS, pData->id, 0, 0, 0.0f, nullptr);
  371. }
  372. }
  373. // -------------------------------------------------------------------
  374. // Plugin processing
  375. void activate() override
  376. {
  377. CARLA_ASSERT(fAudioOutputDevice != nullptr);
  378. fAudioOutputDevice->Play();
  379. }
  380. void deactivate() override
  381. {
  382. CARLA_ASSERT(fAudioOutputDevice != nullptr);
  383. fAudioOutputDevice->Stop();
  384. }
  385. void process(float** const, float** const outBuffer, const uint32_t frames) override
  386. {
  387. uint32_t i, k;
  388. // --------------------------------------------------------------------------------------------------------
  389. // Check if active
  390. if (! pData->active)
  391. {
  392. // disable any output sound
  393. for (i=0; i < pData->audioOut.count; ++i)
  394. {
  395. #ifdef HAVE_JUCE
  396. FloatVectorOperations::clear(outBuffer[i], frames);
  397. #else
  398. #endif
  399. }
  400. return;
  401. }
  402. // --------------------------------------------------------------------------------------------------------
  403. // Check if needs reset
  404. if (pData->needsReset)
  405. {
  406. if (pData->options & PLUGIN_OPTION_SEND_ALL_SOUND_OFF)
  407. {
  408. for (k=0, i=MAX_MIDI_CHANNELS; k < MAX_MIDI_CHANNELS; ++k)
  409. {
  410. fMidiInputPort->DispatchControlChange(MIDI_CONTROL_ALL_NOTES_OFF, 0, k);
  411. fMidiInputPort->DispatchControlChange(MIDI_CONTROL_ALL_SOUND_OFF, 0, k);
  412. }
  413. }
  414. else if (pData->ctrlChannel >= 0 && pData->ctrlChannel < MAX_MIDI_CHANNELS)
  415. {
  416. for (uint8_t i=0; i < MAX_MIDI_NOTE; ++i)
  417. fMidiInputPort->DispatchNoteOff(i, 0, (uint)pData->ctrlChannel);
  418. }
  419. pData->needsReset = false;
  420. }
  421. // --------------------------------------------------------------------------------------------------------
  422. // Event Input and Processing
  423. {
  424. // ----------------------------------------------------------------------------------------------------
  425. // MIDI Input (External)
  426. if (pData->extNotes.mutex.tryLock())
  427. {
  428. while (! pData->extNotes.data.isEmpty())
  429. {
  430. const ExternalMidiNote& note(pData->extNotes.data.getFirst(true));
  431. CARLA_ASSERT(note.channel >= 0 && note.channel < MAX_MIDI_CHANNELS);
  432. if (note.velo > 0)
  433. fMidiInputPort->DispatchNoteOn(note.note, note.velo, note.channel, 0);
  434. else
  435. fMidiInputPort->DispatchNoteOff(note.note, note.velo, note.channel, 0);
  436. }
  437. pData->extNotes.mutex.unlock();
  438. } // End of MIDI Input (External)
  439. // ----------------------------------------------------------------------------------------------------
  440. // Event Input (System)
  441. bool allNotesOffSent = false;
  442. bool sampleAccurate = (pData->options & PLUGIN_OPTION_FIXED_BUFFERS) == 0;
  443. uint32_t time, nEvents = pData->event.portIn->getEventCount();
  444. uint32_t startTime = 0;
  445. uint32_t timeOffset = 0;
  446. uint32_t nextBankId = 0;
  447. if (pData->midiprog.current >= 0 && pData->midiprog.count > 0)
  448. nextBankId = pData->midiprog.data[pData->midiprog.current].bank;
  449. for (i=0; i < nEvents; ++i)
  450. {
  451. const EngineEvent& event(pData->event.portIn->getEvent(i));
  452. time = event.time;
  453. if (time >= frames)
  454. continue;
  455. CARLA_ASSERT_INT2(time >= timeOffset, time, timeOffset);
  456. if (time > timeOffset && sampleAccurate)
  457. {
  458. if (processSingle(outBuffer, time - timeOffset, timeOffset))
  459. {
  460. startTime = 0;
  461. timeOffset = time;
  462. if (pData->midiprog.current >= 0 && pData->midiprog.count > 0)
  463. nextBankId = pData->midiprog.data[pData->midiprog.current].bank;
  464. else
  465. nextBankId = 0;
  466. }
  467. else
  468. startTime += timeOffset;
  469. }
  470. // Control change
  471. switch (event.type)
  472. {
  473. case kEngineEventTypeNull:
  474. break;
  475. case kEngineEventTypeControl:
  476. {
  477. const EngineControlEvent& ctrlEvent = event.ctrl;
  478. switch (ctrlEvent.type)
  479. {
  480. case kEngineControlEventTypeNull:
  481. break;
  482. case kEngineControlEventTypeParameter:
  483. {
  484. #ifndef BUILD_BRIDGE
  485. // Control backend stuff
  486. if (event.channel == pData->ctrlChannel)
  487. {
  488. float value;
  489. if (MIDI_IS_CONTROL_BREATH_CONTROLLER(ctrlEvent.param) && (pData->hints & PLUGIN_CAN_DRYWET) != 0)
  490. {
  491. value = ctrlEvent.value;
  492. setDryWet(value, false, false);
  493. pData->postponeRtEvent(kPluginPostRtEventParameterChange, PARAMETER_DRYWET, 0, value);
  494. }
  495. if (MIDI_IS_CONTROL_CHANNEL_VOLUME(ctrlEvent.param) && (pData->hints & PLUGIN_CAN_VOLUME) != 0)
  496. {
  497. value = ctrlEvent.value*127.0f/100.0f;
  498. setVolume(value, false, false);
  499. pData->postponeRtEvent(kPluginPostRtEventParameterChange, PARAMETER_VOLUME, 0, value);
  500. }
  501. if (MIDI_IS_CONTROL_BALANCE(ctrlEvent.param) && (pData->hints & PLUGIN_CAN_BALANCE) != 0)
  502. {
  503. float left, right;
  504. value = ctrlEvent.value/0.5f - 1.0f;
  505. if (value < 0.0f)
  506. {
  507. left = -1.0f;
  508. right = (value*2.0f)+1.0f;
  509. }
  510. else if (value > 0.0f)
  511. {
  512. left = (value*2.0f)-1.0f;
  513. right = 1.0f;
  514. }
  515. else
  516. {
  517. left = -1.0f;
  518. right = 1.0f;
  519. }
  520. setBalanceLeft(left, false, false);
  521. setBalanceRight(right, false, false);
  522. pData->postponeRtEvent(kPluginPostRtEventParameterChange, PARAMETER_BALANCE_LEFT, 0, left);
  523. pData->postponeRtEvent(kPluginPostRtEventParameterChange, PARAMETER_BALANCE_RIGHT, 0, right);
  524. }
  525. }
  526. #endif
  527. // Control plugin parameters
  528. for (k=0; k < pData->param.count; ++k)
  529. {
  530. if (pData->param.data[k].midiChannel != event.channel)
  531. continue;
  532. if (pData->param.data[k].midiCC != ctrlEvent.param)
  533. continue;
  534. if (pData->param.data[k].hints != PARAMETER_INPUT)
  535. continue;
  536. if ((pData->param.data[k].hints & PARAMETER_IS_AUTOMABLE) == 0)
  537. continue;
  538. float value;
  539. if (pData->param.data[k].hints & PARAMETER_IS_BOOLEAN)
  540. {
  541. value = (ctrlEvent.value < 0.5f) ? pData->param.ranges[k].min : pData->param.ranges[k].max;
  542. }
  543. else
  544. {
  545. value = pData->param.ranges[k].getUnnormalizedValue(ctrlEvent.value);
  546. if (pData->param.data[k].hints & PARAMETER_IS_INTEGER)
  547. value = std::rint(value);
  548. }
  549. setParameterValue(k, value, false, false, false);
  550. pData->postponeRtEvent(kPluginPostRtEventParameterChange, static_cast<int32_t>(k), 0, value);
  551. }
  552. if ((pData->options & PLUGIN_OPTION_SEND_CONTROL_CHANGES) != 0 && ctrlEvent.param <= 0x5F)
  553. {
  554. fMidiInputPort->DispatchControlChange(uint8_t(ctrlEvent.param), uint8_t(ctrlEvent.value*127.0f), event.channel, int32_t(sampleAccurate ? startTime : time));
  555. }
  556. break;
  557. }
  558. case kEngineControlEventTypeMidiBank:
  559. if (event.channel == pData->ctrlChannel && (pData->options & PLUGIN_OPTION_MAP_PROGRAM_CHANGES) != 0)
  560. nextBankId = ctrlEvent.param;
  561. break;
  562. case kEngineControlEventTypeMidiProgram:
  563. if (event.channel == pData->ctrlChannel && (pData->options & PLUGIN_OPTION_MAP_PROGRAM_CHANGES) != 0)
  564. {
  565. const uint32_t nextProgramId = ctrlEvent.param;
  566. for (k=0; k < pData->midiprog.count; ++k)
  567. {
  568. if (pData->midiprog.data[k].bank == nextBankId && pData->midiprog.data[k].program == nextProgramId)
  569. {
  570. setMidiProgram(k, false, false, false);
  571. pData->postponeRtEvent(kPluginPostRtEventMidiProgramChange, k, 0, 0.0f);
  572. break;
  573. }
  574. }
  575. }
  576. break;
  577. case kEngineControlEventTypeAllSoundOff:
  578. if (pData->options & PLUGIN_OPTION_SEND_ALL_SOUND_OFF)
  579. {
  580. fMidiInputPort->DispatchControlChange(MIDI_CONTROL_ALL_SOUND_OFF, 0, event.channel, sampleAccurate ? startTime : time);
  581. }
  582. break;
  583. case kEngineControlEventTypeAllNotesOff:
  584. if (pData->options & PLUGIN_OPTION_SEND_ALL_SOUND_OFF)
  585. {
  586. if (event.channel == pData->ctrlChannel && ! allNotesOffSent)
  587. {
  588. allNotesOffSent = true;
  589. sendMidiAllNotesOffToCallback();
  590. }
  591. fMidiInputPort->DispatchControlChange(MIDI_CONTROL_ALL_NOTES_OFF, 0, event.channel, sampleAccurate ? startTime : time);
  592. }
  593. break;
  594. }
  595. break;
  596. }
  597. case kEngineEventTypeMidi:
  598. {
  599. const EngineMidiEvent& midiEvent(event.midi);
  600. uint8_t status = MIDI_GET_STATUS_FROM_DATA(midiEvent.data);
  601. uint8_t channel = event.channel;
  602. // Fix bad note-off (per DSSI spec)
  603. if (MIDI_IS_STATUS_NOTE_ON(status) && midiEvent.data[2] == 0)
  604. status = MIDI_STATUS_NOTE_OFF;
  605. int32_t fragmentPos = sampleAccurate ? startTime : time;
  606. if (MIDI_IS_STATUS_NOTE_OFF(status))
  607. {
  608. const uint8_t note = midiEvent.data[1];
  609. fMidiInputPort->DispatchNoteOff(note, 0, channel, fragmentPos);
  610. pData->postponeRtEvent(kPluginPostRtEventNoteOff, channel, note, 0.0f);
  611. }
  612. else if (MIDI_IS_STATUS_NOTE_ON(status))
  613. {
  614. const uint8_t note = midiEvent.data[1];
  615. const uint8_t velo = midiEvent.data[2];
  616. fMidiInputPort->DispatchNoteOn(note, velo, channel, fragmentPos);
  617. pData->postponeRtEvent(kPluginPostRtEventNoteOn, channel, note, velo);
  618. }
  619. else if (MIDI_IS_STATUS_POLYPHONIC_AFTERTOUCH(status) && (pData->options & PLUGIN_OPTION_SEND_NOTE_AFTERTOUCH) != 0)
  620. {
  621. //const uint8_t note = midiEvent.data[1];
  622. //const uint8_t pressure = midiEvent.data[2];
  623. // unsupported
  624. }
  625. else if (MIDI_IS_STATUS_CONTROL_CHANGE(status) && (pData->options & PLUGIN_OPTION_SEND_CONTROL_CHANGES) != 0)
  626. {
  627. const uint8_t control = midiEvent.data[1];
  628. const uint8_t value = midiEvent.data[2];
  629. fMidiInputPort->DispatchControlChange(control, value, channel, fragmentPos);
  630. }
  631. else if (MIDI_IS_STATUS_CHANNEL_PRESSURE(status) && (pData->options & PLUGIN_OPTION_SEND_CHANNEL_PRESSURE) != 0)
  632. {
  633. //const uint8_t pressure = midiEvent.data[1];
  634. // unsupported
  635. }
  636. else if (MIDI_IS_STATUS_PITCH_WHEEL_CONTROL(status) && (pData->options & PLUGIN_OPTION_SEND_PITCHBEND) != 0)
  637. {
  638. const uint8_t lsb = midiEvent.data[1];
  639. const uint8_t msb = midiEvent.data[2];
  640. fMidiInputPort->DispatchPitchbend(((msb << 7) | lsb) - 8192, channel, fragmentPos);
  641. }
  642. break;
  643. }
  644. }
  645. }
  646. pData->postRtEvents.trySplice();
  647. if (frames > timeOffset)
  648. processSingle(outBuffer, frames - timeOffset, timeOffset);
  649. } // End of Event Input and Processing
  650. }
  651. bool processSingle(float** const outBuffer, const uint32_t frames, const uint32_t timeOffset)
  652. {
  653. CARLA_ASSERT(outBuffer != nullptr);
  654. CARLA_ASSERT(frames > 0);
  655. if (outBuffer == nullptr)
  656. return false;
  657. if (frames == 0)
  658. return false;
  659. uint32_t i, k;
  660. // --------------------------------------------------------------------------------------------------------
  661. // Try lock, silence otherwise
  662. if (pData->engine->isOffline())
  663. {
  664. pData->singleMutex.lock();
  665. }
  666. else if (! pData->singleMutex.tryLock())
  667. {
  668. for (i=0; i < pData->audioOut.count; ++i)
  669. {
  670. for (k=0; k < frames; ++k)
  671. outBuffer[i][k+timeOffset] = 0.0f;
  672. }
  673. return false;
  674. }
  675. // --------------------------------------------------------------------------------------------------------
  676. // Run plugin
  677. fAudioOutputDevice->Channel(0)->SetBuffer(outBuffer[0] + timeOffset);
  678. fAudioOutputDevice->Channel(1)->SetBuffer(outBuffer[1] + timeOffset);
  679. // QUESTION: Need to clear it before?
  680. fAudioOutputDevice->Render(frames);
  681. #ifndef BUILD_BRIDGE
  682. // --------------------------------------------------------------------------------------------------------
  683. // Post-processing (dry/wet, volume and balance)
  684. {
  685. const bool doVolume = (pData->hints & PLUGIN_CAN_VOLUME) > 0 && pData->postProc.volume != 1.0f;
  686. const bool doBalance = (pData->hints & PLUGIN_CAN_BALANCE) > 0 && (pData->postProc.balanceLeft != -1.0f || pData->postProc.balanceRight != 1.0f);
  687. float oldBufLeft[doBalance ? frames : 1];
  688. for (i=0; i < pData->audioOut.count; ++i)
  689. {
  690. // Balance
  691. if (doBalance)
  692. {
  693. if (i % 2 == 0)
  694. {
  695. #ifdef HAVE_JUCE
  696. FloatVectorOperations::copy(oldBufLeft, outBuffer[i], frames);
  697. #else
  698. #endif
  699. }
  700. float balRangeL = (pData->postProc.balanceLeft + 1.0f)/2.0f;
  701. float balRangeR = (pData->postProc.balanceRight + 1.0f)/2.0f;
  702. for (k=0; k < frames; ++k)
  703. {
  704. if (i % 2 == 0)
  705. {
  706. // left
  707. outBuffer[i][k] = oldBufLeft[k] * (1.0f - balRangeL);
  708. outBuffer[i][k] += outBuffer[i+1][k] * (1.0f - balRangeR);
  709. }
  710. else
  711. {
  712. // right
  713. outBuffer[i][k] = outBuffer[i][k] * balRangeR;
  714. outBuffer[i][k] += oldBufLeft[k] * balRangeL;
  715. }
  716. }
  717. }
  718. // Volume
  719. if (doVolume)
  720. {
  721. for (k=0; k < frames; ++k)
  722. outBuffer[i][k+timeOffset] *= pData->postProc.volume;
  723. }
  724. }
  725. } // End of Post-processing
  726. #endif
  727. // --------------------------------------------------------------------------------------------------------
  728. pData->singleMutex.unlock();
  729. return true;
  730. }
  731. // -------------------------------------------------------------------
  732. // Plugin buffers
  733. // nothing
  734. // -------------------------------------------------------------------
  735. const void* getExtraStuff() const noexcept override
  736. {
  737. return fUses16Outs ? (const void*)0x1 : nullptr;
  738. }
  739. bool init(const char* filename, const char* const name, const char* label)
  740. {
  741. CARLA_ASSERT(pData->engine != nullptr);
  742. CARLA_ASSERT(pData->client == nullptr);
  743. CARLA_ASSERT(filename != nullptr);
  744. CARLA_ASSERT(label != nullptr);
  745. // ---------------------------------------------------------------
  746. // first checks
  747. if (pData->engine == nullptr)
  748. {
  749. return false;
  750. }
  751. if (pData->client != nullptr)
  752. {
  753. pData->engine->setLastError("Plugin client is already registered");
  754. return false;
  755. }
  756. if (filename == nullptr)
  757. {
  758. pData->engine->setLastError("null filename");
  759. return false;
  760. }
  761. if (label == nullptr)
  762. {
  763. pData->engine->setLastError("null label");
  764. return false;
  765. }
  766. // ---------------------------------------------------------------
  767. // Check if file exists
  768. {
  769. // QFileInfo file(filename);
  770. //
  771. // if (! (file.exists() && file.isFile() && file.isReadable()))
  772. // {
  773. // pData->engine->setLastError("Requested file is not valid or does not exist");
  774. // return false;
  775. // }
  776. }
  777. // ---------------------------------------------------------------
  778. // Create the LinuxSampler Engine
  779. CarlaString stype(fFormat);
  780. stype.toLower();
  781. try {
  782. fEngine = LinuxSampler::EngineFactory::Create((const char*)stype);
  783. }
  784. catch (LinuxSampler::Exception& e)
  785. {
  786. pData->engine->setLastError(e.what());
  787. return false;
  788. }
  789. // ---------------------------------------------------------------
  790. // Get the Engine's Instrument Manager
  791. fInstrument = fEngine->GetInstrumentManager();
  792. if (fInstrument == nullptr)
  793. {
  794. pData->engine->setLastError("Failed to get LinuxSampler instrument manager");
  795. LinuxSampler::EngineFactory::Destroy(fEngine);
  796. fEngine = nullptr;
  797. return false;
  798. }
  799. // ---------------------------------------------------------------
  800. // Load the Instrument via filename
  801. try {
  802. fInstrumentIds = fInstrument->GetInstrumentFileContent(filename);
  803. }
  804. catch (const LinuxSampler::InstrumentManagerException& e)
  805. {
  806. pData->engine->setLastError(e.what());
  807. LinuxSampler::EngineFactory::Destroy(fEngine);
  808. fEngine = nullptr;
  809. return false;
  810. }
  811. // ---------------------------------------------------------------
  812. // Get info
  813. if (fInstrumentIds.size() == 0)
  814. {
  815. pData->engine->setLastError("Failed to find any instruments");
  816. LinuxSampler::EngineFactory::Destroy(fEngine);
  817. fEngine = nullptr;
  818. return false;
  819. }
  820. LinuxSampler::InstrumentManager::instrument_info_t info;
  821. try {
  822. info = fInstrument->GetInstrumentInfo(fInstrumentIds[0]);
  823. }
  824. catch (const LinuxSampler::InstrumentManagerException& e)
  825. {
  826. pData->engine->setLastError(e.what());
  827. LinuxSampler::EngineFactory::Destroy(fEngine);
  828. fEngine = nullptr;
  829. return false;
  830. }
  831. fRealName = info.InstrumentName.c_str();
  832. fLabel = info.Product.c_str();
  833. fMaker = info.Artists.c_str();
  834. pData->filename = carla_strdup(filename);
  835. if (fUses16Outs && ! fLabel.endsWith(" (16 outs)"))
  836. fLabel += " (16 outs)";
  837. if (name != nullptr)
  838. pData->name = pData->engine->getUniquePluginName(name);
  839. else
  840. pData->name = pData->engine->getUniquePluginName((const char*)fRealName);
  841. // ---------------------------------------------------------------
  842. // Register client
  843. pData->client = pData->engine->addClient(this);
  844. if (pData->client == nullptr || ! pData->client->isOk())
  845. {
  846. pData->engine->setLastError("Failed to register plugin client");
  847. LinuxSampler::EngineFactory::Destroy(fEngine);
  848. fEngine = nullptr;
  849. return false;
  850. }
  851. // ---------------------------------------------------------------
  852. // Init LinuxSampler stuff
  853. fSamplerChannel = fSampler->AddSamplerChannel();
  854. fSamplerChannel->SetEngineType((const char*)stype);
  855. fSamplerChannel->SetAudioOutputDevice(fAudioOutputDevice);
  856. fEngineChannel = fSamplerChannel->GetEngineChannel();
  857. fEngineChannel->Connect(fAudioOutputDevice);
  858. fEngineChannel->Volume(LinuxSampler::VOLUME_MAX);
  859. fMidiInputPort->Connect(fSamplerChannel->GetEngineChannel(), LinuxSampler::midi_chan_all);
  860. // ---------------------------------------------------------------
  861. // load plugin settings
  862. {
  863. // set default options
  864. pData->options = 0x0;
  865. pData->options |= PLUGIN_OPTION_MAP_PROGRAM_CHANGES;
  866. pData->options |= PLUGIN_OPTION_SEND_PITCHBEND;
  867. pData->options |= PLUGIN_OPTION_SEND_ALL_SOUND_OFF;
  868. // set identifier string
  869. CarlaString identifier(fFormat);
  870. identifier += "/";
  871. if (const char* const shortname = std::strrchr(filename, OS_SEP))
  872. identifier += shortname+1;
  873. else
  874. identifier += label;
  875. pData->identifier = identifier.dup();
  876. // load settings
  877. pData->options = pData->loadSettings(pData->options, getOptionsAvailable());
  878. }
  879. return true;
  880. }
  881. // -------------------------------------------------------------------
  882. private:
  883. const char* fFormat;
  884. const bool fUses16Outs;
  885. CarlaString fRealName;
  886. CarlaString fLabel;
  887. CarlaString fMaker;
  888. LinuxSampler::Sampler* fSampler;
  889. LinuxSampler::SamplerChannel* fSamplerChannel;
  890. LinuxSampler::Engine* fEngine;
  891. LinuxSampler::EngineChannel* fEngineChannel;
  892. LinuxSampler::AudioOutputDevicePlugin* fAudioOutputDevice;
  893. LinuxSampler::MidiInputDevicePlugin* fMidiInputDevice;
  894. LinuxSampler::MidiInputPort* fMidiInputPort;
  895. LinuxSampler::InstrumentManager* fInstrument;
  896. std::vector<LinuxSampler::InstrumentManager::instrument_id_t> fInstrumentIds;
  897. CARLA_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(LinuxSamplerPlugin)
  898. };
  899. CARLA_BACKEND_END_NAMESPACE
  900. #endif // WANT_LINUXSAMPLER
  901. CARLA_BACKEND_START_NAMESPACE
  902. CarlaPlugin* CarlaPlugin::newLinuxSampler(const Initializer& init, const char* const format, const bool use16Outs)
  903. {
  904. carla_debug("LinuxSamplerPlugin::newLinuxSampler({%p, \"%s\", \"%s\", \"%s\"}, %s, %s)", init.engine, init.filename, init.name, init.label, format, bool2str(use16Outs));
  905. #ifdef WANT_FLUIDSYNTH
  906. if (init.engine->getProccessMode() == ENGINE_PROCESS_MODE_CONTINUOUS_RACK && use16Outs)
  907. {
  908. init.engine->setLastError("Carla's rack mode can only work with Stereo modules, please choose the 2-channel only sample-library version");
  909. return nullptr;
  910. }
  911. LinuxSamplerPlugin* const plugin(new LinuxSamplerPlugin(init.engine, init.id, format, use16Outs));
  912. if (! plugin->init(init.filename, init.name, init.label))
  913. {
  914. delete plugin;
  915. return nullptr;
  916. }
  917. plugin->reload();
  918. return plugin;
  919. #else
  920. init.engine->setLastError("linuxsampler support not available");
  921. return nullptr;
  922. // unused
  923. (void)format;
  924. (void)use16Outs;
  925. #endif
  926. }
  927. CARLA_BACKEND_END_NAMESPACE