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.

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