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.

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