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.

1169 lines
39KB

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