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.

2432 lines
82KB

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