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.

1304 lines
45KB

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