Audio plugin host https://kx.studio/carla
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.

1166 lines
39KB

  1. /*
  2. * Carla Juce Plugin
  3. * Copyright (C) 2013-2014 Filipe Coelho <falktx@falktx.com>
  4. *
  5. * This program is free software; you can redistribute it and/or
  6. * modify it under the terms of the GNU General Public License as
  7. * published by the Free Software Foundation; either version 2 of
  8. * the License, or 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 doc/GPL.txt file.
  16. */
  17. #include "CarlaPluginInternal.hpp"
  18. #include "CarlaEngine.hpp"
  19. #ifdef HAVE_JUCE
  20. #include "CarlaBackendUtils.hpp"
  21. #include "JucePluginWindow.hpp"
  22. #include "juce_audio_processors.h"
  23. using namespace juce;
  24. CARLA_BACKEND_START_NAMESPACE
  25. class JucePlugin : public CarlaPlugin,
  26. public AudioPlayHead,
  27. public AudioProcessorListener
  28. {
  29. public:
  30. JucePlugin(CarlaEngine* const engine, const uint id)
  31. : CarlaPlugin(engine, id),
  32. fInstance(nullptr),
  33. fAudioBuffer(1, 0)
  34. {
  35. carla_debug("JucePlugin::JucePlugin(%p, %i)", engine, id);
  36. fMidiBuffer.ensureSize(2048);
  37. fMidiBuffer.clear();
  38. fPosInfo.resetToDefault();
  39. }
  40. ~JucePlugin() override
  41. {
  42. carla_debug("JucePlugin::~JucePlugin()");
  43. // close UI
  44. if (pData->hints & PLUGIN_HAS_CUSTOM_UI)
  45. showCustomUI(false);
  46. pData->singleMutex.lock();
  47. pData->masterMutex.lock();
  48. if (pData->client != nullptr && pData->client->isActive())
  49. pData->client->deactivate();
  50. if (pData->active)
  51. {
  52. deactivate();
  53. pData->active = false;
  54. }
  55. if (fInstance != nullptr)
  56. {
  57. delete fInstance;
  58. fInstance = nullptr;
  59. }
  60. clearBuffers();
  61. }
  62. // -------------------------------------------------------------------
  63. // Information (base)
  64. PluginType getType() const noexcept override
  65. {
  66. PluginType type = PLUGIN_NONE;
  67. try {
  68. type = getPluginTypeFromString(fDesc.pluginFormatName.toRawUTF8());
  69. } catch(...) {}
  70. return type;
  71. }
  72. PluginCategory getCategory() const noexcept override
  73. {
  74. PluginCategory category = PLUGIN_CATEGORY_NONE;
  75. try {
  76. category = getPluginCategoryFromName(fDesc.category.toRawUTF8());
  77. } catch(...) {}
  78. return category;
  79. }
  80. int64_t getUniqueId() const noexcept override
  81. {
  82. return fDesc.uid;
  83. }
  84. // -------------------------------------------------------------------
  85. // Information (count)
  86. // nothing
  87. // -------------------------------------------------------------------
  88. // Information (current data)
  89. // nothing
  90. // -------------------------------------------------------------------
  91. // Information (per-plugin data)
  92. unsigned int getOptionsAvailable() const noexcept override
  93. {
  94. CARLA_SAFE_ASSERT_RETURN(fInstance != nullptr, 0x0);
  95. unsigned int options = 0x0;
  96. options |= PLUGIN_OPTION_MAP_PROGRAM_CHANGES;
  97. //options |= PLUGIN_OPTION_USE_CHUNKS;
  98. if (fInstance->acceptsMidi())
  99. {
  100. options |= PLUGIN_OPTION_SEND_CONTROL_CHANGES;
  101. options |= PLUGIN_OPTION_SEND_CHANNEL_PRESSURE;
  102. options |= PLUGIN_OPTION_SEND_NOTE_AFTERTOUCH;
  103. options |= PLUGIN_OPTION_SEND_PITCHBEND;
  104. options |= PLUGIN_OPTION_SEND_ALL_SOUND_OFF;
  105. }
  106. return options;
  107. }
  108. float getParameterValue(const uint32_t parameterId) const noexcept override
  109. {
  110. CARLA_SAFE_ASSERT_RETURN(parameterId < pData->param.count, 0.0f);
  111. CARLA_SAFE_ASSERT_RETURN(fInstance != nullptr, 0.0f);
  112. return fInstance->getParameter(static_cast<int>(parameterId));
  113. }
  114. void getLabel(char* const strBuf) const noexcept override
  115. {
  116. std::strncpy(strBuf, fDesc.name.toRawUTF8(), STR_MAX);
  117. }
  118. void getMaker(char* const strBuf) const noexcept override
  119. {
  120. std::strncpy(strBuf, fDesc.manufacturerName.toRawUTF8(), STR_MAX);
  121. }
  122. void getCopyright(char* const strBuf) const noexcept override
  123. {
  124. getMaker(strBuf);
  125. }
  126. void getRealName(char* const strBuf) const noexcept override
  127. {
  128. CARLA_SAFE_ASSERT_RETURN(fInstance != nullptr,);
  129. std::strncpy(strBuf, fInstance->getName().toRawUTF8(), STR_MAX);
  130. }
  131. void getParameterName(const uint32_t parameterId, char* const strBuf) const noexcept override
  132. {
  133. CARLA_SAFE_ASSERT_RETURN(parameterId < pData->param.count,);
  134. CARLA_SAFE_ASSERT_RETURN(fInstance != nullptr,);
  135. std::strncpy(strBuf, fInstance->getParameterName(static_cast<int>(parameterId)).toRawUTF8(), STR_MAX);
  136. }
  137. void getParameterUnit(const uint32_t parameterId, char* const strBuf) const noexcept override
  138. {
  139. CARLA_SAFE_ASSERT_RETURN(parameterId < pData->param.count,);
  140. CARLA_SAFE_ASSERT_RETURN(fInstance != nullptr,);
  141. std::strncpy(strBuf, fInstance->getParameterLabel(static_cast<int>(parameterId)).toRawUTF8(), STR_MAX);
  142. }
  143. // -------------------------------------------------------------------
  144. // Set data (state)
  145. // nothing
  146. // -------------------------------------------------------------------
  147. // Set data (internal stuff)
  148. void setName(const char* const newName) override
  149. {
  150. CarlaPlugin::setName(newName);
  151. if (fWindow != nullptr)
  152. {
  153. String uiName(pData->name);
  154. uiName += " (GUI)";
  155. fWindow->setName(uiName);
  156. }
  157. }
  158. // -------------------------------------------------------------------
  159. // Set data (plugin-specific stuff)
  160. void setParameterValue(const uint32_t parameterId, const float value, const bool sendGui, const bool sendOsc, const bool sendCallback) noexcept override
  161. {
  162. CARLA_SAFE_ASSERT_RETURN(parameterId < pData->param.count,);
  163. CARLA_SAFE_ASSERT_RETURN(fInstance != nullptr,);
  164. const float fixedValue(pData->param.getFixedValue(parameterId, value));
  165. fInstance->setParameter(static_cast<int>(parameterId), value);
  166. CarlaPlugin::setParameterValue(parameterId, fixedValue, sendGui, sendOsc, sendCallback);
  167. }
  168. // -------------------------------------------------------------------
  169. // Set ui stuff
  170. void showCustomUI(const bool yesNo) override
  171. {
  172. CARLA_SAFE_ASSERT_RETURN(fInstance != nullptr,);
  173. #ifdef CARLA_OS_LINUX
  174. const MessageManagerLock mmLock;
  175. #endif
  176. if (yesNo)
  177. {
  178. if (fWindow == nullptr)
  179. {
  180. String uiName(pData->name);
  181. uiName += " (GUI)";
  182. fWindow = new JucePluginWindow();
  183. fWindow->setName(uiName);
  184. }
  185. if (AudioProcessorEditor* const editor = fInstance->createEditorIfNeeded())
  186. fWindow->show(editor);
  187. }
  188. else
  189. {
  190. if (fWindow != nullptr)
  191. fWindow->hide();
  192. if (AudioProcessorEditor* const editor = fInstance->getActiveEditor())
  193. delete editor;
  194. fWindow = nullptr;
  195. }
  196. }
  197. void idle() override
  198. {
  199. if (fWindow != nullptr)
  200. {
  201. if (fWindow->wasClosedByUser())
  202. {
  203. showCustomUI(false);
  204. pData->engine->callback(ENGINE_CALLBACK_UI_STATE_CHANGED, pData->id, 0, 0, 0.0f, nullptr);
  205. }
  206. }
  207. CarlaPlugin::idle();
  208. }
  209. // -------------------------------------------------------------------
  210. // Plugin state
  211. void reload() override
  212. {
  213. CARLA_SAFE_ASSERT_RETURN(pData->engine != nullptr,);
  214. CARLA_SAFE_ASSERT_RETURN(fInstance != nullptr,);
  215. carla_debug("VstPlugin::reload() - start");
  216. const EngineProcessMode processMode(pData->engine->getProccessMode());
  217. // Safely disable plugin for reload
  218. const ScopedDisabler sd(this);
  219. if (pData->active)
  220. deactivate();
  221. clearBuffers();
  222. fInstance->refreshParameterList();
  223. uint32_t aIns, aOuts, mIns, mOuts, params;
  224. aIns = aOuts = mIns = mOuts = params = 0;
  225. bool needsCtrlIn, needsCtrlOut;
  226. needsCtrlIn = needsCtrlOut = false;
  227. aIns = (fInstance->getNumInputChannels() > 0) ? static_cast<uint32_t>(fInstance->getNumInputChannels()) : 0;
  228. aOuts = (fInstance->getNumOutputChannels() > 0) ? static_cast<uint32_t>(fInstance->getNumOutputChannels()) : 0;
  229. params = (fInstance->getNumParameters() > 0) ? static_cast<uint32_t>(fInstance->getNumParameters()) : 0;
  230. if (fInstance->acceptsMidi())
  231. {
  232. mIns = 1;
  233. needsCtrlIn = true;
  234. }
  235. if (fInstance->producesMidi())
  236. {
  237. mOuts = 1;
  238. needsCtrlOut = true;
  239. }
  240. if (aIns > 0)
  241. {
  242. pData->audioIn.createNew(aIns);
  243. }
  244. if (aOuts > 0)
  245. {
  246. pData->audioOut.createNew(aOuts);
  247. needsCtrlIn = true;
  248. }
  249. if (params > 0)
  250. {
  251. pData->param.createNew(params, false);
  252. needsCtrlIn = true;
  253. }
  254. const uint portNameSize(pData->engine->getMaxPortNameSize());
  255. CarlaString portName;
  256. // Audio Ins
  257. for (uint32_t j=0; j < aIns; ++j)
  258. {
  259. portName.clear();
  260. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  261. {
  262. portName = pData->name;
  263. portName += ":";
  264. }
  265. if (aIns > 1)
  266. {
  267. portName += "input_";
  268. portName += CarlaString(j+1);
  269. }
  270. else
  271. portName += "input";
  272. portName.truncate(portNameSize);
  273. pData->audioIn.ports[j].port = (CarlaEngineAudioPort*)pData->client->addPort(kEnginePortTypeAudio, portName, true);
  274. pData->audioIn.ports[j].rindex = j;
  275. }
  276. // Audio Outs
  277. for (uint32_t j=0; j < aOuts; ++j)
  278. {
  279. portName.clear();
  280. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  281. {
  282. portName = pData->name;
  283. portName += ":";
  284. }
  285. if (aOuts > 1)
  286. {
  287. portName += "output_";
  288. portName += CarlaString(j+1);
  289. }
  290. else
  291. portName += "output";
  292. portName.truncate(portNameSize);
  293. pData->audioOut.ports[j].port = (CarlaEngineAudioPort*)pData->client->addPort(kEnginePortTypeAudio, portName, false);
  294. pData->audioOut.ports[j].rindex = j;
  295. }
  296. for (uint32_t j=0; j < params; ++j)
  297. {
  298. pData->param.data[j].type = PARAMETER_INPUT;
  299. pData->param.data[j].hints = 0x0;
  300. pData->param.data[j].index = static_cast<int32_t>(j);
  301. pData->param.data[j].rindex = static_cast<int32_t>(j);
  302. pData->param.data[j].midiCC = -1;
  303. pData->param.data[j].midiChannel = 0;
  304. float min, max, def, step, stepSmall, stepLarge;
  305. // TODO
  306. //const int numSteps(fInstance->getParameterNumSteps(static_cast<int>(j)));
  307. {
  308. min = 0.0f;
  309. max = 1.0f;
  310. step = 0.001f;
  311. stepSmall = 0.0001f;
  312. stepLarge = 0.1f;
  313. }
  314. pData->param.data[j].hints |= PARAMETER_IS_ENABLED;
  315. #ifndef BUILD_BRIDGE
  316. //pData->param.data[j].hints |= PARAMETER_USES_CUSTOM_TEXT;
  317. #endif
  318. if (fInstance->isParameterAutomatable(static_cast<int>(j)))
  319. pData->param.data[j].hints |= PARAMETER_IS_AUTOMABLE;
  320. // FIXME?
  321. def = fInstance->getParameterDefaultValue(static_cast<int>(j));
  322. if (def < min)
  323. def = min;
  324. else if (def > max)
  325. def = max;
  326. pData->param.ranges[j].min = min;
  327. pData->param.ranges[j].max = max;
  328. pData->param.ranges[j].def = def;
  329. pData->param.ranges[j].step = step;
  330. pData->param.ranges[j].stepSmall = stepSmall;
  331. pData->param.ranges[j].stepLarge = stepLarge;
  332. }
  333. if (needsCtrlIn)
  334. {
  335. portName.clear();
  336. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  337. {
  338. portName = pData->name;
  339. portName += ":";
  340. }
  341. portName += "events-in";
  342. portName.truncate(portNameSize);
  343. pData->event.portIn = (CarlaEngineEventPort*)pData->client->addPort(kEnginePortTypeEvent, portName, true);
  344. }
  345. if (needsCtrlOut)
  346. {
  347. portName.clear();
  348. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  349. {
  350. portName = pData->name;
  351. portName += ":";
  352. }
  353. portName += "events-out";
  354. portName.truncate(portNameSize);
  355. pData->event.portOut = (CarlaEngineEventPort*)pData->client->addPort(kEnginePortTypeEvent, portName, false);
  356. }
  357. // plugin hints
  358. pData->hints = 0x0;
  359. if (fDesc.isInstrument)
  360. pData->hints |= PLUGIN_IS_SYNTH;
  361. if (fInstance->hasEditor())
  362. {
  363. pData->hints |= PLUGIN_HAS_CUSTOM_UI;
  364. pData->hints |= PLUGIN_NEEDS_SINGLE_THREAD;
  365. }
  366. if (aOuts > 0 && (aIns == aOuts || aIns == 1))
  367. pData->hints |= PLUGIN_CAN_DRYWET;
  368. if (aOuts > 0)
  369. pData->hints |= PLUGIN_CAN_VOLUME;
  370. if (aOuts >= 2 && aOuts % 2 == 0)
  371. pData->hints |= PLUGIN_CAN_BALANCE;
  372. // extra plugin hints
  373. pData->extraHints = 0x0;
  374. if (mIns > 0)
  375. pData->extraHints |= PLUGIN_EXTRA_HINT_HAS_MIDI_IN;
  376. if (mOuts > 0)
  377. pData->extraHints |= PLUGIN_EXTRA_HINT_HAS_MIDI_OUT;
  378. if (aIns <= 2 && aOuts <= 2 && (aIns == aOuts || aIns == 0 || aOuts == 0))
  379. pData->extraHints |= PLUGIN_EXTRA_HINT_CAN_RUN_RACK;
  380. fInstance->setPlayConfigDetails(static_cast<int>(aIns), static_cast<int>(aOuts), pData->engine->getSampleRate(), static_cast<int>(pData->engine->getBufferSize()));
  381. bufferSizeChanged(pData->engine->getBufferSize());
  382. //reloadPrograms(true);
  383. if (pData->active)
  384. activate();
  385. carla_debug("VstPlugin::reload() - end");
  386. }
  387. // -------------------------------------------------------------------
  388. // Plugin processing
  389. void activate() noexcept override
  390. {
  391. CARLA_SAFE_ASSERT_RETURN(fInstance != nullptr,);
  392. try {
  393. fInstance->prepareToPlay(pData->engine->getSampleRate(), static_cast<int>(pData->engine->getBufferSize()));
  394. } catch(...) {}
  395. }
  396. void deactivate() noexcept override
  397. {
  398. CARLA_SAFE_ASSERT_RETURN(fInstance != nullptr,);
  399. try {
  400. fInstance->releaseResources();
  401. } catch(...) {}
  402. }
  403. void process(float** const inBuffer, float** const outBuffer, const uint32_t frames) override
  404. {
  405. // --------------------------------------------------------------------------------------------------------
  406. // Check if active
  407. if (! pData->active)
  408. {
  409. // disable any output sound
  410. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  411. FloatVectorOperations::clear(outBuffer[i], static_cast<int>(frames));
  412. return;
  413. }
  414. // --------------------------------------------------------------------------------------------------------
  415. // Check if needs reset
  416. if (pData->needsReset)
  417. {
  418. fInstance->reset();
  419. pData->needsReset = false;
  420. }
  421. // --------------------------------------------------------------------------------------------------------
  422. // TimeInfo
  423. // TODO
  424. // --------------------------------------------------------------------------------------------------------
  425. // Event Input
  426. fMidiBuffer.clear();
  427. if (pData->event.portIn != nullptr)
  428. {
  429. // ----------------------------------------------------------------------------------------------------
  430. // MIDI Input (External)
  431. if (pData->extNotes.mutex.tryLock())
  432. {
  433. for (; ! pData->extNotes.data.isEmpty();)
  434. {
  435. const ExternalMidiNote& note(pData->extNotes.data.getFirst(true));
  436. CARLA_SAFE_ASSERT_CONTINUE(note.channel >= 0 && note.channel < MAX_MIDI_CHANNELS);
  437. uint8_t midiEvent[3];
  438. midiEvent[0] = static_cast<uint8_t>(note.channel + (note.velo > 0) ? MIDI_STATUS_NOTE_ON : MIDI_STATUS_NOTE_OFF);
  439. midiEvent[1] = note.note;
  440. midiEvent[2] = note.velo;
  441. fMidiBuffer.addEvent(midiEvent, 3, 0);
  442. }
  443. pData->extNotes.mutex.unlock();
  444. } // End of MIDI Input (External)
  445. // ----------------------------------------------------------------------------------------------------
  446. // Event Input (System)
  447. bool allNotesOffSent = false;
  448. uint32_t numEvents = pData->event.portIn->getEventCount();
  449. uint32_t nextBankId;
  450. if (pData->midiprog.current >= 0 && pData->midiprog.count > 0)
  451. nextBankId = pData->midiprog.data[pData->midiprog.current].bank;
  452. else
  453. nextBankId = 0;
  454. for (uint32_t i=0; i < numEvents; ++i)
  455. {
  456. const EngineEvent& event(pData->event.portIn->getEvent(i));
  457. if (event.time >= frames)
  458. continue;
  459. switch (event.type)
  460. {
  461. case kEngineEventTypeNull:
  462. break;
  463. case kEngineEventTypeControl: {
  464. const EngineControlEvent& ctrlEvent(event.ctrl);
  465. switch (ctrlEvent.type)
  466. {
  467. case kEngineControlEventTypeNull:
  468. break;
  469. case kEngineControlEventTypeParameter: {
  470. #ifndef BUILD_BRIDGE
  471. // Control backend stuff
  472. if (event.channel == pData->ctrlChannel)
  473. {
  474. float value;
  475. if (MIDI_IS_CONTROL_BREATH_CONTROLLER(ctrlEvent.param) && (pData->hints & PLUGIN_CAN_DRYWET) != 0)
  476. {
  477. value = ctrlEvent.value;
  478. setDryWet(value, false, false);
  479. pData->postponeRtEvent(kPluginPostRtEventParameterChange, PARAMETER_DRYWET, 0, value);
  480. break;
  481. }
  482. if (MIDI_IS_CONTROL_CHANNEL_VOLUME(ctrlEvent.param) && (pData->hints & PLUGIN_CAN_VOLUME) != 0)
  483. {
  484. value = ctrlEvent.value*127.0f/100.0f;
  485. setVolume(value, false, false);
  486. pData->postponeRtEvent(kPluginPostRtEventParameterChange, PARAMETER_VOLUME, 0, value);
  487. break;
  488. }
  489. if (MIDI_IS_CONTROL_BALANCE(ctrlEvent.param) && (pData->hints & PLUGIN_CAN_BALANCE) != 0)
  490. {
  491. float left, right;
  492. value = ctrlEvent.value/0.5f - 1.0f;
  493. if (value < 0.0f)
  494. {
  495. left = -1.0f;
  496. right = (value*2.0f)+1.0f;
  497. }
  498. else if (value > 0.0f)
  499. {
  500. left = (value*2.0f)-1.0f;
  501. right = 1.0f;
  502. }
  503. else
  504. {
  505. left = -1.0f;
  506. right = 1.0f;
  507. }
  508. setBalanceLeft(left, false, false);
  509. setBalanceRight(right, false, false);
  510. pData->postponeRtEvent(kPluginPostRtEventParameterChange, PARAMETER_BALANCE_LEFT, 0, left);
  511. pData->postponeRtEvent(kPluginPostRtEventParameterChange, PARAMETER_BALANCE_RIGHT, 0, right);
  512. break;
  513. }
  514. }
  515. #endif
  516. // Control plugin parameters
  517. uint32_t k;
  518. for (k=0; k < pData->param.count; ++k)
  519. {
  520. if (pData->param.data[k].midiChannel != event.channel)
  521. continue;
  522. if (pData->param.data[k].midiCC != ctrlEvent.param)
  523. continue;
  524. if (pData->param.data[k].type != PARAMETER_INPUT)
  525. continue;
  526. if ((pData->param.data[k].hints & PARAMETER_IS_AUTOMABLE) == 0)
  527. continue;
  528. float value;
  529. if (pData->param.data[k].hints & PARAMETER_IS_BOOLEAN)
  530. {
  531. value = (ctrlEvent.value < 0.5f) ? pData->param.ranges[k].min : pData->param.ranges[k].max;
  532. }
  533. else
  534. {
  535. value = pData->param.ranges[k].getUnnormalizedValue(ctrlEvent.value);
  536. if (pData->param.data[k].hints & PARAMETER_IS_INTEGER)
  537. value = std::rint(value);
  538. }
  539. setParameterValue(k, value, false, false, false);
  540. pData->postponeRtEvent(kPluginPostRtEventParameterChange, static_cast<int32_t>(k), 0, value);
  541. break;
  542. }
  543. // check if event is already handled
  544. if (k != pData->param.count)
  545. break;
  546. if ((pData->options & PLUGIN_OPTION_SEND_CONTROL_CHANGES) != 0 && ctrlEvent.param <= 0x5F)
  547. {
  548. uint8_t midiData[3];
  549. midiData[0] = static_cast<uint8_t>(MIDI_STATUS_CONTROL_CHANGE + i);
  550. midiData[1] = static_cast<uint8_t>(ctrlEvent.param);
  551. midiData[2] = uint8_t(ctrlEvent.value*127.0f);
  552. fMidiBuffer.addEvent(midiData, 3, static_cast<int>(event.time));
  553. }
  554. break;
  555. } // case kEngineControlEventTypeParameter
  556. case kEngineControlEventTypeMidiBank:
  557. if (event.channel == pData->ctrlChannel && (pData->options & PLUGIN_OPTION_MAP_PROGRAM_CHANGES) != 0)
  558. nextBankId = ctrlEvent.param;
  559. break;
  560. case kEngineControlEventTypeMidiProgram:
  561. if (event.channel == pData->ctrlChannel && (pData->options & PLUGIN_OPTION_MAP_PROGRAM_CHANGES) != 0)
  562. {
  563. const uint32_t nextProgramId = ctrlEvent.param;
  564. for (uint32_t k=0; k < pData->midiprog.count; ++k)
  565. {
  566. if (pData->midiprog.data[k].bank == nextBankId && pData->midiprog.data[k].program == nextProgramId)
  567. {
  568. const int32_t index(static_cast<int32_t>(k));
  569. setMidiProgram(index, false, false, false);
  570. pData->postponeRtEvent(kPluginPostRtEventMidiProgramChange, index, 0, 0.0f);
  571. break;
  572. }
  573. }
  574. }
  575. break;
  576. case kEngineControlEventTypeAllSoundOff:
  577. if (pData->options & PLUGIN_OPTION_SEND_ALL_SOUND_OFF)
  578. {
  579. uint8_t midiData[3];
  580. midiData[0] = static_cast<uint8_t>(MIDI_STATUS_CONTROL_CHANGE + i);
  581. midiData[1] = MIDI_CONTROL_ALL_SOUND_OFF;
  582. midiData[2] = 0;
  583. fMidiBuffer.addEvent(midiData, 3, static_cast<int>(event.time));
  584. }
  585. break;
  586. case kEngineControlEventTypeAllNotesOff:
  587. if (pData->options & PLUGIN_OPTION_SEND_ALL_SOUND_OFF)
  588. {
  589. if (event.channel == pData->ctrlChannel && ! allNotesOffSent)
  590. {
  591. allNotesOffSent = true;
  592. sendMidiAllNotesOffToCallback();
  593. }
  594. uint8_t midiData[3];
  595. midiData[0] = static_cast<uint8_t>(MIDI_STATUS_CONTROL_CHANGE + i);
  596. midiData[1] = MIDI_CONTROL_ALL_NOTES_OFF;
  597. midiData[2] = 0;
  598. fMidiBuffer.addEvent(midiData, 3, static_cast<int>(event.time));
  599. }
  600. break;
  601. } // switch (ctrlEvent.type)
  602. break;
  603. } // case kEngineEventTypeControl
  604. case kEngineEventTypeMidi:
  605. {
  606. const EngineMidiEvent& midiEvent(event.midi);
  607. uint8_t status = uint8_t(MIDI_GET_STATUS_FROM_DATA(midiEvent.data));
  608. uint8_t channel = event.channel;
  609. // Fix bad note-off
  610. if (MIDI_IS_STATUS_NOTE_ON(status) && midiEvent.data[2] == 0)
  611. status = MIDI_STATUS_NOTE_OFF;
  612. if (status == MIDI_STATUS_CHANNEL_PRESSURE && (pData->options & PLUGIN_OPTION_SEND_CHANNEL_PRESSURE) == 0)
  613. continue;
  614. if (status == MIDI_STATUS_CONTROL_CHANGE && (pData->options & PLUGIN_OPTION_SEND_CONTROL_CHANGES) == 0)
  615. continue;
  616. if (status == MIDI_STATUS_POLYPHONIC_AFTERTOUCH && (pData->options & PLUGIN_OPTION_SEND_NOTE_AFTERTOUCH) == 0)
  617. continue;
  618. if (status == MIDI_STATUS_PITCH_WHEEL_CONTROL && (pData->options & PLUGIN_OPTION_SEND_PITCHBEND) == 0)
  619. continue;
  620. fMidiBuffer.addEvent(midiEvent.data, midiEvent.size, static_cast<int>(event.time));
  621. if (status == MIDI_STATUS_NOTE_ON)
  622. pData->postponeRtEvent(kPluginPostRtEventNoteOn, channel, midiEvent.data[1], midiEvent.data[2]);
  623. else if (status == MIDI_STATUS_NOTE_OFF)
  624. pData->postponeRtEvent(kPluginPostRtEventNoteOff, channel, midiEvent.data[1], 0.0f);
  625. break;
  626. } // case kEngineEventTypeMidi
  627. } // switch (event.type)
  628. }
  629. pData->postRtEvents.trySplice();
  630. } // End of Event Input
  631. // --------------------------------------------------------------------------------------------------------
  632. // Set TimeInfo
  633. const EngineTimeInfo& timeInfo(pData->engine->getTimeInfo());
  634. fPosInfo.isPlaying = timeInfo.playing;
  635. if (timeInfo.valid & EngineTimeInfo::kValidBBT)
  636. {
  637. const double ppqBar = double(timeInfo.bbt.bar - 1) * timeInfo.bbt.beatsPerBar;
  638. const double ppqBeat = double(timeInfo.bbt.beat - 1);
  639. const double ppqTick = double(timeInfo.bbt.tick) / timeInfo.bbt.ticksPerBeat;
  640. fPosInfo.bpm = timeInfo.bbt.beatsPerMinute;
  641. fPosInfo.timeSigNumerator = static_cast<int>(timeInfo.bbt.beatsPerBar);
  642. fPosInfo.timeSigDenominator = static_cast<int>(timeInfo.bbt.beatType);
  643. fPosInfo.timeInSamples = static_cast<int64_t>(timeInfo.frame);
  644. fPosInfo.timeInSeconds = static_cast<double>(fPosInfo.timeInSamples)/pData->engine->getSampleRate();
  645. fPosInfo.ppqPosition = ppqBar + ppqBeat + ppqTick;
  646. fPosInfo.ppqPositionOfLastBarStart = ppqBar;
  647. }
  648. // --------------------------------------------------------------------------------------------------------
  649. // Process
  650. processSingle(inBuffer, outBuffer, frames);
  651. // --------------------------------------------------------------------------------------------------------
  652. // MIDI Output
  653. if (pData->event.portOut != nullptr)
  654. {
  655. // TODO
  656. }
  657. }
  658. bool processSingle(float** const inBuffer, float** const outBuffer, const uint32_t frames)
  659. {
  660. CARLA_SAFE_ASSERT_RETURN(frames > 0, false);
  661. if (pData->audioIn.count > 0)
  662. {
  663. CARLA_SAFE_ASSERT_RETURN(inBuffer != nullptr, false);
  664. }
  665. if (pData->audioOut.count > 0)
  666. {
  667. CARLA_SAFE_ASSERT_RETURN(outBuffer != nullptr, false);
  668. }
  669. // --------------------------------------------------------------------------------------------------------
  670. // Try lock, silence otherwise
  671. if (pData->engine->isOffline())
  672. {
  673. pData->singleMutex.lock();
  674. }
  675. else if (! pData->singleMutex.tryLock())
  676. {
  677. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  678. FloatVectorOperations::clear(outBuffer[i], static_cast<int>(frames));
  679. return false;
  680. }
  681. // --------------------------------------------------------------------------------------------------------
  682. // Set audio in buffers
  683. for (uint32_t i=0; i < pData->audioIn.count; ++i)
  684. fAudioBuffer.copyFrom(static_cast<int>(i), 0, inBuffer[i], static_cast<int>(frames));
  685. // --------------------------------------------------------------------------------------------------------
  686. // Run plugin
  687. fInstance->processBlock(fAudioBuffer, fMidiBuffer);
  688. // --------------------------------------------------------------------------------------------------------
  689. // Set audio out buffers
  690. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  691. FloatVectorOperations::copy(outBuffer[i], fAudioBuffer.getSampleData(static_cast<int>(i)), static_cast<int>(frames));
  692. // --------------------------------------------------------------------------------------------------------
  693. // Midi out
  694. if (! fMidiBuffer.isEmpty())
  695. {
  696. if (pData->event.portOut != nullptr)
  697. {
  698. const uint8* midiEventData;
  699. int midiEventSize, midiEventPosition;
  700. for (MidiBuffer::Iterator i(fMidiBuffer); i.getNextEvent(midiEventData, midiEventSize, midiEventPosition);)
  701. {
  702. CARLA_SAFE_ASSERT_BREAK(midiEventPosition >= 0 && midiEventPosition < static_cast<int>(frames));
  703. CARLA_SAFE_ASSERT_BREAK(midiEventSize > 0);
  704. if (! pData->event.portOut->writeMidiEvent(static_cast<uint32_t>(midiEventPosition), static_cast<uint8_t>(midiEventSize), midiEventData))
  705. break;
  706. }
  707. }
  708. fMidiBuffer.clear();
  709. }
  710. // --------------------------------------------------------------------------------------------------------
  711. pData->singleMutex.unlock();
  712. return true;
  713. }
  714. void bufferSizeChanged(const uint32_t newBufferSize) override
  715. {
  716. CARLA_ASSERT_INT(newBufferSize > 0, newBufferSize);
  717. carla_debug("VstPlugin::bufferSizeChanged(%i)", newBufferSize);
  718. fAudioBuffer.setSize(static_cast<int>(std::max<uint32_t>(pData->audioIn.count, pData->audioOut.count)), static_cast<int>(newBufferSize));
  719. if (pData->active)
  720. {
  721. deactivate();
  722. activate();
  723. }
  724. }
  725. void sampleRateChanged(const double newSampleRate) override
  726. {
  727. CARLA_ASSERT_INT(newSampleRate > 0.0, newSampleRate);
  728. carla_debug("VstPlugin::sampleRateChanged(%g)", newSampleRate);
  729. if (pData->active)
  730. {
  731. deactivate();
  732. activate();
  733. }
  734. }
  735. // -------------------------------------------------------------------
  736. // Plugin buffers
  737. // nothing
  738. // -------------------------------------------------------------------
  739. // Post-poned UI Stuff
  740. // nothing
  741. // -------------------------------------------------------------------
  742. protected:
  743. void audioProcessorParameterChanged(AudioProcessor*, int /*parameterIndex*/, float /*newValue*/) override
  744. {
  745. }
  746. void audioProcessorChanged(AudioProcessor*) override
  747. {
  748. }
  749. void audioProcessorParameterChangeGestureBegin(AudioProcessor*, int) {}
  750. void audioProcessorParameterChangeGestureEnd(AudioProcessor*, int) {}
  751. bool getCurrentPosition(CurrentPositionInfo& result) override
  752. {
  753. carla_copyStruct<CurrentPositionInfo>(result, fPosInfo);
  754. return true;
  755. }
  756. // -------------------------------------------------------------------
  757. public:
  758. bool init(const char* const filename, const char* const name, const char* const label, const int64_t uniqueId, const char* const format)
  759. {
  760. CARLA_SAFE_ASSERT_RETURN(pData->engine != nullptr, false);
  761. // ---------------------------------------------------------------
  762. // first checks
  763. if (pData->client != nullptr)
  764. {
  765. pData->engine->setLastError("Plugin client is already registered");
  766. return false;
  767. }
  768. if (filename == nullptr || filename[0] == '\0')
  769. {
  770. pData->engine->setLastError("null filename");
  771. return false;
  772. }
  773. if (label == nullptr || label[0] == '\0')
  774. {
  775. pData->engine->setLastError("null label");
  776. return false;
  777. }
  778. if (format == nullptr || format[0] == '\0')
  779. {
  780. pData->engine->setLastError("null format");
  781. return false;
  782. }
  783. #ifdef CARLA_OS_LINUX
  784. const MessageManagerLock mmLock;
  785. #endif
  786. // ---------------------------------------------------------------
  787. // fix path for wine usage
  788. String jfilename(filename);
  789. #ifdef CARLA_OS_WIN
  790. if (jfilename.startsWith("/"))
  791. {
  792. jfilename.replace("/", "\\");
  793. jfilename = "Z:" + jfilename;
  794. }
  795. #endif
  796. //fDesc.name = fDesc.descriptiveName = label;
  797. fDesc.uid = static_cast<int>(uniqueId);
  798. fDesc.fileOrIdentifier = jfilename;
  799. fDesc.pluginFormatName = format;
  800. fFormatManager.addDefaultFormats();
  801. String error;
  802. fInstance = fFormatManager.createPluginInstance(fDesc, 44100, 512, error);
  803. if (fInstance == nullptr)
  804. {
  805. pData->engine->setLastError(error.toRawUTF8());
  806. return false;
  807. }
  808. fInstance->fillInPluginDescription(fDesc);
  809. fInstance->setPlayHead(this);
  810. fInstance->addListener(this);
  811. // ---------------------------------------------------------------
  812. // get info
  813. if (name != nullptr && name[0] != '\0')
  814. pData->name = pData->engine->getUniquePluginName(name);
  815. else
  816. pData->name = pData->engine->getUniquePluginName(fInstance->getName().toRawUTF8());
  817. pData->filename = carla_strdup(filename);
  818. // ---------------------------------------------------------------
  819. // register client
  820. pData->client = pData->engine->addClient(this);
  821. if (pData->client == nullptr || ! pData->client->isOk())
  822. {
  823. pData->engine->setLastError("Failed to register plugin client");
  824. return false;
  825. }
  826. // ---------------------------------------------------------------
  827. // load plugin settings
  828. {
  829. // set default options
  830. pData->options = 0x0;
  831. pData->options |= PLUGIN_OPTION_FIXED_BUFFERS;
  832. pData->options |= PLUGIN_OPTION_MAP_PROGRAM_CHANGES;
  833. //pData->options |= PLUGIN_OPTION_USE_CHUNKS;
  834. if (fInstance->acceptsMidi())
  835. {
  836. pData->options |= PLUGIN_OPTION_SEND_CHANNEL_PRESSURE;
  837. pData->options |= PLUGIN_OPTION_SEND_NOTE_AFTERTOUCH;
  838. pData->options |= PLUGIN_OPTION_SEND_PITCHBEND;
  839. pData->options |= PLUGIN_OPTION_SEND_ALL_SOUND_OFF;
  840. }
  841. // set identifier string
  842. String juceId(fDesc.createIdentifierString());
  843. CarlaString identifier("Juce/");
  844. identifier += juceId.toRawUTF8();
  845. pData->identifier = identifier.dup();
  846. // load settings
  847. pData->options = pData->loadSettings(pData->options, getOptionsAvailable());
  848. // ignore settings, we need this anyway
  849. pData->options |= PLUGIN_OPTION_FIXED_BUFFERS;
  850. }
  851. return true;
  852. }
  853. private:
  854. PluginDescription fDesc;
  855. AudioPluginInstance* fInstance;
  856. AudioPluginFormatManager fFormatManager;
  857. AudioSampleBuffer fAudioBuffer;
  858. MidiBuffer fMidiBuffer;
  859. CurrentPositionInfo fPosInfo;
  860. const char* fUniqueId;
  861. ScopedPointer<JucePluginWindow> fWindow;
  862. CARLA_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(JucePlugin)
  863. };
  864. CARLA_BACKEND_END_NAMESPACE
  865. #endif // HAVE_JUCE
  866. // -------------------------------------------------------------------------------------------------------------------
  867. CARLA_BACKEND_START_NAMESPACE
  868. CarlaPlugin* CarlaPlugin::newJuce(const Initializer& init, const char* const format)
  869. {
  870. carla_debug("CarlaPlugin::newJuce({%p, \"%s\", \"%s\", \"%s\", " P_INT64 "}, %s)", init.engine, init.filename, init.name, init.label, init.uniqueId, format);
  871. #ifdef HAVE_JUCE
  872. JucePlugin* const plugin(new JucePlugin(init.engine, init.id));
  873. if (! plugin->init(init.filename, init.name, init.label, init.uniqueId, format))
  874. {
  875. delete plugin;
  876. return nullptr;
  877. }
  878. plugin->reload();
  879. if (init.engine->getProccessMode() == ENGINE_PROCESS_MODE_CONTINUOUS_RACK && ! plugin->canRunInRack())
  880. {
  881. init.engine->setLastError("Carla's rack mode can only work with Stereo VST3 plugins, sorry!");
  882. delete plugin;
  883. return nullptr;
  884. }
  885. return plugin;
  886. #else
  887. init.engine->setLastError("Juce support not available");
  888. return nullptr;
  889. // unused
  890. (void)format;
  891. #endif
  892. }
  893. CARLA_BACKEND_END_NAMESPACE
  894. // -------------------------------------------------------------------------------------------------------------------