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.

2982 lines
103KB

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