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.

1284 lines
44KB

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