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.

1324 lines
45KB

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