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.

1387 lines
46KB

  1. /*
  2. * Carla LinuxSampler Plugin
  3. * Copyright (C) 2011-2013 Filipe Coelho <falktx@falktx.com>
  4. *
  5. * This program is free software; you can redistribute it and/or
  6. * modify it under the terms of the GNU General Public License as
  7. * published by the Free Software Foundation; either version 2 of
  8. * the License, or any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * For a full copy of the GNU General Public License see the doc/GPL.txt file.
  16. */
  17. /* TODO
  18. * - implement buffer size changes
  19. * - implement sample rate changes
  20. * - call outDev->ReconnectAll() after changing buffer size or sample rate
  21. * - use CARLA_SAFE_ASSERT_RETURN with err
  22. */
  23. #include "CarlaPluginInternal.hpp"
  24. #ifdef WANT_LINUXSAMPLER
  25. #include "linuxsampler/EngineFactory.h"
  26. #include <linuxsampler/Sampler.h>
  27. #include <QtCore/QFileInfo>
  28. #include <QtCore/QStringList>
  29. namespace LinuxSampler {
  30. using CarlaBackend::CarlaEngine;
  31. using CarlaBackend::CarlaPlugin;
  32. // -----------------------------------------------------------------------
  33. // LinuxSampler static values
  34. static const float kVolumeMax = 3.16227766f; // +10 dB
  35. static const float kVolumeMin = 0.0f; // -inf dB
  36. // -----------------------------------------------------------------------
  37. // LinuxSampler AudioOutputDevice Plugin
  38. class AudioOutputDevicePlugin : public AudioOutputDevice
  39. {
  40. public:
  41. AudioOutputDevicePlugin(const CarlaEngine* const engine, const CarlaPlugin* const plugin)
  42. : AudioOutputDevice(std::map<String, DeviceCreationParameter*>()),
  43. fEngine(engine),
  44. fPlugin(plugin)
  45. {
  46. CARLA_ASSERT(engine != nullptr);
  47. CARLA_ASSERT(plugin != nullptr);
  48. }
  49. ~AudioOutputDevicePlugin() override {}
  50. // -------------------------------------------------------------------
  51. // LinuxSampler virtual methods
  52. void Play() override
  53. {
  54. }
  55. bool IsPlaying() override
  56. {
  57. return (fEngine->isRunning() && fPlugin->isEnabled());
  58. }
  59. void Stop() override
  60. {
  61. }
  62. uint MaxSamplesPerCycle() override
  63. {
  64. return fEngine->getBufferSize();
  65. }
  66. uint SampleRate() override
  67. {
  68. return uint(fEngine->getSampleRate());
  69. }
  70. String Driver() override
  71. {
  72. return "AudioOutputDevicePlugin";
  73. }
  74. AudioChannel* CreateChannel(uint channelNr) override
  75. {
  76. return new AudioChannel(channelNr, nullptr, 0);
  77. }
  78. // -------------------------------------------------------------------
  79. // Give public access to the RenderAudio call
  80. int Render(const uint samples)
  81. {
  82. return RenderAudio(samples);
  83. }
  84. // -------------------------------------------------------------------
  85. private:
  86. const CarlaEngine* const fEngine;
  87. const CarlaPlugin* const fPlugin;
  88. };
  89. // -----------------------------------------------------------------------
  90. // LinuxSampler MidiInputPort Plugin
  91. class MidiInputPortPlugin : public MidiInputPort
  92. {
  93. public:
  94. MidiInputPortPlugin(MidiInputDevice* const device, const int portNumber)
  95. : MidiInputPort(device, portNumber)
  96. {
  97. }
  98. ~MidiInputPortPlugin() override {}
  99. };
  100. // -----------------------------------------------------------------------
  101. // LinuxSampler MidiInputDevice Plugin
  102. class MidiInputDevicePlugin : public MidiInputDevice
  103. {
  104. public:
  105. MidiInputDevicePlugin(Sampler* const sampler)
  106. : MidiInputDevice(std::map<String, DeviceCreationParameter*>(), sampler)
  107. {
  108. }
  109. // -------------------------------------------------------------------
  110. // LinuxSampler virtual methods
  111. void Listen() override
  112. {
  113. }
  114. void StopListen() override
  115. {
  116. }
  117. String Driver() override
  118. {
  119. return "MidiInputDevicePlugin";
  120. }
  121. MidiInputPort* CreateMidiPort() override
  122. {
  123. return new MidiInputPortPlugin(this, int(Ports.size()));
  124. }
  125. MidiInputPortPlugin* CreateMidiPortPlugin()
  126. {
  127. return new MidiInputPortPlugin(this, int(Ports.size()));
  128. }
  129. };
  130. } // namespace LinuxSampler
  131. // -----------------------------------------------------------------------
  132. CARLA_BACKEND_START_NAMESPACE
  133. #if 0
  134. }
  135. #endif
  136. class LinuxSamplerPlugin : public CarlaPlugin
  137. {
  138. public:
  139. LinuxSamplerPlugin(CarlaEngine* const engine, const unsigned int id, const char* const format, const bool use16Outs)
  140. : CarlaPlugin(engine, id),
  141. fFormat(carla_strdup(format)),
  142. fUses16Outs(use16Outs),
  143. fEngine(nullptr),
  144. fMidiInputDevice(nullptr),
  145. fMidiInputPort(nullptr),
  146. fInstrument(nullptr)
  147. {
  148. carla_debug("LinuxSamplerPlugin::LinuxSamplerPlugin(%p, %i, %s, %s)", engine, id, format, bool2str(use16Outs));
  149. for (int i=0; i < 16; ++i)
  150. {
  151. fCurMidiProgs[0] = 0;
  152. fSamplerChannels[i] = nullptr;
  153. fEngineChannels[i] = nullptr;
  154. fAudioOutputDevices[i] = nullptr;
  155. }
  156. }
  157. ~LinuxSamplerPlugin() override
  158. {
  159. carla_debug("LinuxSamplerPlugin::~LinuxSamplerPlugin()");
  160. pData->singleMutex.lock();
  161. pData->masterMutex.lock();
  162. if (pData->client != nullptr && pData->client->isActive())
  163. pData->client->deactivate();
  164. if (pData->active)
  165. {
  166. deactivate();
  167. pData->active = false;
  168. }
  169. if (fEngine != nullptr)
  170. {
  171. if (fMidiInputDevice != nullptr)
  172. {
  173. if (fMidiInputPort != nullptr)
  174. {
  175. for (int i=0; i < 16; ++i)
  176. {
  177. if (fSamplerChannels[i] != nullptr)
  178. {
  179. if (fEngineChannels[i] != nullptr)
  180. {
  181. fMidiInputPort->Disconnect(fEngineChannels[i]);
  182. fEngineChannels[i]->DisconnectAudioOutputDevice();
  183. fEngineChannels[i] = nullptr;
  184. }
  185. fSampler.RemoveSamplerChannel(fSamplerChannels[i]);
  186. fSamplerChannels[i] = nullptr;
  187. if (fAudioOutputDevices[i] != nullptr)
  188. {
  189. delete fAudioOutputDevices[i];
  190. fAudioOutputDevices[i] = nullptr;
  191. }
  192. }
  193. }
  194. delete fMidiInputPort;
  195. fMidiInputPort = nullptr;
  196. }
  197. delete fMidiInputDevice;
  198. fMidiInputDevice = nullptr;
  199. }
  200. fInstrument = nullptr;
  201. LinuxSampler::EngineFactory::Destroy(fEngine);
  202. fEngine = nullptr;
  203. }
  204. fInstrumentIds.clear();
  205. if (fFormat != nullptr)
  206. {
  207. delete[] fFormat;
  208. fFormat = nullptr;
  209. }
  210. clearBuffers();
  211. }
  212. // -------------------------------------------------------------------
  213. // Information (base)
  214. PluginType getType() const noexcept override
  215. {
  216. return getPluginTypeFromString(fFormat);
  217. }
  218. PluginCategory getCategory() const override
  219. {
  220. return PLUGIN_CATEGORY_SYNTH;
  221. }
  222. // -------------------------------------------------------------------
  223. // Information (count)
  224. // nothing
  225. // -------------------------------------------------------------------
  226. // Information (current data)
  227. // nothing
  228. // -------------------------------------------------------------------
  229. // Information (per-plugin data)
  230. unsigned int getOptionsAvailable() const override
  231. {
  232. unsigned int options = 0x0;
  233. options |= PLUGIN_OPTION_MAP_PROGRAM_CHANGES;
  234. options |= PLUGIN_OPTION_SEND_CONTROL_CHANGES;
  235. options |= PLUGIN_OPTION_SEND_PITCHBEND;
  236. options |= PLUGIN_OPTION_SEND_ALL_SOUND_OFF;
  237. return options;
  238. }
  239. void getLabel(char* const strBuf) const override
  240. {
  241. std::strncpy(strBuf, (const char*)fLabel, STR_MAX);
  242. }
  243. void getMaker(char* const strBuf) const override
  244. {
  245. std::strncpy(strBuf, (const char*)fMaker, STR_MAX);
  246. }
  247. void getCopyright(char* const strBuf) const override
  248. {
  249. getMaker(strBuf);
  250. }
  251. void getRealName(char* const strBuf) const override
  252. {
  253. std::strncpy(strBuf, (const char*)fRealName, STR_MAX);
  254. }
  255. // -------------------------------------------------------------------
  256. // Set data (state)
  257. void prepareForSave() override
  258. {
  259. char strBuf[STR_MAX+1];
  260. std::snprintf(strBuf, STR_MAX, "%i:%i:%i:%i:%i:%i:%i:%i:%i:%i:%i:%i:%i:%i:%i:%i", fCurMidiProgs[0], fCurMidiProgs[1], fCurMidiProgs[2], fCurMidiProgs[3],
  261. fCurMidiProgs[4], fCurMidiProgs[5], fCurMidiProgs[6], fCurMidiProgs[7],
  262. fCurMidiProgs[8], fCurMidiProgs[9], fCurMidiProgs[10], fCurMidiProgs[11],
  263. fCurMidiProgs[12], fCurMidiProgs[13], fCurMidiProgs[14], fCurMidiProgs[15]);
  264. CarlaPlugin::setCustomData(CUSTOM_DATA_TYPE_STRING, "midiPrograms", strBuf, false);
  265. }
  266. // -------------------------------------------------------------------
  267. // Set data (internal stuff)
  268. void setCtrlChannel(const int8_t channel, const bool sendOsc, const bool sendCallback) override
  269. {
  270. if (channel < MAX_MIDI_CHANNELS)
  271. pData->midiprog.current = fCurMidiProgs[channel];
  272. CarlaPlugin::setCtrlChannel(channel, sendOsc, sendCallback);
  273. }
  274. // -------------------------------------------------------------------
  275. // Set data (plugin-specific stuff)
  276. void setCustomData(const char* const type, const char* const key, const char* const value, const bool sendGui) override
  277. {
  278. CARLA_SAFE_ASSERT_RETURN(type != nullptr && type[0] != '\0',);
  279. CARLA_SAFE_ASSERT_RETURN(key != nullptr && key[0] != '\0',);
  280. CARLA_SAFE_ASSERT_RETURN(value != nullptr && value[0] != '\0',);
  281. carla_debug("DssiPlugin::setCustomData(%s, \"%s\", \"%s\", %s)", type, key, value, bool2str(sendGui));
  282. if (std::strcmp(type, CUSTOM_DATA_TYPE_STRING) != 0)
  283. return carla_stderr2("LinuxSamplerPlugin::setCustomData(\"%s\", \"%s\", \"%s\", %s) - type is not string", type, key, value, bool2str(sendGui));
  284. if (std::strcmp(key, "midiPrograms") != 0)
  285. return carla_stderr2("LinuxSamplerPlugin::setCustomData(\"%s\", \"%s\", \"%s\", %s) - type is not string", type, key, value, bool2str(sendGui));
  286. if (! fUses16Outs)
  287. return CarlaPlugin::setCustomData(type, key, value, sendGui);
  288. QStringList midiProgramList(QString(value).split(":", QString::SkipEmptyParts));
  289. if (midiProgramList.count() == MAX_MIDI_CHANNELS)
  290. {
  291. uint i = 0;
  292. foreach (const QString& midiProg, midiProgramList)
  293. {
  294. bool ok;
  295. uint index = midiProg.toUInt(&ok);
  296. if (ok && index < pData->midiprog.count)
  297. {
  298. const uint32_t bank = pData->midiprog.data[index].bank;
  299. const uint32_t program = pData->midiprog.data[index].program;
  300. const uint32_t rIndex = bank*128 + program;
  301. if (pData->engine->isOffline())
  302. {
  303. fEngineChannels[i]->PrepareLoadInstrument(pData->filename, rIndex);
  304. fEngineChannels[i]->LoadInstrument();
  305. }
  306. else
  307. {
  308. fInstrument->LoadInstrumentInBackground(fInstrumentIds[rIndex], fEngineChannels[i]);
  309. }
  310. fCurMidiProgs[i] = index;
  311. if (pData->ctrlChannel == static_cast<int32_t>(i))
  312. {
  313. pData->midiprog.current = index;
  314. pData->engine->callback(ENGINE_CALLBACK_MIDI_PROGRAM_CHANGED, pData->id, index, 0, 0.0f, nullptr);
  315. }
  316. }
  317. ++i;
  318. }
  319. }
  320. CarlaPlugin::setCustomData(type, key, value, sendGui);
  321. }
  322. void setMidiProgram(int32_t index, const bool sendGui, const bool sendOsc, const bool sendCallback) override
  323. {
  324. CARLA_ASSERT(index >= -1 && index < static_cast<int32_t>(pData->midiprog.count));
  325. if (index < -1)
  326. index = -1;
  327. else if (index > static_cast<int32_t>(pData->midiprog.count))
  328. return;
  329. if (pData->ctrlChannel < 0 || pData->ctrlChannel >= MAX_MIDI_CHANNELS)
  330. return;
  331. if (index >= 0)
  332. {
  333. const uint32_t bank = pData->midiprog.data[index].bank;
  334. const uint32_t program = pData->midiprog.data[index].program;
  335. const uint32_t rIndex = bank*128 + program;
  336. LinuxSampler::EngineChannel* const engineChannel(fUses16Outs ? fEngineChannels[pData->ctrlChannel] : fEngineChannels[0]);
  337. const ScopedSingleProcessLocker spl(this, (sendGui || sendOsc || sendCallback));
  338. if (pData->engine->isOffline())
  339. {
  340. engineChannel->PrepareLoadInstrument(pData->filename, rIndex);
  341. engineChannel->LoadInstrument();
  342. }
  343. else
  344. {
  345. fInstrument->LoadInstrumentInBackground(fInstrumentIds[rIndex], engineChannel);
  346. }
  347. fCurMidiProgs[pData->ctrlChannel] = index;
  348. }
  349. CarlaPlugin::setMidiProgram(index, sendGui, sendOsc, sendCallback);
  350. }
  351. // -------------------------------------------------------------------
  352. // Plugin state
  353. void reload() override
  354. {
  355. CARLA_SAFE_ASSERT_RETURN(pData->engine != nullptr,);
  356. CARLA_SAFE_ASSERT_RETURN(fInstrument != nullptr,);
  357. carla_debug("LinuxSamplerPlugin::reload() - start");
  358. const EngineProcessMode processMode(pData->engine->getProccessMode());
  359. // Safely disable plugin for reload
  360. const ScopedDisabler sd(this);
  361. if (pData->active)
  362. deactivate();
  363. clearBuffers();
  364. uint32_t aOuts;
  365. aOuts = fUses16Outs ? 16 : 2;
  366. pData->audioOut.createNew(aOuts);
  367. const int portNameSize = pData->engine->getMaxPortNameSize();
  368. CarlaString portName;
  369. // ---------------------------------------
  370. // Audio Outputs
  371. if (fUses16Outs)
  372. {
  373. for (uint32_t i=0; i < 32; ++i)
  374. {
  375. portName.clear();
  376. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  377. {
  378. portName = pData->name;
  379. portName += ":";
  380. }
  381. portName += "out-";
  382. if ((i+2)/2 < 9)
  383. portName += "0";
  384. portName += CarlaString((i+2)/2);
  385. if (i % 2 == 0)
  386. portName += "L";
  387. else
  388. portName += "R";
  389. portName.truncate(portNameSize);
  390. pData->audioOut.ports[i].port = (CarlaEngineAudioPort*)pData->client->addPort(kEnginePortTypeAudio, portName, false);
  391. pData->audioOut.ports[i].rindex = i;
  392. }
  393. }
  394. else
  395. {
  396. // out-left
  397. portName.clear();
  398. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  399. {
  400. portName = pData->name;
  401. portName += ":";
  402. }
  403. portName += "out-left";
  404. portName.truncate(portNameSize);
  405. pData->audioOut.ports[0].port = (CarlaEngineAudioPort*)pData->client->addPort(kEnginePortTypeAudio, portName, false);
  406. pData->audioOut.ports[0].rindex = 0;
  407. // out-right
  408. portName.clear();
  409. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  410. {
  411. portName = pData->name;
  412. portName += ":";
  413. }
  414. portName += "out-right";
  415. portName.truncate(portNameSize);
  416. pData->audioOut.ports[1].port = (CarlaEngineAudioPort*)pData->client->addPort(kEnginePortTypeAudio, portName, false);
  417. pData->audioOut.ports[1].rindex = 1;
  418. }
  419. // ---------------------------------------
  420. // Event Input
  421. {
  422. portName.clear();
  423. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  424. {
  425. portName = pData->name;
  426. portName += ":";
  427. }
  428. portName += "event-in";
  429. portName.truncate(portNameSize);
  430. pData->event.portIn = (CarlaEngineEventPort*)pData->client->addPort(kEnginePortTypeEvent, portName, true);
  431. }
  432. // ---------------------------------------
  433. // plugin hints
  434. pData->hints = 0x0;
  435. pData->hints |= PLUGIN_IS_SYNTH;
  436. pData->hints |= PLUGIN_CAN_VOLUME;
  437. pData->hints |= PLUGIN_CAN_BALANCE;
  438. // extra plugin hints
  439. pData->extraHints = 0x0;
  440. pData->extraHints |= PLUGIN_EXTRA_HINT_HAS_MIDI_IN;
  441. if (! fUses16Outs)
  442. pData->extraHints |= PLUGIN_EXTRA_HINT_CAN_RUN_RACK;
  443. bufferSizeChanged(pData->engine->getBufferSize());
  444. reloadPrograms(true);
  445. if (pData->active)
  446. activate();
  447. carla_debug("LinuxSamplerPlugin::reload() - end");
  448. }
  449. void reloadPrograms(bool init) override
  450. {
  451. carla_debug("LinuxSamplerPlugin::reloadPrograms(%s)", bool2str(init));
  452. // Delete old programs
  453. pData->midiprog.clear();
  454. // Query new programs
  455. uint32_t i, count = (uint32_t)fInstrumentIds.size();
  456. // sound kits must always have at least 1 midi-program
  457. CARLA_SAFE_ASSERT_RETURN(count > 0,);
  458. pData->midiprog.createNew(count);
  459. LinuxSampler::InstrumentManager::instrument_info_t info;
  460. for (i=0; i < pData->midiprog.count; ++i)
  461. {
  462. pData->midiprog.data[i].bank = i / 128;
  463. pData->midiprog.data[i].program = i % 128;
  464. try {
  465. info = fInstrument->GetInstrumentInfo(fInstrumentIds[i]);
  466. }
  467. catch (const LinuxSampler::InstrumentManagerException&)
  468. {
  469. continue;
  470. }
  471. pData->midiprog.data[i].name = carla_strdup(info.InstrumentName.c_str());
  472. }
  473. #ifndef BUILD_BRIDGE
  474. // Update OSC Names
  475. if (pData->engine->isOscControlRegistered())
  476. {
  477. pData->engine->oscSend_control_set_midi_program_count(pData->id, count);
  478. for (i=0; i < count; ++i)
  479. pData->engine->oscSend_control_set_midi_program_data(pData->id, i, pData->midiprog.data[i].bank, pData->midiprog.data[i].program, pData->midiprog.data[i].name);
  480. }
  481. #endif
  482. if (init)
  483. {
  484. for (int i=0; i < 16; ++i)
  485. {
  486. CARLA_SAFE_ASSERT_CONTINUE(fEngineChannels[i] != nullptr);
  487. fEngineChannels[i]->PrepareLoadInstrument(pData->filename, 0);
  488. fEngineChannels[i]->LoadInstrument();
  489. fCurMidiProgs[i] = 0;
  490. }
  491. pData->midiprog.current = 0;
  492. }
  493. else
  494. {
  495. pData->engine->callback(ENGINE_CALLBACK_RELOAD_PROGRAMS, pData->id, 0, 0, 0.0f, nullptr);
  496. }
  497. }
  498. // -------------------------------------------------------------------
  499. // Plugin processing
  500. void activate() override
  501. {
  502. for (int i=0; i < 16; ++i)
  503. {
  504. if (fAudioOutputDevices[i] != nullptr)
  505. fAudioOutputDevices[i]->Play();
  506. }
  507. }
  508. void deactivate() override
  509. {
  510. for (int i=0; i < 16; ++i)
  511. {
  512. if (fAudioOutputDevices[i] != nullptr)
  513. fAudioOutputDevices[i]->Stop();
  514. }
  515. }
  516. void process(float** const, float** const outBuffer, const uint32_t frames) override
  517. {
  518. uint32_t i, k;
  519. // --------------------------------------------------------------------------------------------------------
  520. // Check if active
  521. if (! pData->active)
  522. {
  523. // disable any output sound
  524. for (i=0; i < pData->audioOut.count; ++i)
  525. FLOAT_CLEAR(outBuffer[i], frames);
  526. return;
  527. }
  528. // --------------------------------------------------------------------------------------------------------
  529. // Check if needs reset
  530. if (pData->needsReset)
  531. {
  532. if (pData->options & PLUGIN_OPTION_SEND_ALL_SOUND_OFF)
  533. {
  534. for (k=0, i=MAX_MIDI_CHANNELS; k < MAX_MIDI_CHANNELS; ++k)
  535. {
  536. fMidiInputPort->DispatchControlChange(MIDI_CONTROL_ALL_NOTES_OFF, 0, k);
  537. fMidiInputPort->DispatchControlChange(MIDI_CONTROL_ALL_SOUND_OFF, 0, k);
  538. }
  539. }
  540. else if (pData->ctrlChannel >= 0 && pData->ctrlChannel < MAX_MIDI_CHANNELS)
  541. {
  542. for (uint8_t i=0; i < MAX_MIDI_NOTE; ++i)
  543. fMidiInputPort->DispatchNoteOff(i, 0, (uint)pData->ctrlChannel);
  544. }
  545. pData->needsReset = false;
  546. }
  547. // --------------------------------------------------------------------------------------------------------
  548. // Event Input and Processing
  549. {
  550. // ----------------------------------------------------------------------------------------------------
  551. // MIDI Input (External)
  552. if (pData->extNotes.mutex.tryLock())
  553. {
  554. while (! pData->extNotes.data.isEmpty())
  555. {
  556. const ExternalMidiNote& note(pData->extNotes.data.getFirst(true));
  557. CARLA_ASSERT(note.channel >= 0 && note.channel < MAX_MIDI_CHANNELS);
  558. if (note.velo > 0)
  559. fMidiInputPort->DispatchNoteOn(note.note, note.velo, note.channel, 0);
  560. else
  561. fMidiInputPort->DispatchNoteOff(note.note, note.velo, note.channel, 0);
  562. }
  563. pData->extNotes.mutex.unlock();
  564. } // End of MIDI Input (External)
  565. // ----------------------------------------------------------------------------------------------------
  566. // Event Input (System)
  567. bool allNotesOffSent = false;
  568. bool sampleAccurate = (pData->options & PLUGIN_OPTION_FIXED_BUFFERS) == 0;
  569. uint32_t time, nEvents = pData->event.portIn->getEventCount();
  570. uint32_t startTime = 0;
  571. uint32_t timeOffset = 0;
  572. uint32_t nextBankId = 0;
  573. if (pData->midiprog.current >= 0 && pData->midiprog.count > 0)
  574. nextBankId = pData->midiprog.data[pData->midiprog.current].bank;
  575. for (i=0; i < nEvents; ++i)
  576. {
  577. const EngineEvent& event(pData->event.portIn->getEvent(i));
  578. time = event.time;
  579. if (time >= frames)
  580. continue;
  581. CARLA_ASSERT_INT2(time >= timeOffset, time, timeOffset);
  582. if (time > timeOffset && sampleAccurate)
  583. {
  584. if (processSingle(outBuffer, time - timeOffset, timeOffset))
  585. {
  586. startTime = 0;
  587. timeOffset = time;
  588. if (pData->midiprog.current >= 0 && pData->midiprog.count > 0)
  589. nextBankId = pData->midiprog.data[pData->midiprog.current].bank;
  590. else
  591. nextBankId = 0;
  592. }
  593. else
  594. startTime += timeOffset;
  595. }
  596. // Control change
  597. switch (event.type)
  598. {
  599. case kEngineEventTypeNull:
  600. break;
  601. case kEngineEventTypeControl:
  602. {
  603. const EngineControlEvent& ctrlEvent = event.ctrl;
  604. switch (ctrlEvent.type)
  605. {
  606. case kEngineControlEventTypeNull:
  607. break;
  608. case kEngineControlEventTypeParameter:
  609. {
  610. #ifndef BUILD_BRIDGE
  611. // Control backend stuff
  612. if (event.channel == pData->ctrlChannel)
  613. {
  614. float value;
  615. if (MIDI_IS_CONTROL_BREATH_CONTROLLER(ctrlEvent.param) && (pData->hints & PLUGIN_CAN_DRYWET) != 0)
  616. {
  617. value = ctrlEvent.value;
  618. setDryWet(value, false, false);
  619. pData->postponeRtEvent(kPluginPostRtEventParameterChange, PARAMETER_DRYWET, 0, value);
  620. }
  621. if (MIDI_IS_CONTROL_CHANNEL_VOLUME(ctrlEvent.param) && (pData->hints & PLUGIN_CAN_VOLUME) != 0)
  622. {
  623. value = ctrlEvent.value*127.0f/100.0f;
  624. setVolume(value, false, false);
  625. pData->postponeRtEvent(kPluginPostRtEventParameterChange, PARAMETER_VOLUME, 0, value);
  626. }
  627. if (MIDI_IS_CONTROL_BALANCE(ctrlEvent.param) && (pData->hints & PLUGIN_CAN_BALANCE) != 0)
  628. {
  629. float left, right;
  630. value = ctrlEvent.value/0.5f - 1.0f;
  631. if (value < 0.0f)
  632. {
  633. left = -1.0f;
  634. right = (value*2.0f)+1.0f;
  635. }
  636. else if (value > 0.0f)
  637. {
  638. left = (value*2.0f)-1.0f;
  639. right = 1.0f;
  640. }
  641. else
  642. {
  643. left = -1.0f;
  644. right = 1.0f;
  645. }
  646. setBalanceLeft(left, false, false);
  647. setBalanceRight(right, false, false);
  648. pData->postponeRtEvent(kPluginPostRtEventParameterChange, PARAMETER_BALANCE_LEFT, 0, left);
  649. pData->postponeRtEvent(kPluginPostRtEventParameterChange, PARAMETER_BALANCE_RIGHT, 0, right);
  650. }
  651. }
  652. #endif
  653. // Control plugin parameters
  654. for (k=0; k < pData->param.count; ++k)
  655. {
  656. if (pData->param.data[k].midiChannel != event.channel)
  657. continue;
  658. if (pData->param.data[k].midiCC != ctrlEvent.param)
  659. continue;
  660. if (pData->param.data[k].hints != PARAMETER_INPUT)
  661. continue;
  662. if ((pData->param.data[k].hints & PARAMETER_IS_AUTOMABLE) == 0)
  663. continue;
  664. float value;
  665. if (pData->param.data[k].hints & PARAMETER_IS_BOOLEAN)
  666. {
  667. value = (ctrlEvent.value < 0.5f) ? pData->param.ranges[k].min : pData->param.ranges[k].max;
  668. }
  669. else
  670. {
  671. value = pData->param.ranges[k].getUnnormalizedValue(ctrlEvent.value);
  672. if (pData->param.data[k].hints & PARAMETER_IS_INTEGER)
  673. value = std::rint(value);
  674. }
  675. setParameterValue(k, value, false, false, false);
  676. pData->postponeRtEvent(kPluginPostRtEventParameterChange, static_cast<int32_t>(k), 0, value);
  677. }
  678. if ((pData->options & PLUGIN_OPTION_SEND_CONTROL_CHANGES) != 0 && ctrlEvent.param <= 0x5F)
  679. {
  680. fMidiInputPort->DispatchControlChange(uint8_t(ctrlEvent.param), uint8_t(ctrlEvent.value*127.0f), event.channel, int32_t(sampleAccurate ? startTime : time));
  681. }
  682. break;
  683. }
  684. case kEngineControlEventTypeMidiBank:
  685. if (event.channel == pData->ctrlChannel && (pData->options & PLUGIN_OPTION_MAP_PROGRAM_CHANGES) != 0)
  686. nextBankId = ctrlEvent.param;
  687. break;
  688. case kEngineControlEventTypeMidiProgram:
  689. if (event.channel == pData->ctrlChannel && (pData->options & PLUGIN_OPTION_MAP_PROGRAM_CHANGES) != 0)
  690. {
  691. const uint32_t nextProgramId = ctrlEvent.param;
  692. for (k=0; k < pData->midiprog.count; ++k)
  693. {
  694. if (pData->midiprog.data[k].bank == nextBankId && pData->midiprog.data[k].program == nextProgramId)
  695. {
  696. setMidiProgram(k, false, false, false);
  697. pData->postponeRtEvent(kPluginPostRtEventMidiProgramChange, k, 0, 0.0f);
  698. break;
  699. }
  700. }
  701. }
  702. break;
  703. case kEngineControlEventTypeAllSoundOff:
  704. if (pData->options & PLUGIN_OPTION_SEND_ALL_SOUND_OFF)
  705. {
  706. fMidiInputPort->DispatchControlChange(MIDI_CONTROL_ALL_SOUND_OFF, 0, event.channel, sampleAccurate ? startTime : time);
  707. }
  708. break;
  709. case kEngineControlEventTypeAllNotesOff:
  710. if (pData->options & PLUGIN_OPTION_SEND_ALL_SOUND_OFF)
  711. {
  712. if (event.channel == pData->ctrlChannel && ! allNotesOffSent)
  713. {
  714. allNotesOffSent = true;
  715. sendMidiAllNotesOffToCallback();
  716. }
  717. fMidiInputPort->DispatchControlChange(MIDI_CONTROL_ALL_NOTES_OFF, 0, event.channel, sampleAccurate ? startTime : time);
  718. }
  719. break;
  720. }
  721. break;
  722. }
  723. case kEngineEventTypeMidi:
  724. {
  725. const EngineMidiEvent& midiEvent(event.midi);
  726. uint8_t status = MIDI_GET_STATUS_FROM_DATA(midiEvent.data);
  727. uint8_t channel = event.channel;
  728. // Fix bad note-off (per DSSI spec)
  729. if (MIDI_IS_STATUS_NOTE_ON(status) && midiEvent.data[2] == 0)
  730. status = MIDI_STATUS_NOTE_OFF;
  731. int32_t fragmentPos = sampleAccurate ? startTime : time;
  732. if (MIDI_IS_STATUS_NOTE_OFF(status))
  733. {
  734. const uint8_t note = midiEvent.data[1];
  735. fMidiInputPort->DispatchNoteOff(note, 0, channel, fragmentPos);
  736. pData->postponeRtEvent(kPluginPostRtEventNoteOff, channel, note, 0.0f);
  737. }
  738. else if (MIDI_IS_STATUS_NOTE_ON(status))
  739. {
  740. const uint8_t note = midiEvent.data[1];
  741. const uint8_t velo = midiEvent.data[2];
  742. fMidiInputPort->DispatchNoteOn(note, velo, channel, fragmentPos);
  743. pData->postponeRtEvent(kPluginPostRtEventNoteOn, channel, note, velo);
  744. }
  745. else if (MIDI_IS_STATUS_POLYPHONIC_AFTERTOUCH(status) && (pData->options & PLUGIN_OPTION_SEND_NOTE_AFTERTOUCH) != 0)
  746. {
  747. //const uint8_t note = midiEvent.data[1];
  748. //const uint8_t pressure = midiEvent.data[2];
  749. // unsupported
  750. }
  751. else if (MIDI_IS_STATUS_CONTROL_CHANGE(status) && (pData->options & PLUGIN_OPTION_SEND_CONTROL_CHANGES) != 0)
  752. {
  753. const uint8_t control = midiEvent.data[1];
  754. const uint8_t value = midiEvent.data[2];
  755. fMidiInputPort->DispatchControlChange(control, value, channel, fragmentPos);
  756. }
  757. else if (MIDI_IS_STATUS_CHANNEL_PRESSURE(status) && (pData->options & PLUGIN_OPTION_SEND_CHANNEL_PRESSURE) != 0)
  758. {
  759. //const uint8_t pressure = midiEvent.data[1];
  760. // unsupported
  761. }
  762. else if (MIDI_IS_STATUS_PITCH_WHEEL_CONTROL(status) && (pData->options & PLUGIN_OPTION_SEND_PITCHBEND) != 0)
  763. {
  764. const uint8_t lsb = midiEvent.data[1];
  765. const uint8_t msb = midiEvent.data[2];
  766. fMidiInputPort->DispatchPitchbend(((msb << 7) | lsb) - 8192, channel, fragmentPos);
  767. }
  768. break;
  769. }
  770. }
  771. }
  772. pData->postRtEvents.trySplice();
  773. if (frames > timeOffset)
  774. processSingle(outBuffer, frames - timeOffset, timeOffset);
  775. } // End of Event Input and Processing
  776. }
  777. bool processSingle(float** const outBuffer, const uint32_t frames, const uint32_t timeOffset)
  778. {
  779. CARLA_ASSERT(outBuffer != nullptr);
  780. CARLA_ASSERT(frames > 0);
  781. if (outBuffer == nullptr)
  782. return false;
  783. if (frames == 0)
  784. return false;
  785. uint32_t i, k;
  786. // --------------------------------------------------------------------------------------------------------
  787. // Try lock, silence otherwise
  788. if (pData->engine->isOffline())
  789. {
  790. pData->singleMutex.lock();
  791. }
  792. else if (! pData->singleMutex.tryLock())
  793. {
  794. for (i=0; i < pData->audioOut.count; ++i)
  795. {
  796. for (k=0; k < frames; ++k)
  797. outBuffer[i][k+timeOffset] = 0.0f;
  798. }
  799. return false;
  800. }
  801. // --------------------------------------------------------------------------------------------------------
  802. // Run plugin
  803. if (fUses16Outs)
  804. {
  805. for (int i=0; i < 16; ++i)
  806. {
  807. if (fAudioOutputDevices[i] != nullptr)
  808. {
  809. fAudioOutputDevices[i]->Channel(0)->SetBuffer(outBuffer[i*2 ] + timeOffset);
  810. fAudioOutputDevices[i]->Channel(1)->SetBuffer(outBuffer[i*2+1] + timeOffset);
  811. fAudioOutputDevices[i]->Render(frames);
  812. }
  813. }
  814. }
  815. else
  816. {
  817. fAudioOutputDevices[0]->Channel(0)->SetBuffer(outBuffer[0] + timeOffset);
  818. fAudioOutputDevices[0]->Channel(1)->SetBuffer(outBuffer[1] + timeOffset);
  819. fAudioOutputDevices[0]->Render(frames);
  820. }
  821. #ifndef BUILD_BRIDGE
  822. // --------------------------------------------------------------------------------------------------------
  823. // Post-processing (dry/wet, volume and balance)
  824. {
  825. const bool doVolume = (pData->hints & PLUGIN_CAN_VOLUME) > 0 && pData->postProc.volume != 1.0f;
  826. const bool doBalance = (pData->hints & PLUGIN_CAN_BALANCE) > 0 && (pData->postProc.balanceLeft != -1.0f || pData->postProc.balanceRight != 1.0f);
  827. float oldBufLeft[doBalance ? frames : 1];
  828. for (i=0; i < pData->audioOut.count; ++i)
  829. {
  830. // Balance
  831. if (doBalance)
  832. {
  833. if (i % 2 == 0)
  834. FLOAT_COPY(oldBufLeft, outBuffer[i], frames);
  835. float balRangeL = (pData->postProc.balanceLeft + 1.0f)/2.0f;
  836. float balRangeR = (pData->postProc.balanceRight + 1.0f)/2.0f;
  837. for (k=0; k < frames; ++k)
  838. {
  839. if (i % 2 == 0)
  840. {
  841. // left
  842. outBuffer[i][k] = oldBufLeft[k] * (1.0f - balRangeL);
  843. outBuffer[i][k] += outBuffer[i+1][k] * (1.0f - balRangeR);
  844. }
  845. else
  846. {
  847. // right
  848. outBuffer[i][k] = outBuffer[i][k] * balRangeR;
  849. outBuffer[i][k] += oldBufLeft[k] * balRangeL;
  850. }
  851. }
  852. }
  853. // Volume
  854. if (doVolume)
  855. {
  856. for (k=0; k < frames; ++k)
  857. outBuffer[i][k+timeOffset] *= pData->postProc.volume;
  858. }
  859. }
  860. } // End of Post-processing
  861. #endif
  862. // --------------------------------------------------------------------------------------------------------
  863. pData->singleMutex.unlock();
  864. return true;
  865. }
  866. // -------------------------------------------------------------------
  867. // Plugin buffers
  868. // nothing
  869. // -------------------------------------------------------------------
  870. const void* getExtraStuff() const noexcept override
  871. {
  872. return fUses16Outs ? (const void*)0x1 : nullptr;
  873. }
  874. bool init(const char* filename, const char* const name, const char* label)
  875. {
  876. CARLA_SAFE_ASSERT_RETURN(pData->engine != nullptr, false);
  877. // ---------------------------------------------------------------
  878. // first checks
  879. if (pData->client != nullptr)
  880. {
  881. pData->engine->setLastError("Plugin client is already registered");
  882. return false;
  883. }
  884. if (filename == nullptr)
  885. {
  886. pData->engine->setLastError("null filename");
  887. return false;
  888. }
  889. if (label == nullptr)
  890. {
  891. pData->engine->setLastError("null label");
  892. return false;
  893. }
  894. // ---------------------------------------------------------------
  895. // Store format
  896. CarlaString cstype(fFormat);
  897. cstype.toLower();
  898. const char* const ctype(cstype.getBuffer());
  899. // ---------------------------------------------------------------
  900. // Create the LinuxSampler Engine
  901. try {
  902. fEngine = LinuxSampler::EngineFactory::Create(ctype);
  903. }
  904. catch (LinuxSampler::Exception& e)
  905. {
  906. pData->engine->setLastError(e.what());
  907. return false;
  908. }
  909. // ---------------------------------------------------------------
  910. // Init LinuxSampler stuff
  911. fMidiInputDevice = new LinuxSampler::MidiInputDevicePlugin(&fSampler);
  912. fMidiInputPort = fMidiInputDevice->CreateMidiPortPlugin();
  913. // always needs at least 1 output device
  914. fAudioOutputDevices[0] = new LinuxSampler::AudioOutputDevicePlugin(pData->engine, this);
  915. for (int i=0; i < 16; ++i)
  916. {
  917. fSamplerChannels[i] = fSampler.AddSamplerChannel();
  918. CARLA_SAFE_ASSERT_CONTINUE(fSamplerChannels[i] != nullptr);
  919. fEngineChannels[i] = fSamplerChannels[i]->GetEngineChannel();
  920. CARLA_SAFE_ASSERT_CONTINUE(fEngineChannels[i] != nullptr);
  921. LinuxSampler::AudioOutputDevicePlugin* outputDevice;
  922. if (fUses16Outs)
  923. {
  924. fAudioOutputDevices[i] = new LinuxSampler::AudioOutputDevicePlugin(pData->engine, this);
  925. outputDevice = fAudioOutputDevices[i];
  926. }
  927. else
  928. {
  929. outputDevice = fAudioOutputDevices[0];
  930. }
  931. fSamplerChannels[i]->SetEngineType(ctype);
  932. fSamplerChannels[i]->SetAudioOutputDevice(outputDevice);
  933. fEngineChannels[i]->Connect(outputDevice);
  934. fEngineChannels[i]->Volume(LinuxSampler::kVolumeMax);
  935. fMidiInputPort->Connect(fEngineChannels[i], static_cast<LinuxSampler::midi_chan_t>(i));
  936. }
  937. // ---------------------------------------------------------------
  938. // Get the Engine's Instrument Manager
  939. fInstrument = fEngine->GetInstrumentManager();
  940. if (fInstrument == nullptr)
  941. {
  942. pData->engine->setLastError("Failed to get LinuxSampler instrument manager");
  943. return false;
  944. }
  945. // ---------------------------------------------------------------
  946. // Load the Instrument via filename
  947. try {
  948. fInstrumentIds = fInstrument->GetInstrumentFileContent(filename);
  949. }
  950. catch (const LinuxSampler::InstrumentManagerException& e)
  951. {
  952. pData->engine->setLastError(e.what());
  953. return false;
  954. }
  955. // ---------------------------------------------------------------
  956. // Get info
  957. if (fInstrumentIds.size() == 0)
  958. {
  959. pData->engine->setLastError("Failed to find any instruments");
  960. return false;
  961. }
  962. LinuxSampler::InstrumentManager::instrument_info_t info;
  963. try {
  964. info = fInstrument->GetInstrumentInfo(fInstrumentIds[0]);
  965. }
  966. catch (const LinuxSampler::InstrumentManagerException& e)
  967. {
  968. pData->engine->setLastError(e.what());
  969. return false;
  970. }
  971. fRealName = info.InstrumentName.c_str();
  972. fLabel = info.Product.c_str();
  973. fMaker = info.Artists.c_str();
  974. pData->filename = carla_strdup(filename);
  975. if (fUses16Outs && ! fLabel.endsWith(" (16 outs)"))
  976. fLabel += " (16 outs)";
  977. if (name != nullptr)
  978. pData->name = pData->engine->getUniquePluginName(name);
  979. else
  980. pData->name = pData->engine->getUniquePluginName((const char*)fRealName);
  981. // ---------------------------------------------------------------
  982. // Register client
  983. pData->client = pData->engine->addClient(this);
  984. if (pData->client == nullptr || ! pData->client->isOk())
  985. {
  986. pData->engine->setLastError("Failed to register plugin client");
  987. LinuxSampler::EngineFactory::Destroy(fEngine);
  988. fInstrument = nullptr;
  989. fEngine = nullptr;
  990. return false;
  991. }
  992. // ---------------------------------------------------------------
  993. // load plugin settings
  994. {
  995. // set default options
  996. pData->options = 0x0;
  997. pData->options |= PLUGIN_OPTION_MAP_PROGRAM_CHANGES;
  998. pData->options |= PLUGIN_OPTION_SEND_PITCHBEND;
  999. pData->options |= PLUGIN_OPTION_SEND_ALL_SOUND_OFF;
  1000. // set identifier string
  1001. CarlaString identifier(fFormat);
  1002. identifier += "/";
  1003. if (const char* const shortname = std::strrchr(filename, OS_SEP))
  1004. identifier += shortname+1;
  1005. else
  1006. identifier += label;
  1007. pData->identifier = identifier.dup();
  1008. // load settings
  1009. pData->options = pData->loadSettings(pData->options, getOptionsAvailable());
  1010. }
  1011. return true;
  1012. }
  1013. // -------------------------------------------------------------------
  1014. private:
  1015. const char* fFormat;
  1016. const bool fUses16Outs;
  1017. int32_t fCurMidiProgs[16];
  1018. CarlaString fRealName;
  1019. CarlaString fLabel;
  1020. CarlaString fMaker;
  1021. LinuxSampler::Sampler fSampler;
  1022. LinuxSampler::Engine* fEngine;
  1023. LinuxSampler::SamplerChannel* fSamplerChannels[16];
  1024. LinuxSampler::EngineChannel* fEngineChannels[16];
  1025. LinuxSampler::AudioOutputDevicePlugin* fAudioOutputDevices[16];
  1026. LinuxSampler::MidiInputDevicePlugin* fMidiInputDevice;
  1027. LinuxSampler::MidiInputPortPlugin* fMidiInputPort;
  1028. LinuxSampler::InstrumentManager* fInstrument;
  1029. std::vector<LinuxSampler::InstrumentManager::instrument_id_t> fInstrumentIds;
  1030. CARLA_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(LinuxSamplerPlugin)
  1031. };
  1032. CARLA_BACKEND_END_NAMESPACE
  1033. #endif // WANT_LINUXSAMPLER
  1034. CARLA_BACKEND_START_NAMESPACE
  1035. CarlaPlugin* CarlaPlugin::newLinuxSampler(const Initializer& init, const char* const format, const bool /*use16Outs*/)
  1036. {
  1037. // TESTING
  1038. const bool use16Outs = true;
  1039. carla_debug("LinuxSamplerPlugin::newLinuxSampler({%p, \"%s\", \"%s\", \"%s\"}, %s, %s)", init.engine, init.filename, init.name, init.label, format, bool2str(use16Outs));
  1040. #ifdef WANT_LINUXSAMPLER
  1041. if (init.engine->getProccessMode() == ENGINE_PROCESS_MODE_CONTINUOUS_RACK && use16Outs)
  1042. {
  1043. init.engine->setLastError("Carla's rack mode can only work with Stereo modules, please choose the 2-channel only sample-library version");
  1044. return nullptr;
  1045. }
  1046. // -------------------------------------------------------------------
  1047. // Check if file exists
  1048. {
  1049. QFileInfo file(init.filename);
  1050. if (! file.exists())
  1051. {
  1052. init.engine->setLastError("Requested file does not exist");
  1053. return false;
  1054. }
  1055. if (! file.isFile())
  1056. {
  1057. init.engine->setLastError("Requested file is not valid");
  1058. return false;
  1059. }
  1060. if (! file.isReadable())
  1061. {
  1062. init.engine->setLastError("Requested file is not readable");
  1063. return false;
  1064. }
  1065. }
  1066. LinuxSamplerPlugin* const plugin(new LinuxSamplerPlugin(init.engine, init.id, format, use16Outs));
  1067. if (! plugin->init(init.filename, init.name, init.label))
  1068. {
  1069. delete plugin;
  1070. return nullptr;
  1071. }
  1072. plugin->reload();
  1073. return plugin;
  1074. #else
  1075. init.engine->setLastError("linuxsampler support not available");
  1076. return nullptr;
  1077. // unused
  1078. (void)format;
  1079. (void)use16Outs;
  1080. #endif
  1081. }
  1082. CARLA_BACKEND_END_NAMESPACE