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.

1203 lines
40KB

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