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.

2658 lines
90KB

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