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.

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