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.

2936 lines
101KB

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