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.

1183 lines
40KB

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