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.

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