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.

630 lines
19KB

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