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.

2910 lines
100KB

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