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.

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