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.

628 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. // Safely disable plugin for reload
  107. const ScopedDisabler m(this);
  108. if (x_client->isActive())
  109. x_client->deactivate();
  110. // Remove client ports
  111. removeClientPorts();
  112. // Delete old data
  113. deleteBuffers();
  114. uint32_t aouts;
  115. aouts = 2;
  116. aout.ports = new CarlaEngineAudioPort*[aouts];
  117. aout.rindexes = new uint32_t[aouts];
  118. char portName[STR_MAX];
  119. // ---------------------------------------
  120. // Audio Outputs
  121. #ifndef BUILD_BRIDGE
  122. if (carlaOptions.process_mode != PROCESS_MODE_MULTIPLE_CLIENTS)
  123. {
  124. strcpy(portName, m_name);
  125. strcat(portName, ":out-left");
  126. }
  127. else
  128. #endif
  129. strcpy(portName, "out-left");
  130. aout.ports[0] = (CarlaEngineAudioPort*)x_client->addPort(CarlaEnginePortTypeAudio, portName, false);
  131. aout.rindexes[0] = 0;
  132. #ifndef BUILD_BRIDGE
  133. if (carlaOptions.process_mode != PROCESS_MODE_MULTIPLE_CLIENTS)
  134. {
  135. strcpy(portName, m_name);
  136. strcat(portName, ":out-right");
  137. }
  138. else
  139. #endif
  140. strcpy(portName, "out-right");
  141. aout.ports[1] = (CarlaEngineAudioPort*)x_client->addPort(CarlaEnginePortTypeAudio, portName, false);
  142. aout.rindexes[1] = 1;
  143. // ---------------------------------------
  144. // MIDI Input
  145. #ifndef BUILD_BRIDGE
  146. if (carlaOptions.process_mode != PROCESS_MODE_MULTIPLE_CLIENTS)
  147. {
  148. strcpy(portName, m_name);
  149. strcat(portName, ":midi-in");
  150. }
  151. else
  152. #endif
  153. strcpy(portName, "midi-in");
  154. midi.portMin = (CarlaEngineMidiPort*)x_client->addPort(CarlaEnginePortTypeMIDI, portName, true);
  155. // ---------------------------------------
  156. aout.count = aouts;
  157. // plugin checks
  158. m_hints &= ~(PLUGIN_IS_SYNTH | PLUGIN_USES_CHUNKS | PLUGIN_CAN_DRYWET | PLUGIN_CAN_VOLUME | PLUGIN_CAN_BALANCE);
  159. m_hints |= PLUGIN_IS_SYNTH;
  160. m_hints |= PLUGIN_CAN_VOLUME;
  161. m_hints |= PLUGIN_CAN_BALANCE;
  162. reloadPrograms(true);
  163. x_client->activate();
  164. qDebug("LinuxSamplerPlugin::reload() - end");
  165. }
  166. void reloadPrograms(bool init)
  167. {
  168. qDebug("LinuxSamplerPlugin::reloadPrograms(%s)", bool2str(init));
  169. // Delete old programs
  170. if (midiprog.count > 0)
  171. {
  172. for (uint32_t i=0; i < midiprog.count; i++)
  173. free((void*)midiprog.data[i].name);
  174. delete[] midiprog.data;
  175. }
  176. midiprog.count = 0;
  177. midiprog.data = nullptr;
  178. // Query new programs
  179. uint32_t i = 0;
  180. midiprog.count += instrumentIds.size();
  181. if (midiprog.count > 0)
  182. midiprog.data = new midi_program_t [midiprog.count];
  183. // Update data
  184. for (i=0; i < midiprog.count; i++)
  185. {
  186. LinuxSampler::InstrumentManager::instrument_info_t info = instrument->GetInstrumentInfo(instrumentIds[i]);
  187. // FIXME - use % 128 stuff
  188. midiprog.data[i].bank = 0;
  189. midiprog.data[i].program = i;
  190. midiprog.data[i].name = strdup(info.InstrumentName.c_str());
  191. }
  192. #ifndef BUILD_BRIDGE
  193. // Update OSC Names
  194. //osc_global_send_set_midi_program_count(m_id, midiprog.count);
  195. //for (i=0; i < midiprog.count; i++)
  196. // osc_global_send_set_midi_program_data(m_id, i, midiprog.data[i].bank, midiprog.data[i].program, midiprog.data[i].name);
  197. x_engine->callback(CALLBACK_RELOAD_PROGRAMS, m_id, 0, 0, 0.0);
  198. #endif
  199. if (init)
  200. {
  201. if (midiprog.count > 0)
  202. setMidiProgram(0, false, false, false, true);
  203. }
  204. }
  205. // -------------------------------------------------------------------
  206. // Plugin processing
  207. void process(float**, float** outBuffer, uint32_t frames, uint32_t framesOffset)
  208. {
  209. uint32_t i, k;
  210. uint32_t midiEventCount = 0;
  211. double aouts_peak_tmp[2] = { 0.0 };
  212. CARLA_PROCESS_CONTINUE_CHECK;
  213. // --------------------------------------------------------------------------------------------------------
  214. // MIDI Input (External)
  215. if (cin_channel >= 0 && cin_channel < 16 && m_active && m_activeBefore)
  216. {
  217. engineMidiLock();
  218. for (i=0; i < MAX_MIDI_EVENTS && midiEventCount < MAX_MIDI_EVENTS; i++)
  219. {
  220. if (extMidiNotes[i].channel < 0)
  221. break;
  222. if (extMidiNotes[i].velo)
  223. midiInputPort->DispatchNoteOn(extMidiNotes[i].note, extMidiNotes[i].velo, cin_channel, 0);
  224. else
  225. midiInputPort->DispatchNoteOff(extMidiNotes[i].note, extMidiNotes[i].velo, cin_channel, 0);
  226. extMidiNotes[i].channel = -1;
  227. midiEventCount += 1;
  228. }
  229. engineMidiUnlock();
  230. } // End of MIDI Input (External)
  231. CARLA_PROCESS_CONTINUE_CHECK;
  232. // --------------------------------------------------------------------------------------------------------
  233. // MIDI Input (System)
  234. if (m_active && m_activeBefore)
  235. {
  236. const CarlaEngineMidiEvent* minEvent;
  237. uint32_t time, nEvents = midi.portMin->getEventCount();
  238. for (i=0; i < nEvents && midiEventCount < MAX_MIDI_EVENTS; i++)
  239. {
  240. minEvent = midi.portMin->getEvent(i);
  241. if (! minEvent)
  242. continue;
  243. time = minEvent->time - framesOffset;
  244. if (time >= frames)
  245. continue;
  246. uint8_t status = minEvent->data[0];
  247. uint8_t channel = status & 0x0F;
  248. // Fix bad note-off
  249. if (MIDI_IS_STATUS_NOTE_ON(status) && minEvent->data[2] == 0)
  250. status -= 0x10;
  251. if (MIDI_IS_STATUS_NOTE_OFF(status))
  252. {
  253. uint8_t note = minEvent->data[1];
  254. midiInputPort->DispatchNoteOff(note, 0, channel, time);
  255. if (channel == cin_channel)
  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. if (channel == cin_channel)
  264. postponeEvent(PluginPostEventNoteOn, channel, note, velo);
  265. }
  266. else if (MIDI_IS_STATUS_AFTERTOUCH(status))
  267. {
  268. uint8_t pressure = minEvent->data[1];
  269. midiInputPort->DispatchControlChange(MIDI_STATUS_AFTERTOUCH, pressure, channel, time);
  270. }
  271. else if (MIDI_IS_STATUS_PITCH_WHEEL_CONTROL(status))
  272. {
  273. uint8_t lsb = minEvent->data[1];
  274. uint8_t msb = minEvent->data[2];
  275. midiInputPort->DispatchPitchbend(((msb << 7) | lsb) - 8192, channel, time);
  276. }
  277. else
  278. continue;
  279. midiEventCount += 1;
  280. }
  281. } // End of MIDI Input (System)
  282. CARLA_PROCESS_CONTINUE_CHECK;
  283. // --------------------------------------------------------------------------------------------------------
  284. // Plugin processing
  285. if (m_active)
  286. {
  287. if (! m_activeBefore)
  288. {
  289. if (cin_channel >= 0 && cin_channel < 16)
  290. {
  291. midiInputPort->DispatchControlChange(MIDI_CONTROL_ALL_SOUND_OFF, 0, cin_channel);
  292. midiInputPort->DispatchControlChange(MIDI_CONTROL_ALL_NOTES_OFF, 0, cin_channel);
  293. }
  294. }
  295. audioOutputDevice->Channel(0)->SetBuffer(outBuffer[0]);
  296. audioOutputDevice->Channel(1)->SetBuffer(outBuffer[1]);
  297. // QUESTION: Need to clear it before?
  298. audioOutputDevice->Render(frames);
  299. }
  300. CARLA_PROCESS_CONTINUE_CHECK;
  301. // --------------------------------------------------------------------------------------------------------
  302. // Post-processing (dry/wet, volume and balance)
  303. if (m_active)
  304. {
  305. bool do_volume = x_vol != 1.0;
  306. bool do_balance = (x_bal_left != -1.0 || x_bal_right != 1.0);
  307. double bal_rangeL, bal_rangeR;
  308. float oldBufLeft[do_balance ? frames : 0];
  309. for (i=0; i < aout.count; i++)
  310. {
  311. // Balance
  312. if (do_balance)
  313. {
  314. if (i%2 == 0)
  315. memcpy(&oldBufLeft, outBuffer[i], sizeof(float)*frames);
  316. bal_rangeL = (x_bal_left+1.0)/2;
  317. bal_rangeR = (x_bal_right+1.0)/2;
  318. for (k=0; k < frames; k++)
  319. {
  320. if (i%2 == 0)
  321. {
  322. // left output
  323. outBuffer[i][k] = oldBufLeft[k]*(1.0-bal_rangeL);
  324. outBuffer[i][k] += outBuffer[i+1][k]*(1.0-bal_rangeR);
  325. }
  326. else
  327. {
  328. // right
  329. outBuffer[i][k] = outBuffer[i][k]*bal_rangeR;
  330. outBuffer[i][k] += oldBufLeft[k]*bal_rangeL;
  331. }
  332. }
  333. }
  334. // Volume
  335. if (do_volume)
  336. {
  337. for (k=0; k < frames; k++)
  338. outBuffer[i][k] *= x_vol;
  339. }
  340. // Output VU
  341. for (k=0; i < 2 && k < frames; k++)
  342. {
  343. if (abs(outBuffer[i][k]) > aouts_peak_tmp[i])
  344. aouts_peak_tmp[i] = abs(outBuffer[i][k]);
  345. }
  346. }
  347. }
  348. else
  349. {
  350. // disable any output sound if not active
  351. for (i=0; i < aout.count; i++)
  352. memset(outBuffer[i], 0.0f, sizeof(float)*frames);
  353. aouts_peak_tmp[0] = 0.0;
  354. aouts_peak_tmp[1] = 0.0;
  355. } // End of Post-processing
  356. CARLA_PROCESS_CONTINUE_CHECK;
  357. // --------------------------------------------------------------------------------------------------------
  358. // Peak Values
  359. x_engine->setOutputPeak(m_id, 0, aouts_peak_tmp[0]);
  360. x_engine->setOutputPeak(m_id, 1, aouts_peak_tmp[1]);
  361. m_activeBefore = m_active;
  362. }
  363. // -------------------------------------------------------------------
  364. bool init(const char* filename, const char* const name, const char* label)
  365. {
  366. QFileInfo file(filename);
  367. if (file.exists() && file.isFile() && file.isReadable())
  368. {
  369. const char* stype = m_isGIG ? "gig" : "sfz";
  370. try {
  371. engine = LinuxSampler::EngineFactory::Create(stype);
  372. }
  373. catch (LinuxSampler::Exception& e)
  374. {
  375. setLastError(e.what());
  376. return false;
  377. }
  378. try {
  379. instrument = engine->GetInstrumentManager();
  380. }
  381. catch (LinuxSampler::Exception& e)
  382. {
  383. setLastError(e.what());
  384. return false;
  385. }
  386. try {
  387. instrumentIds = instrument->GetInstrumentFileContent(filename);
  388. }
  389. catch (LinuxSampler::Exception& e)
  390. {
  391. setLastError(e.what());
  392. return false;
  393. }
  394. if (instrumentIds.size() > 0)
  395. {
  396. LinuxSampler::InstrumentManager::instrument_info_t info = instrument->GetInstrumentInfo(instrumentIds[0]);
  397. m_label = strdup(info.Product.c_str());
  398. m_maker = strdup(info.Artists.c_str());
  399. m_filename = strdup(filename);
  400. if (name)
  401. m_name = x_engine->getUniqueName(name);
  402. else
  403. m_name = x_engine->getUniqueName(label && label[0] ? label : info.InstrumentName.c_str());
  404. sampler_channel = sampler->AddSamplerChannel();
  405. sampler_channel->SetEngineType(stype);
  406. sampler_channel->SetAudioOutputDevice(audioOutputDevice);
  407. //sampler_channel->SetMidiInputDevice(midiInputDevice);
  408. //sampler_channel->SetMidiInputChannel(LinuxSampler::midi_chan_1);
  409. midiInputPort->Connect(sampler_channel->GetEngineChannel(), LinuxSampler::midi_chan_all);
  410. engine_channel = sampler_channel->GetEngineChannel();
  411. engine_channel->Connect(audioOutputDevice);
  412. engine_channel->PrepareLoadInstrument(filename, 0); // todo - find instrument from label
  413. engine_channel->LoadInstrument();
  414. engine_channel->Volume(LinuxSampler::VOLUME_MAX);
  415. x_client = x_engine->addClient(this);
  416. if (x_client->isOk())
  417. return true;
  418. else
  419. setLastError("Failed to register plugin client");
  420. }
  421. else
  422. setLastError("Failed to find any instruments");
  423. }
  424. else
  425. setLastError("Requested file is not valid or does not exist");
  426. return false;
  427. }
  428. // -------------------------------------------------------------------
  429. static CarlaPlugin* newLinuxSampler(const initializer& init, bool isGIG);
  430. private:
  431. LinuxSampler::Sampler* sampler;
  432. LinuxSampler::SamplerChannel* sampler_channel;
  433. LinuxSampler::Engine* engine;
  434. LinuxSampler::EngineChannel* engine_channel;
  435. LinuxSampler::InstrumentManager* instrument;
  436. std::vector<LinuxSampler::InstrumentManager::instrument_id_t> instrumentIds;
  437. LinuxSampler::AudioOutputDevicePlugin* audioOutputDevice;
  438. LinuxSampler::MidiInputDevicePlugin* midiInputDevice;
  439. LinuxSampler::MidiInputPort* midiInputPort;
  440. bool m_isGIG;
  441. const char* m_label;
  442. const char* m_maker;
  443. };
  444. CarlaPlugin* LinuxSamplerPlugin::newLinuxSampler(const initializer& init, bool isGIG)
  445. {
  446. qDebug("LinuxSamplerPlugin::newLinuxSampler(%p, \"%s\", \"%s\", \"%s\", %s)", init.engine, init.filename, init.name, init.label, bool2str(isGIG));
  447. short id = init.engine->getNewPluginId();
  448. if (id < 0)
  449. {
  450. setLastError("Maximum number of plugins reached");
  451. return nullptr;
  452. }
  453. LinuxSamplerPlugin* const plugin = new LinuxSamplerPlugin(init.engine, id, isGIG);
  454. if (! plugin->init(init.filename, init.name, init.label))
  455. {
  456. delete plugin;
  457. return nullptr;
  458. }
  459. plugin->reload();
  460. plugin->registerToOsc();
  461. return plugin;
  462. }
  463. #endif // WANT_LINUXSAMPLER
  464. CarlaPlugin* CarlaPlugin::newGIG(const initializer& init)
  465. {
  466. qDebug("CarlaPlugin::newGIG(%p, \"%s\", \"%s\", \"%s\")", init.engine, init.filename, init.name, init.label);
  467. #ifdef WANT_LINUXSAMPLER
  468. return LinuxSamplerPlugin::newLinuxSampler(init, true);
  469. #else
  470. setLastError("linuxsampler support not available");
  471. return nullptr;
  472. #endif
  473. }
  474. CarlaPlugin* CarlaPlugin::newSFZ(const initializer& init)
  475. {
  476. qDebug("CarlaPlugin::newSFZ(%p, \"%s\", \"%s\", \"%s\")", init.engine, init.filename, init.name, init.label);
  477. #ifdef WANT_LINUXSAMPLER
  478. return LinuxSamplerPlugin::newLinuxSampler(init, false);
  479. #else
  480. setLastError("linuxsampler support not available");
  481. return nullptr;
  482. #endif
  483. }
  484. /**@}*/
  485. CARLA_BACKEND_END_NAMESPACE