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.

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