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.

1205 lines
41KB

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