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.

2844 lines
98KB

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