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.

2648 lines
90KB

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