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.

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