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.

2572 lines
86KB

  1. /*
  2. * Carla VST Plugin
  3. * Copyright (C) 2011-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. # define USE_JUCE_FOR_VST
  21. #endif
  22. #ifndef USE_JUCE_FOR_VST
  23. #include "CarlaVstUtils.hpp"
  24. #include "CarlaBase64Utils.hpp"
  25. #include "CarlaMathUtils.hpp"
  26. #include "CarlaPluginUI.hpp"
  27. #include "juce_core.h"
  28. #include <pthread.h>
  29. #undef VST_FORCE_DEPRECATED
  30. #define VST_FORCE_DEPRECATED 0
  31. using juce::File;
  32. CARLA_BACKEND_START_NAMESPACE
  33. // -----------------------------------------------------
  34. const uint PLUGIN_CAN_PROCESS_REPLACING = 0x1000;
  35. const uint PLUGIN_HAS_COCKOS_EXTENSIONS = 0x2000;
  36. const uint PLUGIN_USES_OLD_VSTSDK = 0x4000;
  37. const uint PLUGIN_WANTS_MIDI_INPUT = 0x8000;
  38. // -----------------------------------------------------
  39. class VstPlugin : public CarlaPlugin,
  40. CarlaPluginUI::CloseCallback
  41. {
  42. public:
  43. VstPlugin(CarlaEngine* const engine, const uint id)
  44. : CarlaPlugin(engine, id),
  45. fUnique1(1),
  46. fEffect(nullptr),
  47. fMidiEventCount(0),
  48. fNeedIdle(false),
  49. fLastChunk(nullptr),
  50. fIsProcessing(false),
  51. fUnique2(2)
  52. {
  53. carla_debug("VstPlugin::VstPlugin(%p, %i)", engine, id);
  54. carla_zeroStruct<VstMidiEvent>(fMidiEvents, kPluginMaxMidiEvents*2);
  55. carla_zeroStruct<VstTimeInfo>(fTimeInfo);
  56. for (ushort i=0; i < kPluginMaxMidiEvents*2; ++i)
  57. fEvents.data[i] = (VstEvent*)&fMidiEvents[i];
  58. pData->osc.thread.setMode(CarlaPluginThread::PLUGIN_THREAD_VST_GUI);
  59. #ifdef CARLA_OS_WIN
  60. fProcThread.p = nullptr;
  61. fProcThread.x = 0;
  62. #else
  63. fProcThread = 0;
  64. #endif
  65. // make plugin valid
  66. srand(id);
  67. fUnique1 = fUnique2 = rand();
  68. }
  69. ~VstPlugin() override
  70. {
  71. carla_debug("VstPlugin::~VstPlugin()");
  72. // close UI
  73. if (pData->hints & PLUGIN_HAS_CUSTOM_UI)
  74. {
  75. showCustomUI(false);
  76. if (fUi.type == UI::UI_OSC)
  77. pData->osc.thread.stopThread(static_cast<int>(pData->engine->getOptions().uiBridgesTimeout * 2));
  78. }
  79. pData->singleMutex.lock();
  80. pData->masterMutex.lock();
  81. if (pData->client != nullptr && pData->client->isActive())
  82. pData->client->deactivate();
  83. CARLA_ASSERT(! fIsProcessing);
  84. if (pData->active)
  85. {
  86. deactivate();
  87. pData->active = false;
  88. }
  89. if (fEffect != nullptr)
  90. {
  91. dispatcher(effClose, 0, 0, nullptr, 0.0f);
  92. fEffect = nullptr;
  93. }
  94. // make plugin invalid
  95. fUnique2 += 1;
  96. if (fLastChunk != nullptr)
  97. {
  98. std::free(fLastChunk);
  99. fLastChunk = nullptr;
  100. }
  101. clearBuffers();
  102. }
  103. // -------------------------------------------------------------------
  104. // Information (base)
  105. PluginType getType() const noexcept override
  106. {
  107. return PLUGIN_VST;
  108. }
  109. PluginCategory getCategory() const noexcept override
  110. {
  111. CARLA_SAFE_ASSERT_RETURN(fEffect != nullptr, CarlaPlugin::getCategory());
  112. const intptr_t category(dispatcher(effGetPlugCategory, 0, 0, nullptr, 0.0f));
  113. switch (category)
  114. {
  115. case kPlugCategSynth:
  116. return PLUGIN_CATEGORY_SYNTH;
  117. case kPlugCategAnalysis:
  118. return PLUGIN_CATEGORY_UTILITY;
  119. case kPlugCategMastering:
  120. return PLUGIN_CATEGORY_DYNAMICS;
  121. case kPlugCategRoomFx:
  122. return PLUGIN_CATEGORY_DELAY;
  123. case kPlugCategRestoration:
  124. return PLUGIN_CATEGORY_UTILITY;
  125. case kPlugCategGenerator:
  126. return PLUGIN_CATEGORY_SYNTH;
  127. }
  128. if (fEffect->flags & effFlagsIsSynth)
  129. return PLUGIN_CATEGORY_SYNTH;
  130. return CarlaPlugin::getCategory();
  131. }
  132. int64_t getUniqueId() const noexcept override
  133. {
  134. CARLA_SAFE_ASSERT_RETURN(fEffect != nullptr, 0);
  135. return static_cast<int64_t>(fEffect->uniqueID);
  136. }
  137. // -------------------------------------------------------------------
  138. // Information (count)
  139. // nothing
  140. // -------------------------------------------------------------------
  141. // Information (current data)
  142. std::size_t getChunkData(void** const dataPtr) noexcept override
  143. {
  144. CARLA_SAFE_ASSERT_RETURN(pData->options & PLUGIN_OPTION_USE_CHUNKS, 0);
  145. CARLA_SAFE_ASSERT_RETURN(fEffect != nullptr, 0);
  146. CARLA_SAFE_ASSERT_RETURN(dataPtr != nullptr, 0);
  147. *dataPtr = nullptr;
  148. try {
  149. const intptr_t ret = dispatcher(effGetChunk, 0 /* bank */, 0, dataPtr, 0.0f);
  150. CARLA_SAFE_ASSERT_RETURN(ret >= 0, 0);
  151. return static_cast<std::size_t>(ret);
  152. } CARLA_SAFE_EXCEPTION_RETURN("VstPlugin::getChunkData", 0);
  153. }
  154. // -------------------------------------------------------------------
  155. // Information (per-plugin data)
  156. uint getOptionsAvailable() const noexcept override
  157. {
  158. CARLA_SAFE_ASSERT_RETURN(fEffect != nullptr, 0);
  159. uint options = 0x0;
  160. options |= PLUGIN_OPTION_MAP_PROGRAM_CHANGES;
  161. if (fEffect->flags & effFlagsProgramChunks)
  162. options |= PLUGIN_OPTION_USE_CHUNKS;
  163. if (getMidiInCount() == 0)
  164. {
  165. options |= PLUGIN_OPTION_FIXED_BUFFERS;
  166. }
  167. else
  168. {
  169. options |= PLUGIN_OPTION_SEND_CONTROL_CHANGES;
  170. options |= PLUGIN_OPTION_SEND_CHANNEL_PRESSURE;
  171. options |= PLUGIN_OPTION_SEND_NOTE_AFTERTOUCH;
  172. options |= PLUGIN_OPTION_SEND_PITCHBEND;
  173. options |= PLUGIN_OPTION_SEND_ALL_SOUND_OFF;
  174. }
  175. return options;
  176. }
  177. float getParameterValue(const uint32_t parameterId) const noexcept override
  178. {
  179. CARLA_SAFE_ASSERT_RETURN(fEffect != nullptr, 0.0f);
  180. CARLA_SAFE_ASSERT_RETURN(parameterId < pData->param.count, 0.0f);
  181. return fEffect->getParameter(fEffect, static_cast<int32_t>(parameterId));
  182. }
  183. void getLabel(char* const strBuf) const noexcept override
  184. {
  185. CARLA_SAFE_ASSERT_RETURN(fEffect != nullptr,);
  186. strBuf[0] = '\0';
  187. dispatcher(effGetProductString, 0, 0, strBuf, 0.0f);
  188. }
  189. void getMaker(char* const strBuf) const noexcept override
  190. {
  191. CARLA_SAFE_ASSERT_RETURN(fEffect != nullptr,);
  192. strBuf[0] = '\0';
  193. dispatcher(effGetVendorString, 0, 0, strBuf, 0.0f);
  194. }
  195. void getCopyright(char* const strBuf) const noexcept override
  196. {
  197. getMaker(strBuf);
  198. }
  199. void getRealName(char* const strBuf) const noexcept override
  200. {
  201. CARLA_SAFE_ASSERT_RETURN(fEffect != nullptr,);
  202. strBuf[0] = '\0';
  203. dispatcher(effGetEffectName, 0, 0, strBuf, 0.0f);
  204. }
  205. void getParameterName(const uint32_t parameterId, char* const strBuf) const noexcept override
  206. {
  207. CARLA_SAFE_ASSERT_RETURN(fEffect != nullptr,);
  208. CARLA_SAFE_ASSERT_RETURN(parameterId < pData->param.count,);
  209. strBuf[0] = '\0';
  210. dispatcher(effGetParamName, static_cast<int32_t>(parameterId), 0, strBuf, 0.0f);
  211. }
  212. void getParameterText(const uint32_t parameterId, char* const strBuf) const noexcept override
  213. {
  214. CARLA_SAFE_ASSERT_RETURN(fEffect != nullptr,);
  215. CARLA_SAFE_ASSERT_RETURN(parameterId < pData->param.count,);
  216. strBuf[0] = '\0';
  217. dispatcher(effGetParamDisplay, static_cast<int32_t>(parameterId), 0, strBuf, 0.0f);
  218. if (strBuf[0] == '\0')
  219. std::snprintf(strBuf, STR_MAX, "%f", getParameterValue(parameterId));
  220. }
  221. void getParameterUnit(const uint32_t parameterId, char* const strBuf) const noexcept override
  222. {
  223. CARLA_SAFE_ASSERT_RETURN(fEffect != nullptr,);
  224. CARLA_SAFE_ASSERT_RETURN(parameterId < pData->param.count,);
  225. strBuf[0] = '\0';
  226. dispatcher(effGetParamLabel, static_cast<int32_t>(parameterId), 0, strBuf, 0.0f);
  227. }
  228. // -------------------------------------------------------------------
  229. // Set data (state)
  230. // nothing
  231. // -------------------------------------------------------------------
  232. // Set data (internal stuff)
  233. void setName(const char* const newName) override
  234. {
  235. CarlaPlugin::setName(newName);
  236. if (fUi.window != nullptr)
  237. {
  238. CarlaString guiTitle(pData->name);
  239. guiTitle += " (GUI)";
  240. fUi.window->setTitle(guiTitle.buffer());
  241. }
  242. }
  243. // -------------------------------------------------------------------
  244. // Set data (plugin-specific stuff)
  245. void setParameterValue(const uint32_t parameterId, const float value, const bool sendGui, const bool sendOsc, const bool sendCallback) noexcept override
  246. {
  247. CARLA_SAFE_ASSERT_RETURN(fEffect != nullptr,);
  248. CARLA_SAFE_ASSERT_RETURN(parameterId < pData->param.count,);
  249. const float fixedValue(pData->param.getFixedValue(parameterId, value));
  250. fEffect->setParameter(fEffect, static_cast<int32_t>(parameterId), fixedValue);
  251. CarlaPlugin::setParameterValue(parameterId, fixedValue, sendGui, sendOsc, sendCallback);
  252. }
  253. void setChunkData(const char* const stringData) override
  254. {
  255. CARLA_SAFE_ASSERT_RETURN(pData->options & PLUGIN_OPTION_USE_CHUNKS,);
  256. CARLA_SAFE_ASSERT_RETURN(fEffect != nullptr,);
  257. CARLA_SAFE_ASSERT_RETURN(stringData != nullptr,);
  258. if (fLastChunk != nullptr)
  259. {
  260. std::free(fLastChunk);
  261. fLastChunk = nullptr;
  262. }
  263. std::vector<uint8_t> chunk(carla_getChunkFromBase64String(stringData));
  264. CARLA_SAFE_ASSERT_RETURN(chunk.size() > 0,);
  265. fLastChunk = std::malloc(chunk.size());
  266. CARLA_SAFE_ASSERT_RETURN(fLastChunk != nullptr,);
  267. std::memcpy(fLastChunk, chunk.data(), chunk.size());
  268. {
  269. const ScopedSingleProcessLocker spl(this, true);
  270. dispatcher(effSetChunk, 0 /* bank */, static_cast<intptr_t>(chunk.size()), fLastChunk, 0.0f);
  271. }
  272. // simulate an updateDisplay callback
  273. handleAudioMasterCallback(audioMasterUpdateDisplay, 0, 0, nullptr, 0.0f);
  274. #ifdef BUILD_BRIDGE
  275. const bool sendOsc(false);
  276. #else
  277. const bool sendOsc(pData->engine->isOscControlRegistered());
  278. #endif
  279. pData->updateParameterValues(this, sendOsc, true, false);
  280. }
  281. void setProgram(const int32_t index, const bool sendGui, const bool sendOsc, const bool sendCallback) noexcept override
  282. {
  283. CARLA_SAFE_ASSERT_RETURN(fEffect != nullptr,);
  284. CARLA_SAFE_ASSERT_RETURN(index >= -1 && index < static_cast<int32_t>(pData->prog.count),);
  285. if (index >= 0)
  286. {
  287. try {
  288. dispatcher(effBeginSetProgram, 0, 0, nullptr, 0.0f);
  289. } catch (...) {
  290. return;
  291. }
  292. {
  293. const ScopedSingleProcessLocker spl(this, (sendGui || sendOsc || sendCallback));
  294. try {
  295. dispatcher(effSetProgram, 0, index, nullptr, 0.0f);
  296. } catch(...) {}
  297. }
  298. try {
  299. dispatcher(effEndSetProgram, 0, 0, nullptr, 0.0f);
  300. } catch(...) {}
  301. }
  302. CarlaPlugin::setProgram(index, sendGui, sendOsc, sendCallback);
  303. }
  304. // -------------------------------------------------------------------
  305. // Set ui stuff
  306. void showCustomUI(const bool yesNo) override
  307. {
  308. if (fUi.type == UI::UI_OSC)
  309. {
  310. if (yesNo)
  311. {
  312. pData->osc.data.clear();
  313. pData->osc.thread.startThread();
  314. }
  315. else
  316. {
  317. pData->transientTryCounter = 0;
  318. if (pData->osc.data.target != nullptr)
  319. {
  320. osc_send_hide(pData->osc.data);
  321. osc_send_quit(pData->osc.data);
  322. pData->osc.data.clear();
  323. }
  324. pData->osc.thread.stopThread(static_cast<int>(pData->engine->getOptions().uiBridgesTimeout * 2));
  325. }
  326. return;
  327. }
  328. if (fUi.isVisible == yesNo)
  329. return;
  330. if (yesNo)
  331. {
  332. CarlaString uiTitle(pData->name);
  333. uiTitle += " (GUI)";
  334. intptr_t value = 0;
  335. void* vstPtr = nullptr;
  336. ERect* vstRect = nullptr;
  337. if (fUi.window == nullptr && fUi.type == UI::UI_EMBED)
  338. {
  339. const char* msg = nullptr;
  340. const uintptr_t frontendWinId(pData->engine->getOptions().frontendWinId);
  341. #if defined(CARLA_OS_LINUX)
  342. # ifdef HAVE_X11
  343. fUi.window = CarlaPluginUI::newX11(this, frontendWinId);
  344. # else
  345. msg = "UI is only for systems with X11";
  346. # endif
  347. #elif defined(CARLA_OS_MAC)
  348. # ifdef __LP64__
  349. fUi.window = CarlaPluginUI::newCocoa(this, frontendWinId);
  350. # endif
  351. #elif defined(CARLA_OS_WIN)
  352. fUi.window = CarlaPluginUI::newWindows(this, frontendWinId);
  353. #else
  354. msg = "Unknown UI type";
  355. #endif
  356. if (fUi.window == nullptr)
  357. return pData->engine->callback(ENGINE_CALLBACK_UI_STATE_CHANGED, pData->id, -1, 0, 0.0f, msg);
  358. fUi.window->setTitle(uiTitle.buffer());
  359. }
  360. if (fUi.type == UI::UI_EMBED)
  361. vstPtr = fUi.window->getPtr();
  362. else
  363. vstPtr = const_cast<char*>(uiTitle.buffer());
  364. dispatcher(effEditGetRect, 0, 0, &vstRect, 0.0f);
  365. #ifdef HAVE_X11
  366. value = (intptr_t)fUi.window->getDisplay();
  367. #endif
  368. if (dispatcher(effEditOpen, 0, value, vstPtr, 0.0f) != 0)
  369. {
  370. if (fUi.type == UI::UI_EMBED)
  371. {
  372. if (vstRect == nullptr || vstRect->right - vstRect->left < 2)
  373. dispatcher(effEditGetRect, 0, 0, &vstRect, 0.0f);
  374. if (vstRect != nullptr)
  375. {
  376. const int width(vstRect->right - vstRect->left);
  377. const int height(vstRect->bottom - vstRect->top);
  378. CARLA_SAFE_ASSERT_INT2(width > 1 && height > 1, width, height);
  379. if (width > 1 && height > 1)
  380. fUi.window->setSize(static_cast<uint>(width), static_cast<uint>(height), false);
  381. }
  382. fUi.window->show();
  383. }
  384. else
  385. {
  386. if (pData->engine->getOptions().frontendWinId)
  387. pData->transientTryCounter = 1;
  388. }
  389. fUi.isVisible = true;
  390. }
  391. else
  392. {
  393. if (fUi.type == UI::UI_EMBED)
  394. {
  395. delete fUi.window;
  396. fUi.window = nullptr;
  397. }
  398. return pData->engine->callback(ENGINE_CALLBACK_UI_STATE_CHANGED, pData->id, -1, 0, 0.0f, "Plugin refused to open its own UI");
  399. }
  400. }
  401. else
  402. {
  403. fUi.isVisible = false;
  404. if (fUi.type == UI::UI_EMBED)
  405. {
  406. CARLA_SAFE_ASSERT_RETURN(fUi.window != nullptr,);
  407. fUi.window->hide();
  408. }
  409. else
  410. {
  411. pData->transientTryCounter = 0;
  412. }
  413. dispatcher(effEditClose, 0, 0, nullptr, 0.0f);
  414. }
  415. }
  416. void idle() override
  417. {
  418. if (fNeedIdle)
  419. dispatcher(effIdle, 0, 0, nullptr, 0.0f);
  420. if (fUi.window != nullptr)
  421. {
  422. fUi.window->idle();
  423. if (fUi.isVisible)
  424. dispatcher(effEditIdle, 0, 0, nullptr, 0.0f);
  425. }
  426. CarlaPlugin::idle();
  427. }
  428. // -------------------------------------------------------------------
  429. // Plugin state
  430. void reload() override
  431. {
  432. CARLA_SAFE_ASSERT_RETURN(pData->engine != nullptr,);
  433. CARLA_SAFE_ASSERT_RETURN(fEffect != nullptr,);
  434. carla_debug("VstPlugin::reload() - start");
  435. const EngineProcessMode processMode(pData->engine->getProccessMode());
  436. // Safely disable plugin for reload
  437. const ScopedDisabler sd(this);
  438. if (pData->active)
  439. deactivate();
  440. clearBuffers();
  441. uint32_t aIns, aOuts, mIns, mOuts, params;
  442. bool needsCtrlIn, needsCtrlOut;
  443. needsCtrlIn = needsCtrlOut = false;
  444. aIns = (fEffect->numInputs > 0) ? static_cast<uint32_t>(fEffect->numInputs) : 0;
  445. aOuts = (fEffect->numOutputs > 0) ? static_cast<uint32_t>(fEffect->numOutputs) : 0;
  446. params = (fEffect->numParams > 0) ? static_cast<uint32_t>(fEffect->numParams) : 0;
  447. if (hasMidiInput())
  448. {
  449. mIns = 1;
  450. needsCtrlIn = true;
  451. }
  452. else
  453. mIns = 0;
  454. if (hasMidiOutput())
  455. {
  456. mOuts = 1;
  457. needsCtrlOut = true;
  458. }
  459. else
  460. mOuts = 0;
  461. if (aIns > 0)
  462. {
  463. pData->audioIn.createNew(aIns);
  464. }
  465. if (aOuts > 0)
  466. {
  467. pData->audioOut.createNew(aOuts);
  468. needsCtrlIn = true;
  469. }
  470. if (params > 0)
  471. {
  472. pData->param.createNew(params, false);
  473. needsCtrlIn = true;
  474. }
  475. const uint portNameSize(pData->engine->getMaxPortNameSize());
  476. CarlaString portName;
  477. // Audio Ins
  478. for (uint32_t j=0; j < aIns; ++j)
  479. {
  480. portName.clear();
  481. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  482. {
  483. portName = pData->name;
  484. portName += ":";
  485. }
  486. if (aIns > 1)
  487. {
  488. portName += "input_";
  489. portName += CarlaString(j+1);
  490. }
  491. else
  492. portName += "input";
  493. portName.truncate(portNameSize);
  494. pData->audioIn.ports[j].port = (CarlaEngineAudioPort*)pData->client->addPort(kEnginePortTypeAudio, portName, true);
  495. pData->audioIn.ports[j].rindex = j;
  496. }
  497. // Audio Outs
  498. for (uint32_t j=0; j < aOuts; ++j)
  499. {
  500. portName.clear();
  501. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  502. {
  503. portName = pData->name;
  504. portName += ":";
  505. }
  506. if (aOuts > 1)
  507. {
  508. portName += "output_";
  509. portName += CarlaString(j+1);
  510. }
  511. else
  512. portName += "output";
  513. portName.truncate(portNameSize);
  514. pData->audioOut.ports[j].port = (CarlaEngineAudioPort*)pData->client->addPort(kEnginePortTypeAudio, portName, false);
  515. pData->audioOut.ports[j].rindex = j;
  516. }
  517. for (uint32_t j=0; j < params; ++j)
  518. {
  519. pData->param.data[j].type = PARAMETER_INPUT;
  520. pData->param.data[j].index = static_cast<int32_t>(j);
  521. pData->param.data[j].rindex = static_cast<int32_t>(j);
  522. float min, max, def, step, stepSmall, stepLarge;
  523. VstParameterProperties prop;
  524. carla_zeroStruct<VstParameterProperties>(prop);
  525. if (pData->hints & PLUGIN_HAS_COCKOS_EXTENSIONS)
  526. {
  527. double vrange[2] = { 0.0, 1.0 };
  528. bool isInteger = false;
  529. if (static_cast<uintptr_t>(dispatcher(effVendorSpecific, static_cast<int32_t>(0xdeadbef0), static_cast<int32_t>(j), vrange, 0.0f)) >= 0xbeef)
  530. {
  531. min = static_cast<float>(vrange[0]);
  532. max = static_cast<float>(vrange[1]);
  533. if (min > max)
  534. {
  535. carla_stderr2("WARNING - Broken plugin parameter min > max (with cockos extensions)");
  536. min = max - 0.1f;
  537. }
  538. else if (min == max)
  539. {
  540. carla_stderr2("WARNING - Broken plugin parameter min == max (with cockos extensions)");
  541. max = min + 0.1f;
  542. }
  543. // only use values as integer if we have a proper range
  544. if (max - min >= 1.0f)
  545. isInteger = dispatcher(effVendorSpecific, kVstParameterUsesIntStep, static_cast<int32_t>(j), nullptr, 0.0f) >= 0xbeef;
  546. }
  547. else
  548. {
  549. min = 0.0f;
  550. max = 1.0f;
  551. }
  552. if (isInteger)
  553. {
  554. step = 1.0f;
  555. stepSmall = 1.0f;
  556. stepLarge = 10.0f;
  557. }
  558. else
  559. {
  560. const float range = max - min;
  561. step = range/100.0f;
  562. stepSmall = range/1000.0f;
  563. stepLarge = range/10.0f;
  564. }
  565. }
  566. else if (dispatcher(effGetParameterProperties, static_cast<int32_t>(j), 0, &prop, 0) == 1)
  567. {
  568. if (prop.flags & kVstParameterUsesIntegerMinMax)
  569. {
  570. min = static_cast<float>(prop.minInteger);
  571. max = static_cast<float>(prop.maxInteger);
  572. if (min > max)
  573. {
  574. carla_stderr2("WARNING - Broken plugin parameter min > max");
  575. min = max - 0.1f;
  576. }
  577. else if (min == max)
  578. {
  579. carla_stderr2("WARNING - Broken plugin parameter min == max");
  580. max = min + 0.1f;
  581. }
  582. }
  583. else
  584. {
  585. min = 0.0f;
  586. max = 1.0f;
  587. }
  588. if (prop.flags & kVstParameterIsSwitch)
  589. {
  590. step = max - min;
  591. stepSmall = step;
  592. stepLarge = step;
  593. pData->param.data[j].hints |= PARAMETER_IS_BOOLEAN;
  594. }
  595. else if (prop.flags & kVstParameterUsesIntStep)
  596. {
  597. step = static_cast<float>(prop.stepInteger);
  598. stepSmall = static_cast<float>(prop.stepInteger)/10.0f;
  599. stepLarge = static_cast<float>(prop.largeStepInteger);
  600. pData->param.data[j].hints |= PARAMETER_IS_INTEGER;
  601. }
  602. else if (prop.flags & kVstParameterUsesFloatStep)
  603. {
  604. step = prop.stepFloat;
  605. stepSmall = prop.smallStepFloat;
  606. stepLarge = prop.largeStepFloat;
  607. }
  608. else
  609. {
  610. const float range = max - min;
  611. step = range/100.0f;
  612. stepSmall = range/1000.0f;
  613. stepLarge = range/10.0f;
  614. }
  615. if (prop.flags & kVstParameterCanRamp)
  616. pData->param.data[j].hints |= PARAMETER_IS_LOGARITHMIC;
  617. }
  618. else
  619. {
  620. min = 0.0f;
  621. max = 1.0f;
  622. step = 0.001f;
  623. stepSmall = 0.0001f;
  624. stepLarge = 0.1f;
  625. }
  626. pData->param.data[j].hints |= PARAMETER_IS_ENABLED;
  627. #ifndef BUILD_BRIDGE
  628. pData->param.data[j].hints |= PARAMETER_USES_CUSTOM_TEXT;
  629. #endif
  630. if ((pData->hints & PLUGIN_USES_OLD_VSTSDK) != 0 || dispatcher(effCanBeAutomated, static_cast<int32_t>(j), 0, nullptr, 0.0f) == 1)
  631. pData->param.data[j].hints |= PARAMETER_IS_AUTOMABLE;
  632. // no such thing as VST default parameters
  633. def = fEffect->getParameter(fEffect, static_cast<int32_t>(j));
  634. if (def < min)
  635. def = min;
  636. else if (def > max)
  637. def = max;
  638. pData->param.ranges[j].min = min;
  639. pData->param.ranges[j].max = max;
  640. pData->param.ranges[j].def = def;
  641. pData->param.ranges[j].step = step;
  642. pData->param.ranges[j].stepSmall = stepSmall;
  643. pData->param.ranges[j].stepLarge = stepLarge;
  644. }
  645. if (needsCtrlIn)
  646. {
  647. portName.clear();
  648. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  649. {
  650. portName = pData->name;
  651. portName += ":";
  652. }
  653. portName += "events-in";
  654. portName.truncate(portNameSize);
  655. pData->event.portIn = (CarlaEngineEventPort*)pData->client->addPort(kEnginePortTypeEvent, portName, true);
  656. }
  657. if (needsCtrlOut)
  658. {
  659. portName.clear();
  660. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  661. {
  662. portName = pData->name;
  663. portName += ":";
  664. }
  665. portName += "events-out";
  666. portName.truncate(portNameSize);
  667. pData->event.portOut = (CarlaEngineEventPort*)pData->client->addPort(kEnginePortTypeEvent, portName, false);
  668. }
  669. // plugin hints
  670. const intptr_t vstCategory = dispatcher(effGetPlugCategory, 0, 0, nullptr, 0.0f);
  671. pData->hints = 0x0;
  672. if (vstCategory == kPlugCategSynth || vstCategory == kPlugCategGenerator)
  673. pData->hints |= PLUGIN_IS_SYNTH;
  674. if (fEffect->flags & effFlagsHasEditor)
  675. {
  676. pData->hints |= PLUGIN_HAS_CUSTOM_UI;
  677. if (fUi.type == UI::UI_EMBED)
  678. pData->hints |= PLUGIN_NEEDS_SINGLE_THREAD;
  679. }
  680. if (dispatcher(effGetVstVersion, 0, 0, nullptr, 0.0f) < kVstVersion)
  681. pData->hints |= PLUGIN_USES_OLD_VSTSDK;
  682. if ((fEffect->flags & effFlagsCanReplacing) != 0 && fEffect->processReplacing != fEffect->process)
  683. pData->hints |= PLUGIN_CAN_PROCESS_REPLACING;
  684. if (static_cast<uintptr_t>(dispatcher(effCanDo, 0, 0, const_cast<char*>("hasCockosExtensions"), 0.0f)) == 0xbeef0000)
  685. pData->hints |= PLUGIN_HAS_COCKOS_EXTENSIONS;
  686. if (aOuts > 0 && (aIns == aOuts || aIns == 1))
  687. pData->hints |= PLUGIN_CAN_DRYWET;
  688. if (aOuts > 0)
  689. pData->hints |= PLUGIN_CAN_VOLUME;
  690. if (aOuts >= 2 && aOuts % 2 == 0)
  691. pData->hints |= PLUGIN_CAN_BALANCE;
  692. // extra plugin hints
  693. pData->extraHints = 0x0;
  694. if (mIns > 0)
  695. pData->extraHints |= PLUGIN_EXTRA_HINT_HAS_MIDI_IN;
  696. if (mOuts > 0)
  697. pData->extraHints |= PLUGIN_EXTRA_HINT_HAS_MIDI_OUT;
  698. if (aIns <= 2 && aOuts <= 2 && (aIns == aOuts || aIns == 0 || aOuts == 0))
  699. pData->extraHints |= PLUGIN_EXTRA_HINT_CAN_RUN_RACK;
  700. // dummy pre-start to get latency and wantEvents() on old plugins
  701. {
  702. activate();
  703. deactivate();
  704. }
  705. // check latency
  706. if (pData->hints & PLUGIN_CAN_DRYWET)
  707. {
  708. #ifdef VESTIGE_HEADER
  709. char* const empty3Ptr = &fEffect->empty3[0];
  710. int32_t initialDelay = *(int32_t*)empty3Ptr;
  711. pData->latency = (initialDelay > 0) ? static_cast<uint32_t>(initialDelay) : 0;
  712. #else
  713. pData->latency = (fEffect->initialDelay > 0) ? static_cast<uint32_t>(fEffect->initialDelay) : 0;
  714. #endif
  715. pData->client->setLatency(pData->latency);
  716. #ifndef BUILD_BRIDGE
  717. pData->recreateLatencyBuffers();
  718. #endif
  719. }
  720. // special plugin fixes
  721. // 1. IL Harmless - disable threaded processing
  722. if (fEffect->uniqueID == 1229484653)
  723. {
  724. char strBuf[STR_MAX+1] = { '\0' };
  725. getLabel(strBuf);
  726. if (std::strcmp(strBuf, "IL Harmless") == 0)
  727. {
  728. // TODO - disable threaded processing
  729. }
  730. }
  731. //bufferSizeChanged(pData->engine->getBufferSize());
  732. reloadPrograms(true);
  733. if (pData->active)
  734. activate();
  735. carla_debug("VstPlugin::reload() - end");
  736. }
  737. void reloadPrograms(const bool doInit) override
  738. {
  739. carla_debug("VstPlugin::reloadPrograms(%s)", bool2str(doInit));
  740. const uint32_t oldCount = pData->prog.count;
  741. const int32_t current = pData->prog.current;
  742. // Delete old programs
  743. pData->prog.clear();
  744. // Query new programs
  745. uint32_t newCount = (fEffect->numPrograms > 0) ? static_cast<uint32_t>(fEffect->numPrograms) : 0;
  746. if (newCount > 0)
  747. {
  748. pData->prog.createNew(newCount);
  749. // Update names
  750. for (int32_t i=0; i < fEffect->numPrograms; ++i)
  751. {
  752. char strBuf[STR_MAX+1] = { '\0' };
  753. if (dispatcher(effGetProgramNameIndexed, i, 0, strBuf, 0.0f) != 1)
  754. {
  755. // program will be [re-]changed later
  756. dispatcher(effSetProgram, 0, i, nullptr, 0.0f);
  757. dispatcher(effGetProgramName, 0, 0, strBuf, 0.0f);
  758. }
  759. pData->prog.names[i] = carla_strdup(strBuf);
  760. }
  761. }
  762. #ifndef BUILD_BRIDGE
  763. // Update OSC Names
  764. if (pData->engine->isOscControlRegistered())
  765. {
  766. pData->engine->oscSend_control_set_program_count(pData->id, newCount);
  767. for (uint32_t i=0; i < newCount; ++i)
  768. pData->engine->oscSend_control_set_program_name(pData->id, i, pData->prog.names[i]);
  769. }
  770. #endif
  771. if (doInit)
  772. {
  773. if (newCount > 0)
  774. setProgram(0, false, false, false);
  775. }
  776. else
  777. {
  778. // Check if current program is invalid
  779. bool programChanged = false;
  780. if (newCount == oldCount+1)
  781. {
  782. // one program added, probably created by user
  783. pData->prog.current = static_cast<int32_t>(oldCount);
  784. programChanged = true;
  785. }
  786. else if (current < 0 && newCount > 0)
  787. {
  788. // programs exist now, but not before
  789. pData->prog.current = 0;
  790. programChanged = true;
  791. }
  792. else if (current >= 0 && newCount == 0)
  793. {
  794. // programs existed before, but not anymore
  795. pData->prog.current = -1;
  796. programChanged = true;
  797. }
  798. else if (current >= static_cast<int32_t>(newCount))
  799. {
  800. // current program > count
  801. pData->prog.current = 0;
  802. programChanged = true;
  803. }
  804. else
  805. {
  806. // no change
  807. pData->prog.current = current;
  808. }
  809. if (programChanged)
  810. {
  811. setProgram(pData->prog.current, true, true, true);
  812. }
  813. else
  814. {
  815. // Program was changed during update, re-set it
  816. if (pData->prog.current >= 0)
  817. dispatcher(effSetProgram, 0, pData->prog.current, nullptr, 0.0f);
  818. }
  819. pData->engine->callback(ENGINE_CALLBACK_RELOAD_PROGRAMS, pData->id, 0, 0, 0.0f, nullptr);
  820. }
  821. }
  822. // -------------------------------------------------------------------
  823. // Plugin processing
  824. void activate() noexcept override
  825. {
  826. CARLA_SAFE_ASSERT_RETURN(fEffect != nullptr,);
  827. try {
  828. dispatcher(effMainsChanged, 0, 1, nullptr, 0.0f);
  829. } catch(...) {}
  830. try {
  831. dispatcher(effStartProcess, 0, 0, nullptr, 0.0f);
  832. } catch(...) {}
  833. }
  834. void deactivate() noexcept override
  835. {
  836. CARLA_SAFE_ASSERT_RETURN(fEffect != nullptr,);
  837. try {
  838. dispatcher(effStopProcess, 0, 0, nullptr, 0.0f);
  839. } catch(...) {}
  840. try {
  841. dispatcher(effMainsChanged, 0, 0, nullptr, 0.0f);
  842. } catch(...) {}
  843. }
  844. void process(float** const inBuffer, float** const outBuffer, const uint32_t frames) override
  845. {
  846. fProcThread = pthread_self();
  847. // --------------------------------------------------------------------------------------------------------
  848. // Check if active
  849. if (! pData->active)
  850. {
  851. // disable any output sound
  852. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  853. FloatVectorOperations::clear(outBuffer[i], static_cast<int>(frames));
  854. return;
  855. }
  856. fMidiEventCount = 0;
  857. carla_zeroStruct<VstMidiEvent>(fMidiEvents, kPluginMaxMidiEvents*2);
  858. // --------------------------------------------------------------------------------------------------------
  859. // Check if needs reset
  860. if (pData->needsReset)
  861. {
  862. if (pData->options & PLUGIN_OPTION_SEND_ALL_SOUND_OFF)
  863. {
  864. fMidiEventCount = MAX_MIDI_CHANNELS*2;
  865. for (uint8_t i=0, k=MAX_MIDI_CHANNELS; i < MAX_MIDI_CHANNELS; ++i)
  866. {
  867. fMidiEvents[k].type = kVstMidiType;
  868. fMidiEvents[k].byteSize = static_cast<int32_t>(sizeof(VstMidiEvent));
  869. fMidiEvents[k].midiData[0] = static_cast<char>(MIDI_STATUS_CONTROL_CHANGE + k);
  870. fMidiEvents[k].midiData[1] = MIDI_CONTROL_ALL_NOTES_OFF;
  871. fMidiEvents[k+i].type = kVstMidiType;
  872. fMidiEvents[k+i].byteSize = static_cast<int32_t>(sizeof(VstMidiEvent));
  873. fMidiEvents[k+i].midiData[0] = static_cast<char>(MIDI_STATUS_CONTROL_CHANGE + k);
  874. fMidiEvents[k+i].midiData[1] = MIDI_CONTROL_ALL_SOUND_OFF;
  875. }
  876. }
  877. else if (pData->ctrlChannel >= 0 && pData->ctrlChannel < MAX_MIDI_CHANNELS)
  878. {
  879. fMidiEventCount = MAX_MIDI_NOTE;
  880. for (uint8_t i=0; i < MAX_MIDI_NOTE; ++i)
  881. {
  882. fMidiEvents[i].type = kVstMidiType;
  883. fMidiEvents[i].byteSize = static_cast<int32_t>(sizeof(VstMidiEvent));
  884. fMidiEvents[i].midiData[0] = static_cast<char>(MIDI_STATUS_NOTE_OFF + pData->ctrlChannel);
  885. fMidiEvents[i].midiData[1] = static_cast<char>(i);
  886. }
  887. }
  888. #ifndef BUILD_BRIDGE
  889. if (pData->latency > 0)
  890. {
  891. for (uint32_t i=0; i < pData->audioIn.count; ++i)
  892. FloatVectorOperations::clear(pData->latencyBuffers[i], static_cast<int>(pData->latency));
  893. }
  894. #endif
  895. pData->needsReset = false;
  896. }
  897. // --------------------------------------------------------------------------------------------------------
  898. // Set TimeInfo
  899. const EngineTimeInfo& timeInfo(pData->engine->getTimeInfo());
  900. fTimeInfo.flags = kVstTransportChanged;
  901. if (timeInfo.playing)
  902. fTimeInfo.flags |= kVstTransportPlaying;
  903. fTimeInfo.samplePos = double(timeInfo.frame);
  904. fTimeInfo.sampleRate = pData->engine->getSampleRate();
  905. if (timeInfo.usecs != 0)
  906. {
  907. fTimeInfo.nanoSeconds = double(timeInfo.usecs)/1000.0;
  908. fTimeInfo.flags |= kVstNanosValid;
  909. }
  910. if (timeInfo.valid & EngineTimeInfo::kValidBBT)
  911. {
  912. double ppqBar = double(timeInfo.bbt.bar - 1) * timeInfo.bbt.beatsPerBar;
  913. double ppqBeat = double(timeInfo.bbt.beat - 1);
  914. double ppqTick = double(timeInfo.bbt.tick) / timeInfo.bbt.ticksPerBeat;
  915. // PPQ Pos
  916. fTimeInfo.ppqPos = ppqBar + ppqBeat + ppqTick;
  917. fTimeInfo.flags |= kVstPpqPosValid;
  918. // Tempo
  919. fTimeInfo.tempo = timeInfo.bbt.beatsPerMinute;
  920. fTimeInfo.flags |= kVstTempoValid;
  921. // Bars
  922. fTimeInfo.barStartPos = ppqBar;
  923. fTimeInfo.flags |= kVstBarsValid;
  924. // Time Signature
  925. fTimeInfo.timeSigNumerator = static_cast<int32_t>(timeInfo.bbt.beatsPerBar);
  926. fTimeInfo.timeSigDenominator = static_cast<int32_t>(timeInfo.bbt.beatType);
  927. fTimeInfo.flags |= kVstTimeSigValid;
  928. }
  929. else
  930. {
  931. // Tempo
  932. fTimeInfo.tempo = 120.0;
  933. fTimeInfo.flags |= kVstTempoValid;
  934. // Time Signature
  935. fTimeInfo.timeSigNumerator = 4;
  936. fTimeInfo.timeSigDenominator = 4;
  937. fTimeInfo.flags |= kVstTimeSigValid;
  938. // Missing info
  939. fTimeInfo.ppqPos = 0.0;
  940. fTimeInfo.barStartPos = 0.0;
  941. }
  942. // --------------------------------------------------------------------------------------------------------
  943. // Event Input and Processing
  944. if (pData->event.portIn != nullptr)
  945. {
  946. // ----------------------------------------------------------------------------------------------------
  947. // MIDI Input (External)
  948. if (pData->extNotes.mutex.tryLock())
  949. {
  950. ExternalMidiNote note = { 0, 0, 0 };
  951. for (; fMidiEventCount < kPluginMaxMidiEvents*2 && ! pData->extNotes.data.isEmpty();)
  952. {
  953. note = pData->extNotes.data.getFirst(note, true);
  954. CARLA_SAFE_ASSERT_CONTINUE(note.channel >= 0 && note.channel < MAX_MIDI_CHANNELS);
  955. fMidiEvents[fMidiEventCount].type = kVstMidiType;
  956. fMidiEvents[fMidiEventCount].byteSize = static_cast<int32_t>(sizeof(VstMidiEvent));
  957. fMidiEvents[fMidiEventCount].midiData[0] = static_cast<char>((note.velo > 0 ? MIDI_STATUS_NOTE_ON : MIDI_STATUS_NOTE_OFF) | (note.channel & MIDI_CHANNEL_BIT));
  958. fMidiEvents[fMidiEventCount].midiData[1] = static_cast<char>(note.note);
  959. fMidiEvents[fMidiEventCount].midiData[2] = static_cast<char>(note.velo);
  960. ++fMidiEventCount;
  961. }
  962. pData->extNotes.mutex.unlock();
  963. } // End of MIDI Input (External)
  964. // ----------------------------------------------------------------------------------------------------
  965. // Event Input (System)
  966. #ifndef BUILD_BRIDGE
  967. bool allNotesOffSent = false;
  968. #endif
  969. bool isSampleAccurate = (pData->options & PLUGIN_OPTION_FIXED_BUFFERS) == 0;
  970. uint32_t numEvents = pData->event.portIn->getEventCount();
  971. uint32_t startTime = 0;
  972. uint32_t timeOffset = 0;
  973. for (uint32_t i=0; i < numEvents; ++i)
  974. {
  975. const EngineEvent& event(pData->event.portIn->getEvent(i));
  976. if (event.time >= frames)
  977. continue;
  978. CARLA_ASSERT_INT2(event.time >= timeOffset, event.time, timeOffset);
  979. if (isSampleAccurate && event.time > timeOffset)
  980. {
  981. if (processSingle(inBuffer, outBuffer, event.time - timeOffset, timeOffset))
  982. {
  983. startTime = 0;
  984. timeOffset = event.time;
  985. if (fMidiEventCount > 0)
  986. {
  987. carla_zeroStruct<VstMidiEvent>(fMidiEvents, fMidiEventCount);
  988. fMidiEventCount = 0;
  989. }
  990. }
  991. else
  992. startTime += timeOffset;
  993. }
  994. switch (event.type)
  995. {
  996. case kEngineEventTypeNull:
  997. break;
  998. case kEngineEventTypeControl: {
  999. const EngineControlEvent& ctrlEvent(event.ctrl);
  1000. switch (ctrlEvent.type)
  1001. {
  1002. case kEngineControlEventTypeNull:
  1003. break;
  1004. case kEngineControlEventTypeParameter: {
  1005. #ifndef BUILD_BRIDGE
  1006. // Control backend stuff
  1007. if (event.channel == pData->ctrlChannel)
  1008. {
  1009. float value;
  1010. if (MIDI_IS_CONTROL_BREATH_CONTROLLER(ctrlEvent.param) && (pData->hints & PLUGIN_CAN_DRYWET) != 0)
  1011. {
  1012. value = ctrlEvent.value;
  1013. setDryWet(value, false, false);
  1014. pData->postponeRtEvent(kPluginPostRtEventParameterChange, PARAMETER_DRYWET, 0, value);
  1015. break;
  1016. }
  1017. if (MIDI_IS_CONTROL_CHANNEL_VOLUME(ctrlEvent.param) && (pData->hints & PLUGIN_CAN_VOLUME) != 0)
  1018. {
  1019. value = ctrlEvent.value*127.0f/100.0f;
  1020. setVolume(value, false, false);
  1021. pData->postponeRtEvent(kPluginPostRtEventParameterChange, PARAMETER_VOLUME, 0, value);
  1022. break;
  1023. }
  1024. if (MIDI_IS_CONTROL_BALANCE(ctrlEvent.param) && (pData->hints & PLUGIN_CAN_BALANCE) != 0)
  1025. {
  1026. float left, right;
  1027. value = ctrlEvent.value/0.5f - 1.0f;
  1028. if (value < 0.0f)
  1029. {
  1030. left = -1.0f;
  1031. right = (value*2.0f)+1.0f;
  1032. }
  1033. else if (value > 0.0f)
  1034. {
  1035. left = (value*2.0f)-1.0f;
  1036. right = 1.0f;
  1037. }
  1038. else
  1039. {
  1040. left = -1.0f;
  1041. right = 1.0f;
  1042. }
  1043. setBalanceLeft(left, false, false);
  1044. setBalanceRight(right, false, false);
  1045. pData->postponeRtEvent(kPluginPostRtEventParameterChange, PARAMETER_BALANCE_LEFT, 0, left);
  1046. pData->postponeRtEvent(kPluginPostRtEventParameterChange, PARAMETER_BALANCE_RIGHT, 0, right);
  1047. break;
  1048. }
  1049. }
  1050. // Control plugin parameters
  1051. uint32_t k;
  1052. for (k=0; k < pData->param.count; ++k)
  1053. {
  1054. if (pData->param.data[k].midiChannel != event.channel)
  1055. continue;
  1056. if (pData->param.data[k].midiCC != ctrlEvent.param)
  1057. continue;
  1058. if (pData->param.data[k].type != PARAMETER_INPUT)
  1059. continue;
  1060. if ((pData->param.data[k].hints & PARAMETER_IS_AUTOMABLE) == 0)
  1061. continue;
  1062. float value;
  1063. if (pData->param.data[k].hints & PARAMETER_IS_BOOLEAN)
  1064. {
  1065. value = (ctrlEvent.value < 0.5f) ? pData->param.ranges[k].min : pData->param.ranges[k].max;
  1066. }
  1067. else
  1068. {
  1069. value = pData->param.ranges[k].getUnnormalizedValue(ctrlEvent.value);
  1070. if (pData->param.data[k].hints & PARAMETER_IS_INTEGER)
  1071. value = std::rint(value);
  1072. }
  1073. setParameterValue(k, value, false, false, false);
  1074. pData->postponeRtEvent(kPluginPostRtEventParameterChange, static_cast<int32_t>(k), 0, value);
  1075. break;
  1076. }
  1077. // check if event is already handled
  1078. if (k != pData->param.count)
  1079. break;
  1080. #endif
  1081. if ((pData->options & PLUGIN_OPTION_SEND_CONTROL_CHANGES) != 0 && ctrlEvent.param <= 0x5F)
  1082. {
  1083. if (fMidiEventCount >= kPluginMaxMidiEvents*2)
  1084. continue;
  1085. carla_zeroStruct<VstMidiEvent>(fMidiEvents[fMidiEventCount]);
  1086. fMidiEvents[fMidiEventCount].type = kVstMidiType;
  1087. fMidiEvents[fMidiEventCount].byteSize = static_cast<int32_t>(sizeof(VstMidiEvent));
  1088. fMidiEvents[fMidiEventCount].midiData[0] = static_cast<char>(MIDI_STATUS_CONTROL_CHANGE + event.channel);
  1089. fMidiEvents[fMidiEventCount].midiData[1] = static_cast<char>(ctrlEvent.param);
  1090. fMidiEvents[fMidiEventCount].midiData[2] = char(ctrlEvent.value*127.0f);
  1091. fMidiEvents[fMidiEventCount].deltaFrames = static_cast<int32_t>(isSampleAccurate ? startTime : event.time);
  1092. ++fMidiEventCount;
  1093. }
  1094. break;
  1095. } // case kEngineControlEventTypeParameter
  1096. case kEngineControlEventTypeMidiBank:
  1097. break;
  1098. case kEngineControlEventTypeMidiProgram:
  1099. if (event.channel == pData->ctrlChannel && (pData->options & PLUGIN_OPTION_MAP_PROGRAM_CHANGES) != 0)
  1100. {
  1101. if (ctrlEvent.param < pData->prog.count)
  1102. {
  1103. setProgram(ctrlEvent.param, false, false, false);
  1104. pData->postponeRtEvent(kPluginPostRtEventProgramChange, ctrlEvent.param, 0, 0.0f);
  1105. break;
  1106. }
  1107. }
  1108. break;
  1109. case kEngineControlEventTypeAllSoundOff:
  1110. if (pData->options & PLUGIN_OPTION_SEND_ALL_SOUND_OFF)
  1111. {
  1112. if (fMidiEventCount >= kPluginMaxMidiEvents*2)
  1113. continue;
  1114. carla_zeroStruct<VstMidiEvent>(fMidiEvents[fMidiEventCount]);
  1115. fMidiEvents[fMidiEventCount].type = kVstMidiType;
  1116. fMidiEvents[fMidiEventCount].byteSize = static_cast<int32_t>(sizeof(VstMidiEvent));
  1117. fMidiEvents[fMidiEventCount].midiData[0] = static_cast<char>(MIDI_STATUS_CONTROL_CHANGE + event.channel);
  1118. fMidiEvents[fMidiEventCount].midiData[1] = MIDI_CONTROL_ALL_SOUND_OFF;
  1119. fMidiEvents[fMidiEventCount].deltaFrames = static_cast<int32_t>(isSampleAccurate ? startTime : event.time);
  1120. ++fMidiEventCount;
  1121. }
  1122. break;
  1123. case kEngineControlEventTypeAllNotesOff:
  1124. if (pData->options & PLUGIN_OPTION_SEND_ALL_SOUND_OFF)
  1125. {
  1126. #ifndef BUILD_BRIDGE
  1127. if (event.channel == pData->ctrlChannel && ! allNotesOffSent)
  1128. {
  1129. allNotesOffSent = true;
  1130. sendMidiAllNotesOffToCallback();
  1131. }
  1132. #endif
  1133. if (fMidiEventCount >= kPluginMaxMidiEvents*2)
  1134. continue;
  1135. carla_zeroStruct<VstMidiEvent>(fMidiEvents[fMidiEventCount]);
  1136. fMidiEvents[fMidiEventCount].type = kVstMidiType;
  1137. fMidiEvents[fMidiEventCount].byteSize = static_cast<int32_t>(sizeof(VstMidiEvent));
  1138. fMidiEvents[fMidiEventCount].midiData[0] = static_cast<char>(MIDI_STATUS_CONTROL_CHANGE + event.channel);
  1139. fMidiEvents[fMidiEventCount].midiData[1] = MIDI_CONTROL_ALL_NOTES_OFF;
  1140. fMidiEvents[fMidiEventCount].deltaFrames = static_cast<int32_t>(isSampleAccurate ? startTime : event.time);
  1141. ++fMidiEventCount;
  1142. }
  1143. break;
  1144. } // switch (ctrlEvent.type)
  1145. break;
  1146. } // case kEngineEventTypeControl
  1147. case kEngineEventTypeMidi: {
  1148. if (fMidiEventCount >= kPluginMaxMidiEvents*2)
  1149. continue;
  1150. const EngineMidiEvent& midiEvent(event.midi);
  1151. uint8_t status = static_cast<uint8_t>(MIDI_GET_STATUS_FROM_DATA(midiEvent.data));
  1152. uint8_t channel = event.channel;
  1153. // Fix bad note-off (per VST spec)
  1154. if (MIDI_IS_STATUS_NOTE_ON(status) && midiEvent.data[2] == 0)
  1155. status = MIDI_STATUS_NOTE_OFF;
  1156. if (status == MIDI_STATUS_CHANNEL_PRESSURE && (pData->options & PLUGIN_OPTION_SEND_CHANNEL_PRESSURE) == 0)
  1157. continue;
  1158. if (status == MIDI_STATUS_CONTROL_CHANGE && (pData->options & PLUGIN_OPTION_SEND_CONTROL_CHANGES) == 0)
  1159. continue;
  1160. if (status == MIDI_STATUS_POLYPHONIC_AFTERTOUCH && (pData->options & PLUGIN_OPTION_SEND_NOTE_AFTERTOUCH) == 0)
  1161. continue;
  1162. if (status == MIDI_STATUS_PITCH_WHEEL_CONTROL && (pData->options & PLUGIN_OPTION_SEND_PITCHBEND) == 0)
  1163. continue;
  1164. carla_zeroStruct<VstMidiEvent>(fMidiEvents[fMidiEventCount]);
  1165. fMidiEvents[fMidiEventCount].type = kVstMidiType;
  1166. fMidiEvents[fMidiEventCount].byteSize = static_cast<int32_t>(sizeof(VstMidiEvent));
  1167. fMidiEvents[fMidiEventCount].midiData[0] = static_cast<char>(status + channel);
  1168. fMidiEvents[fMidiEventCount].midiData[1] = static_cast<char>(midiEvent.data[1]);
  1169. fMidiEvents[fMidiEventCount].midiData[2] = static_cast<char>(midiEvent.data[2]);
  1170. fMidiEvents[fMidiEventCount].deltaFrames = static_cast<int32_t>(isSampleAccurate ? startTime : event.time);
  1171. ++fMidiEventCount;
  1172. if (status == MIDI_STATUS_NOTE_ON)
  1173. pData->postponeRtEvent(kPluginPostRtEventNoteOn, channel, midiEvent.data[1], midiEvent.data[2]);
  1174. else if (status == MIDI_STATUS_NOTE_OFF)
  1175. pData->postponeRtEvent(kPluginPostRtEventNoteOff, channel, midiEvent.data[1], 0.0f);
  1176. break;
  1177. } // case kEngineEventTypeMidi
  1178. } // switch (event.type)
  1179. }
  1180. pData->postRtEvents.trySplice();
  1181. if (frames > timeOffset)
  1182. processSingle(inBuffer, outBuffer, frames - timeOffset, timeOffset);
  1183. } // End of Event Input and Processing
  1184. // --------------------------------------------------------------------------------------------------------
  1185. // Plugin processing (no events)
  1186. else
  1187. {
  1188. processSingle(inBuffer, outBuffer, frames, 0);
  1189. } // End of Plugin processing (no events)
  1190. // --------------------------------------------------------------------------------------------------------
  1191. // MIDI Output
  1192. if (pData->event.portOut != nullptr)
  1193. {
  1194. // reverse lookup MIDI events
  1195. for (uint32_t k = (kPluginMaxMidiEvents*2)-1; k >= fMidiEventCount; --k)
  1196. {
  1197. if (fMidiEvents[k].type == 0)
  1198. break;
  1199. CARLA_SAFE_ASSERT_CONTINUE(fMidiEvents[k].deltaFrames >= 0);
  1200. CARLA_SAFE_ASSERT_CONTINUE(fMidiEvents[k].midiData[0] != 0);
  1201. const uint8_t status(static_cast<uint8_t>(fMidiEvents[k].midiData[0]));
  1202. const uint8_t channel(static_cast<uint8_t>(status < MIDI_STATUS_BIT ? status & MIDI_CHANNEL_BIT : 0));
  1203. uint8_t midiData[3];
  1204. midiData[0] = static_cast<uint8_t>(fMidiEvents[k].midiData[0]);
  1205. midiData[1] = static_cast<uint8_t>(fMidiEvents[k].midiData[1]);
  1206. midiData[2] = static_cast<uint8_t>(fMidiEvents[k].midiData[2]);
  1207. pData->event.portOut->writeMidiEvent(static_cast<uint32_t>(fMidiEvents[k].deltaFrames), channel, 0, 3, midiData);
  1208. }
  1209. } // End of MIDI Output
  1210. }
  1211. bool processSingle(float** const inBuffer, float** const outBuffer, const uint32_t frames, const uint32_t timeOffset)
  1212. {
  1213. CARLA_SAFE_ASSERT_RETURN(frames > 0, false);
  1214. if (pData->audioIn.count > 0)
  1215. {
  1216. CARLA_SAFE_ASSERT_RETURN(inBuffer != nullptr, false);
  1217. }
  1218. if (pData->audioOut.count > 0)
  1219. {
  1220. CARLA_SAFE_ASSERT_RETURN(outBuffer != nullptr, false);
  1221. }
  1222. // --------------------------------------------------------------------------------------------------------
  1223. // Try lock, silence otherwise
  1224. if (pData->engine->isOffline())
  1225. {
  1226. pData->singleMutex.lock();
  1227. }
  1228. else if (! pData->singleMutex.tryLock())
  1229. {
  1230. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  1231. {
  1232. for (uint32_t k=0; k < frames; ++k)
  1233. outBuffer[i][k+timeOffset] = 0.0f;
  1234. }
  1235. return false;
  1236. }
  1237. // --------------------------------------------------------------------------------------------------------
  1238. // Set audio buffers
  1239. float* vstInBuffer[pData->audioIn.count];
  1240. float* vstOutBuffer[pData->audioOut.count];
  1241. for (uint32_t i=0; i < pData->audioIn.count; ++i)
  1242. vstInBuffer[i] = inBuffer[i]+timeOffset;
  1243. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  1244. vstOutBuffer[i] = outBuffer[i]+timeOffset;
  1245. // --------------------------------------------------------------------------------------------------------
  1246. // Set MIDI events
  1247. if (fMidiEventCount > 0)
  1248. {
  1249. fEvents.numEvents = static_cast<int32_t>(fMidiEventCount);
  1250. fEvents.reserved = 0;
  1251. dispatcher(effProcessEvents, 0, 0, &fEvents, 0.0f);
  1252. }
  1253. // --------------------------------------------------------------------------------------------------------
  1254. // Run plugin
  1255. fIsProcessing = true;
  1256. if (pData->hints & PLUGIN_CAN_PROCESS_REPLACING)
  1257. {
  1258. fEffect->processReplacing(fEffect, (pData->audioIn.count > 0) ? vstInBuffer : nullptr, (pData->audioOut.count > 0) ? vstOutBuffer : nullptr, static_cast<int32_t>(frames));
  1259. }
  1260. else
  1261. {
  1262. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  1263. FloatVectorOperations::clear(vstOutBuffer[i], static_cast<int>(frames));
  1264. #if ! VST_FORCE_DEPRECATED
  1265. fEffect->process(fEffect, (pData->audioIn.count > 0) ? vstInBuffer : nullptr, (pData->audioOut.count > 0) ? vstOutBuffer : nullptr, static_cast<int32_t>(frames));
  1266. #endif
  1267. }
  1268. fIsProcessing = false;
  1269. fTimeInfo.samplePos += frames;
  1270. #ifndef BUILD_BRIDGE
  1271. // --------------------------------------------------------------------------------------------------------
  1272. // Post-processing (dry/wet, volume and balance)
  1273. {
  1274. const bool doVolume = (pData->hints & PLUGIN_CAN_VOLUME) != 0 && pData->postProc.volume != 1.0f;
  1275. const bool doDryWet = (pData->hints & PLUGIN_CAN_DRYWET) != 0 && pData->postProc.dryWet != 1.0f;
  1276. const bool doBalance = (pData->hints & PLUGIN_CAN_BALANCE) != 0 && (pData->postProc.balanceLeft != -1.0f || pData->postProc.balanceRight != 1.0f);
  1277. bool isPair;
  1278. float bufValue, oldBufLeft[doBalance ? frames : 1];
  1279. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  1280. {
  1281. // Dry/Wet
  1282. if (doDryWet)
  1283. {
  1284. for (uint32_t k=0; k < frames; ++k)
  1285. {
  1286. bufValue = inBuffer[(pData->audioIn.count == 1) ? 0 : i][k+timeOffset];
  1287. outBuffer[i][k+timeOffset] = (outBuffer[i][k+timeOffset] * pData->postProc.dryWet) + (bufValue * (1.0f - pData->postProc.dryWet));
  1288. }
  1289. }
  1290. // Balance
  1291. if (doBalance)
  1292. {
  1293. isPair = (i % 2 == 0);
  1294. if (isPair)
  1295. {
  1296. CARLA_ASSERT(i+1 < pData->audioOut.count);
  1297. FloatVectorOperations::copy(oldBufLeft, outBuffer[i]+timeOffset, static_cast<int>(frames));
  1298. }
  1299. float balRangeL = (pData->postProc.balanceLeft + 1.0f)/2.0f;
  1300. float balRangeR = (pData->postProc.balanceRight + 1.0f)/2.0f;
  1301. for (uint32_t k=0; k < frames; ++k)
  1302. {
  1303. if (isPair)
  1304. {
  1305. // left
  1306. outBuffer[i][k+timeOffset] = oldBufLeft[k] * (1.0f - balRangeL);
  1307. outBuffer[i][k+timeOffset] += outBuffer[i+1][k+timeOffset] * (1.0f - balRangeR);
  1308. }
  1309. else
  1310. {
  1311. // right
  1312. outBuffer[i][k+timeOffset] = outBuffer[i][k+timeOffset] * balRangeR;
  1313. outBuffer[i][k+timeOffset] += oldBufLeft[k] * balRangeL;
  1314. }
  1315. }
  1316. }
  1317. // Volume
  1318. if (doVolume)
  1319. {
  1320. for (uint32_t k=0; k < frames; ++k)
  1321. outBuffer[i][k+timeOffset] *= pData->postProc.volume;
  1322. }
  1323. }
  1324. } // End of Post-processing
  1325. #endif
  1326. // --------------------------------------------------------------------------------------------------------
  1327. pData->singleMutex.unlock();
  1328. return true;
  1329. }
  1330. void bufferSizeChanged(const uint32_t newBufferSize) override
  1331. {
  1332. CARLA_ASSERT_INT(newBufferSize > 0, newBufferSize);
  1333. carla_debug("VstPlugin::bufferSizeChanged(%i)", newBufferSize);
  1334. if (pData->active)
  1335. deactivate();
  1336. #if ! VST_FORCE_DEPRECATED
  1337. dispatcher(effSetBlockSizeAndSampleRate, 0, static_cast<int32_t>(newBufferSize), nullptr, static_cast<float>(pData->engine->getSampleRate()));
  1338. #endif
  1339. dispatcher(effSetBlockSize, 0, static_cast<int32_t>(newBufferSize), nullptr, 0.0f);
  1340. if (pData->active)
  1341. activate();
  1342. }
  1343. void sampleRateChanged(const double newSampleRate) override
  1344. {
  1345. CARLA_ASSERT_INT(newSampleRate > 0.0, newSampleRate);
  1346. carla_debug("VstPlugin::sampleRateChanged(%g)", newSampleRate);
  1347. if (pData->active)
  1348. deactivate();
  1349. #if ! VST_FORCE_DEPRECATED
  1350. dispatcher(effSetBlockSizeAndSampleRate, 0, static_cast<int32_t>(pData->engine->getBufferSize()), nullptr, static_cast<float>(newSampleRate));
  1351. #endif
  1352. dispatcher(effSetSampleRate, 0, 0, nullptr, static_cast<float>(newSampleRate));
  1353. if (pData->active)
  1354. activate();
  1355. }
  1356. // -------------------------------------------------------------------
  1357. // Plugin buffers
  1358. // nothing
  1359. // -------------------------------------------------------------------
  1360. // Post-poned UI Stuff
  1361. void uiParameterChange(const uint32_t index, const float value) noexcept override
  1362. {
  1363. CARLA_SAFE_ASSERT_RETURN(index < pData->param.count,);
  1364. if (fUi.type != UI::UI_OSC)
  1365. return;
  1366. if (pData->osc.data.target == nullptr)
  1367. return;
  1368. osc_send_control(pData->osc.data, pData->param.data[index].rindex, value);
  1369. }
  1370. void uiProgramChange(const uint32_t index) noexcept override
  1371. {
  1372. CARLA_SAFE_ASSERT_RETURN(index < pData->prog.count,);
  1373. if (fUi.type != UI::UI_OSC)
  1374. return;
  1375. if (pData->osc.data.target == nullptr)
  1376. return;
  1377. osc_send_program(pData->osc.data, index);
  1378. }
  1379. void uiNoteOn(const uint8_t channel, const uint8_t note, const uint8_t velo) noexcept override
  1380. {
  1381. CARLA_SAFE_ASSERT_RETURN(channel < MAX_MIDI_CHANNELS,);
  1382. CARLA_SAFE_ASSERT_RETURN(note < MAX_MIDI_NOTE,);
  1383. CARLA_SAFE_ASSERT_RETURN(velo > 0 && velo < MAX_MIDI_VALUE,);
  1384. if (fUi.type != UI::UI_OSC)
  1385. return;
  1386. if (pData->osc.data.target == nullptr)
  1387. return;
  1388. uint8_t midiData[4];
  1389. midiData[0] = 0;
  1390. midiData[1] = static_cast<uint8_t>(MIDI_STATUS_NOTE_ON + channel);
  1391. midiData[2] = note;
  1392. midiData[3] = velo;
  1393. osc_send_midi(pData->osc.data, midiData);
  1394. }
  1395. void uiNoteOff(const uint8_t channel, const uint8_t note) noexcept override
  1396. {
  1397. CARLA_SAFE_ASSERT_RETURN(channel < MAX_MIDI_CHANNELS,);
  1398. CARLA_SAFE_ASSERT_RETURN(note < MAX_MIDI_NOTE,);
  1399. if (fUi.type != UI::UI_OSC)
  1400. return;
  1401. if (pData->osc.data.target == nullptr)
  1402. return;
  1403. uint8_t midiData[4];
  1404. midiData[0] = 0;
  1405. midiData[1] = static_cast<uint8_t>(MIDI_STATUS_NOTE_OFF + channel);
  1406. midiData[2] = note;
  1407. midiData[3] = 0;
  1408. osc_send_midi(pData->osc.data, midiData);
  1409. }
  1410. // -------------------------------------------------------------------
  1411. protected:
  1412. void handlePluginUIClosed() override
  1413. {
  1414. CARLA_SAFE_ASSERT_RETURN(fUi.type == UI::UI_EMBED || fUi.type == UI::UI_EXTERNAL,);
  1415. CARLA_SAFE_ASSERT_RETURN(fUi.window != nullptr,);
  1416. carla_debug("VstPlugin::handlePluginUIClosed()");
  1417. showCustomUI(false);
  1418. pData->engine->callback(ENGINE_CALLBACK_UI_STATE_CHANGED, pData->id, 0, 0, 0.0f, nullptr);
  1419. }
  1420. intptr_t dispatcher(int32_t opcode, int32_t index, intptr_t value, void* ptr, float opt) const
  1421. {
  1422. CARLA_SAFE_ASSERT_RETURN(fEffect != nullptr, 0);
  1423. #ifdef DEBUG
  1424. if (opcode != effIdle && opcode != effEditIdle && opcode != effProcessEvents)
  1425. carla_debug("VstPlugin::dispatcher(%02i:%s, %i, " P_INTPTR ", %p, %f)", opcode, vstEffectOpcode2str(opcode), index, value, ptr, opt);
  1426. #endif
  1427. return fEffect->dispatcher(fEffect, opcode, index, value, ptr, opt);
  1428. }
  1429. intptr_t handleAudioMasterCallback(const int32_t opcode, const int32_t index, const intptr_t value, void* const ptr, const float opt)
  1430. {
  1431. #ifdef DEBUG
  1432. if (opcode != audioMasterGetTime)
  1433. carla_debug("VstPlugin::handleAudioMasterCallback(%02i:%s, %i, " P_INTPTR ", %p, %f)", opcode, vstMasterOpcode2str(opcode), index, value, ptr, opt);
  1434. #endif
  1435. intptr_t ret = 0;
  1436. switch (opcode)
  1437. {
  1438. case audioMasterAutomate: {
  1439. CARLA_SAFE_ASSERT_BREAK(pData->enabled);
  1440. // plugins should never do this:
  1441. CARLA_SAFE_ASSERT_INT(index >= 0 && index < static_cast<int32_t>(pData->param.count), index);
  1442. if (index < 0 || index >= static_cast<int32_t>(pData->param.count))
  1443. break;
  1444. const uint32_t uindex(static_cast<uint32_t>(index));
  1445. const float fixedValue(pData->param.getFixedValue(uindex, opt));
  1446. // Called from plugin process thread, nasty!
  1447. if (pthread_equal(pthread_self(), fProcThread))
  1448. {
  1449. CARLA_SAFE_ASSERT(fIsProcessing);
  1450. pData->postponeRtEvent(kPluginPostRtEventParameterChange, index, 0, fixedValue);
  1451. }
  1452. // Called from UI
  1453. else if (fUi.isVisible)
  1454. {
  1455. CarlaPlugin::setParameterValue(uindex, fixedValue, false, true, true);
  1456. }
  1457. // Unknown
  1458. // TODO - check if plugin or UI is initializing
  1459. else
  1460. {
  1461. carla_stdout("audioMasterAutomate called from unknown source");
  1462. setParameterValue(uindex, fixedValue, true, true, true);
  1463. //pData->postponeRtEvent(kPluginPostRtEventParameterChange, index, 0, fixedValue);
  1464. }
  1465. break;
  1466. }
  1467. case audioMasterCurrentId:
  1468. // TODO
  1469. // if using old sdk, return effect->uniqueID
  1470. break;
  1471. case audioMasterIdle:
  1472. //pData->engine->callback(ENGINE_CALLBACK_IDLE, 0, 0, 0, 0.0f, nullptr);
  1473. //pData->engine->idle();
  1474. break;
  1475. #if ! VST_FORCE_DEPRECATED
  1476. case audioMasterPinConnected:
  1477. // Deprecated in VST SDK 2.4
  1478. // TODO
  1479. break;
  1480. case audioMasterWantMidi:
  1481. // Deprecated in VST SDK 2.4
  1482. pData->hints |= PLUGIN_WANTS_MIDI_INPUT;
  1483. break;
  1484. #endif
  1485. case audioMasterGetTime:
  1486. ret = (intptr_t)&fTimeInfo;
  1487. break;
  1488. case audioMasterProcessEvents:
  1489. CARLA_SAFE_ASSERT_RETURN(pData->enabled, 0);
  1490. CARLA_SAFE_ASSERT_RETURN(fIsProcessing, 0);
  1491. CARLA_SAFE_ASSERT_RETURN(pData->event.portOut != nullptr, 0);
  1492. if (fMidiEventCount >= kPluginMaxMidiEvents*2)
  1493. return 0;
  1494. if (const VstEvents* const vstEvents = (const VstEvents*)ptr)
  1495. {
  1496. for (int32_t i=0; i < vstEvents->numEvents && i < kPluginMaxMidiEvents*2; ++i)
  1497. {
  1498. if (vstEvents->events[i] == nullptr)
  1499. break;
  1500. const VstMidiEvent* const vstMidiEvent((const VstMidiEvent*)vstEvents->events[i]);
  1501. if (vstMidiEvent->type != kVstMidiType)
  1502. continue;
  1503. // reverse-find first free event, and put it there
  1504. for (uint32_t j=(kPluginMaxMidiEvents*2)-1; j >= fMidiEventCount; --j)
  1505. {
  1506. if (fMidiEvents[j].type == 0)
  1507. {
  1508. std::memcpy(&fMidiEvents[j], vstMidiEvent, sizeof(VstMidiEvent));
  1509. break;
  1510. }
  1511. }
  1512. }
  1513. }
  1514. ret = 1;
  1515. break;
  1516. #if ! VST_FORCE_DEPRECATED
  1517. case audioMasterSetTime:
  1518. // Deprecated in VST SDK 2.4
  1519. break;
  1520. case audioMasterTempoAt:
  1521. // Deprecated in VST SDK 2.4
  1522. ret = static_cast<intptr_t>(fTimeInfo.tempo * 10000);
  1523. break;
  1524. case audioMasterGetNumAutomatableParameters:
  1525. // Deprecated in VST SDK 2.4
  1526. ret = carla_fixValue<intptr_t>(0, static_cast<intptr_t>(pData->engine->getOptions().maxParameters), fEffect->numParams);
  1527. break;
  1528. case audioMasterGetParameterQuantization:
  1529. // Deprecated in VST SDK 2.4
  1530. ret = 1; // full single float precision
  1531. break;
  1532. #endif
  1533. #if 0
  1534. case audioMasterIOChanged:
  1535. CARLA_ASSERT(pData->enabled);
  1536. // TESTING
  1537. if (! pData->enabled)
  1538. {
  1539. ret = 1;
  1540. break;
  1541. }
  1542. if (x_engine->getOptions().processMode == PROCESS_MODE_CONTINUOUS_RACK)
  1543. {
  1544. carla_stderr2("VstPlugin::handleAudioMasterIOChanged() - plugin asked IO change, but it's not supported in rack mode");
  1545. return 0;
  1546. }
  1547. engineProcessLock();
  1548. m_enabled = false;
  1549. engineProcessUnlock();
  1550. if (m_active)
  1551. {
  1552. effect->dispatcher(effect, effStopProcess, 0, 0, nullptr, 0.0f);
  1553. effect->dispatcher(effect, effMainsChanged, 0, 0, nullptr, 0.0f);
  1554. }
  1555. reload();
  1556. if (m_active)
  1557. {
  1558. effect->dispatcher(effect, effMainsChanged, 0, 1, nullptr, 0.0f);
  1559. effect->dispatcher(effect, effStartProcess, 0, 0, nullptr, 0.0f);
  1560. }
  1561. x_engine->callback(CALLBACK_RELOAD_ALL, m_id, 0, 0, 0.0, nullptr);
  1562. ret = 1;
  1563. break;
  1564. #endif
  1565. #if ! VST_FORCE_DEPRECATED
  1566. case audioMasterNeedIdle:
  1567. // Deprecated in VST SDK 2.4
  1568. fNeedIdle = true;
  1569. ret = 1;
  1570. break;
  1571. #endif
  1572. case audioMasterSizeWindow:
  1573. CARLA_SAFE_ASSERT_BREAK(fUi.window != nullptr);
  1574. CARLA_SAFE_ASSERT_BREAK(index > 0);
  1575. CARLA_SAFE_ASSERT_BREAK(value > 0);
  1576. fUi.window->setSize(static_cast<uint>(index), static_cast<uint>(value), true);
  1577. ret = 1;
  1578. break;
  1579. case audioMasterGetSampleRate:
  1580. ret = static_cast<intptr_t>(pData->engine->getSampleRate());
  1581. break;
  1582. case audioMasterGetBlockSize:
  1583. ret = static_cast<intptr_t>(pData->engine->getBufferSize());
  1584. break;
  1585. case audioMasterGetInputLatency:
  1586. ret = 0;
  1587. break;
  1588. case audioMasterGetOutputLatency:
  1589. ret = 0;
  1590. break;
  1591. #if ! VST_FORCE_DEPRECATED
  1592. case audioMasterGetPreviousPlug:
  1593. // Deprecated in VST SDK 2.4
  1594. // TODO
  1595. break;
  1596. case audioMasterGetNextPlug:
  1597. // Deprecated in VST SDK 2.4
  1598. // TODO
  1599. break;
  1600. case audioMasterWillReplaceOrAccumulate:
  1601. // Deprecated in VST SDK 2.4
  1602. ret = 1; // replace
  1603. break;
  1604. #endif
  1605. case audioMasterGetCurrentProcessLevel:
  1606. if (pthread_equal(pthread_self(), fProcThread))
  1607. {
  1608. CARLA_SAFE_ASSERT(fIsProcessing);
  1609. if (pData->engine->isOffline())
  1610. ret = kVstProcessLevelOffline;
  1611. else
  1612. ret = kVstProcessLevelRealtime;
  1613. }
  1614. else
  1615. ret = kVstProcessLevelUser;
  1616. break;
  1617. case audioMasterGetAutomationState:
  1618. ret = pData->active ? kVstAutomationReadWrite : kVstAutomationOff;
  1619. break;
  1620. case audioMasterOfflineStart:
  1621. case audioMasterOfflineRead:
  1622. case audioMasterOfflineWrite:
  1623. case audioMasterOfflineGetCurrentPass:
  1624. case audioMasterOfflineGetCurrentMetaPass:
  1625. // TODO
  1626. break;
  1627. #if ! VST_FORCE_DEPRECATED
  1628. case audioMasterSetOutputSampleRate:
  1629. // Deprecated in VST SDK 2.4
  1630. break;
  1631. case audioMasterGetOutputSpeakerArrangement:
  1632. // Deprecated in VST SDK 2.4
  1633. // TODO
  1634. break;
  1635. #endif
  1636. case audioMasterVendorSpecific:
  1637. if (index == 0xedcd && value == 0 && ptr != nullptr && std::strcmp((const char*)ptr, "EditorClosed") == 0)
  1638. {
  1639. CARLA_SAFE_ASSERT_BREAK(fUi.type == UI::UI_EXTERNAL);
  1640. handlePluginUIClosed();
  1641. break;
  1642. }
  1643. // TODO - cockos extensions
  1644. break;
  1645. #if ! VST_FORCE_DEPRECATED
  1646. case audioMasterSetIcon:
  1647. // Deprecated in VST SDK 2.4
  1648. break;
  1649. #endif
  1650. #if ! VST_FORCE_DEPRECATED
  1651. case audioMasterOpenWindow:
  1652. case audioMasterCloseWindow:
  1653. // Deprecated in VST SDK 2.4
  1654. // TODO
  1655. break;
  1656. #endif
  1657. case audioMasterGetDirectory:
  1658. // TODO
  1659. break;
  1660. case audioMasterUpdateDisplay:
  1661. // Idle UI if visible
  1662. if (fUi.isVisible)
  1663. dispatcher(effEditIdle, 0, 0, nullptr, 0.0f);
  1664. // Update current program
  1665. if (pData->prog.count > 0)
  1666. {
  1667. const int32_t current = static_cast<int32_t>(dispatcher(effGetProgram, 0, 0, nullptr, 0.0f));
  1668. if (current >= 0 && current < static_cast<int32_t>(pData->prog.count))
  1669. {
  1670. char strBuf[STR_MAX+1] = { '\0' };
  1671. dispatcher(effGetProgramName, 0, 0, strBuf, 0.0f);
  1672. if (pData->prog.names[current] != nullptr)
  1673. delete[] pData->prog.names[current];
  1674. pData->prog.names[current] = carla_strdup(strBuf);
  1675. if (pData->prog.current != current)
  1676. {
  1677. pData->prog.current = current;
  1678. pData->engine->callback(ENGINE_CALLBACK_PROGRAM_CHANGED, pData->id, current, 0, 0.0f, nullptr);
  1679. }
  1680. }
  1681. }
  1682. pData->engine->callback(ENGINE_CALLBACK_UPDATE, pData->id, 0, 0, 0.0f, nullptr);
  1683. ret = 1;
  1684. break;
  1685. case audioMasterBeginEdit:
  1686. case audioMasterEndEdit:
  1687. // TODO
  1688. break;
  1689. case audioMasterOpenFileSelector:
  1690. case audioMasterCloseFileSelector:
  1691. // TODO
  1692. break;
  1693. #if ! VST_FORCE_DEPRECATED
  1694. case audioMasterEditFile:
  1695. // Deprecated in VST SDK 2.4
  1696. // TODO
  1697. break;
  1698. case audioMasterGetChunkFile:
  1699. // Deprecated in VST SDK 2.4
  1700. // TODO
  1701. break;
  1702. case audioMasterGetInputSpeakerArrangement:
  1703. // Deprecated in VST SDK 2.4
  1704. // TODO
  1705. break;
  1706. #endif
  1707. default:
  1708. carla_debug("VstPlugin::handleAudioMasterCallback(%02i:%s, %i, " P_INTPTR ", %p, %f) UNDEF", opcode, vstMasterOpcode2str(opcode), index, value, ptr, opt);
  1709. break;
  1710. }
  1711. return ret;
  1712. // unused
  1713. (void)opt;
  1714. }
  1715. bool canDo(const char* const feature) const noexcept
  1716. {
  1717. try {
  1718. return (fEffect->dispatcher(fEffect, effCanDo, 0, 0, const_cast<char*>(feature), 0.0f) == 1);
  1719. } CARLA_SAFE_EXCEPTION_RETURN("vstPluginCanDo", false);
  1720. }
  1721. bool hasMidiInput() const noexcept
  1722. {
  1723. return (canDo("receiveVstEvents") || canDo("receiveVstMidiEvent") || (fEffect->flags & effFlagsIsSynth) > 0 || (pData->hints & PLUGIN_WANTS_MIDI_INPUT));
  1724. }
  1725. bool hasMidiOutput() const noexcept
  1726. {
  1727. return (canDo("sendVstEvents") || canDo("sendVstMidiEvent"));
  1728. }
  1729. // -------------------------------------------------------------------
  1730. const void* getNativeDescriptor() const noexcept override
  1731. {
  1732. return fEffect;
  1733. }
  1734. // -------------------------------------------------------------------
  1735. public:
  1736. bool init(const char* const filename, const char* const name, const int64_t uniqueId)
  1737. {
  1738. CARLA_SAFE_ASSERT_RETURN(pData->engine != nullptr, false);
  1739. // ---------------------------------------------------------------
  1740. // first checks
  1741. if (pData->client != nullptr)
  1742. {
  1743. pData->engine->setLastError("Plugin client is already registered");
  1744. return false;
  1745. }
  1746. if (filename == nullptr || filename[0] == '\0')
  1747. {
  1748. pData->engine->setLastError("null filename");
  1749. return false;
  1750. }
  1751. // ---------------------------------------------------------------
  1752. // open DLL
  1753. if (! pData->libOpen(filename))
  1754. {
  1755. pData->engine->setLastError(pData->libError(filename));
  1756. return false;
  1757. }
  1758. // ---------------------------------------------------------------
  1759. // get DLL main entry
  1760. VST_Function vstFn = (VST_Function)pData->libSymbol("VSTPluginMain");
  1761. if (vstFn == nullptr)
  1762. {
  1763. vstFn = (VST_Function)pData->libSymbol("main");
  1764. if (vstFn == nullptr)
  1765. {
  1766. pData->engine->setLastError("Could not find the VST main entry in the plugin library");
  1767. return false;
  1768. }
  1769. }
  1770. // ---------------------------------------------------------------
  1771. // initialize plugin (part 1)
  1772. sLastVstPlugin = this;
  1773. fEffect = vstFn(carla_vst_audioMasterCallback);
  1774. sLastVstPlugin = nullptr;
  1775. if (fEffect == nullptr)
  1776. {
  1777. pData->engine->setLastError("Plugin failed to initialize");
  1778. return false;
  1779. }
  1780. if (fEffect->magic != kEffectMagic)
  1781. {
  1782. pData->engine->setLastError("Plugin is not valid (wrong vst effect magic code)");
  1783. return false;
  1784. }
  1785. #ifdef VESTIGE_HEADER
  1786. fEffect->ptr1 = this;
  1787. #else
  1788. fEffect->resvd1 = (intptr_t)this;
  1789. #endif
  1790. dispatcher(effOpen, 0, 0, nullptr, 0.0f);
  1791. // ---------------------------------------------------------------
  1792. // get info
  1793. if (name != nullptr && name[0] != '\0')
  1794. {
  1795. pData->name = pData->engine->getUniquePluginName(name);
  1796. }
  1797. else
  1798. {
  1799. char strBuf[STR_MAX+1];
  1800. carla_zeroChar(strBuf, STR_MAX+1);
  1801. dispatcher(effGetEffectName, 0, 0, strBuf, 0.0f);
  1802. if (strBuf[0] != '\0')
  1803. pData->name = pData->engine->getUniquePluginName(strBuf);
  1804. else if (const char* const shortname = std::strrchr(filename, OS_SEP))
  1805. pData->name = pData->engine->getUniquePluginName(shortname+1);
  1806. else
  1807. pData->name = pData->engine->getUniquePluginName("unknown");
  1808. }
  1809. pData->filename = carla_strdup(filename);
  1810. // ---------------------------------------------------------------
  1811. // register client
  1812. pData->client = pData->engine->addClient(this);
  1813. if (pData->client == nullptr || ! pData->client->isOk())
  1814. {
  1815. pData->engine->setLastError("Failed to register plugin client");
  1816. return false;
  1817. }
  1818. // ---------------------------------------------------------------
  1819. // initialize plugin (part 2)
  1820. #if ! VST_FORCE_DEPRECATED
  1821. dispatcher(effSetBlockSizeAndSampleRate, 0, static_cast<int32_t>(pData->engine->getBufferSize()), nullptr, static_cast<float>(pData->engine->getSampleRate()));
  1822. #endif
  1823. dispatcher(effSetSampleRate, 0, 0, nullptr, static_cast<float>(pData->engine->getSampleRate()));
  1824. dispatcher(effSetBlockSize, 0, static_cast<int32_t>(pData->engine->getBufferSize()), nullptr, 0.0f);
  1825. dispatcher(effSetProcessPrecision, 0, kVstProcessPrecision32, nullptr, 0.0f);
  1826. if (dispatcher(effGetVstVersion, 0, 0, nullptr, 0.0f) < kVstVersion)
  1827. pData->hints |= PLUGIN_USES_OLD_VSTSDK;
  1828. if (static_cast<uintptr_t>(dispatcher(effCanDo, 0, 0, const_cast<char*>("hasCockosExtensions"), 0.0f)) == 0xbeef0000)
  1829. pData->hints |= PLUGIN_HAS_COCKOS_EXTENSIONS;
  1830. // ---------------------------------------------------------------
  1831. // gui stuff
  1832. if (fEffect->flags & effFlagsHasEditor)
  1833. {
  1834. fUi.type = UI::UI_EMBED;
  1835. if ((fEffect->flags & effFlagsProgramChunks) == 0 && pData->engine->getOptions().preferUiBridges)
  1836. {
  1837. CarlaString bridgeBinary(pData->engine->getOptions().binaryDir);
  1838. #if defined(CARLA_OS_LINUX)
  1839. bridgeBinary += OS_SEP_STR "carla-bridge-vst-x11";
  1840. #endif
  1841. if (bridgeBinary.isNotEmpty() && File(bridgeBinary.buffer()).existsAsFile())
  1842. {
  1843. pData->osc.thread.setOscData(bridgeBinary, nullptr);
  1844. fUi.type = UI::UI_OSC;
  1845. }
  1846. }
  1847. }
  1848. else if (vstPluginCanDo(fEffect, "ExternalUI"))
  1849. {
  1850. fUi.type = UI::UI_EXTERNAL;
  1851. }
  1852. // ---------------------------------------------------------------
  1853. // set default options
  1854. pData->options = 0x0;
  1855. pData->options |= PLUGIN_OPTION_MAP_PROGRAM_CHANGES;
  1856. if (fEffect->flags & effFlagsProgramChunks)
  1857. pData->options |= PLUGIN_OPTION_USE_CHUNKS;
  1858. if (hasMidiInput())
  1859. {
  1860. pData->options |= PLUGIN_OPTION_FIXED_BUFFERS;
  1861. pData->options |= PLUGIN_OPTION_SEND_CHANNEL_PRESSURE;
  1862. pData->options |= PLUGIN_OPTION_SEND_NOTE_AFTERTOUCH;
  1863. pData->options |= PLUGIN_OPTION_SEND_PITCHBEND;
  1864. pData->options |= PLUGIN_OPTION_SEND_ALL_SOUND_OFF;
  1865. }
  1866. return true;
  1867. // unused
  1868. (void)uniqueId;
  1869. }
  1870. private:
  1871. int fUnique1;
  1872. AEffect* fEffect;
  1873. uint32_t fMidiEventCount;
  1874. VstMidiEvent fMidiEvents[kPluginMaxMidiEvents*2];
  1875. VstTimeInfo fTimeInfo;
  1876. bool fNeedIdle;
  1877. void* fLastChunk;
  1878. bool fIsProcessing;
  1879. pthread_t fProcThread;
  1880. struct FixedVstEvents {
  1881. int32_t numEvents;
  1882. intptr_t reserved;
  1883. VstEvent* data[kPluginMaxMidiEvents*2];
  1884. FixedVstEvents()
  1885. : numEvents(0),
  1886. reserved(0)
  1887. {
  1888. carla_fill<VstEvent*>(data, nullptr, kPluginMaxMidiEvents*2);
  1889. }
  1890. } fEvents;
  1891. struct UI {
  1892. enum Type {
  1893. UI_NULL = 0,
  1894. UI_EMBED = 1,
  1895. UI_EXTERNAL = 2,
  1896. UI_OSC = 3
  1897. } type;
  1898. bool isVisible; // not used in OSC mode
  1899. CarlaPluginUI* window;
  1900. UI()
  1901. : type(UI_NULL),
  1902. isVisible(false),
  1903. window(nullptr) {}
  1904. ~UI()
  1905. {
  1906. CARLA_ASSERT(! isVisible);
  1907. if (window != nullptr)
  1908. {
  1909. delete window;
  1910. window = nullptr;
  1911. }
  1912. }
  1913. } fUi;
  1914. int fUnique2;
  1915. static VstPlugin* sLastVstPlugin;
  1916. // -------------------------------------------------------------------
  1917. static intptr_t carla_vst_hostCanDo(const char* const feature)
  1918. {
  1919. carla_debug("carla_vst_hostCanDo(\"%s\")", feature);
  1920. if (std::strcmp(feature, "supplyIdle") == 0)
  1921. return 1;
  1922. if (std::strcmp(feature, "sendVstEvents") == 0)
  1923. return 1;
  1924. if (std::strcmp(feature, "sendVstMidiEvent") == 0)
  1925. return 1;
  1926. if (std::strcmp(feature, "sendVstMidiEventFlagIsRealtime") == 0)
  1927. return 1;
  1928. if (std::strcmp(feature, "sendVstTimeInfo") == 0)
  1929. return 1;
  1930. if (std::strcmp(feature, "receiveVstEvents") == 0)
  1931. return 1;
  1932. if (std::strcmp(feature, "receiveVstMidiEvent") == 0)
  1933. return 1;
  1934. if (std::strcmp(feature, "receiveVstTimeInfo") == 0)
  1935. return -1;
  1936. if (std::strcmp(feature, "reportConnectionChanges") == 0)
  1937. return -1;
  1938. if (std::strcmp(feature, "acceptIOChanges") == 0)
  1939. return 1;
  1940. if (std::strcmp(feature, "sizeWindow") == 0)
  1941. return 1;
  1942. if (std::strcmp(feature, "offline") == 0)
  1943. return -1;
  1944. if (std::strcmp(feature, "openFileSelector") == 0)
  1945. return -1;
  1946. if (std::strcmp(feature, "closeFileSelector") == 0)
  1947. return -1;
  1948. if (std::strcmp(feature, "startStopProcess") == 0)
  1949. return 1;
  1950. if (std::strcmp(feature, "supportShell") == 0)
  1951. return -1;
  1952. if (std::strcmp(feature, "shellCategory") == 0)
  1953. return -1;
  1954. // unimplemented
  1955. carla_stderr("carla_vst_hostCanDo(\"%s\") - unknown feature", feature);
  1956. return 0;
  1957. }
  1958. static intptr_t VSTCALLBACK carla_vst_audioMasterCallback(AEffect* effect, int32_t opcode, int32_t index, intptr_t value, void* ptr, float opt)
  1959. {
  1960. #if defined(DEBUG) && ! defined(CARLA_OS_WIN)
  1961. if (opcode != audioMasterGetTime && opcode != audioMasterProcessEvents && opcode != audioMasterGetCurrentProcessLevel && opcode != audioMasterGetOutputLatency)
  1962. carla_debug("carla_vst_audioMasterCallback(%p, %02i:%s, %i, " P_INTPTR ", %p, %f)", effect, opcode, vstMasterOpcode2str(opcode), index, value, ptr, opt);
  1963. #endif
  1964. switch (opcode)
  1965. {
  1966. case audioMasterVersion:
  1967. return kVstVersion;
  1968. case audioMasterGetVendorString:
  1969. CARLA_SAFE_ASSERT_RETURN(ptr != nullptr, 0);
  1970. std::strcpy((char*)ptr, "falkTX");
  1971. return 1;
  1972. case audioMasterGetProductString:
  1973. CARLA_SAFE_ASSERT_RETURN(ptr != nullptr, 0);
  1974. std::strcpy((char*)ptr, "Carla");
  1975. return 1;
  1976. case audioMasterGetVendorVersion:
  1977. return 0x110; // 1.1.0
  1978. case audioMasterCanDo:
  1979. CARLA_SAFE_ASSERT_RETURN(ptr != nullptr, 0);
  1980. return carla_vst_hostCanDo((const char*)ptr);
  1981. case audioMasterGetLanguage:
  1982. return kVstLangEnglish;
  1983. }
  1984. // Check if 'resvd1' points to us, otherwise register ourselfs if possible
  1985. VstPlugin* self = nullptr;
  1986. if (effect != nullptr)
  1987. {
  1988. #ifdef VESTIGE_HEADER
  1989. if (effect->ptr1 != nullptr)
  1990. {
  1991. self = (VstPlugin*)effect->ptr1;
  1992. if (self->fUnique1 != self->fUnique2)
  1993. self = nullptr;
  1994. }
  1995. #else
  1996. if (effect->resvd1 != 0)
  1997. {
  1998. self = (VstPlugin*)effect->resvd1;
  1999. if (self->fUnique1 != self->fUnique2)
  2000. self = nullptr;
  2001. }
  2002. #endif
  2003. if (self != nullptr)
  2004. {
  2005. if (self->fEffect == nullptr)
  2006. self->fEffect = effect;
  2007. if (self->fEffect != effect)
  2008. {
  2009. carla_stderr2("carla_vst_audioMasterCallback() - host pointer mismatch: %p != %p", self->fEffect, effect);
  2010. self = nullptr;
  2011. }
  2012. }
  2013. else if (sLastVstPlugin != nullptr)
  2014. {
  2015. #ifdef VESTIGE_HEADER
  2016. effect->ptr1 = sLastVstPlugin;
  2017. #else
  2018. effect->resvd1 = (intptr_t)sLastVstPlugin;
  2019. #endif
  2020. self = sLastVstPlugin;
  2021. }
  2022. }
  2023. return (self != nullptr) ? self->handleAudioMasterCallback(opcode, index, value, ptr, opt) : 0;
  2024. }
  2025. CARLA_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(VstPlugin)
  2026. };
  2027. VstPlugin* VstPlugin::sLastVstPlugin = nullptr;
  2028. CARLA_BACKEND_END_NAMESPACE
  2029. #endif // ! USE_JUCE_FOR_VST
  2030. // -------------------------------------------------------------------------------------------------------------------
  2031. CARLA_BACKEND_START_NAMESPACE
  2032. CarlaPlugin* CarlaPlugin::newVST(const Initializer& init)
  2033. {
  2034. carla_debug("CarlaPlugin::newVST({%p, \"%s\", \"%s\", " P_INT64 "})", init.engine, init.filename, init.name, init.uniqueId);
  2035. #ifdef USE_JUCE_FOR_VST
  2036. return newJuce(init, "VST");
  2037. #else
  2038. VstPlugin* const plugin(new VstPlugin(init.engine, init.id));
  2039. if (! plugin->init(init.filename, init.name, init.uniqueId))
  2040. {
  2041. delete plugin;
  2042. return nullptr;
  2043. }
  2044. plugin->reload();
  2045. if (init.engine->getProccessMode() == ENGINE_PROCESS_MODE_CONTINUOUS_RACK && ! plugin->canRunInRack())
  2046. {
  2047. init.engine->setLastError("Carla's rack mode can only work with Stereo VST plugins, sorry!");
  2048. delete plugin;
  2049. return nullptr;
  2050. }
  2051. return plugin;
  2052. #endif
  2053. }
  2054. // -------------------------------------------------------------------------------------------------------------------
  2055. CARLA_BACKEND_END_NAMESPACE