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.

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