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.

2657 lines
90KB

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