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.

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