Collection of tools useful for audio production
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.

647 lines
20KB

  1. /*
  2. * Carla Backend
  3. * Copyright (C) 2011-2012 Filipe Coelho <falktx@falktx.com>
  4. *
  5. * This program is free software; you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation; either version 2 of the License, or
  8. * 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 COPYING file
  16. */
  17. // TODO - setMidiProgram()
  18. #ifdef BUILD_BRIDGE
  19. # error Should not use linuxsampler for bridges!
  20. #endif
  21. #include "carla_plugin.h"
  22. #ifdef WANT_LINUXSAMPLER
  23. #include "carla_linuxsampler.h"
  24. #include <QtCore/QFileInfo>
  25. CARLA_BACKEND_START_NAMESPACE
  26. /*!
  27. * @defgroup CarlaBackendLinuxSamplerPlugin Carla Backend LinuxSampler Plugin
  28. *
  29. * The Carla Backend LinuxSampler Plugin.\n
  30. * http://www.linuxsampler.org/
  31. * @{
  32. */
  33. class LinuxSamplerPlugin : public CarlaPlugin
  34. {
  35. public:
  36. LinuxSamplerPlugin(CarlaEngine* const engine_, unsigned short id, bool isGIG) : CarlaPlugin(engine_, id)
  37. {
  38. qDebug("LinuxSamplerPlugin::LinuxSamplerPlugin()");
  39. m_type = isGIG ? PLUGIN_GIG : PLUGIN_SFZ;
  40. sampler = new LinuxSampler::Sampler;
  41. sampler_channel = nullptr;
  42. engine = nullptr;
  43. engine_channel = nullptr;
  44. instrument = nullptr;
  45. audioOutputDevice = new LinuxSampler::AudioOutputDevicePlugin(engine_, this);
  46. midiInputDevice = new LinuxSampler::MidiInputDevicePlugin(sampler);
  47. midiInputPort = midiInputDevice->CreateMidiPort();
  48. m_isGIG = isGIG;
  49. m_label = nullptr;
  50. m_maker = nullptr;
  51. }
  52. ~LinuxSamplerPlugin()
  53. {
  54. qDebug("LinuxSamplerPlugin::~LinuxSamplerPlugin()");
  55. if (sampler_channel)
  56. {
  57. midiInputPort->Disconnect(sampler_channel->GetEngineChannel());
  58. sampler->RemoveSamplerChannel(sampler_channel);
  59. }
  60. midiInputDevice->DeleteMidiPort(midiInputPort);
  61. delete audioOutputDevice;
  62. delete midiInputDevice;
  63. delete sampler;
  64. instrumentIds.clear();
  65. if (m_label)
  66. free((void*)m_label);
  67. if (m_maker)
  68. free((void*)m_maker);
  69. }
  70. // -------------------------------------------------------------------
  71. // Information (base)
  72. PluginCategory category()
  73. {
  74. return PLUGIN_CATEGORY_SYNTH;
  75. }
  76. // -------------------------------------------------------------------
  77. // Information (per-plugin data)
  78. void getLabel(char* const strBuf)
  79. {
  80. strncpy(strBuf, m_label, STR_MAX);
  81. }
  82. void getMaker(char* const strBuf)
  83. {
  84. strncpy(strBuf, m_maker, STR_MAX);
  85. }
  86. void getCopyright(char* const strBuf)
  87. {
  88. getMaker(strBuf);
  89. }
  90. void getRealName(char* const strBuf)
  91. {
  92. strncpy(strBuf, m_name, STR_MAX);
  93. }
  94. // -------------------------------------------------------------------
  95. // Plugin state
  96. void reload()
  97. {
  98. qDebug("LinuxSamplerPlugin::reload() - start");
  99. Q_ASSERT(instrument);
  100. // Safely disable plugin for reload
  101. const ScopedDisabler m(this);
  102. if (x_client->isActive())
  103. x_client->deactivate();
  104. // Remove client ports
  105. removeClientPorts();
  106. // Delete old data
  107. deleteBuffers();
  108. uint32_t aOuts;
  109. aOuts = 2;
  110. aOut.ports = new CarlaEngineAudioPort*[aOuts];
  111. aOut.rindexes = new uint32_t[aOuts];
  112. const int portNameSize = CarlaEngine::maxPortNameSize() - 1;
  113. char portName[portNameSize];
  114. // ---------------------------------------
  115. // Audio Outputs
  116. #ifndef BUILD_BRIDGE
  117. if (carlaOptions.processMode != PROCESS_MODE_MULTIPLE_CLIENTS)
  118. {
  119. strcpy(portName, m_name);
  120. strcat(portName, ":out-left");
  121. }
  122. else
  123. #endif
  124. strcpy(portName, "out-left");
  125. aOut.ports[0] = (CarlaEngineAudioPort*)x_client->addPort(CarlaEnginePortTypeAudio, portName, false);
  126. aOut.rindexes[0] = 0;
  127. #ifndef BUILD_BRIDGE
  128. if (carlaOptions.processMode != PROCESS_MODE_MULTIPLE_CLIENTS)
  129. {
  130. strcpy(portName, m_name);
  131. strcat(portName, ":out-right");
  132. }
  133. else
  134. #endif
  135. strcpy(portName, "out-right");
  136. aOut.ports[1] = (CarlaEngineAudioPort*)x_client->addPort(CarlaEnginePortTypeAudio, portName, false);
  137. aOut.rindexes[1] = 1;
  138. // ---------------------------------------
  139. // MIDI Input
  140. #ifndef BUILD_BRIDGE
  141. if (carlaOptions.processMode != PROCESS_MODE_MULTIPLE_CLIENTS)
  142. {
  143. strcpy(portName, m_name);
  144. strcat(portName, ":midi-in");
  145. }
  146. else
  147. #endif
  148. strcpy(portName, "midi-in");
  149. midi.portMin = (CarlaEngineMidiPort*)x_client->addPort(CarlaEnginePortTypeMIDI, portName, true);
  150. // ---------------------------------------
  151. aOut.count = aOuts;
  152. // plugin checks
  153. m_hints &= ~(PLUGIN_IS_SYNTH | PLUGIN_USES_CHUNKS | PLUGIN_CAN_DRYWET | PLUGIN_CAN_VOLUME | PLUGIN_CAN_BALANCE);
  154. m_hints |= PLUGIN_IS_SYNTH;
  155. m_hints |= PLUGIN_CAN_VOLUME;
  156. m_hints |= PLUGIN_CAN_BALANCE;
  157. reloadPrograms(true);
  158. x_client->activate();
  159. qDebug("LinuxSamplerPlugin::reload() - end");
  160. }
  161. void reloadPrograms(bool init)
  162. {
  163. qDebug("LinuxSamplerPlugin::reloadPrograms(%s)", bool2str(init));
  164. // Delete old programs
  165. if (midiprog.count > 0)
  166. {
  167. for (uint32_t i=0; i < midiprog.count; i++)
  168. free((void*)midiprog.data[i].name);
  169. delete[] midiprog.data;
  170. }
  171. midiprog.count = 0;
  172. midiprog.data = nullptr;
  173. // Query new programs
  174. uint32_t i = 0;
  175. midiprog.count += instrumentIds.size();
  176. // sound kits must always have at least 1 midi-program
  177. Q_ASSERT(midiprog.count > 0);
  178. if (midiprog.count > 0)
  179. midiprog.data = new midi_program_t [midiprog.count];
  180. // Update data
  181. for (i=0; i < midiprog.count; i++)
  182. {
  183. LinuxSampler::InstrumentManager::instrument_info_t info = instrument->GetInstrumentInfo(instrumentIds[i]);
  184. // FIXME - use % 128 stuff
  185. midiprog.data[i].bank = 0;
  186. midiprog.data[i].program = i;
  187. midiprog.data[i].name = strdup(info.InstrumentName.c_str());
  188. }
  189. #ifndef BUILD_BRIDGE
  190. // Update OSC Names
  191. if (x_engine->isOscControllerRegisted())
  192. {
  193. x_engine->osc_send_control_set_midi_program_count(m_id, midiprog.count);
  194. for (i=0; i < midiprog.count; i++)
  195. x_engine->osc_send_control_set_midi_program_data(m_id, i, midiprog.data[i].bank, midiprog.data[i].program, midiprog.data[i].name);
  196. }
  197. #endif
  198. if (init)
  199. {
  200. if (midiprog.count > 0)
  201. setMidiProgram(0, false, false, false, true);
  202. }
  203. else
  204. {
  205. x_engine->callback(CALLBACK_RELOAD_PROGRAMS, m_id, 0, 0, 0.0);
  206. }
  207. }
  208. // -------------------------------------------------------------------
  209. // Plugin processing
  210. void process(float** const, float** const outBuffer, const uint32_t frames, const uint32_t framesOffset)
  211. {
  212. uint32_t i, k;
  213. uint32_t midiEventCount = 0;
  214. double aOutsPeak[2] = { 0.0 };
  215. CARLA_PROCESS_CONTINUE_CHECK;
  216. // --------------------------------------------------------------------------------------------------------
  217. // MIDI Input
  218. if (m_active && m_activeBefore)
  219. {
  220. // ----------------------------------------------------------------------------------------------------
  221. // MIDI Input (External)
  222. {
  223. engineMidiLock();
  224. for (i=0; i < MAX_MIDI_EVENTS && midiEventCount < MAX_MIDI_EVENTS; i++)
  225. {
  226. if (extMidiNotes[i].channel < 0)
  227. break;
  228. if (extMidiNotes[i].velo)
  229. midiInputPort->DispatchNoteOn(extMidiNotes[i].note, extMidiNotes[i].velo, m_ctrlInChannel, 0);
  230. else
  231. midiInputPort->DispatchNoteOff(extMidiNotes[i].note, extMidiNotes[i].velo, m_ctrlInChannel, 0);
  232. extMidiNotes[i].channel = -1; // mark as invalid
  233. midiEventCount += 1;
  234. }
  235. engineMidiUnlock();
  236. } // End of MIDI Input (External)
  237. CARLA_PROCESS_CONTINUE_CHECK;
  238. // ----------------------------------------------------------------------------------------------------
  239. // MIDI Input (System)
  240. {
  241. const CarlaEngineMidiEvent* minEvent;
  242. uint32_t time, nEvents = midi.portMin->getEventCount();
  243. for (i=0; i < nEvents && midiEventCount < MAX_MIDI_EVENTS; i++)
  244. {
  245. minEvent = midi.portMin->getEvent(i);
  246. if (! minEvent)
  247. continue;
  248. time = minEvent->time - framesOffset;
  249. if (time >= frames)
  250. continue;
  251. uint8_t status = minEvent->data[0];
  252. uint8_t channel = status & 0x0F;
  253. // Fix bad note-off
  254. if (MIDI_IS_STATUS_NOTE_ON(status) && minEvent->data[2] == 0)
  255. status -= 0x10;
  256. if (MIDI_IS_STATUS_NOTE_OFF(status))
  257. {
  258. uint8_t note = minEvent->data[1];
  259. midiInputPort->DispatchNoteOff(note, 0, channel, time);
  260. postponeEvent(PluginPostEventNoteOff, channel, note, 0.0);
  261. }
  262. else if (MIDI_IS_STATUS_NOTE_ON(status))
  263. {
  264. uint8_t note = minEvent->data[1];
  265. uint8_t velo = minEvent->data[2];
  266. midiInputPort->DispatchNoteOn(note, velo, channel, time);
  267. postponeEvent(PluginPostEventNoteOn, channel, note, velo);
  268. }
  269. else if (MIDI_IS_STATUS_POLYPHONIC_AFTERTOUCH(status))
  270. {
  271. //uint8_t note = minEvent->data[1];
  272. //uint8_t pressure = minEvent->data[2];
  273. // TODO, not in linuxsampler API?
  274. }
  275. else if (MIDI_IS_STATUS_AFTERTOUCH(status))
  276. {
  277. uint8_t pressure = minEvent->data[1];
  278. midiInputPort->DispatchControlChange(MIDI_STATUS_AFTERTOUCH, pressure, channel, time);
  279. }
  280. else if (MIDI_IS_STATUS_PITCH_WHEEL_CONTROL(status))
  281. {
  282. uint8_t lsb = minEvent->data[1];
  283. uint8_t msb = minEvent->data[2];
  284. midiInputPort->DispatchPitchbend(((msb << 7) | lsb) - 8192, channel, time);
  285. }
  286. else
  287. continue;
  288. midiEventCount += 1;
  289. }
  290. } // End of MIDI Input (System)
  291. } // End of MIDI Input
  292. CARLA_PROCESS_CONTINUE_CHECK;
  293. // --------------------------------------------------------------------------------------------------------
  294. // Plugin processing
  295. if (m_active)
  296. {
  297. if (! m_activeBefore)
  298. {
  299. if (m_ctrlInChannel >= 0 && m_ctrlInChannel < 16)
  300. {
  301. midiInputPort->DispatchControlChange(MIDI_CONTROL_ALL_SOUND_OFF, 0, m_ctrlInChannel);
  302. midiInputPort->DispatchControlChange(MIDI_CONTROL_ALL_NOTES_OFF, 0, m_ctrlInChannel);
  303. }
  304. }
  305. audioOutputDevice->Channel(0)->SetBuffer(outBuffer[0]);
  306. audioOutputDevice->Channel(1)->SetBuffer(outBuffer[1]);
  307. // QUESTION: Need to clear it before?
  308. audioOutputDevice->Render(frames);
  309. }
  310. CARLA_PROCESS_CONTINUE_CHECK;
  311. // --------------------------------------------------------------------------------------------------------
  312. // Post-processing (dry/wet, volume and balance)
  313. if (m_active)
  314. {
  315. bool do_volume = x_volume != 1.0;
  316. bool do_balance = (x_balanceLeft != -1.0 || x_balanceRight != 1.0);
  317. double bal_rangeL, bal_rangeR;
  318. float oldBufLeft[do_balance ? frames : 0];
  319. for (i=0; i < aOut.count; i++)
  320. {
  321. // Balance
  322. if (do_balance)
  323. {
  324. if (i%2 == 0)
  325. memcpy(&oldBufLeft, outBuffer[i], sizeof(float)*frames);
  326. bal_rangeL = (x_balanceLeft+1.0)/2;
  327. bal_rangeR = (x_balanceRight+1.0)/2;
  328. for (k=0; k < frames; k++)
  329. {
  330. if (i%2 == 0)
  331. {
  332. // left output
  333. outBuffer[i][k] = oldBufLeft[k]*(1.0-bal_rangeL);
  334. outBuffer[i][k] += outBuffer[i+1][k]*(1.0-bal_rangeR);
  335. }
  336. else
  337. {
  338. // right
  339. outBuffer[i][k] = outBuffer[i][k]*bal_rangeR;
  340. outBuffer[i][k] += oldBufLeft[k]*bal_rangeL;
  341. }
  342. }
  343. }
  344. // Volume
  345. if (do_volume)
  346. {
  347. for (k=0; k < frames; k++)
  348. outBuffer[i][k] *= x_volume;
  349. }
  350. // Output VU
  351. for (k=0; i < 2 && k < frames; k++)
  352. {
  353. if (abs(outBuffer[i][k]) > aOutsPeak[i])
  354. aOutsPeak[i] = abs(outBuffer[i][k]);
  355. }
  356. }
  357. }
  358. else
  359. {
  360. // disable any output sound if not active
  361. for (i=0; i < aOut.count; i++)
  362. memset(outBuffer[i], 0.0f, sizeof(float)*frames);
  363. aOutsPeak[0] = 0.0;
  364. aOutsPeak[1] = 0.0;
  365. } // End of Post-processing
  366. CARLA_PROCESS_CONTINUE_CHECK;
  367. // --------------------------------------------------------------------------------------------------------
  368. // Peak Values
  369. x_engine->setOutputPeak(m_id, 0, aOutsPeak[0]);
  370. x_engine->setOutputPeak(m_id, 1, aOutsPeak[1]);
  371. m_activeBefore = m_active;
  372. }
  373. // -------------------------------------------------------------------
  374. bool init(const char* filename, const char* const name, const char* label)
  375. {
  376. QFileInfo file(filename);
  377. if (file.exists() && file.isFile() && file.isReadable())
  378. {
  379. const char* stype = m_isGIG ? "gig" : "sfz";
  380. try {
  381. engine = LinuxSampler::EngineFactory::Create(stype);
  382. }
  383. catch (LinuxSampler::Exception& e)
  384. {
  385. setLastError(e.what());
  386. return false;
  387. }
  388. try {
  389. instrument = engine->GetInstrumentManager();
  390. }
  391. catch (LinuxSampler::Exception& e)
  392. {
  393. setLastError(e.what());
  394. return false;
  395. }
  396. try {
  397. instrumentIds = instrument->GetInstrumentFileContent(filename);
  398. }
  399. catch (LinuxSampler::Exception& e)
  400. {
  401. setLastError(e.what());
  402. return false;
  403. }
  404. if (instrumentIds.size() > 0)
  405. {
  406. LinuxSampler::InstrumentManager::instrument_info_t info = instrument->GetInstrumentInfo(instrumentIds[0]);
  407. m_label = strdup(info.Product.c_str());
  408. m_maker = strdup(info.Artists.c_str());
  409. m_filename = strdup(filename);
  410. if (name)
  411. m_name = x_engine->getUniqueName(name);
  412. else
  413. m_name = x_engine->getUniqueName(label && label[0] ? label : info.InstrumentName.c_str());
  414. sampler_channel = sampler->AddSamplerChannel();
  415. sampler_channel->SetEngineType(stype);
  416. sampler_channel->SetAudioOutputDevice(audioOutputDevice);
  417. //sampler_channel->SetMidiInputDevice(midiInputDevice);
  418. //sampler_channel->SetMidiInputChannel(LinuxSampler::midi_chan_1);
  419. midiInputPort->Connect(sampler_channel->GetEngineChannel(), LinuxSampler::midi_chan_all);
  420. engine_channel = sampler_channel->GetEngineChannel();
  421. engine_channel->Connect(audioOutputDevice);
  422. engine_channel->PrepareLoadInstrument(filename, 0); // todo - find instrument from label
  423. engine_channel->LoadInstrument();
  424. engine_channel->Volume(LinuxSampler::VOLUME_MAX);
  425. x_client = x_engine->addClient(this);
  426. if (x_client->isOk())
  427. return true;
  428. else
  429. setLastError("Failed to register plugin client");
  430. }
  431. else
  432. setLastError("Failed to find any instruments");
  433. }
  434. else
  435. setLastError("Requested file is not valid or does not exist");
  436. return false;
  437. }
  438. // -------------------------------------------------------------------
  439. static CarlaPlugin* newLinuxSampler(const initializer& init, bool isGIG);
  440. private:
  441. LinuxSampler::Sampler* sampler;
  442. LinuxSampler::SamplerChannel* sampler_channel;
  443. LinuxSampler::Engine* engine;
  444. LinuxSampler::EngineChannel* engine_channel;
  445. LinuxSampler::InstrumentManager* instrument;
  446. std::vector<LinuxSampler::InstrumentManager::instrument_id_t> instrumentIds;
  447. LinuxSampler::AudioOutputDevicePlugin* audioOutputDevice;
  448. LinuxSampler::MidiInputDevicePlugin* midiInputDevice;
  449. LinuxSampler::MidiInputPort* midiInputPort;
  450. bool m_isGIG;
  451. const char* m_label;
  452. const char* m_maker;
  453. };
  454. CarlaPlugin* LinuxSamplerPlugin::newLinuxSampler(const initializer& init, bool isGIG)
  455. {
  456. qDebug("LinuxSamplerPlugin::newLinuxSampler(%p, \"%s\", \"%s\", \"%s\", %s)", init.engine, init.filename, init.name, init.label, bool2str(isGIG));
  457. short id = init.engine->getNewPluginId();
  458. if (id < 0 || id > CarlaEngine::maxPluginNumber())
  459. {
  460. setLastError("Maximum number of plugins reached");
  461. return nullptr;
  462. }
  463. LinuxSamplerPlugin* const plugin = new LinuxSamplerPlugin(init.engine, id, isGIG);
  464. if (! plugin->init(init.filename, init.name, init.label))
  465. {
  466. delete plugin;
  467. return nullptr;
  468. }
  469. plugin->reload();
  470. plugin->registerToOsc();
  471. return plugin;
  472. }
  473. /**@}*/
  474. CARLA_BACKEND_END_NAMESPACE
  475. #else // WANT_LINUXSAMPLER
  476. # warning linuxsampler not available (no GIG and SFZ support)
  477. #endif
  478. CARLA_BACKEND_START_NAMESPACE
  479. CarlaPlugin* CarlaPlugin::newGIG(const initializer& init)
  480. {
  481. qDebug("CarlaPlugin::newGIG(%p, \"%s\", \"%s\", \"%s\")", init.engine, init.filename, init.name, init.label);
  482. #ifdef WANT_LINUXSAMPLER
  483. return LinuxSamplerPlugin::newLinuxSampler(init, true);
  484. #else
  485. setLastError("linuxsampler support not available");
  486. return nullptr;
  487. #endif
  488. }
  489. CarlaPlugin* CarlaPlugin::newSFZ(const initializer& init)
  490. {
  491. qDebug("CarlaPlugin::newSFZ(%p, \"%s\", \"%s\", \"%s\")", init.engine, init.filename, init.name, init.label);
  492. #ifdef WANT_LINUXSAMPLER
  493. return LinuxSamplerPlugin::newLinuxSampler(init, false);
  494. #else
  495. setLastError("linuxsampler support not available");
  496. return nullptr;
  497. #endif
  498. }
  499. CARLA_BACKEND_END_NAMESPACE