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.

1208 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. #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. // 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. #endif
  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. // -------------------------------------------------------------------------------------------------------------------