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.

1186 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 GPL.txt file
  16. */
  17. #include "CarlaPluginInternal.hpp"
  18. #ifdef WANT_LINUXSAMPLER
  19. #include "linuxsampler/EngineFactory.h"
  20. #include <linuxsampler/Sampler.h>
  21. #include <QtCore/QFileInfo>
  22. namespace LinuxSampler {
  23. // -----------------------------------------------------------------------
  24. // LinuxSampler static values
  25. static const float VOLUME_MAX = 3.16227766f; // +10 dB
  26. static const float VOLUME_MIN = 0.0f; // -inf dB
  27. // -----------------------------------------------------------------------
  28. // LinuxSampler AudioOutputDevice Plugin
  29. class AudioOutputDevicePlugin : public AudioOutputDevice
  30. {
  31. public:
  32. AudioOutputDevicePlugin(CarlaBackend::CarlaEngine* const engine, CarlaBackend::CarlaPlugin* const plugin)
  33. : AudioOutputDevice(std::map<String, DeviceCreationParameter*>()),
  34. kEngine(engine),
  35. kPlugin(plugin)
  36. {
  37. CARLA_ASSERT(engine != nullptr);
  38. CARLA_ASSERT(plugin != nullptr);
  39. }
  40. // -------------------------------------------------------------------
  41. // LinuxSampler virtual methods
  42. void Play() override
  43. {
  44. }
  45. bool IsPlaying() override
  46. {
  47. return (kEngine->isRunning() && kPlugin->enabled());
  48. }
  49. void Stop() override
  50. {
  51. }
  52. uint MaxSamplesPerCycle() override
  53. {
  54. return kEngine->getBufferSize();
  55. }
  56. uint SampleRate() override
  57. {
  58. return kEngine->getSampleRate();
  59. }
  60. String Driver() override
  61. {
  62. return "AudioOutputDevicePlugin";
  63. }
  64. AudioChannel* CreateChannel(uint channelNr) override
  65. {
  66. return new AudioChannel(channelNr, nullptr, 0);
  67. }
  68. // -------------------------------------------------------------------
  69. // Give public access to the RenderAudio call
  70. int Render(const uint samples)
  71. {
  72. return RenderAudio(samples);
  73. }
  74. private:
  75. CarlaBackend::CarlaEngine* const kEngine;
  76. CarlaBackend::CarlaPlugin* const kPlugin;
  77. };
  78. // -----------------------------------------------------------------------
  79. // LinuxSampler MidiInputDevice Plugin
  80. class MidiInputDevicePlugin : public MidiInputDevice
  81. {
  82. public:
  83. MidiInputDevicePlugin(Sampler* const sampler)
  84. : MidiInputDevice(std::map<String, DeviceCreationParameter*>(), sampler)
  85. {
  86. }
  87. // -------------------------------------------------------------------
  88. // LinuxSampler virtual methods
  89. void Listen() override
  90. {
  91. }
  92. void StopListen() override
  93. {
  94. }
  95. String Driver() override
  96. {
  97. return "MidiInputDevicePlugin";
  98. }
  99. MidiInputPort* CreateMidiPort() override
  100. {
  101. return new MidiInputPortPlugin(this, Ports.size());
  102. }
  103. // -------------------------------------------------------------------
  104. // Properly delete port (destructor is protected)
  105. void DeleteMidiPort(MidiInputPort* const port)
  106. {
  107. delete (MidiInputPortPlugin*)port;
  108. }
  109. // -------------------------------------------------------------------
  110. // MIDI Port implementation for this plugin MIDI input driver
  111. // (Constructor and destructor are protected)
  112. class MidiInputPortPlugin : public MidiInputPort
  113. {
  114. protected:
  115. MidiInputPortPlugin(MidiInputDevicePlugin* const device, const int portNumber)
  116. : MidiInputPort(device, portNumber) {}
  117. friend class MidiInputDevicePlugin;
  118. };
  119. };
  120. } // namespace LinuxSampler
  121. // -----------------------------------------------------------------------
  122. CARLA_BACKEND_START_NAMESPACE
  123. #if 0
  124. }
  125. #endif
  126. class LinuxSamplerPlugin : public CarlaPlugin
  127. {
  128. public:
  129. LinuxSamplerPlugin(CarlaEngine* const engine, const unsigned short id, const bool isGIG, const bool use16Outs)
  130. : CarlaPlugin(engine, id),
  131. kIsGIG(isGIG),
  132. kUses16Outs(use16Outs),
  133. fSampler(new LinuxSampler::Sampler()),
  134. fSamplerChannel(nullptr),
  135. fEngine(nullptr),
  136. fEngineChannel(nullptr),
  137. fAudioOutputDevice(new LinuxSampler::AudioOutputDevicePlugin(engine, this)),
  138. fMidiInputDevice(new LinuxSampler::MidiInputDevicePlugin(fSampler)),
  139. fMidiInputPort(fMidiInputDevice->CreateMidiPort()),
  140. fInstrument(nullptr)
  141. {
  142. carla_debug("LinuxSamplerPlugin::LinuxSamplerPlugin(%p, %i, %s)", engine, id, bool2str(isGIG));
  143. }
  144. ~LinuxSamplerPlugin() override
  145. {
  146. carla_debug("LinuxSamplerPlugin::~LinuxSamplerPlugin()");
  147. kData->singleMutex.lock();
  148. kData->masterMutex.lock();
  149. if (kData->client != nullptr && kData->client->isActive())
  150. kData->client->deactivate();
  151. if (kData->active)
  152. {
  153. deactivate();
  154. kData->active = false;
  155. }
  156. if (fEngine != nullptr)
  157. {
  158. if (fSamplerChannel != nullptr)
  159. {
  160. fMidiInputPort->Disconnect(fSamplerChannel->GetEngineChannel());
  161. fEngineChannel->DisconnectAudioOutputDevice();
  162. fSampler->RemoveSamplerChannel(fSamplerChannel);
  163. }
  164. LinuxSampler::EngineFactory::Destroy(fEngine);
  165. }
  166. // destructor is private
  167. fMidiInputDevice->DeleteMidiPort(fMidiInputPort);
  168. delete fMidiInputDevice;
  169. delete fAudioOutputDevice;
  170. delete fSampler;
  171. fInstrumentIds.clear();
  172. clearBuffers();
  173. }
  174. // -------------------------------------------------------------------
  175. // Information (base)
  176. PluginType type() const override
  177. {
  178. return kIsGIG ? PLUGIN_GIG : PLUGIN_SFZ;
  179. }
  180. PluginCategory category() override
  181. {
  182. return PLUGIN_CATEGORY_SYNTH;
  183. }
  184. // -------------------------------------------------------------------
  185. // Information (count)
  186. // nothing
  187. // -------------------------------------------------------------------
  188. // Information (current data)
  189. // nothing
  190. // -------------------------------------------------------------------
  191. // Information (per-plugin data)
  192. unsigned int availableOptions() override
  193. {
  194. unsigned int options = 0x0;
  195. options |= PLUGIN_OPTION_MAP_PROGRAM_CHANGES;
  196. options |= PLUGIN_OPTION_SEND_CONTROL_CHANGES;
  197. options |= PLUGIN_OPTION_SEND_PITCHBEND;
  198. options |= PLUGIN_OPTION_SEND_ALL_SOUND_OFF;
  199. return options;
  200. }
  201. void getLabel(char* const strBuf) override
  202. {
  203. std::strncpy(strBuf, (const char*)fLabel, STR_MAX);
  204. }
  205. void getMaker(char* const strBuf) override
  206. {
  207. std::strncpy(strBuf, (const char*)fMaker, STR_MAX);
  208. }
  209. void getCopyright(char* const strBuf) override
  210. {
  211. getMaker(strBuf);
  212. }
  213. void getRealName(char* const strBuf) override
  214. {
  215. std::strncpy(strBuf, (const char*)fRealName, STR_MAX);
  216. }
  217. // -------------------------------------------------------------------
  218. // Set data (state)
  219. // nothing
  220. // -------------------------------------------------------------------
  221. // Set data (internal stuff)
  222. // nothing
  223. // -------------------------------------------------------------------
  224. // Set data (plugin-specific stuff)
  225. void setMidiProgram(int32_t index, const bool sendGui, const bool sendOsc, const bool sendCallback) override
  226. {
  227. CARLA_ASSERT(index >= -1 && index < static_cast<int32_t>(kData->midiprog.count));
  228. if (index < -1)
  229. index = -1;
  230. else if (index > static_cast<int32_t>(kData->midiprog.count))
  231. return;
  232. if (kData->ctrlChannel < 0 || kData->ctrlChannel >= 16)
  233. return;
  234. if (index >= 0)
  235. {
  236. const uint32_t bank = kData->midiprog.data[index].bank;
  237. const uint32_t program = kData->midiprog.data[index].program;
  238. const uint32_t rIndex = bank*128 + program;
  239. const ScopedSingleProcessLocker spl(this, (sendGui || sendOsc || sendCallback));
  240. if (kData->engine->isOffline())
  241. {
  242. fEngineChannel->PrepareLoadInstrument((const char*)fFilename, rIndex);
  243. fEngineChannel->LoadInstrument();
  244. }
  245. else
  246. {
  247. fInstrument->LoadInstrumentInBackground(fInstrumentIds[rIndex], fEngineChannel);
  248. }
  249. }
  250. CarlaPlugin::setMidiProgram(index, sendGui, sendOsc, sendCallback);
  251. }
  252. // -------------------------------------------------------------------
  253. // Plugin state
  254. void reload() override
  255. {
  256. carla_debug("LinuxSamplerPlugin::reload() - start");
  257. CARLA_ASSERT(kData->engine != nullptr);
  258. CARLA_ASSERT(fInstrument != nullptr);
  259. if (kData->engine == nullptr)
  260. return;
  261. if (fInstrument == nullptr)
  262. return;
  263. const ProcessMode processMode(kData->engine->getProccessMode());
  264. // Safely disable plugin for reload
  265. const ScopedDisabler sd(this);
  266. if (kData->active)
  267. deactivate();
  268. clearBuffers();
  269. uint32_t aOuts;
  270. aOuts = 2;
  271. kData->audioOut.createNew(aOuts);
  272. const int portNameSize = kData->engine->maxPortNameSize();
  273. CarlaString portName;
  274. // ---------------------------------------
  275. // Audio Outputs
  276. {
  277. // out-left
  278. portName.clear();
  279. if (processMode == PROCESS_MODE_SINGLE_CLIENT)
  280. {
  281. portName = fName;
  282. portName += ":";
  283. }
  284. portName += "out-left";
  285. portName.truncate(portNameSize);
  286. kData->audioOut.ports[0].port = (CarlaEngineAudioPort*)kData->client->addPort(kEnginePortTypeAudio, portName, false);
  287. kData->audioOut.ports[0].rindex = 0;
  288. // out-right
  289. portName.clear();
  290. if (processMode == PROCESS_MODE_SINGLE_CLIENT)
  291. {
  292. portName = fName;
  293. portName += ":";
  294. }
  295. portName += "out-right";
  296. portName.truncate(portNameSize);
  297. kData->audioOut.ports[1].port = (CarlaEngineAudioPort*)kData->client->addPort(kEnginePortTypeAudio, portName, false);
  298. kData->audioOut.ports[1].rindex = 1;
  299. }
  300. // ---------------------------------------
  301. // Event Input
  302. {
  303. portName.clear();
  304. if (processMode == PROCESS_MODE_SINGLE_CLIENT)
  305. {
  306. portName = fName;
  307. portName += ":";
  308. }
  309. portName += "event-in";
  310. portName.truncate(portNameSize);
  311. kData->event.portIn = (CarlaEngineEventPort*)kData->client->addPort(kEnginePortTypeEvent, portName, true);
  312. }
  313. // ---------------------------------------
  314. // plugin hints
  315. fHints = 0x0;
  316. fHints |= PLUGIN_IS_SYNTH;
  317. fHints |= PLUGIN_CAN_VOLUME;
  318. fHints |= PLUGIN_CAN_BALANCE;
  319. // extra plugin hints
  320. kData->extraHints = 0x0;
  321. kData->extraHints |= PLUGIN_HINT_HAS_MIDI_IN;
  322. kData->extraHints |= PLUGIN_HINT_CAN_RUN_RACK;
  323. bufferSizeChanged(kData->engine->getBufferSize());
  324. reloadPrograms(true);
  325. if (kData->active)
  326. activate();
  327. carla_debug("LinuxSamplerPlugin::reload() - end");
  328. }
  329. void reloadPrograms(bool init) override
  330. {
  331. carla_debug("LinuxSamplerPlugin::reloadPrograms(%s)", bool2str(init));
  332. // Delete old programs
  333. kData->midiprog.clear();
  334. // Query new programs
  335. uint32_t i, count = fInstrumentIds.size();
  336. // sound kits must always have at least 1 midi-program
  337. CARLA_ASSERT(count > 0);
  338. if (count == 0)
  339. return;
  340. kData->midiprog.createNew(count);
  341. LinuxSampler::InstrumentManager::instrument_info_t info;
  342. for (i=0; i < kData->midiprog.count; ++i)
  343. {
  344. kData->midiprog.data[i].bank = i / 128;
  345. kData->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. kData->midiprog.data[i].name = carla_strdup(info.InstrumentName.c_str());
  354. }
  355. #ifndef BUILD_BRIDGE
  356. // Update OSC Names
  357. if (kData->engine->isOscControlRegistered())
  358. {
  359. kData->engine->osc_send_control_set_midi_program_count(fId, count);
  360. for (i=0; i < count; ++i)
  361. kData->engine->osc_send_control_set_midi_program_data(fId, i, kData->midiprog.data[i].bank, kData->midiprog.data[i].program, kData->midiprog.data[i].name);
  362. }
  363. #endif
  364. if (init)
  365. {
  366. setMidiProgram(0, false, false, false);
  367. }
  368. else
  369. {
  370. kData->engine->callback(CALLBACK_RELOAD_PROGRAMS, fId, 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 (! kData->active)
  391. {
  392. // disable any output sound
  393. for (i=0; i < kData->audioOut.count; ++i)
  394. carla_zeroFloat(outBuffer[i], frames);
  395. return;
  396. }
  397. // --------------------------------------------------------------------------------------------------------
  398. // Check if needs reset
  399. if (kData->needsReset)
  400. {
  401. if (fOptions & 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 (kData->ctrlChannel >= 0 && kData->ctrlChannel < MAX_MIDI_CHANNELS)
  410. {
  411. for (k=0; k < MAX_MIDI_NOTE; ++k)
  412. fMidiInputPort->DispatchNoteOff(k, 0, kData->ctrlChannel);
  413. }
  414. kData->needsReset = false;
  415. }
  416. // --------------------------------------------------------------------------------------------------------
  417. // Event Input and Processing
  418. {
  419. // ----------------------------------------------------------------------------------------------------
  420. // MIDI Input (External)
  421. if (kData->extNotes.mutex.tryLock())
  422. {
  423. while (! kData->extNotes.data.isEmpty())
  424. {
  425. const ExternalMidiNote& note(kData->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. kData->extNotes.mutex.unlock();
  433. } // End of MIDI Input (External)
  434. // ----------------------------------------------------------------------------------------------------
  435. // Event Input (System)
  436. bool allNotesOffSent = false;
  437. bool sampleAccurate = (fOptions & PLUGIN_OPTION_FIXED_BUFFER) == 0;
  438. uint32_t time, nEvents = kData->event.portIn->getEventCount();
  439. uint32_t startTime = 0;
  440. uint32_t timeOffset = 0;
  441. uint32_t nextBankId = 0;
  442. if (kData->midiprog.current >= 0 && kData->midiprog.count > 0)
  443. nextBankId = kData->midiprog.data[kData->midiprog.current].bank;
  444. for (i=0; i < nEvents; ++i)
  445. {
  446. const EngineEvent& event(kData->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 (kData->midiprog.current >= 0 && kData->midiprog.count > 0)
  458. nextBankId = kData->midiprog.data[kData->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 == kData->ctrlChannel)
  482. {
  483. float value;
  484. if (MIDI_IS_CONTROL_BREATH_CONTROLLER(ctrlEvent.param) && (fHints & PLUGIN_CAN_DRYWET) > 0)
  485. {
  486. value = ctrlEvent.value;
  487. setDryWet(value, false, false);
  488. postponeRtEvent(kPluginPostRtEventParameterChange, PARAMETER_DRYWET, 0, value);
  489. }
  490. if (MIDI_IS_CONTROL_CHANNEL_VOLUME(ctrlEvent.param) && (fHints & PLUGIN_CAN_VOLUME) > 0)
  491. {
  492. value = ctrlEvent.value*127.0f/100.0f;
  493. setVolume(value, false, false);
  494. postponeRtEvent(kPluginPostRtEventParameterChange, PARAMETER_VOLUME, 0, value);
  495. }
  496. if (MIDI_IS_CONTROL_BALANCE(ctrlEvent.param) && (fHints & 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. postponeRtEvent(kPluginPostRtEventParameterChange, PARAMETER_BALANCE_LEFT, 0, left);
  518. postponeRtEvent(kPluginPostRtEventParameterChange, PARAMETER_BALANCE_RIGHT, 0, right);
  519. }
  520. }
  521. #endif
  522. // Control plugin parameters
  523. for (k=0; k < kData->param.count; ++k)
  524. {
  525. if (kData->param.data[k].midiChannel != event.channel)
  526. continue;
  527. if (kData->param.data[k].midiCC != ctrlEvent.param)
  528. continue;
  529. if (kData->param.data[k].type != PARAMETER_INPUT)
  530. continue;
  531. if ((kData->param.data[k].hints & PARAMETER_IS_AUTOMABLE) == 0)
  532. continue;
  533. double value;
  534. if (kData->param.data[k].hints & PARAMETER_IS_BOOLEAN)
  535. {
  536. value = (ctrlEvent.value < 0.5f) ? kData->param.ranges[k].min : kData->param.ranges[k].max;
  537. }
  538. else
  539. {
  540. value = kData->param.ranges[i].unnormalizeValue(ctrlEvent.value);
  541. if (kData->param.data[k].hints & PARAMETER_IS_INTEGER)
  542. value = std::rint(value);
  543. }
  544. setParameterValue(k, value, false, false, false);
  545. postponeRtEvent(kPluginPostRtEventParameterChange, static_cast<int32_t>(k), 0, value);
  546. }
  547. if ((fOptions & PLUGIN_OPTION_SEND_CONTROL_CHANGES) != 0 && ctrlEvent.param <= 0x5F)
  548. {
  549. fMidiInputPort->DispatchControlChange(ctrlEvent.param, ctrlEvent.value*127.0f, event.channel, sampleAccurate ? startTime : time);
  550. }
  551. break;
  552. }
  553. case kEngineControlEventTypeMidiBank:
  554. if (event.channel == kData->ctrlChannel && (fOptions & PLUGIN_OPTION_MAP_PROGRAM_CHANGES) != 0)
  555. nextBankId = ctrlEvent.param;
  556. break;
  557. case kEngineControlEventTypeMidiProgram:
  558. if (event.channel == kData->ctrlChannel && (fOptions & PLUGIN_OPTION_MAP_PROGRAM_CHANGES) != 0)
  559. {
  560. const uint32_t nextProgramId = ctrlEvent.param;
  561. for (k=0; k < kData->midiprog.count; ++k)
  562. {
  563. if (kData->midiprog.data[k].bank == nextBankId && kData->midiprog.data[k].program == nextProgramId)
  564. {
  565. setMidiProgram(k, false, false, false);
  566. postponeRtEvent(kPluginPostRtEventMidiProgramChange, k, 0, 0.0f);
  567. break;
  568. }
  569. }
  570. }
  571. break;
  572. case kEngineControlEventTypeAllSoundOff:
  573. if (fOptions & 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 (fOptions & PLUGIN_OPTION_SEND_ALL_SOUND_OFF)
  580. {
  581. if (event.channel == kData->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 -= 0x10;
  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. 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. postponeRtEvent(kPluginPostRtEventNoteOn, channel, note, velo);
  613. }
  614. else if (MIDI_IS_STATUS_POLYPHONIC_AFTERTOUCH(status) && (fOptions & 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) && (fOptions & 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_AFTERTOUCH(status) && (fOptions & 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) && (fOptions & 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. kData->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 (kData->engine->isOffline())
  658. {
  659. kData->singleMutex.lock();
  660. }
  661. else if (! kData->singleMutex.tryLock())
  662. {
  663. for (i=0; i < kData->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 = (fHints & PLUGIN_CAN_VOLUME) > 0 && kData->postProc.volume != 1.0f;
  681. const bool doBalance = (fHints & PLUGIN_CAN_BALANCE) > 0 && (kData->postProc.balanceLeft != -1.0f || kData->postProc.balanceRight != 1.0f);
  682. float oldBufLeft[doBalance ? frames : 1];
  683. for (i=0; i < kData->audioOut.count; ++i)
  684. {
  685. // Balance
  686. if (doBalance)
  687. {
  688. if (i % 2 == 0)
  689. carla_copyFloat(oldBufLeft, outBuffer[i], frames);
  690. float balRangeL = (kData->postProc.balanceLeft + 1.0f)/2.0f;
  691. float balRangeR = (kData->postProc.balanceRight + 1.0f)/2.0f;
  692. for (k=0; k < frames; ++k)
  693. {
  694. if (i % 2 == 0)
  695. {
  696. // left
  697. outBuffer[i][k] = oldBufLeft[k] * (1.0f - balRangeL);
  698. outBuffer[i][k] += outBuffer[i+1][k] * (1.0f - balRangeR);
  699. }
  700. else
  701. {
  702. // right
  703. outBuffer[i][k] = outBuffer[i][k] * balRangeR;
  704. outBuffer[i][k] += oldBufLeft[k] * balRangeL;
  705. }
  706. }
  707. }
  708. // Volume
  709. if (doVolume)
  710. {
  711. for (k=0; k < frames; ++k)
  712. outBuffer[i][k+timeOffset] *= kData->postProc.volume;
  713. }
  714. }
  715. } // End of Post-processing
  716. #endif
  717. // --------------------------------------------------------------------------------------------------------
  718. kData->singleMutex.unlock();
  719. return true;
  720. }
  721. // -------------------------------------------------------------------
  722. // Plugin buffers
  723. // nothing
  724. // -------------------------------------------------------------------
  725. const void* getExtraStuff() const override
  726. {
  727. return kUses16Outs ? (const void*)0x1 : nullptr;
  728. }
  729. bool init(const char* filename, const char* const name, const char* label)
  730. {
  731. CARLA_ASSERT(kData->engine != nullptr);
  732. CARLA_ASSERT(kData->client == nullptr);
  733. CARLA_ASSERT(filename != nullptr);
  734. CARLA_ASSERT(label != nullptr);
  735. // ---------------------------------------------------------------
  736. // first checks
  737. if (kData->engine == nullptr)
  738. {
  739. return false;
  740. }
  741. if (kData->client != nullptr)
  742. {
  743. kData->engine->setLastError("Plugin client is already registered");
  744. return false;
  745. }
  746. if (filename == nullptr)
  747. {
  748. kData->engine->setLastError("null filename");
  749. return false;
  750. }
  751. if (label == nullptr)
  752. {
  753. kData->engine->setLastError("null label");
  754. return false;
  755. }
  756. // ---------------------------------------------------------------
  757. // Check if file exists
  758. {
  759. QFileInfo file(filename);
  760. if (! (file.exists() && file.isFile() && file.isReadable()))
  761. {
  762. kData->engine->setLastError("Requested file is not valid or does not exist");
  763. return false;
  764. }
  765. }
  766. // ---------------------------------------------------------------
  767. // Create the LinuxSampler Engine
  768. const char* const stype = kIsGIG ? "gig" : "sfz";
  769. try {
  770. fEngine = LinuxSampler::EngineFactory::Create(stype);
  771. }
  772. catch (LinuxSampler::Exception& e)
  773. {
  774. kData->engine->setLastError(e.what());
  775. return false;
  776. }
  777. // ---------------------------------------------------------------
  778. // Get the Engine's Instrument Manager
  779. fInstrument = fEngine->GetInstrumentManager();
  780. if (fInstrument == nullptr)
  781. {
  782. kData->engine->setLastError("Failed to get LinuxSampler instrument manager");
  783. LinuxSampler::EngineFactory::Destroy(fEngine);
  784. fEngine = nullptr;
  785. return false;
  786. }
  787. // ---------------------------------------------------------------
  788. // Load the Instrument via filename
  789. try {
  790. fInstrumentIds = fInstrument->GetInstrumentFileContent(filename);
  791. }
  792. catch (const LinuxSampler::InstrumentManagerException& e)
  793. {
  794. kData->engine->setLastError(e.what());
  795. LinuxSampler::EngineFactory::Destroy(fEngine);
  796. fEngine = nullptr;
  797. return false;
  798. }
  799. // ---------------------------------------------------------------
  800. // Get info
  801. if (fInstrumentIds.size() == 0)
  802. {
  803. kData->engine->setLastError("Failed to find any instruments");
  804. LinuxSampler::EngineFactory::Destroy(fEngine);
  805. fEngine = nullptr;
  806. return false;
  807. }
  808. LinuxSampler::InstrumentManager::instrument_info_t info;
  809. try {
  810. info = fInstrument->GetInstrumentInfo(fInstrumentIds[0]);
  811. }
  812. catch (const LinuxSampler::InstrumentManagerException& e)
  813. {
  814. kData->engine->setLastError(e.what());
  815. LinuxSampler::EngineFactory::Destroy(fEngine);
  816. fEngine = nullptr;
  817. return false;
  818. }
  819. fRealName = info.InstrumentName.c_str();
  820. fLabel = info.Product.c_str();
  821. fMaker = info.Artists.c_str();
  822. fFilename = filename;
  823. if (name != nullptr)
  824. fName = kData->engine->getUniquePluginName(name);
  825. else
  826. fName = kData->engine->getUniquePluginName((const char*)fRealName);
  827. // ---------------------------------------------------------------
  828. // Register client
  829. kData->client = kData->engine->addClient(this);
  830. if (kData->client == nullptr || ! kData->client->isOk())
  831. {
  832. kData->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. kData->idStr = kIsGIG ? "GIG" : "SFZ";
  856. kData->idStr += "/";
  857. kData->idStr += label;
  858. fOptions = kData->loadSettings(fOptions, availableOptions());
  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