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.

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