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.

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