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.

648 lines
20KB

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