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.

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