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.

2993 lines
103KB

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