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.

LinuxSamplerPlugin.cpp 39KB

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