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.

2629 lines
89KB

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