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.

1201 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(float** const inBuffer, float** const outBuffer, 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(outBuffer[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] = 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. #ifndef BUILD_BRIDGE
  484. bool allNotesOffSent = false;
  485. #endif
  486. uint32_t numEvents = pData->event.portIn->getEventCount();
  487. uint32_t nextBankId;
  488. if (pData->midiprog.current >= 0 && pData->midiprog.count > 0)
  489. nextBankId = pData->midiprog.data[pData->midiprog.current].bank;
  490. else
  491. nextBankId = 0;
  492. for (uint32_t i=0; i < numEvents; ++i)
  493. {
  494. const EngineEvent& event(pData->event.portIn->getEvent(i));
  495. if (event.time >= frames)
  496. continue;
  497. switch (event.type)
  498. {
  499. case kEngineEventTypeNull:
  500. break;
  501. case kEngineEventTypeControl: {
  502. const EngineControlEvent& ctrlEvent(event.ctrl);
  503. switch (ctrlEvent.type)
  504. {
  505. case kEngineControlEventTypeNull:
  506. break;
  507. case kEngineControlEventTypeParameter: {
  508. #ifndef BUILD_BRIDGE
  509. // Control backend stuff
  510. if (event.channel == pData->ctrlChannel)
  511. {
  512. float value;
  513. if (MIDI_IS_CONTROL_BREATH_CONTROLLER(ctrlEvent.param) && (pData->hints & PLUGIN_CAN_DRYWET) != 0)
  514. {
  515. value = ctrlEvent.value;
  516. setDryWet(value, false, false);
  517. pData->postponeRtEvent(kPluginPostRtEventParameterChange, PARAMETER_DRYWET, 0, value);
  518. break;
  519. }
  520. if (MIDI_IS_CONTROL_CHANNEL_VOLUME(ctrlEvent.param) && (pData->hints & PLUGIN_CAN_VOLUME) != 0)
  521. {
  522. value = ctrlEvent.value*127.0f/100.0f;
  523. setVolume(value, false, false);
  524. pData->postponeRtEvent(kPluginPostRtEventParameterChange, PARAMETER_VOLUME, 0, value);
  525. break;
  526. }
  527. if (MIDI_IS_CONTROL_BALANCE(ctrlEvent.param) && (pData->hints & PLUGIN_CAN_BALANCE) != 0)
  528. {
  529. float left, right;
  530. value = ctrlEvent.value/0.5f - 1.0f;
  531. if (value < 0.0f)
  532. {
  533. left = -1.0f;
  534. right = (value*2.0f)+1.0f;
  535. }
  536. else if (value > 0.0f)
  537. {
  538. left = (value*2.0f)-1.0f;
  539. right = 1.0f;
  540. }
  541. else
  542. {
  543. left = -1.0f;
  544. right = 1.0f;
  545. }
  546. setBalanceLeft(left, false, false);
  547. setBalanceRight(right, false, false);
  548. pData->postponeRtEvent(kPluginPostRtEventParameterChange, PARAMETER_BALANCE_LEFT, 0, left);
  549. pData->postponeRtEvent(kPluginPostRtEventParameterChange, PARAMETER_BALANCE_RIGHT, 0, right);
  550. break;
  551. }
  552. }
  553. #endif
  554. // Control plugin parameters
  555. uint32_t k;
  556. for (k=0; k < pData->param.count; ++k)
  557. {
  558. if (pData->param.data[k].midiChannel != event.channel)
  559. continue;
  560. if (pData->param.data[k].midiCC != ctrlEvent.param)
  561. continue;
  562. if (pData->param.data[k].type != PARAMETER_INPUT)
  563. continue;
  564. if ((pData->param.data[k].hints & PARAMETER_IS_AUTOMABLE) == 0)
  565. continue;
  566. float value;
  567. if (pData->param.data[k].hints & PARAMETER_IS_BOOLEAN)
  568. {
  569. value = (ctrlEvent.value < 0.5f) ? pData->param.ranges[k].min : pData->param.ranges[k].max;
  570. }
  571. else
  572. {
  573. value = pData->param.ranges[k].getUnnormalizedValue(ctrlEvent.value);
  574. if (pData->param.data[k].hints & PARAMETER_IS_INTEGER)
  575. value = std::rint(value);
  576. }
  577. setParameterValue(k, value, false, false, false);
  578. pData->postponeRtEvent(kPluginPostRtEventParameterChange, static_cast<int32_t>(k), 0, value);
  579. break;
  580. }
  581. // check if event is already handled
  582. if (k != pData->param.count)
  583. break;
  584. if ((pData->options & PLUGIN_OPTION_SEND_CONTROL_CHANGES) != 0 && ctrlEvent.param <= 0x5F)
  585. {
  586. uint8_t midiData[3];
  587. midiData[0] = static_cast<uint8_t>(MIDI_STATUS_CONTROL_CHANGE + i);
  588. midiData[1] = static_cast<uint8_t>(ctrlEvent.param);
  589. midiData[2] = uint8_t(ctrlEvent.value*127.0f);
  590. fMidiBuffer.addEvent(midiData, 3, static_cast<int>(event.time));
  591. }
  592. break;
  593. } // case kEngineControlEventTypeParameter
  594. case kEngineControlEventTypeMidiBank:
  595. if (event.channel == pData->ctrlChannel && (pData->options & PLUGIN_OPTION_MAP_PROGRAM_CHANGES) != 0)
  596. nextBankId = ctrlEvent.param;
  597. break;
  598. case kEngineControlEventTypeMidiProgram:
  599. if (event.channel == pData->ctrlChannel && (pData->options & PLUGIN_OPTION_MAP_PROGRAM_CHANGES) != 0)
  600. {
  601. const uint32_t nextProgramId = ctrlEvent.param;
  602. for (uint32_t k=0; k < pData->midiprog.count; ++k)
  603. {
  604. if (pData->midiprog.data[k].bank == nextBankId && pData->midiprog.data[k].program == nextProgramId)
  605. {
  606. const int32_t index(static_cast<int32_t>(k));
  607. setMidiProgram(index, false, false, false);
  608. pData->postponeRtEvent(kPluginPostRtEventMidiProgramChange, index, 0, 0.0f);
  609. break;
  610. }
  611. }
  612. }
  613. break;
  614. case kEngineControlEventTypeAllSoundOff:
  615. if (pData->options & PLUGIN_OPTION_SEND_ALL_SOUND_OFF)
  616. {
  617. uint8_t midiData[3];
  618. midiData[0] = static_cast<uint8_t>(MIDI_STATUS_CONTROL_CHANGE + i);
  619. midiData[1] = MIDI_CONTROL_ALL_SOUND_OFF;
  620. midiData[2] = 0;
  621. fMidiBuffer.addEvent(midiData, 3, static_cast<int>(event.time));
  622. }
  623. break;
  624. case kEngineControlEventTypeAllNotesOff:
  625. if (pData->options & PLUGIN_OPTION_SEND_ALL_SOUND_OFF)
  626. {
  627. #ifndef BUILD_BRIDGE
  628. if (event.channel == pData->ctrlChannel && ! allNotesOffSent)
  629. {
  630. allNotesOffSent = true;
  631. sendMidiAllNotesOffToCallback();
  632. }
  633. #endif
  634. uint8_t midiData[3];
  635. midiData[0] = static_cast<uint8_t>(MIDI_STATUS_CONTROL_CHANGE + i);
  636. midiData[1] = MIDI_CONTROL_ALL_NOTES_OFF;
  637. midiData[2] = 0;
  638. fMidiBuffer.addEvent(midiData, 3, static_cast<int>(event.time));
  639. }
  640. break;
  641. } // switch (ctrlEvent.type)
  642. break;
  643. } // case kEngineEventTypeControl
  644. case kEngineEventTypeMidi:
  645. {
  646. const EngineMidiEvent& midiEvent(event.midi);
  647. uint8_t status = uint8_t(MIDI_GET_STATUS_FROM_DATA(midiEvent.data));
  648. uint8_t channel = event.channel;
  649. // Fix bad note-off
  650. if (MIDI_IS_STATUS_NOTE_ON(status) && midiEvent.data[2] == 0)
  651. status = MIDI_STATUS_NOTE_OFF;
  652. if (status == MIDI_STATUS_CHANNEL_PRESSURE && (pData->options & PLUGIN_OPTION_SEND_CHANNEL_PRESSURE) == 0)
  653. continue;
  654. if (status == MIDI_STATUS_CONTROL_CHANGE && (pData->options & PLUGIN_OPTION_SEND_CONTROL_CHANGES) == 0)
  655. continue;
  656. if (status == MIDI_STATUS_POLYPHONIC_AFTERTOUCH && (pData->options & PLUGIN_OPTION_SEND_NOTE_AFTERTOUCH) == 0)
  657. continue;
  658. if (status == MIDI_STATUS_PITCH_WHEEL_CONTROL && (pData->options & PLUGIN_OPTION_SEND_PITCHBEND) == 0)
  659. continue;
  660. fMidiBuffer.addEvent(midiEvent.data, midiEvent.size, static_cast<int>(event.time));
  661. if (status == MIDI_STATUS_NOTE_ON)
  662. pData->postponeRtEvent(kPluginPostRtEventNoteOn, channel, midiEvent.data[1], midiEvent.data[2]);
  663. else if (status == MIDI_STATUS_NOTE_OFF)
  664. pData->postponeRtEvent(kPluginPostRtEventNoteOff, channel, midiEvent.data[1], 0.0f);
  665. break;
  666. } // case kEngineEventTypeMidi
  667. } // switch (event.type)
  668. }
  669. pData->postRtEvents.trySplice();
  670. } // End of Event Input
  671. // --------------------------------------------------------------------------------------------------------
  672. // Set TimeInfo
  673. const EngineTimeInfo& timeInfo(pData->engine->getTimeInfo());
  674. fPosInfo.isPlaying = timeInfo.playing;
  675. if (timeInfo.valid & EngineTimeInfo::kValidBBT)
  676. {
  677. const double ppqBar = double(timeInfo.bbt.bar - 1) * timeInfo.bbt.beatsPerBar;
  678. const double ppqBeat = double(timeInfo.bbt.beat - 1);
  679. const double ppqTick = double(timeInfo.bbt.tick) / timeInfo.bbt.ticksPerBeat;
  680. fPosInfo.bpm = timeInfo.bbt.beatsPerMinute;
  681. fPosInfo.timeSigNumerator = static_cast<int>(timeInfo.bbt.beatsPerBar);
  682. fPosInfo.timeSigDenominator = static_cast<int>(timeInfo.bbt.beatType);
  683. fPosInfo.timeInSamples = static_cast<int64_t>(timeInfo.frame);
  684. fPosInfo.timeInSeconds = static_cast<double>(fPosInfo.timeInSamples)/pData->engine->getSampleRate();
  685. fPosInfo.ppqPosition = ppqBar + ppqBeat + ppqTick;
  686. fPosInfo.ppqPositionOfLastBarStart = ppqBar;
  687. }
  688. // --------------------------------------------------------------------------------------------------------
  689. // Process
  690. processSingle(inBuffer, outBuffer, frames);
  691. // --------------------------------------------------------------------------------------------------------
  692. // MIDI Output
  693. if (pData->event.portOut != nullptr)
  694. {
  695. // TODO
  696. }
  697. }
  698. bool processSingle(float** const inBuffer, float** const outBuffer, const uint32_t frames)
  699. {
  700. CARLA_SAFE_ASSERT_RETURN(frames > 0, false);
  701. if (pData->audioIn.count > 0)
  702. {
  703. CARLA_SAFE_ASSERT_RETURN(inBuffer != nullptr, false);
  704. }
  705. if (pData->audioOut.count > 0)
  706. {
  707. CARLA_SAFE_ASSERT_RETURN(outBuffer != nullptr, false);
  708. }
  709. // --------------------------------------------------------------------------------------------------------
  710. // Try lock, silence otherwise
  711. if (pData->engine->isOffline())
  712. {
  713. pData->singleMutex.lock();
  714. }
  715. else if (! pData->singleMutex.tryLock())
  716. {
  717. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  718. FloatVectorOperations::clear(outBuffer[i], static_cast<int>(frames));
  719. return false;
  720. }
  721. // --------------------------------------------------------------------------------------------------------
  722. // Set audio in buffers
  723. for (uint32_t i=0; i < pData->audioIn.count; ++i)
  724. fAudioBuffer.copyFrom(static_cast<int>(i), 0, inBuffer[i], static_cast<int>(frames));
  725. // --------------------------------------------------------------------------------------------------------
  726. // Run plugin
  727. fInstance->processBlock(fAudioBuffer, fMidiBuffer);
  728. // --------------------------------------------------------------------------------------------------------
  729. // Set audio out buffers
  730. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  731. FloatVectorOperations::copy(outBuffer[i], fAudioBuffer.getReadPointer(static_cast<int>(i)), static_cast<int>(frames));
  732. // --------------------------------------------------------------------------------------------------------
  733. // Midi out
  734. if (! fMidiBuffer.isEmpty())
  735. {
  736. if (pData->event.portOut != nullptr)
  737. {
  738. const uint8* midiEventData;
  739. int midiEventSize, midiEventPosition;
  740. for (MidiBuffer::Iterator i(fMidiBuffer); i.getNextEvent(midiEventData, midiEventSize, midiEventPosition);)
  741. {
  742. CARLA_SAFE_ASSERT_BREAK(midiEventPosition >= 0 && midiEventPosition < static_cast<int>(frames));
  743. CARLA_SAFE_ASSERT_BREAK(midiEventSize > 0);
  744. if (! pData->event.portOut->writeMidiEvent(static_cast<uint32_t>(midiEventPosition), static_cast<uint8_t>(midiEventSize), midiEventData))
  745. break;
  746. }
  747. }
  748. fMidiBuffer.clear();
  749. }
  750. // --------------------------------------------------------------------------------------------------------
  751. pData->singleMutex.unlock();
  752. return true;
  753. }
  754. void bufferSizeChanged(const uint32_t newBufferSize) override
  755. {
  756. CARLA_ASSERT_INT(newBufferSize > 0, newBufferSize);
  757. carla_debug("VstPlugin::bufferSizeChanged(%i)", newBufferSize);
  758. fAudioBuffer.setSize(static_cast<int>(std::max<uint32_t>(pData->audioIn.count, pData->audioOut.count)), static_cast<int>(newBufferSize));
  759. if (pData->active)
  760. {
  761. deactivate();
  762. activate();
  763. }
  764. }
  765. void sampleRateChanged(const double newSampleRate) override
  766. {
  767. CARLA_ASSERT_INT(newSampleRate > 0.0, newSampleRate);
  768. carla_debug("VstPlugin::sampleRateChanged(%g)", newSampleRate);
  769. if (pData->active)
  770. {
  771. deactivate();
  772. activate();
  773. }
  774. }
  775. // -------------------------------------------------------------------
  776. // Plugin buffers
  777. // nothing
  778. // -------------------------------------------------------------------
  779. // Post-poned UI Stuff
  780. // nothing
  781. // -------------------------------------------------------------------
  782. void* getNativeHandle() const noexcept override
  783. {
  784. return (fInstance != nullptr) ? fInstance->getPlatformSpecificData() : nullptr;
  785. }
  786. // -------------------------------------------------------------------
  787. protected:
  788. void audioProcessorParameterChanged(AudioProcessor*, int index, float value) override
  789. {
  790. CARLA_SAFE_ASSERT_RETURN(index >= 0,);
  791. const uint32_t uindex(static_cast<uint32_t>(index));
  792. const float fixedValue(pData->param.getFixedValue(uindex, value));
  793. CarlaPlugin::setParameterValue(static_cast<uint32_t>(index), fixedValue, false, true, true);
  794. }
  795. void audioProcessorChanged(AudioProcessor*) override
  796. {
  797. pData->engine->callback(ENGINE_CALLBACK_UPDATE, pData->id, 0, 0, 0.0f, nullptr);
  798. }
  799. void audioProcessorParameterChangeGestureBegin(AudioProcessor*, int) override {}
  800. void audioProcessorParameterChangeGestureEnd(AudioProcessor*, int) override {}
  801. bool getCurrentPosition(CurrentPositionInfo& result) override
  802. {
  803. carla_copyStruct<CurrentPositionInfo>(result, fPosInfo);
  804. return true;
  805. }
  806. // -------------------------------------------------------------------
  807. public:
  808. bool init(const char* const filename, const char* const name, /*const char* const label, */const int64_t uniqueId, const char* const format)
  809. {
  810. CARLA_SAFE_ASSERT_RETURN(pData->engine != nullptr, false);
  811. // ---------------------------------------------------------------
  812. // first checks
  813. if (pData->client != nullptr)
  814. {
  815. pData->engine->setLastError("Plugin client is already registered");
  816. return false;
  817. }
  818. if (filename == nullptr || filename[0] == '\0')
  819. {
  820. pData->engine->setLastError("null filename");
  821. return false;
  822. }
  823. #if 0
  824. if (label == nullptr || label[0] == '\0')
  825. {
  826. pData->engine->setLastError("null label");
  827. return false;
  828. }
  829. #endif
  830. if (format == nullptr || format[0] == '\0')
  831. {
  832. pData->engine->setLastError("null format");
  833. return false;
  834. }
  835. // ---------------------------------------------------------------
  836. // fix path for wine usage
  837. String jfilename(filename);
  838. #ifdef CARLA_OS_WIN
  839. if (jfilename.startsWith("/"))
  840. {
  841. jfilename.replace("/", "\\");
  842. jfilename = "Z:" + jfilename;
  843. }
  844. #endif
  845. //fDesc.name = fDesc.descriptiveName = label;
  846. fDesc.uid = static_cast<int>(uniqueId);
  847. fDesc.fileOrIdentifier = jfilename;
  848. fDesc.pluginFormatName = format;
  849. fFormatManager.addDefaultFormats();
  850. String error;
  851. fInstance = fFormatManager.createPluginInstance(fDesc, 44100, 512, error);
  852. if (fInstance == nullptr)
  853. {
  854. pData->engine->setLastError(error.toRawUTF8());
  855. return false;
  856. }
  857. fInstance->fillInPluginDescription(fDesc);
  858. fInstance->setPlayHead(this);
  859. fInstance->addListener(this);
  860. // ---------------------------------------------------------------
  861. // get info
  862. if (name != nullptr && name[0] != '\0')
  863. pData->name = pData->engine->getUniquePluginName(name);
  864. else
  865. pData->name = pData->engine->getUniquePluginName(fInstance->getName().toRawUTF8());
  866. pData->filename = carla_strdup(filename);
  867. // ---------------------------------------------------------------
  868. // register client
  869. pData->client = pData->engine->addClient(this);
  870. if (pData->client == nullptr || ! pData->client->isOk())
  871. {
  872. pData->engine->setLastError("Failed to register plugin client");
  873. return false;
  874. }
  875. // ---------------------------------------------------------------
  876. // set default options
  877. pData->options = 0x0;
  878. pData->options |= PLUGIN_OPTION_FIXED_BUFFERS;
  879. pData->options |= PLUGIN_OPTION_MAP_PROGRAM_CHANGES;
  880. pData->options |= PLUGIN_OPTION_USE_CHUNKS;
  881. if (fInstance->acceptsMidi())
  882. {
  883. pData->options |= PLUGIN_OPTION_SEND_CHANNEL_PRESSURE;
  884. pData->options |= PLUGIN_OPTION_SEND_NOTE_AFTERTOUCH;
  885. pData->options |= PLUGIN_OPTION_SEND_PITCHBEND;
  886. pData->options |= PLUGIN_OPTION_SEND_ALL_SOUND_OFF;
  887. }
  888. return true;
  889. }
  890. private:
  891. PluginDescription fDesc;
  892. AudioPluginInstance* fInstance;
  893. AudioPluginFormatManager fFormatManager;
  894. AudioSampleBuffer fAudioBuffer;
  895. MidiBuffer fMidiBuffer;
  896. CurrentPositionInfo fPosInfo;
  897. MemoryBlock fChunk;
  898. const char* fUniqueId;
  899. ScopedPointer<JucePluginWindow> fWindow;
  900. CARLA_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(JucePlugin)
  901. };
  902. CARLA_BACKEND_END_NAMESPACE
  903. #endif // defined(CARLA_OS_MAC) || defined(CARLA_OS_WIN)
  904. // -------------------------------------------------------------------------------------------------------------------
  905. CARLA_BACKEND_START_NAMESPACE
  906. CarlaPlugin* CarlaPlugin::newJuce(const Initializer& init, const char* const format)
  907. {
  908. carla_debug("CarlaPlugin::newJuce({%p, \"%s\", \"%s\", \"%s\", " P_INT64 "}, %s)", init.engine, init.filename, init.name, init.label, init.uniqueId, format);
  909. #if (defined(CARLA_OS_MAC) || defined(CARLA_OS_WIN))
  910. JucePlugin* const plugin(new JucePlugin(init.engine, init.id));
  911. if (! plugin->init(init.filename, init.name, /*init.label,*/ init.uniqueId, format))
  912. {
  913. delete plugin;
  914. return nullptr;
  915. }
  916. plugin->reload();
  917. if (init.engine->getProccessMode() == ENGINE_PROCESS_MODE_CONTINUOUS_RACK && ! plugin->canRunInRack())
  918. {
  919. init.engine->setLastError("Carla's rack mode can only work with Stereo VST3 plugins, sorry!");
  920. delete plugin;
  921. return nullptr;
  922. }
  923. return plugin;
  924. #else
  925. init.engine->setLastError("Juce plugin not available");
  926. return nullptr;
  927. (void)format;
  928. #endif
  929. }
  930. CARLA_BACKEND_END_NAMESPACE
  931. // -------------------------------------------------------------------------------------------------------------------