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.

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