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.

1289 lines
44KB

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