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.

2985 lines
103KB

  1. /*
  2. * Carla VST2 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[64]; // 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;
  1450. float* const oldBufLeft = pData->postProc.extraBuffer;
  1451. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  1452. {
  1453. // Dry/Wet
  1454. if (doDryWet)
  1455. {
  1456. const uint32_t c = isMono ? 0 : i;
  1457. for (uint32_t k=0; k < frames; ++k)
  1458. {
  1459. bufValue = inBuffer[c][k+timeOffset];
  1460. fAudioOutBuffers[i][k] = (fAudioOutBuffers[i][k] * pData->postProc.dryWet) + (bufValue * (1.0f - pData->postProc.dryWet));
  1461. }
  1462. }
  1463. // Balance
  1464. if (doBalance)
  1465. {
  1466. isPair = (i % 2 == 0);
  1467. if (isPair)
  1468. {
  1469. CARLA_ASSERT(i+1 < pData->audioOut.count);
  1470. carla_copyFloats(oldBufLeft, fAudioOutBuffers[i], frames);
  1471. }
  1472. float balRangeL = (pData->postProc.balanceLeft + 1.0f)/2.0f;
  1473. float balRangeR = (pData->postProc.balanceRight + 1.0f)/2.0f;
  1474. for (uint32_t k=0; k < frames; ++k)
  1475. {
  1476. if (isPair)
  1477. {
  1478. // left
  1479. fAudioOutBuffers[i][k] = oldBufLeft[k] * (1.0f - balRangeL);
  1480. fAudioOutBuffers[i][k] += fAudioOutBuffers[i+1][k] * (1.0f - balRangeR);
  1481. }
  1482. else
  1483. {
  1484. // right
  1485. fAudioOutBuffers[i][k] = fAudioOutBuffers[i][k] * balRangeR;
  1486. fAudioOutBuffers[i][k] += oldBufLeft[k] * balRangeL;
  1487. }
  1488. }
  1489. }
  1490. // Volume (and buffer copy)
  1491. {
  1492. for (uint32_t k=0; k < frames; ++k)
  1493. outBuffer[i][k+timeOffset] = fAudioOutBuffers[i][k] * pData->postProc.volume;
  1494. }
  1495. }
  1496. } // End of Post-processing
  1497. #else // BUILD_BRIDGE_ALTERNATIVE_ARCH
  1498. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  1499. {
  1500. for (uint32_t k=0; k < frames; ++k)
  1501. outBuffer[i][k+timeOffset] = fAudioOutBuffers[i][k];
  1502. }
  1503. #endif
  1504. // --------------------------------------------------------------------------------------------------------
  1505. pData->singleMutex.unlock();
  1506. return true;
  1507. }
  1508. void bufferSizeChanged(const uint32_t newBufferSize) override
  1509. {
  1510. CARLA_ASSERT_INT(newBufferSize > 0, newBufferSize);
  1511. carla_debug("CarlaPluginVST2::bufferSizeChanged(%i)", newBufferSize);
  1512. fBufferSize = pData->engine->getBufferSize();
  1513. if (pData->active)
  1514. deactivate();
  1515. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  1516. {
  1517. if (fAudioOutBuffers[i] != nullptr)
  1518. delete[] fAudioOutBuffers[i];
  1519. fAudioOutBuffers[i] = new float[newBufferSize];
  1520. }
  1521. #if ! VST_FORCE_DEPRECATED
  1522. dispatcher(effSetBlockSizeAndSampleRate, 0, static_cast<int32_t>(newBufferSize), nullptr, static_cast<float>(pData->engine->getSampleRate()));
  1523. #endif
  1524. dispatcher(effSetBlockSize, 0, static_cast<int32_t>(newBufferSize), nullptr, 0.0f);
  1525. if (pData->active)
  1526. activate();
  1527. CarlaPlugin::bufferSizeChanged(newBufferSize);
  1528. }
  1529. void sampleRateChanged(const double newSampleRate) override
  1530. {
  1531. CARLA_ASSERT_INT(newSampleRate > 0.0, newSampleRate);
  1532. carla_debug("CarlaPluginVST2::sampleRateChanged(%g)", newSampleRate);
  1533. if (pData->active)
  1534. deactivate();
  1535. #if ! VST_FORCE_DEPRECATED
  1536. dispatcher(effSetBlockSizeAndSampleRate, 0, static_cast<int32_t>(pData->engine->getBufferSize()), nullptr, static_cast<float>(newSampleRate));
  1537. #endif
  1538. dispatcher(effSetSampleRate, 0, 0, nullptr, static_cast<float>(newSampleRate));
  1539. if (pData->active)
  1540. activate();
  1541. }
  1542. // -------------------------------------------------------------------
  1543. // Plugin buffers
  1544. void clearBuffers() noexcept override
  1545. {
  1546. carla_debug("CarlaPluginVST2::clearBuffers() - start");
  1547. if (fAudioOutBuffers != nullptr)
  1548. {
  1549. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  1550. {
  1551. if (fAudioOutBuffers[i] != nullptr)
  1552. {
  1553. delete[] fAudioOutBuffers[i];
  1554. fAudioOutBuffers[i] = nullptr;
  1555. }
  1556. }
  1557. delete[] fAudioOutBuffers;
  1558. fAudioOutBuffers = nullptr;
  1559. }
  1560. CarlaPlugin::clearBuffers();
  1561. carla_debug("CarlaPluginVST2::clearBuffers() - end");
  1562. }
  1563. // -------------------------------------------------------------------
  1564. // Post-poned UI Stuff
  1565. // nothing
  1566. // -------------------------------------------------------------------
  1567. protected:
  1568. void handlePluginUIClosed() override
  1569. {
  1570. CARLA_SAFE_ASSERT_RETURN(fUI.window != nullptr,);
  1571. carla_debug("CarlaPluginVST2::handlePluginUIClosed()");
  1572. showCustomUI(false);
  1573. pData->engine->callback(true, true,
  1574. ENGINE_CALLBACK_UI_STATE_CHANGED,
  1575. pData->id,
  1576. 0,
  1577. 0, 0, 0.0f, nullptr);
  1578. }
  1579. void handlePluginUIResized(const uint width, const uint height) override
  1580. {
  1581. CARLA_SAFE_ASSERT_RETURN(fUI.window != nullptr,);
  1582. carla_debug("CarlaPluginVST2::handlePluginUIResized(%u, %u)", width, height);
  1583. return; // unused
  1584. (void)width; (void)height;
  1585. }
  1586. // -------------------------------------------------------------------
  1587. intptr_t dispatcher(int32_t opcode, int32_t index = 0, intptr_t value = 0, void* ptr = nullptr, float opt = 0.0f) const noexcept
  1588. {
  1589. CARLA_SAFE_ASSERT_RETURN(fEffect != nullptr, 0);
  1590. #ifdef DEBUG
  1591. if (opcode != effIdle && opcode != effEditIdle && opcode != effProcessEvents)
  1592. carla_debug("CarlaPluginVST2::dispatcher(%02i:%s, %i, " P_INTPTR ", %p, %f)",
  1593. opcode, vstEffectOpcode2str(opcode), index, value, ptr, static_cast<double>(opt));
  1594. #endif
  1595. try {
  1596. return fEffect->dispatcher(fEffect, opcode, index, value, ptr, opt);
  1597. } CARLA_SAFE_EXCEPTION_RETURN("Vst dispatcher", 0);
  1598. }
  1599. intptr_t handleAudioMasterCallback(const int32_t opcode, const int32_t index, const intptr_t value, void* const ptr, const float opt)
  1600. {
  1601. #ifdef DEBUG
  1602. if (opcode != audioMasterGetTime)
  1603. carla_debug("CarlaPluginVST2::handleAudioMasterCallback(%02i:%s, %i, " P_INTPTR ", %p, %f)",
  1604. opcode, vstMasterOpcode2str(opcode), index, value, ptr, static_cast<double>(opt));
  1605. #endif
  1606. intptr_t ret = 0;
  1607. switch (opcode)
  1608. {
  1609. case audioMasterAutomate: {
  1610. if (fIsInitializing) {
  1611. // some plugins can be stupid...
  1612. if (pData->param.count == 0)
  1613. break;
  1614. } else {
  1615. CARLA_CUSTOM_SAFE_ASSERT_BREAK("audioMasterAutomate while disabled", pData->enabled);
  1616. }
  1617. // plugins should never do this:
  1618. CARLA_SAFE_ASSERT_INT2_BREAK(index >= 0 && index < static_cast<int32_t>(pData->param.count),
  1619. index,
  1620. static_cast<int32_t>(pData->param.count));
  1621. const uint32_t uindex(static_cast<uint32_t>(index));
  1622. const float fixedValue(pData->param.getFixedValue(uindex, opt));
  1623. const pthread_t thisThread = pthread_self();
  1624. if (pthread_equal(thisThread, kNullThread))
  1625. {
  1626. carla_stderr("audioMasterAutomate called with null thread!?");
  1627. setParameterValue(uindex, fixedValue, false, true, true);
  1628. }
  1629. // Called from plugin process thread, nasty! (likely MIDI learn)
  1630. else if (pthread_equal(thisThread, fProcThread))
  1631. {
  1632. CARLA_SAFE_ASSERT(fIsProcessing);
  1633. pData->postponeParameterChangeRtEvent(true, index, fixedValue);
  1634. }
  1635. // Called from effSetChunk or effSetProgram
  1636. else if (pthread_equal(thisThread, fChangingValuesThread))
  1637. {
  1638. carla_debug("audioMasterAutomate called while setting state");
  1639. pData->postponeParameterChangeRtEvent(true, index, fixedValue);
  1640. }
  1641. // Called from effIdle
  1642. else if (pthread_equal(thisThread, fIdleThread))
  1643. {
  1644. carla_debug("audioMasterAutomate called from idle thread");
  1645. pData->postponeParameterChangeRtEvent(true, index, fixedValue);
  1646. }
  1647. // Called from main thread, why?
  1648. else if (pthread_equal(thisThread, fMainThread))
  1649. {
  1650. if (fFirstActive) {
  1651. carla_stdout("audioMasterAutomate called while loading, nasty!");
  1652. } else {
  1653. carla_debug("audioMasterAutomate called from main thread");
  1654. }
  1655. CarlaPlugin::setParameterValue(uindex, fixedValue, false, true, true);
  1656. }
  1657. // Called from UI?
  1658. else if (fUI.isVisible)
  1659. {
  1660. carla_debug("audioMasterAutomate called while UI visible");
  1661. CarlaPlugin::setParameterValue(uindex, fixedValue, false, true, true);
  1662. }
  1663. // Unknown
  1664. else
  1665. {
  1666. carla_stdout("audioMasterAutomate called from unknown source");
  1667. CarlaPlugin::setParameterValue(uindex, fixedValue, false, true, true);
  1668. }
  1669. break;
  1670. }
  1671. case audioMasterCurrentId:
  1672. if (fEffect != nullptr)
  1673. ret = fEffect->uniqueID;
  1674. break;
  1675. case audioMasterIdle:
  1676. CARLA_SAFE_ASSERT_BREAK(pthread_equal(pthread_self(), fMainThread));
  1677. pData->engine->callback(true, false, ENGINE_CALLBACK_IDLE, 0, 0, 0, 0, 0.0f, nullptr);
  1678. if (pData->engine->getType() != kEngineTypePlugin)
  1679. pData->engine->idle();
  1680. break;
  1681. #if ! VST_FORCE_DEPRECATED
  1682. case audioMasterPinConnected:
  1683. // Deprecated in VST SDK 2.4
  1684. // TODO
  1685. break;
  1686. case audioMasterWantMidi:
  1687. // Deprecated in VST SDK 2.4
  1688. pData->hints |= PLUGIN_WANTS_MIDI_INPUT;
  1689. break;
  1690. #endif
  1691. case audioMasterGetTime:
  1692. ret = (intptr_t)&fTimeInfo;
  1693. break;
  1694. case audioMasterProcessEvents:
  1695. CARLA_SAFE_ASSERT_RETURN(pData->enabled, 0);
  1696. CARLA_SAFE_ASSERT_RETURN(fIsProcessing, 0);
  1697. CARLA_SAFE_ASSERT_RETURN(pData->event.portOut != nullptr, 0);
  1698. if (fMidiEventCount >= kPluginMaxMidiEvents*2-1)
  1699. return 0;
  1700. if (const VstEvents* const vstEvents = (const VstEvents*)ptr)
  1701. {
  1702. for (int32_t i=0; i < vstEvents->numEvents && i < kPluginMaxMidiEvents*2; ++i)
  1703. {
  1704. if (vstEvents->events[i] == nullptr)
  1705. break;
  1706. const VstMidiEvent* const vstMidiEvent((const VstMidiEvent*)vstEvents->events[i]);
  1707. if (vstMidiEvent->type != kVstMidiType)
  1708. continue;
  1709. // reverse-find first free event, and put it there
  1710. for (uint32_t j=(kPluginMaxMidiEvents*2)-1; j >= fMidiEventCount; --j)
  1711. {
  1712. if (fMidiEvents[j].type == 0)
  1713. {
  1714. std::memcpy(&fMidiEvents[j], vstMidiEvent, sizeof(VstMidiEvent));
  1715. break;
  1716. }
  1717. }
  1718. }
  1719. }
  1720. ret = 1;
  1721. break;
  1722. #if ! VST_FORCE_DEPRECATED
  1723. case audioMasterSetTime:
  1724. // Deprecated in VST SDK 2.4
  1725. break;
  1726. case audioMasterTempoAt:
  1727. // Deprecated in VST SDK 2.4
  1728. ret = static_cast<intptr_t>(fTimeInfo.tempo * 10000);
  1729. break;
  1730. case audioMasterGetNumAutomatableParameters:
  1731. // Deprecated in VST SDK 2.4
  1732. ret = static_cast<intptr_t>(pData->engine->getOptions().maxParameters);
  1733. ret = carla_minPositive<intptr_t>(ret, fEffect->numParams);
  1734. break;
  1735. case audioMasterGetParameterQuantization:
  1736. // Deprecated in VST SDK 2.4
  1737. ret = 1; // full single float precision
  1738. break;
  1739. #endif
  1740. #if 0
  1741. case audioMasterIOChanged:
  1742. CARLA_ASSERT(pData->enabled);
  1743. // TESTING
  1744. if (! pData->enabled)
  1745. {
  1746. ret = 1;
  1747. break;
  1748. }
  1749. if (x_engine->getOptions().processMode == PROCESS_MODE_CONTINUOUS_RACK)
  1750. {
  1751. carla_stderr2("CarlaPluginVST2::handleAudioMasterIOChanged() - plugin asked IO change, but it's not supported in rack mode");
  1752. return 0;
  1753. }
  1754. engineProcessLock();
  1755. m_enabled = false;
  1756. engineProcessUnlock();
  1757. if (m_active)
  1758. {
  1759. effect->dispatcher(effect, effStopProcess);
  1760. effect->dispatcher(effect, effMainsChanged, 0, 0);
  1761. }
  1762. reload();
  1763. if (m_active)
  1764. {
  1765. effect->dispatcher(effect, effMainsChanged, 0, 1, nullptr, 0.0f);
  1766. effect->dispatcher(effect, effStartProcess);
  1767. }
  1768. x_engine->callback(CALLBACK_RELOAD_ALL, m_id, 0, 0, 0, 0.0, nullptr);
  1769. ret = 1;
  1770. break;
  1771. #endif
  1772. #if ! VST_FORCE_DEPRECATED
  1773. case audioMasterNeedIdle:
  1774. // Deprecated in VST SDK 2.4
  1775. fNeedIdle = true;
  1776. ret = 1;
  1777. break;
  1778. #endif
  1779. case audioMasterSizeWindow:
  1780. CARLA_SAFE_ASSERT_BREAK(index > 0);
  1781. CARLA_SAFE_ASSERT_BREAK(value > 0);
  1782. if (fUI.isEmbed)
  1783. {
  1784. pData->engine->callback(true, true,
  1785. ENGINE_CALLBACK_EMBED_UI_RESIZED,
  1786. pData->id, index, static_cast<int>(value),
  1787. 0, 0.0f, nullptr);
  1788. }
  1789. else
  1790. {
  1791. CARLA_SAFE_ASSERT_BREAK(fUI.window != nullptr);
  1792. fUI.window->setSize(static_cast<uint>(index), static_cast<uint>(value), true, false);
  1793. }
  1794. ret = 1;
  1795. break;
  1796. case audioMasterGetSampleRate:
  1797. ret = static_cast<intptr_t>(pData->engine->getSampleRate());
  1798. break;
  1799. case audioMasterGetBlockSize:
  1800. ret = static_cast<intptr_t>(pData->engine->getBufferSize());
  1801. break;
  1802. case audioMasterGetInputLatency:
  1803. ret = 0;
  1804. break;
  1805. case audioMasterGetOutputLatency:
  1806. ret = 0;
  1807. break;
  1808. #if ! VST_FORCE_DEPRECATED
  1809. case audioMasterGetPreviousPlug:
  1810. // Deprecated in VST SDK 2.4
  1811. // TODO
  1812. break;
  1813. case audioMasterGetNextPlug:
  1814. // Deprecated in VST SDK 2.4
  1815. // TODO
  1816. break;
  1817. case audioMasterWillReplaceOrAccumulate:
  1818. // Deprecated in VST SDK 2.4
  1819. ret = 1; // replace
  1820. break;
  1821. #endif
  1822. case audioMasterGetCurrentProcessLevel:
  1823. if (pthread_equal(pthread_self(), fProcThread))
  1824. {
  1825. CARLA_SAFE_ASSERT(fIsProcessing);
  1826. if (pData->engine->isOffline())
  1827. ret = kVstProcessLevelOffline;
  1828. else
  1829. ret = kVstProcessLevelRealtime;
  1830. }
  1831. else
  1832. {
  1833. ret = kVstProcessLevelUser;
  1834. }
  1835. break;
  1836. case audioMasterGetAutomationState:
  1837. ret = pData->active ? kVstAutomationReadWrite : kVstAutomationOff;
  1838. break;
  1839. case audioMasterOfflineStart:
  1840. case audioMasterOfflineRead:
  1841. case audioMasterOfflineWrite:
  1842. case audioMasterOfflineGetCurrentPass:
  1843. case audioMasterOfflineGetCurrentMetaPass:
  1844. // TODO
  1845. break;
  1846. #if ! VST_FORCE_DEPRECATED
  1847. case audioMasterSetOutputSampleRate:
  1848. // Deprecated in VST SDK 2.4
  1849. break;
  1850. case audioMasterGetOutputSpeakerArrangement:
  1851. // Deprecated in VST SDK 2.4
  1852. // TODO
  1853. break;
  1854. #endif
  1855. case audioMasterVendorSpecific:
  1856. // TODO - cockos extensions
  1857. break;
  1858. #if ! VST_FORCE_DEPRECATED
  1859. case audioMasterSetIcon:
  1860. // Deprecated in VST SDK 2.4
  1861. break;
  1862. #endif
  1863. #if ! VST_FORCE_DEPRECATED
  1864. case audioMasterOpenWindow:
  1865. case audioMasterCloseWindow:
  1866. // Deprecated in VST SDK 2.4
  1867. // TODO
  1868. break;
  1869. #endif
  1870. case audioMasterGetDirectory:
  1871. // TODO
  1872. break;
  1873. case audioMasterUpdateDisplay: {
  1874. bool programNamesUpdated = false;
  1875. // Update current program
  1876. if (pData->prog.count > 1)
  1877. {
  1878. const int32_t current = static_cast<int32_t>(dispatcher(effGetProgram));
  1879. if (current >= 0 && current < static_cast<int32_t>(pData->prog.count))
  1880. {
  1881. char strBuf[STR_MAX+1] = { '\0' };
  1882. dispatcher(effGetProgramName, 0, 0, strBuf);
  1883. if (pData->prog.names[current] != nullptr)
  1884. delete[] pData->prog.names[current];
  1885. pData->prog.names[current] = carla_strdup(strBuf);
  1886. if (pData->prog.current != current)
  1887. {
  1888. pData->prog.current = current;
  1889. pData->engine->callback(true, true,
  1890. ENGINE_CALLBACK_PROGRAM_CHANGED,
  1891. pData->id,
  1892. current,
  1893. 0, 0, 0.0f, nullptr);
  1894. }
  1895. }
  1896. // Check for updated program names
  1897. char strBuf[STR_MAX+1];
  1898. for (int32_t i=0; i < fEffect->numPrograms && i < static_cast<int32_t>(pData->prog.count); ++i)
  1899. {
  1900. carla_zeroStruct(strBuf);
  1901. if (dispatcher(effGetProgramNameIndexed, i, 0, strBuf) != 1)
  1902. {
  1903. // stop here if plugin does not support indexed names
  1904. break;
  1905. }
  1906. if (std::strcmp(pData->prog.names[i], strBuf) != 0)
  1907. {
  1908. const char* const old = pData->prog.names[i];
  1909. pData->prog.names[i] = carla_strdup(strBuf);
  1910. delete[] old;
  1911. programNamesUpdated = true;
  1912. }
  1913. }
  1914. }
  1915. if (! fIsInitializing)
  1916. {
  1917. if (programNamesUpdated)
  1918. pData->engine->callback(true, true,
  1919. ENGINE_CALLBACK_RELOAD_PROGRAMS,
  1920. pData->id, 0, 0, 0, 0.0f, nullptr);
  1921. pData->engine->callback(true, true,
  1922. ENGINE_CALLBACK_RELOAD_PARAMETERS,
  1923. pData->id, 0, 0, 0, 0.0f, nullptr);
  1924. }
  1925. ret = 1;
  1926. break;
  1927. }
  1928. case audioMasterBeginEdit:
  1929. CARLA_SAFE_ASSERT_BREAK(index >= 0);
  1930. pData->engine->touchPluginParameter(pData->id, static_cast<uint32_t>(index), true);
  1931. break;
  1932. case audioMasterEndEdit:
  1933. CARLA_SAFE_ASSERT_BREAK(index >= 0);
  1934. pData->engine->touchPluginParameter(pData->id, static_cast<uint32_t>(index), false);
  1935. break;
  1936. case audioMasterOpenFileSelector:
  1937. case audioMasterCloseFileSelector:
  1938. // TODO
  1939. break;
  1940. #if ! VST_FORCE_DEPRECATED
  1941. case audioMasterEditFile:
  1942. // Deprecated in VST SDK 2.4
  1943. // TODO
  1944. break;
  1945. case audioMasterGetChunkFile:
  1946. // Deprecated in VST SDK 2.4
  1947. // TODO
  1948. break;
  1949. case audioMasterGetInputSpeakerArrangement:
  1950. // Deprecated in VST SDK 2.4
  1951. // TODO
  1952. break;
  1953. #endif
  1954. default:
  1955. carla_debug("CarlaPluginVST2::handleAudioMasterCallback(%02i:%s, %i, " P_INTPTR ", %p, %f) UNDEF",
  1956. opcode, vstMasterOpcode2str(opcode), index, value, ptr, static_cast<double>(opt));
  1957. break;
  1958. }
  1959. return ret;
  1960. // unused
  1961. (void)opt;
  1962. }
  1963. bool canDo(const char* const feature) const noexcept
  1964. {
  1965. try {
  1966. return (dispatcher(effCanDo, 0, 0, const_cast<char*>(feature)) == 1);
  1967. } CARLA_SAFE_EXCEPTION_RETURN("vstPluginCanDo", false);
  1968. }
  1969. bool hasMidiInput() const noexcept
  1970. {
  1971. return (fEffect->flags & effFlagsIsSynth) != 0 ||
  1972. (pData->hints & PLUGIN_WANTS_MIDI_INPUT) != 0 ||
  1973. canDo("receiveVstEvents") || canDo("receiveVstMidiEvent");
  1974. }
  1975. bool hasMidiOutput() const noexcept
  1976. {
  1977. return canDo("sendVstEvents") || canDo("sendVstMidiEvent");
  1978. }
  1979. // -------------------------------------------------------------------
  1980. const void* getNativeDescriptor() const noexcept override
  1981. {
  1982. return fEffect;
  1983. }
  1984. // -------------------------------------------------------------------
  1985. public:
  1986. bool init(const CarlaPluginPtr plugin,
  1987. const char* const filename, const char* const name, const int64_t uniqueId, const uint options)
  1988. {
  1989. CARLA_SAFE_ASSERT_RETURN(pData->engine != nullptr, false);
  1990. // ---------------------------------------------------------------
  1991. // first checks
  1992. if (pData->client != nullptr)
  1993. {
  1994. pData->engine->setLastError("Plugin client is already registered");
  1995. return false;
  1996. }
  1997. if (filename == nullptr || filename[0] == '\0')
  1998. {
  1999. pData->engine->setLastError("null filename");
  2000. return false;
  2001. }
  2002. // ---------------------------------------------------------------
  2003. VST_Function vstFn;
  2004. #ifdef CARLA_OS_MAC
  2005. CarlaString filenameCheck(filename);
  2006. filenameCheck.toLower();
  2007. if (filenameCheck.endsWith(".vst") || filenameCheck.endsWith(".vst/"))
  2008. {
  2009. if (! fBundleLoader.load(filename))
  2010. {
  2011. pData->engine->setLastError("Failed to load VST2 bundle executable");
  2012. return false;
  2013. }
  2014. vstFn = fBundleLoader.getSymbol<VST_Function>(CFSTR("VSTPluginMain"));
  2015. if (vstFn == nullptr)
  2016. vstFn = fBundleLoader.getSymbol<VST_Function>(CFSTR("main_macho"));
  2017. if (vstFn == nullptr)
  2018. {
  2019. pData->engine->setLastError("Not a VST2 plugin");
  2020. return false;
  2021. }
  2022. }
  2023. else
  2024. #endif
  2025. {
  2026. // -----------------------------------------------------------
  2027. // open DLL
  2028. if (! pData->libOpen(filename))
  2029. {
  2030. pData->engine->setLastError(pData->libError(filename));
  2031. return false;
  2032. }
  2033. // -----------------------------------------------------------
  2034. // get DLL main entry
  2035. vstFn = pData->libSymbol<VST_Function>("VSTPluginMain");
  2036. if (vstFn == nullptr)
  2037. {
  2038. vstFn = pData->libSymbol<VST_Function>("main");
  2039. if (vstFn == nullptr)
  2040. {
  2041. pData->engine->setLastError("Could not find the VST2 main entry in the plugin library");
  2042. return false;
  2043. }
  2044. }
  2045. }
  2046. // ---------------------------------------------------------------
  2047. // initialize plugin (part 1)
  2048. sCurrentUniqueId = static_cast<intptr_t>(uniqueId);
  2049. sLastCarlaPluginVST2 = this;
  2050. bool wasTriggered, wasThrown = false;
  2051. {
  2052. #if !(defined(CARLA_OS_WASM) || defined(CARLA_OS_WIN))
  2053. const ScopedAbortCatcher sac;
  2054. #endif
  2055. try {
  2056. fEffect = vstFn(carla_vst_audioMasterCallback);
  2057. } CARLA_CATCH_UNWIND catch(...) {
  2058. wasThrown = true;
  2059. }
  2060. #if !(defined(CARLA_OS_WASM) || defined(CARLA_OS_WIN))
  2061. wasTriggered = sac.wasTriggered();
  2062. #else
  2063. wasTriggered = false;
  2064. #endif
  2065. }
  2066. // try again if plugin blows
  2067. if (wasTriggered || wasThrown)
  2068. {
  2069. #if !(defined(CARLA_OS_WASM) || defined(CARLA_OS_WIN))
  2070. const ScopedAbortCatcher sac;
  2071. #endif
  2072. try {
  2073. fEffect = vstFn(carla_vst_audioMasterCallback);
  2074. } CARLA_SAFE_EXCEPTION_RETURN("VST init 2nd attempt", false);
  2075. }
  2076. sLastCarlaPluginVST2 = nullptr;
  2077. sCurrentUniqueId = 0;
  2078. if (fEffect == nullptr)
  2079. {
  2080. pData->engine->setLastError("Plugin failed to initialize");
  2081. return false;
  2082. }
  2083. if (fEffect->magic != kEffectMagic)
  2084. {
  2085. pData->engine->setLastError("Plugin is not valid (wrong vst effect magic code)");
  2086. return false;
  2087. }
  2088. fEffect->ptr1 = this;
  2089. const int32_t iBufferSize = static_cast<int32_t>(fBufferSize);
  2090. const float fSampleRate = static_cast<float>(pData->engine->getSampleRate());
  2091. dispatcher(effIdentify);
  2092. dispatcher(effSetProcessPrecision, 0, kVstProcessPrecision32);
  2093. dispatcher(effSetBlockSizeAndSampleRate, 0, iBufferSize, nullptr, fSampleRate);
  2094. dispatcher(effSetSampleRate, 0, 0, nullptr, fSampleRate);
  2095. dispatcher(effSetBlockSize, 0, iBufferSize);
  2096. dispatcher(effOpen);
  2097. const bool isShell = (dispatcher(effGetPlugCategory) == kPlugCategShell);
  2098. if (uniqueId == 0 && isShell)
  2099. {
  2100. char strBuf[STR_MAX+1];
  2101. carla_zeroChars(strBuf, STR_MAX+1);
  2102. sCurrentUniqueId = dispatcher(effShellGetNextPlugin, 0, 0, strBuf);
  2103. dispatcher(effClose);
  2104. fEffect = nullptr;
  2105. sLastCarlaPluginVST2 = this;
  2106. try {
  2107. fEffect = vstFn(carla_vst_audioMasterCallback);
  2108. } CARLA_SAFE_EXCEPTION_RETURN("Vst init", false);
  2109. sLastCarlaPluginVST2 = nullptr;
  2110. sCurrentUniqueId = 0;
  2111. dispatcher(effIdentify);
  2112. dispatcher(effSetProcessPrecision, 0, kVstProcessPrecision32);
  2113. dispatcher(effSetBlockSizeAndSampleRate, 0, iBufferSize, nullptr, fSampleRate);
  2114. dispatcher(effSetSampleRate, 0, 0, nullptr, fSampleRate);
  2115. dispatcher(effSetBlockSize, 0, iBufferSize);
  2116. dispatcher(effOpen);
  2117. }
  2118. if (fEffect->uniqueID == 0 && !isShell)
  2119. {
  2120. dispatcher(effClose);
  2121. fEffect = nullptr;
  2122. pData->engine->setLastError("Plugin is not valid (no unique ID after being open)");
  2123. return false;
  2124. }
  2125. // ---------------------------------------------------------------
  2126. // get info
  2127. if (name != nullptr && name[0] != '\0')
  2128. {
  2129. pData->name = pData->engine->getUniquePluginName(name);
  2130. }
  2131. else
  2132. {
  2133. char strBuf[STR_MAX+1];
  2134. carla_zeroChars(strBuf, STR_MAX+1);
  2135. dispatcher(effGetEffectName, 0, 0, strBuf);
  2136. if (strBuf[0] != '\0')
  2137. pData->name = pData->engine->getUniquePluginName(strBuf);
  2138. else if (const char* const shortname = std::strrchr(filename, CARLA_OS_SEP))
  2139. pData->name = pData->engine->getUniquePluginName(shortname+1);
  2140. else
  2141. pData->name = pData->engine->getUniquePluginName("unknown");
  2142. }
  2143. pData->filename = carla_strdup(filename);
  2144. // ---------------------------------------------------------------
  2145. // register client
  2146. pData->client = pData->engine->addClient(plugin);
  2147. if (pData->client == nullptr || ! pData->client->isOk())
  2148. {
  2149. pData->engine->setLastError("Failed to register plugin client");
  2150. return false;
  2151. }
  2152. // ---------------------------------------------------------------
  2153. // initialize plugin (part 2)
  2154. for (int i = fEffect->numInputs; --i >= 0;) dispatcher(effConnectInput, i, 1);
  2155. for (int i = fEffect->numOutputs; --i >= 0;) dispatcher(effConnectOutput, i, 1);
  2156. if (dispatcher(effGetVstVersion) < kVstVersion)
  2157. pData->hints |= PLUGIN_USES_OLD_VSTSDK;
  2158. static const char kHasCockosExtensions[] = "hasCockosExtensions";
  2159. if (static_cast<uintptr_t>(dispatcher(effCanDo, 0, 0, const_cast<char*>(kHasCockosExtensions))) == 0xbeef0000)
  2160. pData->hints |= PLUGIN_HAS_COCKOS_EXTENSIONS;
  2161. // ---------------------------------------------------------------
  2162. // set default options
  2163. pData->options = 0x0;
  2164. if (fEffect->initialDelay > 0 || hasMidiOutput() || isPluginOptionEnabled(options, PLUGIN_OPTION_FIXED_BUFFERS))
  2165. pData->options |= PLUGIN_OPTION_FIXED_BUFFERS;
  2166. if (fEffect->flags & effFlagsProgramChunks)
  2167. if (isPluginOptionEnabled(options, PLUGIN_OPTION_USE_CHUNKS))
  2168. pData->options |= PLUGIN_OPTION_USE_CHUNKS;
  2169. if (hasMidiInput())
  2170. {
  2171. if (isPluginOptionEnabled(options, PLUGIN_OPTION_SEND_CONTROL_CHANGES))
  2172. pData->options |= PLUGIN_OPTION_SEND_CONTROL_CHANGES;
  2173. if (isPluginOptionEnabled(options, PLUGIN_OPTION_SEND_CHANNEL_PRESSURE))
  2174. pData->options |= PLUGIN_OPTION_SEND_CHANNEL_PRESSURE;
  2175. if (isPluginOptionEnabled(options, PLUGIN_OPTION_SEND_NOTE_AFTERTOUCH))
  2176. pData->options |= PLUGIN_OPTION_SEND_NOTE_AFTERTOUCH;
  2177. if (isPluginOptionEnabled(options, PLUGIN_OPTION_SEND_PITCHBEND))
  2178. pData->options |= PLUGIN_OPTION_SEND_PITCHBEND;
  2179. if (isPluginOptionEnabled(options, PLUGIN_OPTION_SEND_ALL_SOUND_OFF))
  2180. pData->options |= PLUGIN_OPTION_SEND_ALL_SOUND_OFF;
  2181. if (isPluginOptionEnabled(options, PLUGIN_OPTION_SEND_PROGRAM_CHANGES))
  2182. pData->options |= PLUGIN_OPTION_SEND_PROGRAM_CHANGES;
  2183. if (isPluginOptionInverseEnabled(options, PLUGIN_OPTION_SKIP_SENDING_NOTES))
  2184. pData->options |= PLUGIN_OPTION_SKIP_SENDING_NOTES;
  2185. }
  2186. if (fEffect->numPrograms > 1 && (pData->options & PLUGIN_OPTION_SEND_PROGRAM_CHANGES) == 0)
  2187. if (isPluginOptionEnabled(options, PLUGIN_OPTION_MAP_PROGRAM_CHANGES))
  2188. pData->options |= PLUGIN_OPTION_MAP_PROGRAM_CHANGES;
  2189. return true;
  2190. }
  2191. private:
  2192. int fUnique1;
  2193. AEffect* fEffect;
  2194. uint32_t fMidiEventCount;
  2195. VstMidiEvent fMidiEvents[kPluginMaxMidiEvents*2];
  2196. VstTimeInfo fTimeInfo;
  2197. bool fNeedIdle;
  2198. void* fLastChunk;
  2199. bool fIsInitializing;
  2200. bool fIsProcessing;
  2201. pthread_t fChangingValuesThread;
  2202. pthread_t fIdleThread;
  2203. pthread_t fMainThread;
  2204. pthread_t fProcThread;
  2205. #ifdef CARLA_OS_MAC
  2206. BundleLoader fBundleLoader;
  2207. #endif
  2208. bool fFirstActive; // first process() call after activate()
  2209. uint32_t fBufferSize;
  2210. float** fAudioOutBuffers;
  2211. EngineTimeInfo fLastTimeInfo;
  2212. struct FixedVstEvents {
  2213. int32_t numEvents;
  2214. intptr_t reserved;
  2215. VstEvent* data[kPluginMaxMidiEvents*2];
  2216. FixedVstEvents() noexcept
  2217. : numEvents(0),
  2218. reserved(0)
  2219. {
  2220. carla_zeroPointers(data, kPluginMaxMidiEvents*2);
  2221. }
  2222. CARLA_DECLARE_NON_COPYABLE(FixedVstEvents);
  2223. } fEvents;
  2224. struct UI {
  2225. bool isEmbed;
  2226. bool isOpen;
  2227. bool isVisible;
  2228. CarlaPluginUI* window;
  2229. UI() noexcept
  2230. : isEmbed(false),
  2231. isOpen(false),
  2232. isVisible(false),
  2233. window(nullptr) {}
  2234. ~UI()
  2235. {
  2236. CARLA_ASSERT(isEmbed || ! isVisible);
  2237. if (window != nullptr)
  2238. {
  2239. delete window;
  2240. window = nullptr;
  2241. }
  2242. }
  2243. CARLA_DECLARE_NON_COPYABLE(UI);
  2244. } fUI;
  2245. int fUnique2;
  2246. static intptr_t sCurrentUniqueId;
  2247. static CarlaPluginVST2* sLastCarlaPluginVST2;
  2248. // -------------------------------------------------------------------
  2249. static bool compareMagic(int32_t magic, const char* name) noexcept
  2250. {
  2251. return magic == (int32_t)ByteOrder::littleEndianInt (name)
  2252. || magic == (int32_t)ByteOrder::bigEndianInt (name);
  2253. }
  2254. static int32_t fxbSwap(const int32_t x) noexcept
  2255. {
  2256. return (int32_t)ByteOrder::swapIfLittleEndian ((uint32_t) x);
  2257. }
  2258. bool loadJuceSaveFormat(const void* const data, const std::size_t dataSize)
  2259. {
  2260. if (dataSize < 28)
  2261. return false;
  2262. const int32_t* const set = (const int32_t*)data;
  2263. if (set[1] != 0)
  2264. return false;
  2265. if (! compareMagic(set[0], "CcnK"))
  2266. return false;
  2267. if (! compareMagic(set[2], "FBCh") && ! compareMagic(set[2], "FJuc"))
  2268. return false;
  2269. if (fxbSwap(set[3]) > 1)
  2270. return false;
  2271. const int32_t chunkSize = fxbSwap(set[39]);
  2272. CARLA_SAFE_ASSERT_RETURN(chunkSize > 0, false);
  2273. if (static_cast<std::size_t>(chunkSize + 160) > dataSize)
  2274. return false;
  2275. carla_stdout("NOTE: Loading plugin state in VST2/JUCE compatibility mode");
  2276. setChunkData(&set[40], static_cast<std::size_t>(chunkSize));
  2277. return true;
  2278. }
  2279. static intptr_t carla_vst_hostCanDo(const char* const feature)
  2280. {
  2281. carla_debug("carla_vst_hostCanDo(\"%s\")", feature);
  2282. if (std::strcmp(feature, "supplyIdle") == 0)
  2283. return 1;
  2284. if (std::strcmp(feature, "sendVstEvents") == 0)
  2285. return 1;
  2286. if (std::strcmp(feature, "sendVstMidiEvent") == 0)
  2287. return 1;
  2288. if (std::strcmp(feature, "sendVstMidiEventFlagIsRealtime") == 0)
  2289. return 1;
  2290. if (std::strcmp(feature, "sendVstTimeInfo") == 0)
  2291. return 1;
  2292. if (std::strcmp(feature, "receiveVstEvents") == 0)
  2293. return 1;
  2294. if (std::strcmp(feature, "receiveVstMidiEvent") == 0)
  2295. return 1;
  2296. if (std::strcmp(feature, "receiveVstTimeInfo") == 0)
  2297. return -1;
  2298. if (std::strcmp(feature, "reportConnectionChanges") == 0)
  2299. return -1;
  2300. if (std::strcmp(feature, "acceptIOChanges") == 0)
  2301. return 1;
  2302. if (std::strcmp(feature, "sizeWindow") == 0)
  2303. return 1;
  2304. if (std::strcmp(feature, "offline") == 0)
  2305. return -1;
  2306. if (std::strcmp(feature, "openFileSelector") == 0)
  2307. return -1;
  2308. if (std::strcmp(feature, "closeFileSelector") == 0)
  2309. return -1;
  2310. if (std::strcmp(feature, "startStopProcess") == 0)
  2311. return 1;
  2312. if (std::strcmp(feature, "supportShell") == 0)
  2313. return 1;
  2314. if (std::strcmp(feature, "shellCategory") == 0)
  2315. return 1;
  2316. if (std::strcmp(feature, "NIMKPIVendorSpecificCallbacks") == 0)
  2317. return -1;
  2318. // unimplemented
  2319. carla_stderr("carla_vst_hostCanDo(\"%s\") - unknown feature", feature);
  2320. return 0;
  2321. }
  2322. static intptr_t VSTCALLBACK carla_vst_audioMasterCallback(AEffect* effect, int32_t opcode, int32_t index, intptr_t value, void* ptr, float opt)
  2323. {
  2324. #if defined(DEBUG) && ! defined(CARLA_OS_WIN)
  2325. if (opcode != audioMasterGetTime && opcode != audioMasterProcessEvents && opcode != audioMasterGetCurrentProcessLevel && opcode != audioMasterGetOutputLatency)
  2326. carla_debug("carla_vst_audioMasterCallback(%p, %02i:%s, %i, " P_INTPTR ", %p, %f)",
  2327. effect, opcode, vstMasterOpcode2str(opcode), index, value, ptr, static_cast<double>(opt));
  2328. #endif
  2329. switch (opcode)
  2330. {
  2331. case audioMasterVersion:
  2332. return kVstVersion;
  2333. case audioMasterCurrentId:
  2334. if (sCurrentUniqueId != 0)
  2335. return sCurrentUniqueId;
  2336. break;
  2337. case audioMasterGetVendorString:
  2338. CARLA_SAFE_ASSERT_RETURN(ptr != nullptr, 0);
  2339. std::strcpy((char*)ptr, "falkTX");
  2340. return 1;
  2341. case audioMasterGetProductString:
  2342. CARLA_SAFE_ASSERT_RETURN(ptr != nullptr, 0);
  2343. std::strcpy((char*)ptr, "Carla");
  2344. return 1;
  2345. case audioMasterGetVendorVersion:
  2346. return CARLA_VERSION_HEX;
  2347. case audioMasterCanDo:
  2348. CARLA_SAFE_ASSERT_RETURN(ptr != nullptr, 0);
  2349. return carla_vst_hostCanDo((const char*)ptr);
  2350. case audioMasterGetLanguage:
  2351. return kVstLangEnglish;
  2352. }
  2353. // Check if 'resvd1' points to us, otherwise register ourselves if possible
  2354. CarlaPluginVST2* self = nullptr;
  2355. if (effect != nullptr)
  2356. {
  2357. if (effect->ptr1 != nullptr)
  2358. {
  2359. self = (CarlaPluginVST2*)effect->ptr1;
  2360. if (self->fUnique1 != self->fUnique2)
  2361. self = nullptr;
  2362. }
  2363. if (self != nullptr)
  2364. {
  2365. if (self->fEffect == nullptr)
  2366. self->fEffect = effect;
  2367. if (self->fEffect != effect)
  2368. {
  2369. carla_stderr2("carla_vst_audioMasterCallback() - host pointer mismatch: %p != %p", self->fEffect, effect);
  2370. self = nullptr;
  2371. }
  2372. }
  2373. else if (sLastCarlaPluginVST2 != nullptr)
  2374. {
  2375. effect->ptr1 = sLastCarlaPluginVST2;
  2376. self = sLastCarlaPluginVST2;
  2377. }
  2378. }
  2379. return (self != nullptr) ? self->handleAudioMasterCallback(opcode, index, value, ptr, opt) : 0;
  2380. }
  2381. CARLA_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(CarlaPluginVST2)
  2382. };
  2383. intptr_t CarlaPluginVST2::sCurrentUniqueId = 0;
  2384. CarlaPluginVST2* CarlaPluginVST2::sLastCarlaPluginVST2 = nullptr;
  2385. CARLA_BACKEND_END_NAMESPACE
  2386. // --------------------------------------------------------------------------------------------------------------------
  2387. CARLA_BACKEND_START_NAMESPACE
  2388. CarlaPluginPtr CarlaPlugin::newVST2(const Initializer& init)
  2389. {
  2390. carla_debug("CarlaPlugin::newVST2({%p, \"%s\", \"%s\", " P_INT64 "})",
  2391. init.engine, init.filename, init.name, init.uniqueId);
  2392. #ifdef USE_JUCE_FOR_VST2
  2393. if (std::getenv("CARLA_DO_NOT_USE_JUCE_FOR_VST2") == nullptr)
  2394. return newJuce(init, "VST2");
  2395. #endif
  2396. std::shared_ptr<CarlaPluginVST2> plugin(new CarlaPluginVST2(init.engine, init.id));
  2397. if (! plugin->init(plugin, init.filename, init.name, init.uniqueId, init.options))
  2398. return nullptr;
  2399. return plugin;
  2400. }
  2401. // --------------------------------------------------------------------------------------------------------------------
  2402. CARLA_BACKEND_END_NAMESPACE