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.

1158 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_CHANNEL_PRESSURE;
  198. options |= PLUGIN_OPTION_SEND_PITCHBEND;
  199. options |= PLUGIN_OPTION_SEND_ALL_SOUND_OFF;
  200. return options;
  201. }
  202. void getLabel(char* const strBuf) override
  203. {
  204. std::strncpy(strBuf, (const char*)fLabel, STR_MAX);
  205. }
  206. void getMaker(char* const strBuf) override
  207. {
  208. std::strncpy(strBuf, (const char*)fMaker, STR_MAX);
  209. }
  210. void getCopyright(char* const strBuf) override
  211. {
  212. getMaker(strBuf);
  213. }
  214. void getRealName(char* const strBuf) 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>(kData->midiprog.count));
  229. if (index < -1)
  230. index = -1;
  231. else if (index > static_cast<int32_t>(kData->midiprog.count))
  232. return;
  233. if (kData->ctrlChannel < 0 || kData->ctrlChannel >= 16)
  234. return;
  235. if (index >= 0)
  236. {
  237. const uint32_t bank = kData->midiprog.data[index].bank;
  238. const uint32_t program = kData->midiprog.data[index].program;
  239. const uint32_t rIndex = bank*128 + program;
  240. const ScopedSingleProcessLocker spl(this, (sendGui || sendOsc || sendCallback));
  241. if (kData->engine->isOffline())
  242. {
  243. fEngineChannel->PrepareLoadInstrument((const char*)fFilename, rIndex);
  244. fEngineChannel->LoadInstrument();
  245. }
  246. else
  247. {
  248. fInstrument->LoadInstrumentInBackground(fInstrumentIds[rIndex], fEngineChannel);
  249. }
  250. }
  251. CarlaPlugin::setMidiProgram(index, sendGui, sendOsc, sendCallback);
  252. }
  253. // -------------------------------------------------------------------
  254. // Plugin state
  255. void reload() override
  256. {
  257. carla_debug("LinuxSamplerPlugin::reload() - start");
  258. CARLA_ASSERT(kData->engine != nullptr);
  259. CARLA_ASSERT(fInstrument != nullptr);
  260. if (kData->engine == nullptr)
  261. return;
  262. if (fInstrument == nullptr)
  263. return;
  264. const ProcessMode processMode(kData->engine->getProccessMode());
  265. // Safely disable plugin for reload
  266. const ScopedDisabler sd(this);
  267. if (kData->active)
  268. deactivate();
  269. clearBuffers();
  270. uint32_t aOuts;
  271. aOuts = 2;
  272. kData->audioOut.createNew(aOuts);
  273. const int portNameSize = kData->engine->maxPortNameSize();
  274. CarlaString portName;
  275. // ---------------------------------------
  276. // Audio Outputs
  277. {
  278. // out-left
  279. portName.clear();
  280. if (processMode == PROCESS_MODE_SINGLE_CLIENT)
  281. {
  282. portName = fName;
  283. portName += ":";
  284. }
  285. portName += "out-left";
  286. portName.truncate(portNameSize);
  287. kData->audioOut.ports[0].port = (CarlaEngineAudioPort*)kData->client->addPort(kEnginePortTypeAudio, portName, false);
  288. kData->audioOut.ports[0].rindex = 0;
  289. // out-right
  290. portName.clear();
  291. if (processMode == PROCESS_MODE_SINGLE_CLIENT)
  292. {
  293. portName = fName;
  294. portName += ":";
  295. }
  296. portName += "out-right";
  297. portName.truncate(portNameSize);
  298. kData->audioOut.ports[1].port = (CarlaEngineAudioPort*)kData->client->addPort(kEnginePortTypeAudio, portName, false);
  299. kData->audioOut.ports[1].rindex = 1;
  300. }
  301. // ---------------------------------------
  302. // Event Input
  303. {
  304. portName.clear();
  305. if (processMode == PROCESS_MODE_SINGLE_CLIENT)
  306. {
  307. portName = fName;
  308. portName += ":";
  309. }
  310. portName += "event-in";
  311. portName.truncate(portNameSize);
  312. kData->event.portIn = (CarlaEngineEventPort*)kData->client->addPort(kEnginePortTypeEvent, portName, true);
  313. }
  314. // ---------------------------------------
  315. // plugin hints
  316. fHints = 0x0;
  317. fHints |= PLUGIN_IS_SYNTH;
  318. fHints |= PLUGIN_CAN_VOLUME;
  319. fHints |= PLUGIN_CAN_BALANCE;
  320. // extra plugin hints
  321. kData->extraHints = 0x0;
  322. kData->extraHints |= PLUGIN_HINT_HAS_MIDI_IN;
  323. kData->extraHints |= PLUGIN_HINT_CAN_RUN_RACK;
  324. bufferSizeChanged(kData->engine->getBufferSize());
  325. reloadPrograms(true);
  326. if (kData->active)
  327. activate();
  328. carla_debug("LinuxSamplerPlugin::reload() - end");
  329. }
  330. void reloadPrograms(bool init) override
  331. {
  332. carla_debug("LinuxSamplerPlugin::reloadPrograms(%s)", bool2str(init));
  333. // Delete old programs
  334. kData->midiprog.clear();
  335. // Query new programs
  336. uint32_t i, count = fInstrumentIds.size();
  337. // sound kits must always have at least 1 midi-program
  338. CARLA_ASSERT(count > 0);
  339. if (count == 0)
  340. return;
  341. kData->midiprog.createNew(count);
  342. LinuxSampler::InstrumentManager::instrument_info_t info;
  343. for (i=0; i < kData->midiprog.count; ++i)
  344. {
  345. kData->midiprog.data[i].bank = i / 128;
  346. kData->midiprog.data[i].program = i % 128;
  347. try {
  348. info = fInstrument->GetInstrumentInfo(fInstrumentIds[i]);
  349. }
  350. catch (const LinuxSampler::InstrumentManagerException&)
  351. {
  352. continue;
  353. }
  354. kData->midiprog.data[i].name = carla_strdup(info.InstrumentName.c_str());
  355. }
  356. #ifndef BUILD_BRIDGE
  357. // Update OSC Names
  358. if (kData->engine->isOscControlRegistered())
  359. {
  360. kData->engine->osc_send_control_set_midi_program_count(fId, count);
  361. for (i=0; i < count; ++i)
  362. 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);
  363. }
  364. #endif
  365. if (init)
  366. {
  367. setMidiProgram(0, false, false, false);
  368. }
  369. else
  370. {
  371. kData->engine->callback(CALLBACK_RELOAD_PROGRAMS, fId, 0, 0, 0.0f, nullptr);
  372. }
  373. }
  374. // -------------------------------------------------------------------
  375. // Plugin processing
  376. void activate() override
  377. {
  378. CARLA_ASSERT(fAudioOutputDevice != nullptr);
  379. fAudioOutputDevice->Play();
  380. }
  381. void deactivate() override
  382. {
  383. CARLA_ASSERT(fAudioOutputDevice != nullptr);
  384. fAudioOutputDevice->Stop();
  385. }
  386. void process(float** const, float** const outBuffer, const uint32_t frames) override
  387. {
  388. uint32_t i, k;
  389. // --------------------------------------------------------------------------------------------------------
  390. // Check if active
  391. if (! kData->active)
  392. {
  393. // disable any output sound
  394. for (i=0; i < kData->audioOut.count; ++i)
  395. carla_zeroFloat(outBuffer[i], frames);
  396. return;
  397. }
  398. // --------------------------------------------------------------------------------------------------------
  399. // Check if needs reset
  400. if (kData->needsReset)
  401. {
  402. if (fOptions & PLUGIN_OPTION_SEND_ALL_SOUND_OFF)
  403. {
  404. for (k=0, i=MAX_MIDI_CHANNELS; k < MAX_MIDI_CHANNELS; ++k)
  405. {
  406. fMidiInputPort->DispatchControlChange(MIDI_CONTROL_ALL_NOTES_OFF, 0, k);
  407. fMidiInputPort->DispatchControlChange(MIDI_CONTROL_ALL_SOUND_OFF, 0, k);
  408. }
  409. }
  410. else if (kData->ctrlChannel >= 0 && kData->ctrlChannel < MAX_MIDI_CHANNELS)
  411. {
  412. for (k=0; k < MAX_MIDI_NOTE; ++k)
  413. fMidiInputPort->DispatchNoteOff(k, 0, kData->ctrlChannel);
  414. }
  415. kData->needsReset = false;
  416. }
  417. // --------------------------------------------------------------------------------------------------------
  418. // Event Input and Processing
  419. {
  420. // ----------------------------------------------------------------------------------------------------
  421. // MIDI Input (External)
  422. if (kData->extNotes.mutex.tryLock())
  423. {
  424. while (! kData->extNotes.data.isEmpty())
  425. {
  426. const ExternalMidiNote& note(kData->extNotes.data.getFirst(true));
  427. CARLA_ASSERT(note.channel >= 0 && note.channel < MAX_MIDI_CHANNELS);
  428. if (note.velo > 0)
  429. fMidiInputPort->DispatchNoteOn(note.note, note.velo, note.channel, 0);
  430. else
  431. fMidiInputPort->DispatchNoteOff(note.note, note.velo, note.channel, 0);
  432. }
  433. kData->extNotes.mutex.unlock();
  434. } // End of MIDI Input (External)
  435. // ----------------------------------------------------------------------------------------------------
  436. // Event Input (System)
  437. bool allNotesOffSent = false;
  438. bool sampleAccurate = (fOptions & PLUGIN_OPTION_FIXED_BUFFER) == 0;
  439. uint32_t time, nEvents = kData->event.portIn->getEventCount();
  440. uint32_t startTime = 0;
  441. uint32_t timeOffset = 0;
  442. uint32_t nextBankId = 0;
  443. if (kData->midiprog.current >= 0 && kData->midiprog.count > 0)
  444. nextBankId = kData->midiprog.data[kData->midiprog.current].bank;
  445. for (i=0; i < nEvents; ++i)
  446. {
  447. const EngineEvent& event(kData->event.portIn->getEvent(i));
  448. time = event.time;
  449. if (time >= frames)
  450. continue;
  451. CARLA_ASSERT_INT2(time >= timeOffset, time, timeOffset);
  452. if (time > timeOffset && sampleAccurate)
  453. {
  454. if (processSingle(outBuffer, time - timeOffset, timeOffset))
  455. {
  456. startTime = 0;
  457. timeOffset = time;
  458. if (kData->midiprog.current >= 0 && kData->midiprog.count > 0)
  459. nextBankId = kData->midiprog.data[kData->midiprog.current].bank;
  460. else
  461. nextBankId = 0;
  462. }
  463. else
  464. startTime += timeOffset;
  465. }
  466. // Control change
  467. switch (event.type)
  468. {
  469. case kEngineEventTypeNull:
  470. break;
  471. case kEngineEventTypeControl:
  472. {
  473. const EngineControlEvent& ctrlEvent = event.ctrl;
  474. switch (ctrlEvent.type)
  475. {
  476. case kEngineControlEventTypeNull:
  477. break;
  478. case kEngineControlEventTypeParameter:
  479. {
  480. #ifndef BUILD_BRIDGE
  481. // Control backend stuff
  482. if (event.channel == kData->ctrlChannel)
  483. {
  484. float value;
  485. if (MIDI_IS_CONTROL_BREATH_CONTROLLER(ctrlEvent.param) && (fHints & PLUGIN_CAN_DRYWET) > 0)
  486. {
  487. value = ctrlEvent.value;
  488. setDryWet(value, false, false);
  489. postponeRtEvent(kPluginPostRtEventParameterChange, PARAMETER_DRYWET, 0, value);
  490. }
  491. if (MIDI_IS_CONTROL_CHANNEL_VOLUME(ctrlEvent.param) && (fHints & PLUGIN_CAN_VOLUME) > 0)
  492. {
  493. value = ctrlEvent.value*127.0f/100.0f;
  494. setVolume(value, false, false);
  495. postponeRtEvent(kPluginPostRtEventParameterChange, PARAMETER_VOLUME, 0, value);
  496. }
  497. if (MIDI_IS_CONTROL_BALANCE(ctrlEvent.param) && (fHints & PLUGIN_CAN_BALANCE) > 0)
  498. {
  499. float left, right;
  500. value = ctrlEvent.value/0.5f - 1.0f;
  501. if (value < 0.0f)
  502. {
  503. left = -1.0f;
  504. right = (value*2.0f)+1.0f;
  505. }
  506. else if (value > 0.0f)
  507. {
  508. left = (value*2.0f)-1.0f;
  509. right = 1.0f;
  510. }
  511. else
  512. {
  513. left = -1.0f;
  514. right = 1.0f;
  515. }
  516. setBalanceLeft(left, false, false);
  517. setBalanceRight(right, false, false);
  518. postponeRtEvent(kPluginPostRtEventParameterChange, PARAMETER_BALANCE_LEFT, 0, left);
  519. postponeRtEvent(kPluginPostRtEventParameterChange, PARAMETER_BALANCE_RIGHT, 0, right);
  520. }
  521. }
  522. #endif
  523. // Control plugin parameters
  524. for (k=0; k < kData->param.count; ++k)
  525. {
  526. if (kData->param.data[k].midiChannel != event.channel)
  527. continue;
  528. if (kData->param.data[k].midiCC != ctrlEvent.param)
  529. continue;
  530. if (kData->param.data[k].type != PARAMETER_INPUT)
  531. continue;
  532. if ((kData->param.data[k].hints & PARAMETER_IS_AUTOMABLE) == 0)
  533. continue;
  534. double value;
  535. if (kData->param.data[k].hints & PARAMETER_IS_BOOLEAN)
  536. {
  537. value = (ctrlEvent.value < 0.5f) ? kData->param.ranges[k].min : kData->param.ranges[k].max;
  538. }
  539. else
  540. {
  541. value = kData->param.ranges[k].unnormalizeValue(ctrlEvent.value);
  542. if (kData->param.data[k].hints & PARAMETER_IS_INTEGER)
  543. value = std::rint(value);
  544. }
  545. setParameterValue(k, value, false, false, false);
  546. postponeRtEvent(kPluginPostRtEventParameterChange, static_cast<int32_t>(k), 0, value);
  547. }
  548. if ((fOptions & PLUGIN_OPTION_SEND_CONTROL_CHANGES) != 0 && ctrlEvent.param <= 0x5F)
  549. {
  550. fMidiInputPort->DispatchControlChange(ctrlEvent.param, ctrlEvent.value*127.0f, event.channel, sampleAccurate ? startTime : time);
  551. }
  552. break;
  553. }
  554. case kEngineControlEventTypeMidiBank:
  555. if (event.channel == kData->ctrlChannel && (fOptions & PLUGIN_OPTION_MAP_PROGRAM_CHANGES) != 0)
  556. nextBankId = ctrlEvent.param;
  557. break;
  558. case kEngineControlEventTypeMidiProgram:
  559. if (event.channel == kData->ctrlChannel && (fOptions & PLUGIN_OPTION_MAP_PROGRAM_CHANGES) != 0)
  560. {
  561. const uint32_t nextProgramId = ctrlEvent.param;
  562. for (k=0; k < kData->midiprog.count; ++k)
  563. {
  564. if (kData->midiprog.data[k].bank == nextBankId && kData->midiprog.data[k].program == nextProgramId)
  565. {
  566. setMidiProgram(k, false, false, false);
  567. postponeRtEvent(kPluginPostRtEventMidiProgramChange, k, 0, 0.0f);
  568. break;
  569. }
  570. }
  571. }
  572. break;
  573. case kEngineControlEventTypeAllSoundOff:
  574. if (fOptions & PLUGIN_OPTION_SEND_ALL_SOUND_OFF)
  575. {
  576. fMidiInputPort->DispatchControlChange(MIDI_CONTROL_ALL_SOUND_OFF, 0, event.channel, sampleAccurate ? startTime : time);
  577. }
  578. break;
  579. case kEngineControlEventTypeAllNotesOff:
  580. if (fOptions & PLUGIN_OPTION_SEND_ALL_SOUND_OFF)
  581. {
  582. if (event.channel == kData->ctrlChannel && ! allNotesOffSent)
  583. {
  584. allNotesOffSent = true;
  585. sendMidiAllNotesOffToCallback();
  586. }
  587. fMidiInputPort->DispatchControlChange(MIDI_CONTROL_ALL_NOTES_OFF, 0, event.channel, sampleAccurate ? startTime : time);
  588. }
  589. break;
  590. }
  591. break;
  592. }
  593. case kEngineEventTypeMidi:
  594. {
  595. const EngineMidiEvent& midiEvent(event.midi);
  596. uint8_t status = MIDI_GET_STATUS_FROM_DATA(midiEvent.data);
  597. uint8_t channel = event.channel;
  598. uint32_t mtime = sampleAccurate ? startTime : time;
  599. if (MIDI_IS_STATUS_AFTERTOUCH(status) && (fOptions & PLUGIN_OPTION_SEND_CHANNEL_PRESSURE) == 0)
  600. continue;
  601. if (MIDI_IS_STATUS_CONTROL_CHANGE(status) && (fOptions & PLUGIN_OPTION_SEND_CONTROL_CHANGES) == 0)
  602. continue;
  603. if (MIDI_IS_STATUS_POLYPHONIC_AFTERTOUCH(status) && (fOptions & PLUGIN_OPTION_SEND_NOTE_AFTERTOUCH) == 0)
  604. continue;
  605. if (MIDI_IS_STATUS_PITCH_WHEEL_CONTROL(status) && (fOptions & PLUGIN_OPTION_SEND_PITCHBEND) == 0)
  606. continue;
  607. fMidiInputPort->DispatchRaw((uint8_t*)midiEvent.data, mtime);
  608. if (status == MIDI_STATUS_NOTE_ON)
  609. postponeRtEvent(kPluginPostRtEventNoteOn, channel, midiEvent.data[1], midiEvent.data[2]);
  610. else if (status == MIDI_STATUS_NOTE_OFF)
  611. postponeRtEvent(kPluginPostRtEventNoteOff, channel, midiEvent.data[1], 0.0f);
  612. break;
  613. }
  614. }
  615. }
  616. kData->postRtEvents.trySplice();
  617. if (frames > timeOffset)
  618. processSingle(outBuffer, frames - timeOffset, timeOffset);
  619. } // End of Event Input and Processing
  620. }
  621. bool processSingle(float** const outBuffer, const uint32_t frames, const uint32_t timeOffset)
  622. {
  623. CARLA_ASSERT(outBuffer != nullptr);
  624. CARLA_ASSERT(frames > 0);
  625. if (outBuffer == nullptr)
  626. return false;
  627. if (frames == 0)
  628. return false;
  629. uint32_t i, k;
  630. // --------------------------------------------------------------------------------------------------------
  631. // Try lock, silence otherwise
  632. if (kData->engine->isOffline())
  633. {
  634. kData->singleMutex.lock();
  635. }
  636. else if (! kData->singleMutex.tryLock())
  637. {
  638. for (i=0; i < kData->audioOut.count; ++i)
  639. {
  640. for (k=0; k < frames; ++k)
  641. outBuffer[i][k+timeOffset] = 0.0f;
  642. }
  643. return false;
  644. }
  645. // --------------------------------------------------------------------------------------------------------
  646. // Run plugin
  647. fAudioOutputDevice->Channel(0)->SetBuffer(outBuffer[0] + timeOffset);
  648. fAudioOutputDevice->Channel(1)->SetBuffer(outBuffer[1] + timeOffset);
  649. // QUESTION: Need to clear it before?
  650. fAudioOutputDevice->Render(frames);
  651. #ifndef BUILD_BRIDGE
  652. // --------------------------------------------------------------------------------------------------------
  653. // Post-processing (dry/wet, volume and balance)
  654. {
  655. const bool doVolume = (fHints & PLUGIN_CAN_VOLUME) > 0 && kData->postProc.volume != 1.0f;
  656. const bool doBalance = (fHints & PLUGIN_CAN_BALANCE) > 0 && (kData->postProc.balanceLeft != -1.0f || kData->postProc.balanceRight != 1.0f);
  657. float oldBufLeft[doBalance ? frames : 1];
  658. for (i=0; i < kData->audioOut.count; ++i)
  659. {
  660. // Balance
  661. if (doBalance)
  662. {
  663. if (i % 2 == 0)
  664. carla_copyFloat(oldBufLeft, outBuffer[i], frames);
  665. float balRangeL = (kData->postProc.balanceLeft + 1.0f)/2.0f;
  666. float balRangeR = (kData->postProc.balanceRight + 1.0f)/2.0f;
  667. for (k=0; k < frames; ++k)
  668. {
  669. if (i % 2 == 0)
  670. {
  671. // left
  672. outBuffer[i][k] = oldBufLeft[k] * (1.0f - balRangeL);
  673. outBuffer[i][k] += outBuffer[i+1][k] * (1.0f - balRangeR);
  674. }
  675. else
  676. {
  677. // right
  678. outBuffer[i][k] = outBuffer[i][k] * balRangeR;
  679. outBuffer[i][k] += oldBufLeft[k] * balRangeL;
  680. }
  681. }
  682. }
  683. // Volume
  684. if (doVolume)
  685. {
  686. for (k=0; k < frames; ++k)
  687. outBuffer[i][k+timeOffset] *= kData->postProc.volume;
  688. }
  689. }
  690. } // End of Post-processing
  691. #endif
  692. // --------------------------------------------------------------------------------------------------------
  693. kData->singleMutex.unlock();
  694. return true;
  695. }
  696. // -------------------------------------------------------------------
  697. // Plugin buffers
  698. // nothing
  699. // -------------------------------------------------------------------
  700. const void* getExtraStuff() const override
  701. {
  702. return kUses16Outs ? (const void*)0x1 : nullptr;
  703. }
  704. bool init(const char* filename, const char* const name, const char* label)
  705. {
  706. CARLA_ASSERT(kData->engine != nullptr);
  707. CARLA_ASSERT(kData->client == nullptr);
  708. CARLA_ASSERT(filename != nullptr);
  709. CARLA_ASSERT(label != nullptr);
  710. // ---------------------------------------------------------------
  711. // first checks
  712. if (kData->engine == nullptr)
  713. {
  714. return false;
  715. }
  716. if (kData->client != nullptr)
  717. {
  718. kData->engine->setLastError("Plugin client is already registered");
  719. return false;
  720. }
  721. if (filename == nullptr)
  722. {
  723. kData->engine->setLastError("null filename");
  724. return false;
  725. }
  726. if (label == nullptr)
  727. {
  728. kData->engine->setLastError("null label");
  729. return false;
  730. }
  731. // ---------------------------------------------------------------
  732. // Check if file exists
  733. {
  734. QFileInfo file(filename);
  735. if (! (file.exists() && file.isFile() && file.isReadable()))
  736. {
  737. kData->engine->setLastError("Requested file is not valid or does not exist");
  738. return false;
  739. }
  740. }
  741. // ---------------------------------------------------------------
  742. // Create the LinuxSampler Engine
  743. const char* const stype = kIsGIG ? "gig" : "sfz";
  744. try {
  745. fEngine = LinuxSampler::EngineFactory::Create(stype);
  746. }
  747. catch (LinuxSampler::Exception& e)
  748. {
  749. kData->engine->setLastError(e.what());
  750. return false;
  751. }
  752. // ---------------------------------------------------------------
  753. // Get the Engine's Instrument Manager
  754. fInstrument = fEngine->GetInstrumentManager();
  755. if (fInstrument == nullptr)
  756. {
  757. kData->engine->setLastError("Failed to get LinuxSampler instrument manager");
  758. LinuxSampler::EngineFactory::Destroy(fEngine);
  759. fEngine = nullptr;
  760. return false;
  761. }
  762. // ---------------------------------------------------------------
  763. // Load the Instrument via filename
  764. try {
  765. fInstrumentIds = fInstrument->GetInstrumentFileContent(filename);
  766. }
  767. catch (const LinuxSampler::InstrumentManagerException& e)
  768. {
  769. kData->engine->setLastError(e.what());
  770. LinuxSampler::EngineFactory::Destroy(fEngine);
  771. fEngine = nullptr;
  772. return false;
  773. }
  774. // ---------------------------------------------------------------
  775. // Get info
  776. if (fInstrumentIds.size() == 0)
  777. {
  778. kData->engine->setLastError("Failed to find any instruments");
  779. LinuxSampler::EngineFactory::Destroy(fEngine);
  780. fEngine = nullptr;
  781. return false;
  782. }
  783. LinuxSampler::InstrumentManager::instrument_info_t info;
  784. try {
  785. info = fInstrument->GetInstrumentInfo(fInstrumentIds[0]);
  786. }
  787. catch (const LinuxSampler::InstrumentManagerException& e)
  788. {
  789. kData->engine->setLastError(e.what());
  790. LinuxSampler::EngineFactory::Destroy(fEngine);
  791. fEngine = nullptr;
  792. return false;
  793. }
  794. fRealName = info.InstrumentName.c_str();
  795. fLabel = info.Product.c_str();
  796. fMaker = info.Artists.c_str();
  797. fFilename = filename;
  798. if (kUses16Outs && ! fLabel.endsWith(" (16 outs)"))
  799. fLabel += " (16 outs)";
  800. if (name != nullptr)
  801. fName = kData->engine->getUniquePluginName(name);
  802. else
  803. fName = kData->engine->getUniquePluginName((const char*)fRealName);
  804. // ---------------------------------------------------------------
  805. // Register client
  806. kData->client = kData->engine->addClient(this);
  807. if (kData->client == nullptr || ! kData->client->isOk())
  808. {
  809. kData->engine->setLastError("Failed to register plugin client");
  810. LinuxSampler::EngineFactory::Destroy(fEngine);
  811. fEngine = nullptr;
  812. return false;
  813. }
  814. // ---------------------------------------------------------------
  815. // Init LinuxSampler stuff
  816. fSamplerChannel = fSampler->AddSamplerChannel();
  817. fSamplerChannel->SetEngineType(stype);
  818. fSamplerChannel->SetAudioOutputDevice(fAudioOutputDevice);
  819. fEngineChannel = fSamplerChannel->GetEngineChannel();
  820. fEngineChannel->Connect(fAudioOutputDevice);
  821. fEngineChannel->Volume(LinuxSampler::VOLUME_MAX);
  822. fMidiInputPort->Connect(fSamplerChannel->GetEngineChannel(), LinuxSampler::midi_chan_all);
  823. // ---------------------------------------------------------------
  824. // load plugin settings
  825. {
  826. // set default options
  827. fOptions = 0x0;
  828. fOptions |= PLUGIN_OPTION_MAP_PROGRAM_CHANGES;
  829. fOptions |= PLUGIN_OPTION_SEND_CONTROL_CHANGES;
  830. fOptions |= PLUGIN_OPTION_SEND_CHANNEL_PRESSURE;
  831. fOptions |= PLUGIN_OPTION_SEND_PITCHBEND;
  832. fOptions |= PLUGIN_OPTION_SEND_ALL_SOUND_OFF;
  833. // load settings
  834. kData->idStr = kIsGIG ? "GIG" : "SFZ";
  835. kData->idStr += "/";
  836. kData->idStr += label;
  837. fOptions = kData->loadSettings(fOptions, availableOptions());
  838. }
  839. return true;
  840. }
  841. // -------------------------------------------------------------------
  842. static CarlaPlugin* newLinuxSampler(const Initializer& init, bool isGIG, const bool use16Outs);
  843. private:
  844. const bool kIsGIG; // sfz if false
  845. const bool kUses16Outs;
  846. CarlaString fRealName;
  847. CarlaString fLabel;
  848. CarlaString fMaker;
  849. LinuxSampler::Sampler* fSampler;
  850. LinuxSampler::SamplerChannel* fSamplerChannel;
  851. LinuxSampler::Engine* fEngine;
  852. LinuxSampler::EngineChannel* fEngineChannel;
  853. LinuxSampler::AudioOutputDevicePlugin* fAudioOutputDevice;
  854. LinuxSampler::MidiInputDevicePlugin* fMidiInputDevice;
  855. LinuxSampler::MidiInputPort* fMidiInputPort;
  856. LinuxSampler::InstrumentManager* fInstrument;
  857. std::vector<LinuxSampler::InstrumentManager::instrument_id_t> fInstrumentIds;
  858. CARLA_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(LinuxSamplerPlugin)
  859. };
  860. CarlaPlugin* LinuxSamplerPlugin::newLinuxSampler(const Initializer& init, const bool isGIG, const bool use16Outs)
  861. {
  862. carla_debug("LinuxSamplerPlugin::newLinuxSampler({%p, \"%s\", \"%s\", \"%s\"}, %s, %s)", init.engine, init.filename, init.name, init.label, bool2str(isGIG), bool2str(use16Outs));
  863. if (init.engine->getProccessMode() == PROCESS_MODE_CONTINUOUS_RACK && use16Outs)
  864. {
  865. init.engine->setLastError("Carla's rack mode can only work with Stereo modules, please choose the 2-channel only sample-library version");
  866. return nullptr;
  867. }
  868. LinuxSamplerPlugin* const plugin(new LinuxSamplerPlugin(init.engine, init.id, isGIG, use16Outs));
  869. if (! plugin->init(init.filename, init.name, init.label))
  870. {
  871. delete plugin;
  872. return nullptr;
  873. }
  874. plugin->reload();
  875. return plugin;
  876. }
  877. CARLA_BACKEND_END_NAMESPACE
  878. #else // WANT_LINUXSAMPLER
  879. # warning linuxsampler not available (no GIG and SFZ support)
  880. #endif
  881. CARLA_BACKEND_START_NAMESPACE
  882. CarlaPlugin* CarlaPlugin::newGIG(const Initializer& init, const bool use16Outs)
  883. {
  884. carla_debug("CarlaPlugin::newGIG({%p, \"%s\", \"%s\", \"%s\"}, %s)", init.engine, init.filename, init.name, init.label, bool2str(use16Outs));
  885. #ifdef WANT_LINUXSAMPLER
  886. return LinuxSamplerPlugin::newLinuxSampler(init, true, use16Outs);
  887. #else
  888. init.engine->setLastError("linuxsampler support not available");
  889. return nullptr;
  890. #endif
  891. }
  892. CarlaPlugin* CarlaPlugin::newSFZ(const Initializer& init, const bool use16Outs)
  893. {
  894. carla_debug("CarlaPlugin::newSFZ({%p, \"%s\", \"%s\", \"%s\"}, %s)", init.engine, init.filename, init.name, init.label, bool2str(use16Outs));
  895. #ifdef WANT_LINUXSAMPLER
  896. return LinuxSamplerPlugin::newLinuxSampler(init, false, use16Outs);
  897. #else
  898. init.engine->setLastError("linuxsampler support not available");
  899. return nullptr;
  900. #endif
  901. }
  902. CARLA_BACKEND_END_NAMESPACE