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.

2707 lines
92KB

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