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.

2938 lines
101KB

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