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.

1130 lines
38KB

  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. #ifdef HAVE_JUCE
  20. #include "CarlaBackendUtils.hpp"
  21. #include "JucePluginWindow.hpp"
  22. #include "juce_audio_processors.h"
  23. using namespace juce;
  24. CARLA_BACKEND_START_NAMESPACE
  25. class JucePlugin : public CarlaPlugin,
  26. public AudioPlayHead
  27. {
  28. public:
  29. JucePlugin(CarlaEngine* const engine, const uint id)
  30. : CarlaPlugin(engine, id),
  31. fInstance(nullptr),
  32. fAudioBuffer(1, 0)
  33. {
  34. carla_debug("JucePlugin::JucePlugin(%p, %i)", engine, id);
  35. fMidiBuffer.ensureSize(2048);
  36. fMidiBuffer.clear();
  37. fPosInfo.resetToDefault();
  38. }
  39. ~JucePlugin() override
  40. {
  41. carla_debug("JucePlugin::~JucePlugin()");
  42. // close UI
  43. if (pData->hints & PLUGIN_HAS_CUSTOM_UI)
  44. showCustomUI(false);
  45. pData->singleMutex.lock();
  46. pData->masterMutex.lock();
  47. if (pData->client != nullptr && pData->client->isActive())
  48. pData->client->deactivate();
  49. if (pData->active)
  50. {
  51. deactivate();
  52. pData->active = false;
  53. }
  54. if (fInstance != nullptr)
  55. {
  56. delete fInstance;
  57. fInstance = nullptr;
  58. }
  59. clearBuffers();
  60. }
  61. // -------------------------------------------------------------------
  62. // Information (base)
  63. PluginType getType() const noexcept override
  64. {
  65. PluginType type = PLUGIN_NONE;
  66. try {
  67. type = getPluginTypeFromString(fDesc.pluginFormatName.toRawUTF8());
  68. } catch(...) {}
  69. return type;
  70. }
  71. PluginCategory getCategory() const noexcept override
  72. {
  73. PluginCategory category = PLUGIN_CATEGORY_NONE;
  74. try {
  75. category = getPluginCategoryFromName(fDesc.category.toRawUTF8());
  76. } catch(...) {}
  77. return category;
  78. }
  79. int64_t getUniqueId() const noexcept override
  80. {
  81. return fDesc.uid;
  82. }
  83. // -------------------------------------------------------------------
  84. // Information (count)
  85. // nothing
  86. // -------------------------------------------------------------------
  87. // Information (current data)
  88. // nothing
  89. // -------------------------------------------------------------------
  90. // Information (per-plugin data)
  91. unsigned int getOptionsAvailable() const noexcept override
  92. {
  93. CARLA_SAFE_ASSERT_RETURN(fInstance != nullptr, 0x0);
  94. unsigned int options = 0x0;
  95. options |= PLUGIN_OPTION_MAP_PROGRAM_CHANGES;
  96. //options |= PLUGIN_OPTION_USE_CHUNKS;
  97. if (fInstance->acceptsMidi())
  98. {
  99. options |= PLUGIN_OPTION_SEND_CONTROL_CHANGES;
  100. options |= PLUGIN_OPTION_SEND_CHANNEL_PRESSURE;
  101. options |= PLUGIN_OPTION_SEND_NOTE_AFTERTOUCH;
  102. options |= PLUGIN_OPTION_SEND_PITCHBEND;
  103. options |= PLUGIN_OPTION_SEND_ALL_SOUND_OFF;
  104. }
  105. return options;
  106. }
  107. float getParameterValue(const uint32_t parameterId) const noexcept override
  108. {
  109. CARLA_SAFE_ASSERT_RETURN(parameterId < pData->param.count, 0.0f);
  110. CARLA_SAFE_ASSERT_RETURN(fInstance != nullptr, 0.0f);
  111. return fInstance->getParameter(static_cast<int>(parameterId));
  112. }
  113. void getLabel(char* const strBuf) const noexcept override
  114. {
  115. std::strncpy(strBuf, fDesc.name.toRawUTF8(), STR_MAX);
  116. }
  117. void getMaker(char* const strBuf) const noexcept override
  118. {
  119. std::strncpy(strBuf, fDesc.manufacturerName.toRawUTF8(), STR_MAX);
  120. }
  121. void getCopyright(char* const strBuf) const noexcept override
  122. {
  123. getMaker(strBuf);
  124. }
  125. void getRealName(char* const strBuf) const noexcept override
  126. {
  127. CARLA_SAFE_ASSERT_RETURN(fInstance != nullptr,);
  128. std::strncpy(strBuf, fInstance->getName().toRawUTF8(), STR_MAX);
  129. }
  130. void getParameterName(const uint32_t parameterId, char* const strBuf) const noexcept override
  131. {
  132. CARLA_SAFE_ASSERT_RETURN(parameterId < pData->param.count,);
  133. CARLA_SAFE_ASSERT_RETURN(fInstance != nullptr,);
  134. std::strncpy(strBuf, fInstance->getParameterName(static_cast<int>(parameterId)).toRawUTF8(), STR_MAX);
  135. }
  136. void getParameterUnit(const uint32_t parameterId, char* const strBuf) const noexcept override
  137. {
  138. CARLA_SAFE_ASSERT_RETURN(parameterId < pData->param.count,);
  139. CARLA_SAFE_ASSERT_RETURN(fInstance != nullptr,);
  140. std::strncpy(strBuf, fInstance->getParameterLabel(static_cast<int>(parameterId)).toRawUTF8(), STR_MAX);
  141. }
  142. // -------------------------------------------------------------------
  143. // Set data (state)
  144. // nothing
  145. // -------------------------------------------------------------------
  146. // Set data (internal stuff)
  147. void setName(const char* const newName) override
  148. {
  149. CarlaPlugin::setName(newName);
  150. if (fWindow != nullptr)
  151. {
  152. String uiName(pData->name);
  153. uiName += " (GUI)";
  154. fWindow->setName(uiName);
  155. }
  156. }
  157. // -------------------------------------------------------------------
  158. // Set data (plugin-specific stuff)
  159. void setParameterValue(const uint32_t parameterId, const float value, const bool sendGui, const bool sendOsc, const bool sendCallback) noexcept override
  160. {
  161. CARLA_SAFE_ASSERT_RETURN(parameterId < pData->param.count,);
  162. CARLA_SAFE_ASSERT_RETURN(fInstance != nullptr,);
  163. const float fixedValue(pData->param.getFixedValue(parameterId, value));
  164. fInstance->setParameter(static_cast<int>(parameterId), value);
  165. CarlaPlugin::setParameterValue(parameterId, fixedValue, sendGui, sendOsc, sendCallback);
  166. }
  167. // -------------------------------------------------------------------
  168. // Set ui stuff
  169. void showCustomUI(const bool yesNo) override
  170. {
  171. CARLA_SAFE_ASSERT_RETURN(fInstance != nullptr,);
  172. #ifdef CARLA_OS_LINUX
  173. const MessageManagerLock mmLock;
  174. #endif
  175. if (yesNo)
  176. {
  177. if (fWindow == nullptr)
  178. {
  179. String uiName(pData->name);
  180. uiName += " (GUI)";
  181. fWindow = new JucePluginWindow();
  182. fWindow->setName(uiName);
  183. }
  184. if (AudioProcessorEditor* const editor = fInstance->createEditorIfNeeded())
  185. fWindow->show(editor);
  186. }
  187. else
  188. {
  189. if (fWindow != nullptr)
  190. fWindow->hide();
  191. if (AudioProcessorEditor* const editor = fInstance->getActiveEditor())
  192. delete editor;
  193. fWindow = nullptr;
  194. }
  195. }
  196. void idle() override
  197. {
  198. if (fWindow != nullptr)
  199. {
  200. if (fWindow->wasClosedByUser())
  201. {
  202. showCustomUI(false);
  203. pData->engine->callback(ENGINE_CALLBACK_UI_STATE_CHANGED, pData->id, 0, 0, 0.0f, nullptr);
  204. }
  205. }
  206. CarlaPlugin::idle();
  207. }
  208. // -------------------------------------------------------------------
  209. // Plugin state
  210. void reload() override
  211. {
  212. CARLA_SAFE_ASSERT_RETURN(pData->engine != nullptr,);
  213. CARLA_SAFE_ASSERT_RETURN(fInstance != nullptr,);
  214. carla_debug("VstPlugin::reload() - start");
  215. const EngineProcessMode processMode(pData->engine->getProccessMode());
  216. // Safely disable plugin for reload
  217. const ScopedDisabler sd(this);
  218. if (pData->active)
  219. deactivate();
  220. clearBuffers();
  221. fInstance->refreshParameterList();
  222. uint32_t aIns, aOuts, mIns, mOuts, params;
  223. aIns = aOuts = mIns = mOuts = params = 0;
  224. bool needsCtrlIn, needsCtrlOut;
  225. needsCtrlIn = needsCtrlOut = false;
  226. aIns = (fInstance->getNumInputChannels() > 0) ? static_cast<uint32_t>(fInstance->getNumInputChannels()) : 0;
  227. aOuts = (fInstance->getNumOutputChannels() > 0) ? static_cast<uint32_t>(fInstance->getNumOutputChannels()) : 0;
  228. params = (fInstance->getNumParameters() > 0) ? static_cast<uint32_t>(fInstance->getNumParameters()) : 0;
  229. if (fInstance->acceptsMidi())
  230. {
  231. mIns = 1;
  232. needsCtrlIn = true;
  233. }
  234. if (fInstance->producesMidi())
  235. {
  236. mOuts = 1;
  237. needsCtrlOut = true;
  238. }
  239. if (aIns > 0)
  240. {
  241. pData->audioIn.createNew(aIns);
  242. }
  243. if (aOuts > 0)
  244. {
  245. pData->audioOut.createNew(aOuts);
  246. needsCtrlIn = true;
  247. }
  248. if (params > 0)
  249. {
  250. pData->param.createNew(params, false);
  251. needsCtrlIn = true;
  252. }
  253. const uint portNameSize(pData->engine->getMaxPortNameSize());
  254. CarlaString portName;
  255. // Audio Ins
  256. for (uint32_t j=0; j < aIns; ++j)
  257. {
  258. portName.clear();
  259. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  260. {
  261. portName = pData->name;
  262. portName += ":";
  263. }
  264. if (aIns > 1)
  265. {
  266. portName += "input_";
  267. portName += CarlaString(j+1);
  268. }
  269. else
  270. portName += "input";
  271. portName.truncate(portNameSize);
  272. pData->audioIn.ports[j].port = (CarlaEngineAudioPort*)pData->client->addPort(kEnginePortTypeAudio, portName, true);
  273. pData->audioIn.ports[j].rindex = j;
  274. }
  275. // Audio Outs
  276. for (uint32_t j=0; j < aOuts; ++j)
  277. {
  278. portName.clear();
  279. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  280. {
  281. portName = pData->name;
  282. portName += ":";
  283. }
  284. if (aOuts > 1)
  285. {
  286. portName += "output_";
  287. portName += CarlaString(j+1);
  288. }
  289. else
  290. portName += "output";
  291. portName.truncate(portNameSize);
  292. pData->audioOut.ports[j].port = (CarlaEngineAudioPort*)pData->client->addPort(kEnginePortTypeAudio, portName, false);
  293. pData->audioOut.ports[j].rindex = j;
  294. }
  295. for (uint32_t j=0; j < params; ++j)
  296. {
  297. pData->param.data[j].type = PARAMETER_INPUT;
  298. pData->param.data[j].hints = 0x0;
  299. pData->param.data[j].index = static_cast<int32_t>(j);
  300. pData->param.data[j].rindex = static_cast<int32_t>(j);
  301. pData->param.data[j].midiCC = -1;
  302. pData->param.data[j].midiChannel = 0;
  303. float min, max, def, step, stepSmall, stepLarge;
  304. // TODO
  305. //const int numSteps(fInstance->getParameterNumSteps(static_cast<int>(j)));
  306. {
  307. min = 0.0f;
  308. max = 1.0f;
  309. step = 0.001f;
  310. stepSmall = 0.0001f;
  311. stepLarge = 0.1f;
  312. }
  313. pData->param.data[j].hints |= PARAMETER_IS_ENABLED;
  314. #ifndef BUILD_BRIDGE
  315. //pData->param.data[j].hints |= PARAMETER_USES_CUSTOM_TEXT;
  316. #endif
  317. if (fInstance->isParameterAutomatable(static_cast<int>(j)))
  318. pData->param.data[j].hints |= PARAMETER_IS_AUTOMABLE;
  319. // FIXME?
  320. def = fInstance->getParameterDefaultValue(static_cast<int>(j));
  321. if (def < min)
  322. def = min;
  323. else if (def > max)
  324. def = max;
  325. pData->param.ranges[j].min = min;
  326. pData->param.ranges[j].max = max;
  327. pData->param.ranges[j].def = def;
  328. pData->param.ranges[j].step = step;
  329. pData->param.ranges[j].stepSmall = stepSmall;
  330. pData->param.ranges[j].stepLarge = stepLarge;
  331. }
  332. if (needsCtrlIn)
  333. {
  334. portName.clear();
  335. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  336. {
  337. portName = pData->name;
  338. portName += ":";
  339. }
  340. portName += "events-in";
  341. portName.truncate(portNameSize);
  342. pData->event.portIn = (CarlaEngineEventPort*)pData->client->addPort(kEnginePortTypeEvent, portName, true);
  343. }
  344. if (needsCtrlOut)
  345. {
  346. portName.clear();
  347. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  348. {
  349. portName = pData->name;
  350. portName += ":";
  351. }
  352. portName += "events-out";
  353. portName.truncate(portNameSize);
  354. pData->event.portOut = (CarlaEngineEventPort*)pData->client->addPort(kEnginePortTypeEvent, portName, false);
  355. }
  356. // plugin hints
  357. pData->hints = 0x0;
  358. if (fDesc.isInstrument)
  359. pData->hints |= PLUGIN_IS_SYNTH;
  360. if (fInstance->hasEditor())
  361. {
  362. pData->hints |= PLUGIN_HAS_CUSTOM_UI;
  363. pData->hints |= PLUGIN_NEEDS_SINGLE_THREAD;
  364. }
  365. if (aOuts > 0 && (aIns == aOuts || aIns == 1))
  366. pData->hints |= PLUGIN_CAN_DRYWET;
  367. if (aOuts > 0)
  368. pData->hints |= PLUGIN_CAN_VOLUME;
  369. if (aOuts >= 2 && aOuts % 2 == 0)
  370. pData->hints |= PLUGIN_CAN_BALANCE;
  371. // extra plugin hints
  372. pData->extraHints = 0x0;
  373. if (mIns > 0)
  374. pData->extraHints |= PLUGIN_EXTRA_HINT_HAS_MIDI_IN;
  375. if (mOuts > 0)
  376. pData->extraHints |= PLUGIN_EXTRA_HINT_HAS_MIDI_OUT;
  377. if (aIns <= 2 && aOuts <= 2 && (aIns == aOuts || aIns == 0 || aOuts == 0))
  378. pData->extraHints |= PLUGIN_EXTRA_HINT_CAN_RUN_RACK;
  379. fInstance->setPlayConfigDetails(static_cast<int>(aIns), static_cast<int>(aOuts), pData->engine->getSampleRate(), static_cast<int>(pData->engine->getBufferSize()));
  380. bufferSizeChanged(pData->engine->getBufferSize());
  381. //reloadPrograms(true);
  382. if (pData->active)
  383. activate();
  384. carla_debug("VstPlugin::reload() - end");
  385. }
  386. // -------------------------------------------------------------------
  387. // Plugin processing
  388. void activate() noexcept override
  389. {
  390. CARLA_SAFE_ASSERT_RETURN(fInstance != nullptr,);
  391. try {
  392. fInstance->prepareToPlay(pData->engine->getSampleRate(), static_cast<int>(pData->engine->getBufferSize()));
  393. } catch(...) {}
  394. }
  395. void deactivate() noexcept override
  396. {
  397. CARLA_SAFE_ASSERT_RETURN(fInstance != nullptr,);
  398. try {
  399. fInstance->releaseResources();
  400. } catch(...) {}
  401. }
  402. void process(float** const inBuffer, float** const outBuffer, const uint32_t frames) override
  403. {
  404. // --------------------------------------------------------------------------------------------------------
  405. // Check if active
  406. if (! pData->active)
  407. {
  408. // disable any output sound
  409. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  410. FloatVectorOperations::clear(outBuffer[i], static_cast<int>(frames));
  411. return;
  412. }
  413. // --------------------------------------------------------------------------------------------------------
  414. // Check if needs reset
  415. if (pData->needsReset)
  416. {
  417. fInstance->reset();
  418. pData->needsReset = false;
  419. }
  420. // --------------------------------------------------------------------------------------------------------
  421. // TimeInfo
  422. // TODO
  423. // --------------------------------------------------------------------------------------------------------
  424. // Event Input
  425. fMidiBuffer.clear();
  426. if (pData->event.portIn != nullptr)
  427. {
  428. // ----------------------------------------------------------------------------------------------------
  429. // MIDI Input (External)
  430. if (pData->extNotes.mutex.tryLock())
  431. {
  432. for (; ! pData->extNotes.data.isEmpty();)
  433. {
  434. const ExternalMidiNote& note(pData->extNotes.data.getFirst(true));
  435. CARLA_SAFE_ASSERT_CONTINUE(note.channel >= 0 && note.channel < MAX_MIDI_CHANNELS);
  436. uint8_t midiEvent[3];
  437. midiEvent[0] = static_cast<uint8_t>(note.channel + (note.velo > 0) ? MIDI_STATUS_NOTE_ON : MIDI_STATUS_NOTE_OFF);
  438. midiEvent[1] = note.note;
  439. midiEvent[2] = note.velo;
  440. fMidiBuffer.addEvent(midiEvent, 3, 0);
  441. }
  442. pData->extNotes.mutex.unlock();
  443. } // End of MIDI Input (External)
  444. // ----------------------------------------------------------------------------------------------------
  445. // Event Input (System)
  446. bool allNotesOffSent = false;
  447. uint32_t numEvents = pData->event.portIn->getEventCount();
  448. uint32_t nextBankId;
  449. if (pData->midiprog.current >= 0 && pData->midiprog.count > 0)
  450. nextBankId = pData->midiprog.data[pData->midiprog.current].bank;
  451. else
  452. nextBankId = 0;
  453. for (uint32_t i=0; i < numEvents; ++i)
  454. {
  455. const EngineEvent& event(pData->event.portIn->getEvent(i));
  456. if (event.time >= frames)
  457. continue;
  458. switch (event.type)
  459. {
  460. case kEngineEventTypeNull:
  461. break;
  462. case kEngineEventTypeControl: {
  463. const EngineControlEvent& ctrlEvent(event.ctrl);
  464. switch (ctrlEvent.type)
  465. {
  466. case kEngineControlEventTypeNull:
  467. break;
  468. case kEngineControlEventTypeParameter: {
  469. #ifndef BUILD_BRIDGE
  470. // Control backend stuff
  471. if (event.channel == pData->ctrlChannel)
  472. {
  473. float value;
  474. if (MIDI_IS_CONTROL_BREATH_CONTROLLER(ctrlEvent.param) && (pData->hints & PLUGIN_CAN_DRYWET) != 0)
  475. {
  476. value = ctrlEvent.value;
  477. setDryWet(value, false, false);
  478. pData->postponeRtEvent(kPluginPostRtEventParameterChange, PARAMETER_DRYWET, 0, value);
  479. break;
  480. }
  481. if (MIDI_IS_CONTROL_CHANNEL_VOLUME(ctrlEvent.param) && (pData->hints & PLUGIN_CAN_VOLUME) != 0)
  482. {
  483. value = ctrlEvent.value*127.0f/100.0f;
  484. setVolume(value, false, false);
  485. pData->postponeRtEvent(kPluginPostRtEventParameterChange, PARAMETER_VOLUME, 0, value);
  486. break;
  487. }
  488. if (MIDI_IS_CONTROL_BALANCE(ctrlEvent.param) && (pData->hints & PLUGIN_CAN_BALANCE) != 0)
  489. {
  490. float left, right;
  491. value = ctrlEvent.value/0.5f - 1.0f;
  492. if (value < 0.0f)
  493. {
  494. left = -1.0f;
  495. right = (value*2.0f)+1.0f;
  496. }
  497. else if (value > 0.0f)
  498. {
  499. left = (value*2.0f)-1.0f;
  500. right = 1.0f;
  501. }
  502. else
  503. {
  504. left = -1.0f;
  505. right = 1.0f;
  506. }
  507. setBalanceLeft(left, false, false);
  508. setBalanceRight(right, false, false);
  509. pData->postponeRtEvent(kPluginPostRtEventParameterChange, PARAMETER_BALANCE_LEFT, 0, left);
  510. pData->postponeRtEvent(kPluginPostRtEventParameterChange, PARAMETER_BALANCE_RIGHT, 0, right);
  511. break;
  512. }
  513. }
  514. #endif
  515. // Control plugin parameters
  516. uint32_t k;
  517. for (k=0; k < pData->param.count; ++k)
  518. {
  519. if (pData->param.data[k].midiChannel != event.channel)
  520. continue;
  521. if (pData->param.data[k].midiCC != ctrlEvent.param)
  522. continue;
  523. if (pData->param.data[k].type != PARAMETER_INPUT)
  524. continue;
  525. if ((pData->param.data[k].hints & PARAMETER_IS_AUTOMABLE) == 0)
  526. continue;
  527. float value;
  528. if (pData->param.data[k].hints & PARAMETER_IS_BOOLEAN)
  529. {
  530. value = (ctrlEvent.value < 0.5f) ? pData->param.ranges[k].min : pData->param.ranges[k].max;
  531. }
  532. else
  533. {
  534. value = pData->param.ranges[k].getUnnormalizedValue(ctrlEvent.value);
  535. if (pData->param.data[k].hints & PARAMETER_IS_INTEGER)
  536. value = std::rint(value);
  537. }
  538. setParameterValue(k, value, false, false, false);
  539. pData->postponeRtEvent(kPluginPostRtEventParameterChange, static_cast<int32_t>(k), 0, value);
  540. break;
  541. }
  542. // check if event is already handled
  543. if (k != pData->param.count)
  544. break;
  545. if ((pData->options & PLUGIN_OPTION_SEND_CONTROL_CHANGES) != 0 && ctrlEvent.param <= 0x5F)
  546. {
  547. uint8_t midiData[3];
  548. midiData[0] = static_cast<uint8_t>(MIDI_STATUS_CONTROL_CHANGE + i);
  549. midiData[1] = static_cast<uint8_t>(ctrlEvent.param);
  550. midiData[2] = uint8_t(ctrlEvent.value*127.0f);
  551. fMidiBuffer.addEvent(midiData, 3, static_cast<int>(event.time));
  552. }
  553. break;
  554. } // case kEngineControlEventTypeParameter
  555. case kEngineControlEventTypeMidiBank:
  556. if (event.channel == pData->ctrlChannel && (pData->options & PLUGIN_OPTION_MAP_PROGRAM_CHANGES) != 0)
  557. nextBankId = ctrlEvent.param;
  558. break;
  559. case kEngineControlEventTypeMidiProgram:
  560. if (event.channel == pData->ctrlChannel && (pData->options & PLUGIN_OPTION_MAP_PROGRAM_CHANGES) != 0)
  561. {
  562. const uint32_t nextProgramId = ctrlEvent.param;
  563. for (uint32_t k=0; k < pData->midiprog.count; ++k)
  564. {
  565. if (pData->midiprog.data[k].bank == nextBankId && pData->midiprog.data[k].program == nextProgramId)
  566. {
  567. const int32_t index(static_cast<int32_t>(k));
  568. setMidiProgram(index, false, false, false);
  569. pData->postponeRtEvent(kPluginPostRtEventMidiProgramChange, index, 0, 0.0f);
  570. break;
  571. }
  572. }
  573. }
  574. break;
  575. case kEngineControlEventTypeAllSoundOff:
  576. if (pData->options & PLUGIN_OPTION_SEND_ALL_SOUND_OFF)
  577. {
  578. uint8_t midiData[3];
  579. midiData[0] = static_cast<uint8_t>(MIDI_STATUS_CONTROL_CHANGE + i);
  580. midiData[1] = MIDI_CONTROL_ALL_SOUND_OFF;
  581. midiData[2] = 0;
  582. fMidiBuffer.addEvent(midiData, 3, static_cast<int>(event.time));
  583. }
  584. break;
  585. case kEngineControlEventTypeAllNotesOff:
  586. if (pData->options & PLUGIN_OPTION_SEND_ALL_SOUND_OFF)
  587. {
  588. if (event.channel == pData->ctrlChannel && ! allNotesOffSent)
  589. {
  590. allNotesOffSent = true;
  591. sendMidiAllNotesOffToCallback();
  592. }
  593. uint8_t midiData[3];
  594. midiData[0] = static_cast<uint8_t>(MIDI_STATUS_CONTROL_CHANGE + i);
  595. midiData[1] = MIDI_CONTROL_ALL_NOTES_OFF;
  596. midiData[2] = 0;
  597. fMidiBuffer.addEvent(midiData, 3, static_cast<int>(event.time));
  598. }
  599. break;
  600. } // switch (ctrlEvent.type)
  601. break;
  602. } // case kEngineEventTypeControl
  603. case kEngineEventTypeMidi:
  604. {
  605. const EngineMidiEvent& midiEvent(event.midi);
  606. uint8_t status = uint8_t(MIDI_GET_STATUS_FROM_DATA(midiEvent.data));
  607. uint8_t channel = event.channel;
  608. // Fix bad note-off
  609. if (MIDI_IS_STATUS_NOTE_ON(status) && midiEvent.data[2] == 0)
  610. status = MIDI_STATUS_NOTE_OFF;
  611. if (status == MIDI_STATUS_CHANNEL_PRESSURE && (pData->options & PLUGIN_OPTION_SEND_CHANNEL_PRESSURE) == 0)
  612. continue;
  613. if (status == MIDI_STATUS_CONTROL_CHANGE && (pData->options & PLUGIN_OPTION_SEND_CONTROL_CHANGES) == 0)
  614. continue;
  615. if (status == MIDI_STATUS_POLYPHONIC_AFTERTOUCH && (pData->options & PLUGIN_OPTION_SEND_NOTE_AFTERTOUCH) == 0)
  616. continue;
  617. if (status == MIDI_STATUS_PITCH_WHEEL_CONTROL && (pData->options & PLUGIN_OPTION_SEND_PITCHBEND) == 0)
  618. continue;
  619. fMidiBuffer.addEvent(midiEvent.data, midiEvent.size, static_cast<int>(event.time));
  620. if (status == MIDI_STATUS_NOTE_ON)
  621. pData->postponeRtEvent(kPluginPostRtEventNoteOn, channel, midiEvent.data[1], midiEvent.data[2]);
  622. else if (status == MIDI_STATUS_NOTE_OFF)
  623. pData->postponeRtEvent(kPluginPostRtEventNoteOff, channel, midiEvent.data[1], 0.0f);
  624. break;
  625. } // case kEngineEventTypeMidi
  626. } // switch (event.type)
  627. }
  628. pData->postRtEvents.trySplice();
  629. } // End of Event Input
  630. // --------------------------------------------------------------------------------------------------------
  631. // Set TimeInfo
  632. const EngineTimeInfo& timeInfo(pData->engine->getTimeInfo());
  633. fPosInfo.isPlaying = timeInfo.playing;
  634. if (timeInfo.valid & EngineTimeInfo::kValidBBT)
  635. {
  636. const double ppqBar = double(timeInfo.bbt.bar - 1) * timeInfo.bbt.beatsPerBar;
  637. const double ppqBeat = double(timeInfo.bbt.beat - 1);
  638. const double ppqTick = double(timeInfo.bbt.tick) / timeInfo.bbt.ticksPerBeat;
  639. fPosInfo.bpm = timeInfo.bbt.beatsPerMinute;
  640. fPosInfo.timeSigNumerator = static_cast<int>(timeInfo.bbt.beatsPerBar);
  641. fPosInfo.timeSigDenominator = static_cast<int>(timeInfo.bbt.beatType);
  642. fPosInfo.timeInSamples = static_cast<int64_t>(timeInfo.frame);
  643. fPosInfo.timeInSeconds = static_cast<double>(fPosInfo.timeInSamples)/pData->engine->getSampleRate();
  644. fPosInfo.ppqPosition = ppqBar + ppqBeat + ppqTick;
  645. fPosInfo.ppqPositionOfLastBarStart = ppqBar;
  646. }
  647. // --------------------------------------------------------------------------------------------------------
  648. // Process
  649. processSingle(inBuffer, outBuffer, frames);
  650. // --------------------------------------------------------------------------------------------------------
  651. // MIDI Output
  652. if (pData->event.portOut != nullptr)
  653. {
  654. // TODO
  655. }
  656. }
  657. bool processSingle(float** const inBuffer, float** const outBuffer, const uint32_t frames)
  658. {
  659. CARLA_SAFE_ASSERT_RETURN(frames > 0, false);
  660. if (pData->audioIn.count > 0)
  661. {
  662. CARLA_SAFE_ASSERT_RETURN(inBuffer != nullptr, false);
  663. }
  664. if (pData->audioOut.count > 0)
  665. {
  666. CARLA_SAFE_ASSERT_RETURN(outBuffer != nullptr, false);
  667. }
  668. // --------------------------------------------------------------------------------------------------------
  669. // Try lock, silence otherwise
  670. if (pData->engine->isOffline())
  671. {
  672. pData->singleMutex.lock();
  673. }
  674. else if (! pData->singleMutex.tryLock())
  675. {
  676. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  677. FloatVectorOperations::clear(outBuffer[i], static_cast<int>(frames));
  678. return false;
  679. }
  680. // --------------------------------------------------------------------------------------------------------
  681. // Set audio in buffers
  682. for (uint32_t i=0; i < pData->audioIn.count; ++i)
  683. fAudioBuffer.copyFrom(static_cast<int>(i), 0, inBuffer[i], static_cast<int>(frames));
  684. // --------------------------------------------------------------------------------------------------------
  685. // Run plugin
  686. fInstance->processBlock(fAudioBuffer, fMidiBuffer);
  687. // --------------------------------------------------------------------------------------------------------
  688. // Set audio out buffers
  689. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  690. FloatVectorOperations::copy(outBuffer[i], fAudioBuffer.getSampleData(static_cast<int>(i)), static_cast<int>(frames));
  691. // --------------------------------------------------------------------------------------------------------
  692. pData->singleMutex.unlock();
  693. return true;
  694. }
  695. void bufferSizeChanged(const uint32_t newBufferSize) override
  696. {
  697. CARLA_ASSERT_INT(newBufferSize > 0, newBufferSize);
  698. carla_debug("VstPlugin::bufferSizeChanged(%i)", newBufferSize);
  699. fAudioBuffer.setSize(static_cast<int>(std::max<uint32_t>(pData->audioIn.count, pData->audioOut.count)), static_cast<int>(newBufferSize));
  700. if (pData->active)
  701. {
  702. deactivate();
  703. activate();
  704. }
  705. }
  706. void sampleRateChanged(const double newSampleRate) override
  707. {
  708. CARLA_ASSERT_INT(newSampleRate > 0.0, newSampleRate);
  709. carla_debug("VstPlugin::sampleRateChanged(%g)", newSampleRate);
  710. if (pData->active)
  711. {
  712. deactivate();
  713. activate();
  714. }
  715. }
  716. // -------------------------------------------------------------------
  717. // Plugin buffers
  718. // nothing
  719. // -------------------------------------------------------------------
  720. // Post-poned UI Stuff
  721. // nothing
  722. // -------------------------------------------------------------------
  723. protected:
  724. bool getCurrentPosition(CurrentPositionInfo& result) override
  725. {
  726. carla_copyStruct<CurrentPositionInfo>(result, fPosInfo);
  727. return true;
  728. }
  729. // -------------------------------------------------------------------
  730. public:
  731. bool init(const char* const filename, const char* const name, const char* const label, const int64_t uniqueId, const char* const format)
  732. {
  733. CARLA_SAFE_ASSERT_RETURN(pData->engine != nullptr, false);
  734. // ---------------------------------------------------------------
  735. // first checks
  736. if (pData->client != nullptr)
  737. {
  738. pData->engine->setLastError("Plugin client is already registered");
  739. return false;
  740. }
  741. if (filename == nullptr || filename[0] == '\0')
  742. {
  743. pData->engine->setLastError("null filename");
  744. return false;
  745. }
  746. if (label == nullptr || label[0] == '\0')
  747. {
  748. pData->engine->setLastError("null label");
  749. return false;
  750. }
  751. if (format == nullptr || format[0] == '\0')
  752. {
  753. pData->engine->setLastError("null format");
  754. return false;
  755. }
  756. #ifdef CARLA_OS_LINUX
  757. const MessageManagerLock mmLock;
  758. #endif
  759. // ---------------------------------------------------------------
  760. // fix path for wine usage
  761. String jfilename(filename);
  762. #ifdef CARLA_OS_WIN
  763. if (jfilename.startsWith("/"))
  764. {
  765. jfilename.replace("/", "\\");
  766. jfilename = "Z:" + jfilename;
  767. }
  768. #endif
  769. //fDesc.name = fDesc.descriptiveName = label;
  770. fDesc.uid = static_cast<int>(uniqueId);
  771. fDesc.fileOrIdentifier = jfilename;
  772. fDesc.pluginFormatName = format;
  773. fFormatManager.addDefaultFormats();
  774. String error;
  775. fInstance = fFormatManager.createPluginInstance(fDesc, 44100, 512, error);
  776. if (fInstance == nullptr)
  777. {
  778. pData->engine->setLastError(error.toRawUTF8());
  779. return false;
  780. }
  781. fInstance->fillInPluginDescription(fDesc);
  782. fInstance->setPlayHead(this);
  783. // ---------------------------------------------------------------
  784. // get info
  785. if (name != nullptr && name[0] != '\0')
  786. pData->name = pData->engine->getUniquePluginName(name);
  787. else
  788. pData->name = pData->engine->getUniquePluginName(fInstance->getName().toRawUTF8());
  789. pData->filename = carla_strdup(filename);
  790. // ---------------------------------------------------------------
  791. // register client
  792. pData->client = pData->engine->addClient(this);
  793. if (pData->client == nullptr || ! pData->client->isOk())
  794. {
  795. pData->engine->setLastError("Failed to register plugin client");
  796. return false;
  797. }
  798. // ---------------------------------------------------------------
  799. // load plugin settings
  800. {
  801. // set default options
  802. pData->options = 0x0;
  803. pData->options |= PLUGIN_OPTION_FIXED_BUFFERS;
  804. pData->options |= PLUGIN_OPTION_MAP_PROGRAM_CHANGES;
  805. //pData->options |= PLUGIN_OPTION_USE_CHUNKS;
  806. if (fInstance->acceptsMidi())
  807. {
  808. pData->options |= PLUGIN_OPTION_SEND_CHANNEL_PRESSURE;
  809. pData->options |= PLUGIN_OPTION_SEND_NOTE_AFTERTOUCH;
  810. pData->options |= PLUGIN_OPTION_SEND_PITCHBEND;
  811. pData->options |= PLUGIN_OPTION_SEND_ALL_SOUND_OFF;
  812. }
  813. // set identifier string
  814. String juceId(fDesc.createIdentifierString());
  815. CarlaString identifier("Juce/");
  816. identifier += juceId.toRawUTF8();
  817. pData->identifier = identifier.dup();
  818. // load settings
  819. pData->options = pData->loadSettings(pData->options, getOptionsAvailable());
  820. // ignore settings, we need this anyway
  821. pData->options |= PLUGIN_OPTION_FIXED_BUFFERS;
  822. }
  823. return true;
  824. }
  825. private:
  826. PluginDescription fDesc;
  827. AudioPluginInstance* fInstance;
  828. AudioPluginFormatManager fFormatManager;
  829. AudioSampleBuffer fAudioBuffer;
  830. MidiBuffer fMidiBuffer;
  831. CurrentPositionInfo fPosInfo;
  832. const char* fUniqueId;
  833. ScopedPointer<JucePluginWindow> fWindow;
  834. CARLA_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(JucePlugin)
  835. };
  836. CARLA_BACKEND_END_NAMESPACE
  837. #endif // HAVE_JUCE
  838. // -------------------------------------------------------------------------------------------------------------------
  839. CARLA_BACKEND_START_NAMESPACE
  840. CarlaPlugin* CarlaPlugin::newJuce(const Initializer& init, const char* const format)
  841. {
  842. carla_debug("CarlaPlugin::newJuce({%p, \"%s\", \"%s\", \"%s\", " P_INT64 "}, %s)", init.engine, init.filename, init.name, init.label, init.uniqueId, format);
  843. #ifdef HAVE_JUCE
  844. JucePlugin* const plugin(new JucePlugin(init.engine, init.id));
  845. if (! plugin->init(init.filename, init.name, init.label, init.uniqueId, format))
  846. {
  847. delete plugin;
  848. return nullptr;
  849. }
  850. plugin->reload();
  851. if (init.engine->getProccessMode() == ENGINE_PROCESS_MODE_CONTINUOUS_RACK && ! plugin->canRunInRack())
  852. {
  853. init.engine->setLastError("Carla's rack mode can only work with Stereo VST3 plugins, sorry!");
  854. delete plugin;
  855. return nullptr;
  856. }
  857. return plugin;
  858. #else
  859. init.engine->setLastError("Juce support not available");
  860. return nullptr;
  861. // unused
  862. (void)format;
  863. #endif
  864. }
  865. CARLA_BACKEND_END_NAMESPACE
  866. // -------------------------------------------------------------------------------------------------------------------