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.

2965 lines
102KB

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