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.

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