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.

1201 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, 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 (RtLinkedList<ExternalMidiNote>::Itenerator it = pData->extNotes.data.begin(); it.valid(); it.next())
  456. {
  457. const ExternalMidiNote& note(it.getValue());
  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.velo > 0 ? MIDI_STATUS_NOTE_ON : MIDI_STATUS_NOTE_OFF) | (note.channel & MIDI_CHANNEL_BIT));
  461. midiEvent[1] = note.note;
  462. midiEvent[2] = note.velo;
  463. fMidiBuffer.addEvent(midiEvent, 3, 0);
  464. }
  465. pData->extNotes.data.clear();
  466. pData->extNotes.mutex.unlock();
  467. } // End of MIDI Input (External)
  468. // ----------------------------------------------------------------------------------------------------
  469. // Event Input (System)
  470. bool allNotesOffSent = false;
  471. uint32_t numEvents = pData->event.portIn->getEventCount();
  472. uint32_t nextBankId;
  473. if (pData->midiprog.current >= 0 && pData->midiprog.count > 0)
  474. nextBankId = pData->midiprog.data[pData->midiprog.current].bank;
  475. else
  476. nextBankId = 0;
  477. for (uint32_t i=0; i < numEvents; ++i)
  478. {
  479. const EngineEvent& event(pData->event.portIn->getEvent(i));
  480. if (event.time >= frames)
  481. continue;
  482. switch (event.type)
  483. {
  484. case kEngineEventTypeNull:
  485. break;
  486. case kEngineEventTypeControl: {
  487. const EngineControlEvent& ctrlEvent(event.ctrl);
  488. switch (ctrlEvent.type)
  489. {
  490. case kEngineControlEventTypeNull:
  491. break;
  492. case kEngineControlEventTypeParameter: {
  493. #ifndef BUILD_BRIDGE
  494. // Control backend stuff
  495. if (event.channel == pData->ctrlChannel)
  496. {
  497. float value;
  498. if (MIDI_IS_CONTROL_BREATH_CONTROLLER(ctrlEvent.param) && (pData->hints & PLUGIN_CAN_DRYWET) != 0)
  499. {
  500. value = ctrlEvent.value;
  501. setDryWet(value, false, false);
  502. pData->postponeRtEvent(kPluginPostRtEventParameterChange, PARAMETER_DRYWET, 0, value);
  503. break;
  504. }
  505. if (MIDI_IS_CONTROL_CHANNEL_VOLUME(ctrlEvent.param) && (pData->hints & PLUGIN_CAN_VOLUME) != 0)
  506. {
  507. value = ctrlEvent.value*127.0f/100.0f;
  508. setVolume(value, false, false);
  509. pData->postponeRtEvent(kPluginPostRtEventParameterChange, PARAMETER_VOLUME, 0, value);
  510. break;
  511. }
  512. if (MIDI_IS_CONTROL_BALANCE(ctrlEvent.param) && (pData->hints & PLUGIN_CAN_BALANCE) != 0)
  513. {
  514. float left, right;
  515. value = ctrlEvent.value/0.5f - 1.0f;
  516. if (value < 0.0f)
  517. {
  518. left = -1.0f;
  519. right = (value*2.0f)+1.0f;
  520. }
  521. else if (value > 0.0f)
  522. {
  523. left = (value*2.0f)-1.0f;
  524. right = 1.0f;
  525. }
  526. else
  527. {
  528. left = -1.0f;
  529. right = 1.0f;
  530. }
  531. setBalanceLeft(left, false, false);
  532. setBalanceRight(right, false, false);
  533. pData->postponeRtEvent(kPluginPostRtEventParameterChange, PARAMETER_BALANCE_LEFT, 0, left);
  534. pData->postponeRtEvent(kPluginPostRtEventParameterChange, PARAMETER_BALANCE_RIGHT, 0, right);
  535. break;
  536. }
  537. }
  538. #endif
  539. // Control plugin parameters
  540. uint32_t k;
  541. for (k=0; k < pData->param.count; ++k)
  542. {
  543. if (pData->param.data[k].midiChannel != event.channel)
  544. continue;
  545. if (pData->param.data[k].midiCC != ctrlEvent.param)
  546. continue;
  547. if (pData->param.data[k].type != PARAMETER_INPUT)
  548. continue;
  549. if ((pData->param.data[k].hints & PARAMETER_IS_AUTOMABLE) == 0)
  550. continue;
  551. float value;
  552. if (pData->param.data[k].hints & PARAMETER_IS_BOOLEAN)
  553. {
  554. value = (ctrlEvent.value < 0.5f) ? pData->param.ranges[k].min : pData->param.ranges[k].max;
  555. }
  556. else
  557. {
  558. value = pData->param.ranges[k].getUnnormalizedValue(ctrlEvent.value);
  559. if (pData->param.data[k].hints & PARAMETER_IS_INTEGER)
  560. value = std::rint(value);
  561. }
  562. setParameterValue(k, value, false, false, false);
  563. pData->postponeRtEvent(kPluginPostRtEventParameterChange, static_cast<int32_t>(k), 0, value);
  564. break;
  565. }
  566. // check if event is already handled
  567. if (k != pData->param.count)
  568. break;
  569. if ((pData->options & PLUGIN_OPTION_SEND_CONTROL_CHANGES) != 0 && ctrlEvent.param <= 0x5F)
  570. {
  571. uint8_t midiData[3];
  572. midiData[0] = static_cast<uint8_t>(MIDI_STATUS_CONTROL_CHANGE + i);
  573. midiData[1] = static_cast<uint8_t>(ctrlEvent.param);
  574. midiData[2] = uint8_t(ctrlEvent.value*127.0f);
  575. fMidiBuffer.addEvent(midiData, 3, static_cast<int>(event.time));
  576. }
  577. break;
  578. } // case kEngineControlEventTypeParameter
  579. case kEngineControlEventTypeMidiBank:
  580. if (event.channel == pData->ctrlChannel && (pData->options & PLUGIN_OPTION_MAP_PROGRAM_CHANGES) != 0)
  581. nextBankId = ctrlEvent.param;
  582. break;
  583. case kEngineControlEventTypeMidiProgram:
  584. if (event.channel == pData->ctrlChannel && (pData->options & PLUGIN_OPTION_MAP_PROGRAM_CHANGES) != 0)
  585. {
  586. const uint32_t nextProgramId = ctrlEvent.param;
  587. for (uint32_t k=0; k < pData->midiprog.count; ++k)
  588. {
  589. if (pData->midiprog.data[k].bank == nextBankId && pData->midiprog.data[k].program == nextProgramId)
  590. {
  591. const int32_t index(static_cast<int32_t>(k));
  592. setMidiProgram(index, false, false, false);
  593. pData->postponeRtEvent(kPluginPostRtEventMidiProgramChange, index, 0, 0.0f);
  594. break;
  595. }
  596. }
  597. }
  598. break;
  599. case kEngineControlEventTypeAllSoundOff:
  600. if (pData->options & PLUGIN_OPTION_SEND_ALL_SOUND_OFF)
  601. {
  602. uint8_t midiData[3];
  603. midiData[0] = static_cast<uint8_t>(MIDI_STATUS_CONTROL_CHANGE + i);
  604. midiData[1] = MIDI_CONTROL_ALL_SOUND_OFF;
  605. midiData[2] = 0;
  606. fMidiBuffer.addEvent(midiData, 3, static_cast<int>(event.time));
  607. }
  608. break;
  609. case kEngineControlEventTypeAllNotesOff:
  610. if (pData->options & PLUGIN_OPTION_SEND_ALL_SOUND_OFF)
  611. {
  612. if (event.channel == pData->ctrlChannel && ! allNotesOffSent)
  613. {
  614. allNotesOffSent = true;
  615. sendMidiAllNotesOffToCallback();
  616. }
  617. uint8_t midiData[3];
  618. midiData[0] = static_cast<uint8_t>(MIDI_STATUS_CONTROL_CHANGE + i);
  619. midiData[1] = MIDI_CONTROL_ALL_NOTES_OFF;
  620. midiData[2] = 0;
  621. fMidiBuffer.addEvent(midiData, 3, static_cast<int>(event.time));
  622. }
  623. break;
  624. } // switch (ctrlEvent.type)
  625. break;
  626. } // case kEngineEventTypeControl
  627. case kEngineEventTypeMidi:
  628. {
  629. const EngineMidiEvent& midiEvent(event.midi);
  630. uint8_t status = uint8_t(MIDI_GET_STATUS_FROM_DATA(midiEvent.data));
  631. uint8_t channel = event.channel;
  632. // Fix bad note-off
  633. if (MIDI_IS_STATUS_NOTE_ON(status) && midiEvent.data[2] == 0)
  634. status = MIDI_STATUS_NOTE_OFF;
  635. if (status == MIDI_STATUS_CHANNEL_PRESSURE && (pData->options & PLUGIN_OPTION_SEND_CHANNEL_PRESSURE) == 0)
  636. continue;
  637. if (status == MIDI_STATUS_CONTROL_CHANGE && (pData->options & PLUGIN_OPTION_SEND_CONTROL_CHANGES) == 0)
  638. continue;
  639. if (status == MIDI_STATUS_POLYPHONIC_AFTERTOUCH && (pData->options & PLUGIN_OPTION_SEND_NOTE_AFTERTOUCH) == 0)
  640. continue;
  641. if (status == MIDI_STATUS_PITCH_WHEEL_CONTROL && (pData->options & PLUGIN_OPTION_SEND_PITCHBEND) == 0)
  642. continue;
  643. fMidiBuffer.addEvent(midiEvent.data, midiEvent.size, static_cast<int>(event.time));
  644. if (status == MIDI_STATUS_NOTE_ON)
  645. pData->postponeRtEvent(kPluginPostRtEventNoteOn, channel, midiEvent.data[1], midiEvent.data[2]);
  646. else if (status == MIDI_STATUS_NOTE_OFF)
  647. pData->postponeRtEvent(kPluginPostRtEventNoteOff, channel, midiEvent.data[1], 0.0f);
  648. break;
  649. } // case kEngineEventTypeMidi
  650. } // switch (event.type)
  651. }
  652. pData->postRtEvents.trySplice();
  653. } // End of Event Input
  654. // --------------------------------------------------------------------------------------------------------
  655. // Set TimeInfo
  656. const EngineTimeInfo& timeInfo(pData->engine->getTimeInfo());
  657. fPosInfo.isPlaying = timeInfo.playing;
  658. if (timeInfo.valid & EngineTimeInfo::kValidBBT)
  659. {
  660. const double ppqBar = double(timeInfo.bbt.bar - 1) * timeInfo.bbt.beatsPerBar;
  661. const double ppqBeat = double(timeInfo.bbt.beat - 1);
  662. const double ppqTick = double(timeInfo.bbt.tick) / timeInfo.bbt.ticksPerBeat;
  663. fPosInfo.bpm = timeInfo.bbt.beatsPerMinute;
  664. fPosInfo.timeSigNumerator = static_cast<int>(timeInfo.bbt.beatsPerBar);
  665. fPosInfo.timeSigDenominator = static_cast<int>(timeInfo.bbt.beatType);
  666. fPosInfo.timeInSamples = static_cast<int64_t>(timeInfo.frame);
  667. fPosInfo.timeInSeconds = static_cast<double>(fPosInfo.timeInSamples)/pData->engine->getSampleRate();
  668. fPosInfo.ppqPosition = ppqBar + ppqBeat + ppqTick;
  669. fPosInfo.ppqPositionOfLastBarStart = ppqBar;
  670. }
  671. // --------------------------------------------------------------------------------------------------------
  672. // Process
  673. processSingle(inBuffer, outBuffer, frames);
  674. // --------------------------------------------------------------------------------------------------------
  675. // MIDI Output
  676. if (pData->event.portOut != nullptr)
  677. {
  678. // TODO
  679. }
  680. }
  681. bool processSingle(float** const inBuffer, float** const outBuffer, const uint32_t frames)
  682. {
  683. CARLA_SAFE_ASSERT_RETURN(frames > 0, false);
  684. if (pData->audioIn.count > 0)
  685. {
  686. CARLA_SAFE_ASSERT_RETURN(inBuffer != nullptr, false);
  687. }
  688. if (pData->audioOut.count > 0)
  689. {
  690. CARLA_SAFE_ASSERT_RETURN(outBuffer != nullptr, false);
  691. }
  692. // --------------------------------------------------------------------------------------------------------
  693. // Try lock, silence otherwise
  694. if (pData->engine->isOffline())
  695. {
  696. pData->singleMutex.lock();
  697. }
  698. else if (! pData->singleMutex.tryLock())
  699. {
  700. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  701. FloatVectorOperations::clear(outBuffer[i], static_cast<int>(frames));
  702. return false;
  703. }
  704. // --------------------------------------------------------------------------------------------------------
  705. // Set audio in buffers
  706. for (uint32_t i=0; i < pData->audioIn.count; ++i)
  707. fAudioBuffer.copyFrom(static_cast<int>(i), 0, inBuffer[i], static_cast<int>(frames));
  708. // --------------------------------------------------------------------------------------------------------
  709. // Run plugin
  710. fInstance->processBlock(fAudioBuffer, fMidiBuffer);
  711. // --------------------------------------------------------------------------------------------------------
  712. // Set audio out buffers
  713. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  714. FloatVectorOperations::copy(outBuffer[i], fAudioBuffer.getReadPointer(static_cast<int>(i)), static_cast<int>(frames));
  715. // --------------------------------------------------------------------------------------------------------
  716. // Midi out
  717. if (! fMidiBuffer.isEmpty())
  718. {
  719. if (pData->event.portOut != nullptr)
  720. {
  721. const uint8* midiEventData;
  722. int midiEventSize, midiEventPosition;
  723. for (MidiBuffer::Iterator i(fMidiBuffer); i.getNextEvent(midiEventData, midiEventSize, midiEventPosition);)
  724. {
  725. CARLA_SAFE_ASSERT_BREAK(midiEventPosition >= 0 && midiEventPosition < static_cast<int>(frames));
  726. CARLA_SAFE_ASSERT_BREAK(midiEventSize > 0);
  727. if (! pData->event.portOut->writeMidiEvent(static_cast<uint32_t>(midiEventPosition), static_cast<uint8_t>(midiEventSize), midiEventData))
  728. break;
  729. }
  730. }
  731. fMidiBuffer.clear();
  732. }
  733. // --------------------------------------------------------------------------------------------------------
  734. pData->singleMutex.unlock();
  735. return true;
  736. }
  737. void bufferSizeChanged(const uint32_t newBufferSize) override
  738. {
  739. CARLA_ASSERT_INT(newBufferSize > 0, newBufferSize);
  740. carla_debug("VstPlugin::bufferSizeChanged(%i)", newBufferSize);
  741. fAudioBuffer.setSize(static_cast<int>(std::max<uint32_t>(pData->audioIn.count, pData->audioOut.count)), static_cast<int>(newBufferSize));
  742. if (pData->active)
  743. {
  744. deactivate();
  745. activate();
  746. }
  747. }
  748. void sampleRateChanged(const double newSampleRate) override
  749. {
  750. CARLA_ASSERT_INT(newSampleRate > 0.0, newSampleRate);
  751. carla_debug("VstPlugin::sampleRateChanged(%g)", newSampleRate);
  752. if (pData->active)
  753. {
  754. deactivate();
  755. activate();
  756. }
  757. }
  758. // -------------------------------------------------------------------
  759. // Plugin buffers
  760. // nothing
  761. // -------------------------------------------------------------------
  762. // Post-poned UI Stuff
  763. // nothing
  764. // -------------------------------------------------------------------
  765. protected:
  766. void audioProcessorParameterChanged(AudioProcessor*, int index, float value) override
  767. {
  768. CARLA_SAFE_ASSERT_RETURN(index >= 0,);
  769. const uint32_t uindex(static_cast<uint32_t>(index));
  770. const float fixedValue(pData->param.getFixedValue(uindex, value));
  771. CarlaPlugin::setParameterValue(static_cast<uint32_t>(index), fixedValue, false, true, true);
  772. }
  773. void audioProcessorChanged(AudioProcessor*) override
  774. {
  775. pData->engine->callback(ENGINE_CALLBACK_UPDATE, pData->id, 0, 0, 0.0f, nullptr);
  776. }
  777. void audioProcessorParameterChangeGestureBegin(AudioProcessor*, int) {}
  778. void audioProcessorParameterChangeGestureEnd(AudioProcessor*, int) {}
  779. bool getCurrentPosition(CurrentPositionInfo& result) override
  780. {
  781. carla_copyStruct<CurrentPositionInfo>(result, fPosInfo);
  782. return true;
  783. }
  784. // -------------------------------------------------------------------
  785. public:
  786. bool init(const char* const filename, const char* const name, /*const char* const label, */const int64_t uniqueId, const char* const format)
  787. {
  788. CARLA_SAFE_ASSERT_RETURN(pData->engine != nullptr, false);
  789. // ---------------------------------------------------------------
  790. // first checks
  791. if (pData->client != nullptr)
  792. {
  793. pData->engine->setLastError("Plugin client is already registered");
  794. return false;
  795. }
  796. if (filename == nullptr || filename[0] == '\0')
  797. {
  798. pData->engine->setLastError("null filename");
  799. return false;
  800. }
  801. #if 0
  802. if (label == nullptr || label[0] == '\0')
  803. {
  804. pData->engine->setLastError("null label");
  805. return false;
  806. }
  807. #endif
  808. if (format == nullptr || format[0] == '\0')
  809. {
  810. pData->engine->setLastError("null format");
  811. return false;
  812. }
  813. #ifdef CARLA_OS_LINUX
  814. const MessageManagerLock mmLock;
  815. #endif
  816. // ---------------------------------------------------------------
  817. // fix path for wine usage
  818. String jfilename(filename);
  819. #ifdef CARLA_OS_WIN
  820. if (jfilename.startsWith("/"))
  821. {
  822. jfilename.replace("/", "\\");
  823. jfilename = "Z:" + jfilename;
  824. }
  825. #endif
  826. //fDesc.name = fDesc.descriptiveName = label;
  827. fDesc.uid = static_cast<int>(uniqueId);
  828. fDesc.fileOrIdentifier = jfilename;
  829. fDesc.pluginFormatName = format;
  830. fFormatManager.addDefaultFormats();
  831. String error;
  832. fInstance = fFormatManager.createPluginInstance(fDesc, 44100, 512, error);
  833. if (fInstance == nullptr)
  834. {
  835. pData->engine->setLastError(error.toRawUTF8());
  836. return false;
  837. }
  838. fInstance->fillInPluginDescription(fDesc);
  839. fInstance->setPlayHead(this);
  840. fInstance->addListener(this);
  841. // ---------------------------------------------------------------
  842. // get info
  843. if (name != nullptr && name[0] != '\0')
  844. pData->name = pData->engine->getUniquePluginName(name);
  845. else
  846. pData->name = pData->engine->getUniquePluginName(fInstance->getName().toRawUTF8());
  847. pData->filename = carla_strdup(filename);
  848. // ---------------------------------------------------------------
  849. // register client
  850. pData->client = pData->engine->addClient(this);
  851. if (pData->client == nullptr || ! pData->client->isOk())
  852. {
  853. pData->engine->setLastError("Failed to register plugin client");
  854. return false;
  855. }
  856. // ---------------------------------------------------------------
  857. // load plugin settings
  858. {
  859. // set default options
  860. pData->options = 0x0;
  861. pData->options |= PLUGIN_OPTION_FIXED_BUFFERS;
  862. pData->options |= PLUGIN_OPTION_MAP_PROGRAM_CHANGES;
  863. //pData->options |= PLUGIN_OPTION_USE_CHUNKS;
  864. if (fInstance->acceptsMidi())
  865. {
  866. pData->options |= PLUGIN_OPTION_SEND_CHANNEL_PRESSURE;
  867. pData->options |= PLUGIN_OPTION_SEND_NOTE_AFTERTOUCH;
  868. pData->options |= PLUGIN_OPTION_SEND_PITCHBEND;
  869. pData->options |= PLUGIN_OPTION_SEND_ALL_SOUND_OFF;
  870. }
  871. // set identifier string
  872. String juceId(fDesc.createIdentifierString());
  873. CarlaString identifier("Juce/");
  874. identifier += juceId.toRawUTF8();
  875. pData->identifier = identifier.dup();
  876. // load settings
  877. pData->options = pData->loadSettings(pData->options, getOptionsAvailable());
  878. // ignore settings, we need this anyway
  879. pData->options |= PLUGIN_OPTION_FIXED_BUFFERS;
  880. }
  881. return true;
  882. }
  883. private:
  884. PluginDescription fDesc;
  885. AudioPluginInstance* fInstance;
  886. AudioPluginFormatManager fFormatManager;
  887. AudioSampleBuffer fAudioBuffer;
  888. MidiBuffer fMidiBuffer;
  889. CurrentPositionInfo fPosInfo;
  890. const char* fUniqueId;
  891. ScopedPointer<JucePluginWindow> fWindow;
  892. CARLA_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(JucePlugin)
  893. };
  894. CARLA_BACKEND_END_NAMESPACE
  895. #endif // HAVE_JUCE
  896. // -------------------------------------------------------------------------------------------------------------------
  897. CARLA_BACKEND_START_NAMESPACE
  898. CarlaPlugin* CarlaPlugin::newJuce(const Initializer& init, const char* const format)
  899. {
  900. carla_debug("CarlaPlugin::newJuce({%p, \"%s\", \"%s\", \"%s\", " P_INT64 "}, %s)", init.engine, init.filename, init.name, init.label, init.uniqueId, format);
  901. #ifdef HAVE_JUCE
  902. JucePlugin* const plugin(new JucePlugin(init.engine, init.id));
  903. if (! plugin->init(init.filename, init.name, /*init.label,*/ init.uniqueId, format))
  904. {
  905. delete plugin;
  906. return nullptr;
  907. }
  908. plugin->reload();
  909. if (init.engine->getProccessMode() == ENGINE_PROCESS_MODE_CONTINUOUS_RACK && ! plugin->canRunInRack())
  910. {
  911. init.engine->setLastError("Carla's rack mode can only work with Stereo VST3 plugins, sorry!");
  912. delete plugin;
  913. return nullptr;
  914. }
  915. return plugin;
  916. #else
  917. init.engine->setLastError("Juce support not available");
  918. return nullptr;
  919. // unused
  920. (void)format;
  921. #endif
  922. }
  923. CARLA_BACKEND_END_NAMESPACE
  924. // -------------------------------------------------------------------------------------------------------------------