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.

2682 lines
91KB

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