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.

627 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. //osc_global_send_set_midi_program_count(m_id, midiprog.count);
  196. //for (i=0; i < midiprog.count; i++)
  197. // osc_global_send_set_midi_program_data(m_id, i, midiprog.data[i].bank, midiprog.data[i].program, midiprog.data[i].name);
  198. x_engine->callback(CALLBACK_RELOAD_PROGRAMS, m_id, 0, 0, 0.0);
  199. #endif
  200. if (init)
  201. {
  202. if (midiprog.count > 0)
  203. setMidiProgram(0, false, false, false, true);
  204. }
  205. }
  206. // -------------------------------------------------------------------
  207. // Plugin processing
  208. void process(float** const, float** const outBuffer, const uint32_t frames, const uint32_t framesOffset)
  209. {
  210. uint32_t i, k;
  211. uint32_t midiEventCount = 0;
  212. double aouts_peak_tmp[2] = { 0.0 };
  213. CARLA_PROCESS_CONTINUE_CHECK;
  214. // --------------------------------------------------------------------------------------------------------
  215. // MIDI Input (External)
  216. if (m_ctrlInChannel >= 0 && m_ctrlInChannel < 16 && m_active && m_activeBefore)
  217. {
  218. engineMidiLock();
  219. for (i=0; i < MAX_MIDI_EVENTS && midiEventCount < MAX_MIDI_EVENTS; i++)
  220. {
  221. if (extMidiNotes[i].channel < 0)
  222. break;
  223. if (extMidiNotes[i].velo)
  224. midiInputPort->DispatchNoteOn(extMidiNotes[i].note, extMidiNotes[i].velo, m_ctrlInChannel, 0);
  225. else
  226. midiInputPort->DispatchNoteOff(extMidiNotes[i].note, extMidiNotes[i].velo, m_ctrlInChannel, 0);
  227. extMidiNotes[i].channel = -1;
  228. midiEventCount += 1;
  229. }
  230. engineMidiUnlock();
  231. } // End of MIDI Input (External)
  232. CARLA_PROCESS_CONTINUE_CHECK;
  233. // --------------------------------------------------------------------------------------------------------
  234. // MIDI Input (System)
  235. if (m_active && m_activeBefore)
  236. {
  237. const CarlaEngineMidiEvent* minEvent;
  238. uint32_t time, nEvents = midi.portMin->getEventCount();
  239. for (i=0; i < nEvents && midiEventCount < MAX_MIDI_EVENTS; i++)
  240. {
  241. minEvent = midi.portMin->getEvent(i);
  242. if (! minEvent)
  243. continue;
  244. time = minEvent->time - framesOffset;
  245. if (time >= frames)
  246. continue;
  247. uint8_t status = minEvent->data[0];
  248. uint8_t channel = status & 0x0F;
  249. // Fix bad note-off
  250. if (MIDI_IS_STATUS_NOTE_ON(status) && minEvent->data[2] == 0)
  251. status -= 0x10;
  252. if (MIDI_IS_STATUS_NOTE_OFF(status))
  253. {
  254. uint8_t note = minEvent->data[1];
  255. midiInputPort->DispatchNoteOff(note, 0, channel, time);
  256. postponeEvent(PluginPostEventNoteOff, channel, note, 0.0);
  257. }
  258. else if (MIDI_IS_STATUS_NOTE_ON(status))
  259. {
  260. uint8_t note = minEvent->data[1];
  261. uint8_t velo = minEvent->data[2];
  262. midiInputPort->DispatchNoteOn(note, velo, channel, time);
  263. postponeEvent(PluginPostEventNoteOn, channel, note, velo);
  264. }
  265. else if (MIDI_IS_STATUS_AFTERTOUCH(status))
  266. {
  267. uint8_t pressure = minEvent->data[1];
  268. midiInputPort->DispatchControlChange(MIDI_STATUS_AFTERTOUCH, pressure, channel, time);
  269. }
  270. else if (MIDI_IS_STATUS_PITCH_WHEEL_CONTROL(status))
  271. {
  272. uint8_t lsb = minEvent->data[1];
  273. uint8_t msb = minEvent->data[2];
  274. midiInputPort->DispatchPitchbend(((msb << 7) | lsb) - 8192, channel, time);
  275. }
  276. else
  277. continue;
  278. midiEventCount += 1;
  279. }
  280. } // End of MIDI Input (System)
  281. CARLA_PROCESS_CONTINUE_CHECK;
  282. // --------------------------------------------------------------------------------------------------------
  283. // Plugin processing
  284. if (m_active)
  285. {
  286. if (! m_activeBefore)
  287. {
  288. if (m_ctrlInChannel >= 0 && m_ctrlInChannel < 16)
  289. {
  290. midiInputPort->DispatchControlChange(MIDI_CONTROL_ALL_SOUND_OFF, 0, m_ctrlInChannel);
  291. midiInputPort->DispatchControlChange(MIDI_CONTROL_ALL_NOTES_OFF, 0, m_ctrlInChannel);
  292. }
  293. }
  294. audioOutputDevice->Channel(0)->SetBuffer(outBuffer[0]);
  295. audioOutputDevice->Channel(1)->SetBuffer(outBuffer[1]);
  296. // QUESTION: Need to clear it before?
  297. audioOutputDevice->Render(frames);
  298. }
  299. CARLA_PROCESS_CONTINUE_CHECK;
  300. // --------------------------------------------------------------------------------------------------------
  301. // Post-processing (dry/wet, volume and balance)
  302. if (m_active)
  303. {
  304. bool do_volume = x_volume != 1.0;
  305. bool do_balance = (x_balanceLeft != -1.0 || x_balanceRight != 1.0);
  306. double bal_rangeL, bal_rangeR;
  307. float oldBufLeft[do_balance ? frames : 0];
  308. for (i=0; i < aOut.count; i++)
  309. {
  310. // Balance
  311. if (do_balance)
  312. {
  313. if (i%2 == 0)
  314. memcpy(&oldBufLeft, outBuffer[i], sizeof(float)*frames);
  315. bal_rangeL = (x_balanceLeft+1.0)/2;
  316. bal_rangeR = (x_balanceRight+1.0)/2;
  317. for (k=0; k < frames; k++)
  318. {
  319. if (i%2 == 0)
  320. {
  321. // left output
  322. outBuffer[i][k] = oldBufLeft[k]*(1.0-bal_rangeL);
  323. outBuffer[i][k] += outBuffer[i+1][k]*(1.0-bal_rangeR);
  324. }
  325. else
  326. {
  327. // right
  328. outBuffer[i][k] = outBuffer[i][k]*bal_rangeR;
  329. outBuffer[i][k] += oldBufLeft[k]*bal_rangeL;
  330. }
  331. }
  332. }
  333. // Volume
  334. if (do_volume)
  335. {
  336. for (k=0; k < frames; k++)
  337. outBuffer[i][k] *= x_volume;
  338. }
  339. // Output VU
  340. for (k=0; i < 2 && k < frames; k++)
  341. {
  342. if (abs(outBuffer[i][k]) > aouts_peak_tmp[i])
  343. aouts_peak_tmp[i] = abs(outBuffer[i][k]);
  344. }
  345. }
  346. }
  347. else
  348. {
  349. // disable any output sound if not active
  350. for (i=0; i < aOut.count; i++)
  351. memset(outBuffer[i], 0.0f, sizeof(float)*frames);
  352. aouts_peak_tmp[0] = 0.0;
  353. aouts_peak_tmp[1] = 0.0;
  354. } // End of Post-processing
  355. CARLA_PROCESS_CONTINUE_CHECK;
  356. // --------------------------------------------------------------------------------------------------------
  357. // Peak Values
  358. x_engine->setOutputPeak(m_id, 0, aouts_peak_tmp[0]);
  359. x_engine->setOutputPeak(m_id, 1, aouts_peak_tmp[1]);
  360. m_activeBefore = m_active;
  361. }
  362. // -------------------------------------------------------------------
  363. bool init(const char* filename, const char* const name, const char* label)
  364. {
  365. QFileInfo file(filename);
  366. if (file.exists() && file.isFile() && file.isReadable())
  367. {
  368. const char* stype = m_isGIG ? "gig" : "sfz";
  369. try {
  370. engine = LinuxSampler::EngineFactory::Create(stype);
  371. }
  372. catch (LinuxSampler::Exception& e)
  373. {
  374. setLastError(e.what());
  375. return false;
  376. }
  377. try {
  378. instrument = engine->GetInstrumentManager();
  379. }
  380. catch (LinuxSampler::Exception& e)
  381. {
  382. setLastError(e.what());
  383. return false;
  384. }
  385. try {
  386. instrumentIds = instrument->GetInstrumentFileContent(filename);
  387. }
  388. catch (LinuxSampler::Exception& e)
  389. {
  390. setLastError(e.what());
  391. return false;
  392. }
  393. if (instrumentIds.size() > 0)
  394. {
  395. LinuxSampler::InstrumentManager::instrument_info_t info = instrument->GetInstrumentInfo(instrumentIds[0]);
  396. m_label = strdup(info.Product.c_str());
  397. m_maker = strdup(info.Artists.c_str());
  398. m_filename = strdup(filename);
  399. if (name)
  400. m_name = x_engine->getUniqueName(name);
  401. else
  402. m_name = x_engine->getUniqueName(label && label[0] ? label : info.InstrumentName.c_str());
  403. sampler_channel = sampler->AddSamplerChannel();
  404. sampler_channel->SetEngineType(stype);
  405. sampler_channel->SetAudioOutputDevice(audioOutputDevice);
  406. //sampler_channel->SetMidiInputDevice(midiInputDevice);
  407. //sampler_channel->SetMidiInputChannel(LinuxSampler::midi_chan_1);
  408. midiInputPort->Connect(sampler_channel->GetEngineChannel(), LinuxSampler::midi_chan_all);
  409. engine_channel = sampler_channel->GetEngineChannel();
  410. engine_channel->Connect(audioOutputDevice);
  411. engine_channel->PrepareLoadInstrument(filename, 0); // todo - find instrument from label
  412. engine_channel->LoadInstrument();
  413. engine_channel->Volume(LinuxSampler::VOLUME_MAX);
  414. x_client = x_engine->addClient(this);
  415. if (x_client->isOk())
  416. return true;
  417. else
  418. setLastError("Failed to register plugin client");
  419. }
  420. else
  421. setLastError("Failed to find any instruments");
  422. }
  423. else
  424. setLastError("Requested file is not valid or does not exist");
  425. return false;
  426. }
  427. // -------------------------------------------------------------------
  428. static CarlaPlugin* newLinuxSampler(const initializer& init, bool isGIG);
  429. private:
  430. LinuxSampler::Sampler* sampler;
  431. LinuxSampler::SamplerChannel* sampler_channel;
  432. LinuxSampler::Engine* engine;
  433. LinuxSampler::EngineChannel* engine_channel;
  434. LinuxSampler::InstrumentManager* instrument;
  435. std::vector<LinuxSampler::InstrumentManager::instrument_id_t> instrumentIds;
  436. LinuxSampler::AudioOutputDevicePlugin* audioOutputDevice;
  437. LinuxSampler::MidiInputDevicePlugin* midiInputDevice;
  438. LinuxSampler::MidiInputPort* midiInputPort;
  439. bool m_isGIG;
  440. const char* m_label;
  441. const char* m_maker;
  442. };
  443. CarlaPlugin* LinuxSamplerPlugin::newLinuxSampler(const initializer& init, bool isGIG)
  444. {
  445. qDebug("LinuxSamplerPlugin::newLinuxSampler(%p, \"%s\", \"%s\", \"%s\", %s)", init.engine, init.filename, init.name, init.label, bool2str(isGIG));
  446. short id = init.engine->getNewPluginId();
  447. if (id < 0 || id > MAX_PLUGINS)
  448. {
  449. setLastError("Maximum number of plugins reached");
  450. return nullptr;
  451. }
  452. LinuxSamplerPlugin* const plugin = new LinuxSamplerPlugin(init.engine, id, isGIG);
  453. if (! plugin->init(init.filename, init.name, init.label))
  454. {
  455. delete plugin;
  456. return nullptr;
  457. }
  458. plugin->reload();
  459. plugin->registerToOsc();
  460. return plugin;
  461. }
  462. #endif // WANT_LINUXSAMPLER
  463. CarlaPlugin* CarlaPlugin::newGIG(const initializer& init)
  464. {
  465. qDebug("CarlaPlugin::newGIG(%p, \"%s\", \"%s\", \"%s\")", init.engine, init.filename, init.name, init.label);
  466. #ifdef WANT_LINUXSAMPLER
  467. return LinuxSamplerPlugin::newLinuxSampler(init, true);
  468. #else
  469. setLastError("linuxsampler support not available");
  470. return nullptr;
  471. #endif
  472. }
  473. CarlaPlugin* CarlaPlugin::newSFZ(const initializer& init)
  474. {
  475. qDebug("CarlaPlugin::newSFZ(%p, \"%s\", \"%s\", \"%s\")", init.engine, init.filename, init.name, init.label);
  476. #ifdef WANT_LINUXSAMPLER
  477. return LinuxSamplerPlugin::newLinuxSampler(init, false);
  478. #else
  479. setLastError("linuxsampler support not available");
  480. return nullptr;
  481. #endif
  482. }
  483. /**@}*/
  484. CARLA_BACKEND_END_NAMESPACE