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.

1155 lines
38KB

  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[k].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. uint32_t mtime = sampleAccurate ? startTime : time;
  598. if (MIDI_IS_STATUS_AFTERTOUCH(status) && (fOptions & PLUGIN_OPTION_SEND_CHANNEL_PRESSURE) == 0)
  599. continue;
  600. if (MIDI_IS_STATUS_CONTROL_CHANGE(status) && (fOptions & PLUGIN_OPTION_SEND_CONTROL_CHANGES) == 0)
  601. continue;
  602. if (MIDI_IS_STATUS_POLYPHONIC_AFTERTOUCH(status) && (fOptions & PLUGIN_OPTION_SEND_NOTE_AFTERTOUCH) == 0)
  603. continue;
  604. if (MIDI_IS_STATUS_PITCH_WHEEL_CONTROL(status) && (fOptions & PLUGIN_OPTION_SEND_PITCHBEND) == 0)
  605. continue;
  606. fMidiInputPort->DispatchRaw((uint8_t*)midiEvent.data, mtime);
  607. if (status == MIDI_STATUS_NOTE_ON)
  608. postponeRtEvent(kPluginPostRtEventNoteOn, channel, midiEvent.data[1], midiEvent.data[2]);
  609. else if (status == MIDI_STATUS_NOTE_OFF)
  610. postponeRtEvent(kPluginPostRtEventNoteOff, channel, midiEvent.data[1], 0.0f);
  611. break;
  612. }
  613. }
  614. }
  615. kData->postRtEvents.trySplice();
  616. if (frames > timeOffset)
  617. processSingle(outBuffer, frames - timeOffset, timeOffset);
  618. } // End of Event Input and Processing
  619. }
  620. bool processSingle(float** const outBuffer, const uint32_t frames, const uint32_t timeOffset)
  621. {
  622. CARLA_ASSERT(outBuffer != nullptr);
  623. CARLA_ASSERT(frames > 0);
  624. if (outBuffer == nullptr)
  625. return false;
  626. if (frames == 0)
  627. return false;
  628. uint32_t i, k;
  629. // --------------------------------------------------------------------------------------------------------
  630. // Try lock, silence otherwise
  631. if (kData->engine->isOffline())
  632. {
  633. kData->singleMutex.lock();
  634. }
  635. else if (! kData->singleMutex.tryLock())
  636. {
  637. for (i=0; i < kData->audioOut.count; ++i)
  638. {
  639. for (k=0; k < frames; ++k)
  640. outBuffer[i][k+timeOffset] = 0.0f;
  641. }
  642. return false;
  643. }
  644. // --------------------------------------------------------------------------------------------------------
  645. // Run plugin
  646. fAudioOutputDevice->Channel(0)->SetBuffer(outBuffer[0] + timeOffset);
  647. fAudioOutputDevice->Channel(1)->SetBuffer(outBuffer[1] + timeOffset);
  648. // QUESTION: Need to clear it before?
  649. fAudioOutputDevice->Render(frames);
  650. #ifndef BUILD_BRIDGE
  651. // --------------------------------------------------------------------------------------------------------
  652. // Post-processing (dry/wet, volume and balance)
  653. {
  654. const bool doVolume = (fHints & PLUGIN_CAN_VOLUME) > 0 && kData->postProc.volume != 1.0f;
  655. const bool doBalance = (fHints & PLUGIN_CAN_BALANCE) > 0 && (kData->postProc.balanceLeft != -1.0f || kData->postProc.balanceRight != 1.0f);
  656. float oldBufLeft[doBalance ? frames : 1];
  657. for (i=0; i < kData->audioOut.count; ++i)
  658. {
  659. // Balance
  660. if (doBalance)
  661. {
  662. if (i % 2 == 0)
  663. carla_copyFloat(oldBufLeft, outBuffer[i], frames);
  664. float balRangeL = (kData->postProc.balanceLeft + 1.0f)/2.0f;
  665. float balRangeR = (kData->postProc.balanceRight + 1.0f)/2.0f;
  666. for (k=0; k < frames; ++k)
  667. {
  668. if (i % 2 == 0)
  669. {
  670. // left
  671. outBuffer[i][k] = oldBufLeft[k] * (1.0f - balRangeL);
  672. outBuffer[i][k] += outBuffer[i+1][k] * (1.0f - balRangeR);
  673. }
  674. else
  675. {
  676. // right
  677. outBuffer[i][k] = outBuffer[i][k] * balRangeR;
  678. outBuffer[i][k] += oldBufLeft[k] * balRangeL;
  679. }
  680. }
  681. }
  682. // Volume
  683. if (doVolume)
  684. {
  685. for (k=0; k < frames; ++k)
  686. outBuffer[i][k+timeOffset] *= kData->postProc.volume;
  687. }
  688. }
  689. } // End of Post-processing
  690. #endif
  691. // --------------------------------------------------------------------------------------------------------
  692. kData->singleMutex.unlock();
  693. return true;
  694. }
  695. // -------------------------------------------------------------------
  696. // Plugin buffers
  697. // nothing
  698. // -------------------------------------------------------------------
  699. const void* getExtraStuff() const override
  700. {
  701. return kUses16Outs ? (const void*)0x1 : nullptr;
  702. }
  703. bool init(const char* filename, const char* const name, const char* label)
  704. {
  705. CARLA_ASSERT(kData->engine != nullptr);
  706. CARLA_ASSERT(kData->client == nullptr);
  707. CARLA_ASSERT(filename != nullptr);
  708. CARLA_ASSERT(label != nullptr);
  709. // ---------------------------------------------------------------
  710. // first checks
  711. if (kData->engine == nullptr)
  712. {
  713. return false;
  714. }
  715. if (kData->client != nullptr)
  716. {
  717. kData->engine->setLastError("Plugin client is already registered");
  718. return false;
  719. }
  720. if (filename == nullptr)
  721. {
  722. kData->engine->setLastError("null filename");
  723. return false;
  724. }
  725. if (label == nullptr)
  726. {
  727. kData->engine->setLastError("null label");
  728. return false;
  729. }
  730. // ---------------------------------------------------------------
  731. // Check if file exists
  732. {
  733. QFileInfo file(filename);
  734. if (! (file.exists() && file.isFile() && file.isReadable()))
  735. {
  736. kData->engine->setLastError("Requested file is not valid or does not exist");
  737. return false;
  738. }
  739. }
  740. // ---------------------------------------------------------------
  741. // Create the LinuxSampler Engine
  742. const char* const stype = kIsGIG ? "gig" : "sfz";
  743. try {
  744. fEngine = LinuxSampler::EngineFactory::Create(stype);
  745. }
  746. catch (LinuxSampler::Exception& e)
  747. {
  748. kData->engine->setLastError(e.what());
  749. return false;
  750. }
  751. // ---------------------------------------------------------------
  752. // Get the Engine's Instrument Manager
  753. fInstrument = fEngine->GetInstrumentManager();
  754. if (fInstrument == nullptr)
  755. {
  756. kData->engine->setLastError("Failed to get LinuxSampler instrument manager");
  757. LinuxSampler::EngineFactory::Destroy(fEngine);
  758. fEngine = nullptr;
  759. return false;
  760. }
  761. // ---------------------------------------------------------------
  762. // Load the Instrument via filename
  763. try {
  764. fInstrumentIds = fInstrument->GetInstrumentFileContent(filename);
  765. }
  766. catch (const LinuxSampler::InstrumentManagerException& e)
  767. {
  768. kData->engine->setLastError(e.what());
  769. LinuxSampler::EngineFactory::Destroy(fEngine);
  770. fEngine = nullptr;
  771. return false;
  772. }
  773. // ---------------------------------------------------------------
  774. // Get info
  775. if (fInstrumentIds.size() == 0)
  776. {
  777. kData->engine->setLastError("Failed to find any instruments");
  778. LinuxSampler::EngineFactory::Destroy(fEngine);
  779. fEngine = nullptr;
  780. return false;
  781. }
  782. LinuxSampler::InstrumentManager::instrument_info_t info;
  783. try {
  784. info = fInstrument->GetInstrumentInfo(fInstrumentIds[0]);
  785. }
  786. catch (const LinuxSampler::InstrumentManagerException& e)
  787. {
  788. kData->engine->setLastError(e.what());
  789. LinuxSampler::EngineFactory::Destroy(fEngine);
  790. fEngine = nullptr;
  791. return false;
  792. }
  793. fRealName = info.InstrumentName.c_str();
  794. fLabel = info.Product.c_str();
  795. fMaker = info.Artists.c_str();
  796. fFilename = filename;
  797. if (kUses16Outs && ! fLabel.endsWith(" (16 outs)"))
  798. fLabel += " (16 outs)";
  799. if (name != nullptr)
  800. fName = kData->engine->getUniquePluginName(name);
  801. else
  802. fName = kData->engine->getUniquePluginName((const char*)fRealName);
  803. // ---------------------------------------------------------------
  804. // Register client
  805. kData->client = kData->engine->addClient(this);
  806. if (kData->client == nullptr || ! kData->client->isOk())
  807. {
  808. kData->engine->setLastError("Failed to register plugin client");
  809. LinuxSampler::EngineFactory::Destroy(fEngine);
  810. fEngine = nullptr;
  811. return false;
  812. }
  813. // ---------------------------------------------------------------
  814. // Init LinuxSampler stuff
  815. fSamplerChannel = fSampler->AddSamplerChannel();
  816. fSamplerChannel->SetEngineType(stype);
  817. fSamplerChannel->SetAudioOutputDevice(fAudioOutputDevice);
  818. fEngineChannel = fSamplerChannel->GetEngineChannel();
  819. fEngineChannel->Connect(fAudioOutputDevice);
  820. fEngineChannel->Volume(LinuxSampler::VOLUME_MAX);
  821. fMidiInputPort->Connect(fSamplerChannel->GetEngineChannel(), LinuxSampler::midi_chan_all);
  822. // ---------------------------------------------------------------
  823. // load plugin settings
  824. {
  825. // set default options
  826. fOptions = 0x0;
  827. fOptions |= PLUGIN_OPTION_MAP_PROGRAM_CHANGES;
  828. fOptions |= PLUGIN_OPTION_SEND_PITCHBEND;
  829. fOptions |= PLUGIN_OPTION_SEND_ALL_SOUND_OFF;
  830. // load settings
  831. kData->idStr = kIsGIG ? "GIG" : "SFZ";
  832. kData->idStr += "/";
  833. kData->idStr += label;
  834. fOptions = kData->loadSettings(fOptions, availableOptions());
  835. }
  836. return true;
  837. }
  838. // -------------------------------------------------------------------
  839. static CarlaPlugin* newLinuxSampler(const Initializer& init, bool isGIG, const bool use16Outs);
  840. private:
  841. const bool kIsGIG; // sfz if false
  842. const bool kUses16Outs;
  843. CarlaString fRealName;
  844. CarlaString fLabel;
  845. CarlaString fMaker;
  846. LinuxSampler::Sampler* fSampler;
  847. LinuxSampler::SamplerChannel* fSamplerChannel;
  848. LinuxSampler::Engine* fEngine;
  849. LinuxSampler::EngineChannel* fEngineChannel;
  850. LinuxSampler::AudioOutputDevicePlugin* fAudioOutputDevice;
  851. LinuxSampler::MidiInputDevicePlugin* fMidiInputDevice;
  852. LinuxSampler::MidiInputPort* fMidiInputPort;
  853. LinuxSampler::InstrumentManager* fInstrument;
  854. std::vector<LinuxSampler::InstrumentManager::instrument_id_t> fInstrumentIds;
  855. CARLA_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(LinuxSamplerPlugin)
  856. };
  857. CarlaPlugin* LinuxSamplerPlugin::newLinuxSampler(const Initializer& init, const bool isGIG, const bool use16Outs)
  858. {
  859. carla_debug("LinuxSamplerPlugin::newLinuxSampler({%p, \"%s\", \"%s\", \"%s\"}, %s, %s)", init.engine, init.filename, init.name, init.label, bool2str(isGIG), bool2str(use16Outs));
  860. if (init.engine->getProccessMode() == PROCESS_MODE_CONTINUOUS_RACK && use16Outs)
  861. {
  862. init.engine->setLastError("Carla's rack mode can only work with Stereo modules, please choose the 2-channel only sample-library version");
  863. return nullptr;
  864. }
  865. LinuxSamplerPlugin* const plugin(new LinuxSamplerPlugin(init.engine, init.id, isGIG, use16Outs));
  866. if (! plugin->init(init.filename, init.name, init.label))
  867. {
  868. delete plugin;
  869. return nullptr;
  870. }
  871. plugin->reload();
  872. return plugin;
  873. }
  874. CARLA_BACKEND_END_NAMESPACE
  875. #else // WANT_LINUXSAMPLER
  876. # warning linuxsampler not available (no GIG and SFZ support)
  877. #endif
  878. CARLA_BACKEND_START_NAMESPACE
  879. CarlaPlugin* CarlaPlugin::newGIG(const Initializer& init, const bool use16Outs)
  880. {
  881. carla_debug("CarlaPlugin::newGIG({%p, \"%s\", \"%s\", \"%s\"}, %s)", init.engine, init.filename, init.name, init.label, bool2str(use16Outs));
  882. #ifdef WANT_LINUXSAMPLER
  883. return LinuxSamplerPlugin::newLinuxSampler(init, true, use16Outs);
  884. #else
  885. init.engine->setLastError("linuxsampler support not available");
  886. return nullptr;
  887. #endif
  888. }
  889. CarlaPlugin* CarlaPlugin::newSFZ(const Initializer& init, const bool use16Outs)
  890. {
  891. carla_debug("CarlaPlugin::newSFZ({%p, \"%s\", \"%s\", \"%s\"}, %s)", init.engine, init.filename, init.name, init.label, bool2str(use16Outs));
  892. #ifdef WANT_LINUXSAMPLER
  893. return LinuxSamplerPlugin::newLinuxSampler(init, false, use16Outs);
  894. #else
  895. init.engine->setLastError("linuxsampler support not available");
  896. return nullptr;
  897. #endif
  898. }
  899. CARLA_BACKEND_END_NAMESPACE