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.

2847 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. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  700. pData->event.cvSourcePorts = pData->client->createCVSourcePorts();
  701. #endif
  702. }
  703. if (needsCtrlOut)
  704. {
  705. portName.clear();
  706. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  707. {
  708. portName = pData->name;
  709. portName += ":";
  710. }
  711. portName += "events-out";
  712. portName.truncate(portNameSize);
  713. pData->event.portOut = (CarlaEngineEventPort*)pData->client->addPort(kEnginePortTypeEvent, portName, false, 0);
  714. }
  715. // plugin hints
  716. const intptr_t vstCategory = dispatcher(effGetPlugCategory);
  717. pData->hints = 0x0;
  718. if (vstCategory == kPlugCategSynth || vstCategory == kPlugCategGenerator)
  719. pData->hints |= PLUGIN_IS_SYNTH;
  720. if (fEffect->flags & effFlagsHasEditor)
  721. {
  722. #if defined(CARLA_OS_MAC) && ! defined(CARLA_OS_64BIT)
  723. if (static_cast<uintptr_t>(dispatcher(effCanDo, 0, 0, const_cast<char*>("hasCockosViewAsConfig")) & 0xffff0000) == 0xbeef0000)
  724. #endif
  725. {
  726. pData->hints |= PLUGIN_HAS_CUSTOM_UI;
  727. }
  728. pData->hints |= PLUGIN_NEEDS_UI_MAIN_THREAD;
  729. }
  730. if (dispatcher(effGetVstVersion) < kVstVersion)
  731. pData->hints |= PLUGIN_USES_OLD_VSTSDK;
  732. if ((fEffect->flags & effFlagsCanReplacing) != 0 && fEffect->processReplacing != fEffect->process)
  733. pData->hints |= PLUGIN_CAN_PROCESS_REPLACING;
  734. if (static_cast<uintptr_t>(dispatcher(effCanDo, 0, 0, const_cast<char*>("hasCockosExtensions"))) == 0xbeef0000)
  735. pData->hints |= PLUGIN_HAS_COCKOS_EXTENSIONS;
  736. if (aOuts > 0 && (aIns == aOuts || aIns == 1))
  737. pData->hints |= PLUGIN_CAN_DRYWET;
  738. if (aOuts > 0)
  739. pData->hints |= PLUGIN_CAN_VOLUME;
  740. if (aOuts >= 2 && aOuts % 2 == 0)
  741. pData->hints |= PLUGIN_CAN_BALANCE;
  742. // extra plugin hints
  743. pData->extraHints = 0x0;
  744. if (mIns > 0)
  745. pData->extraHints |= PLUGIN_EXTRA_HINT_HAS_MIDI_IN;
  746. if (mOuts > 0)
  747. pData->extraHints |= PLUGIN_EXTRA_HINT_HAS_MIDI_OUT;
  748. // dummy pre-start to get latency and wantEvents() on old plugins
  749. {
  750. activate();
  751. deactivate();
  752. }
  753. // check initial latency
  754. const uint32_t latency = (fEffect->initialDelay > 0) ? static_cast<uint32_t>(fEffect->initialDelay) : 0;
  755. if (latency != 0)
  756. {
  757. pData->client->setLatency(latency);
  758. #ifndef BUILD_BRIDGE
  759. pData->latency.recreateBuffers(std::max(aIns, aOuts), latency);
  760. #endif
  761. }
  762. bufferSizeChanged(pData->engine->getBufferSize());
  763. reloadPrograms(true);
  764. if (pData->active)
  765. activate();
  766. carla_debug("CarlaPluginVST2::reload() - end");
  767. }
  768. void reloadPrograms(const bool doInit) override
  769. {
  770. carla_debug("CarlaPluginVST2::reloadPrograms(%s)", bool2str(doInit));
  771. const uint32_t oldCount = pData->prog.count;
  772. const int32_t current = pData->prog.current;
  773. // Delete old programs
  774. pData->prog.clear();
  775. // Query new programs
  776. uint32_t newCount = (fEffect->numPrograms > 0) ? static_cast<uint32_t>(fEffect->numPrograms) : 0;
  777. if (newCount > 0)
  778. {
  779. pData->prog.createNew(newCount);
  780. // Update names
  781. for (int32_t i=0; i < fEffect->numPrograms; ++i)
  782. {
  783. char strBuf[STR_MAX+1] = { '\0' };
  784. if (dispatcher(effGetProgramNameIndexed, i, 0, strBuf) != 1)
  785. {
  786. // program will be [re-]changed later
  787. dispatcher(effSetProgram, 0, i);
  788. dispatcher(effGetProgramName, 0, 0, strBuf);
  789. }
  790. pData->prog.names[i] = carla_strdup(strBuf);
  791. }
  792. }
  793. if (doInit)
  794. {
  795. if (newCount > 0)
  796. setProgram(0, false, false, false, true);
  797. else
  798. dispatcher(effSetProgram, 0, 0);
  799. }
  800. else
  801. {
  802. // Check if current program is invalid
  803. bool programChanged = false;
  804. if (newCount == oldCount+1)
  805. {
  806. // one program added, probably created by user
  807. pData->prog.current = static_cast<int32_t>(oldCount);
  808. programChanged = true;
  809. }
  810. else if (current < 0 && newCount > 0)
  811. {
  812. // programs exist now, but not before
  813. pData->prog.current = 0;
  814. programChanged = true;
  815. }
  816. else if (current >= 0 && newCount == 0)
  817. {
  818. // programs existed before, but not anymore
  819. pData->prog.current = -1;
  820. programChanged = true;
  821. }
  822. else if (current >= static_cast<int32_t>(newCount))
  823. {
  824. // current program > count
  825. pData->prog.current = 0;
  826. programChanged = true;
  827. }
  828. else
  829. {
  830. // no change
  831. pData->prog.current = current;
  832. }
  833. if (programChanged)
  834. {
  835. setProgram(pData->prog.current, true, true, true, false);
  836. }
  837. else
  838. {
  839. // Program was changed during update, re-set it
  840. if (pData->prog.current >= 0)
  841. dispatcher(effSetProgram, 0, pData->prog.current);
  842. }
  843. pData->engine->callback(true, true, ENGINE_CALLBACK_RELOAD_PROGRAMS, pData->id, 0, 0, 0, 0.0f, nullptr);
  844. }
  845. }
  846. // -------------------------------------------------------------------
  847. // Plugin processing
  848. void activate() noexcept override
  849. {
  850. CARLA_SAFE_ASSERT_RETURN(fEffect != nullptr,);
  851. const int32_t iBufferSize = static_cast<int32_t>(fBufferSize);
  852. const float fSampleRate = static_cast<float>(pData->engine->getSampleRate());
  853. dispatcher(effSetProcessPrecision, 0, kVstProcessPrecision32);
  854. dispatcher(effSetBlockSizeAndSampleRate, 0, iBufferSize, nullptr, fSampleRate);
  855. dispatcher(effSetSampleRate, 0, 0, nullptr, fSampleRate);
  856. dispatcher(effSetBlockSize, 0, iBufferSize);
  857. try {
  858. dispatcher(effMainsChanged, 0, 1);
  859. } catch(...) {}
  860. try {
  861. dispatcher(effStartProcess, 0, 0);
  862. } catch(...) {}
  863. fFirstActive = true;
  864. }
  865. void deactivate() noexcept override
  866. {
  867. CARLA_SAFE_ASSERT_RETURN(fEffect != nullptr,);
  868. try {
  869. dispatcher(effStopProcess);
  870. } catch(...) {}
  871. try {
  872. dispatcher(effMainsChanged);
  873. } catch(...) {}
  874. }
  875. void process(const float** const audioIn,
  876. float** const audioOut,
  877. const float** const cvIn,
  878. float** const,
  879. const uint32_t frames) override
  880. {
  881. const CarlaScopedValueSetter<pthread_t> svs(fProcThread, pthread_self(), kNullThread);
  882. // --------------------------------------------------------------------------------------------------------
  883. // Check if active
  884. if (! pData->active)
  885. {
  886. // disable any output sound
  887. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  888. carla_zeroFloats(audioOut[i], frames);
  889. return;
  890. }
  891. fMidiEventCount = 0;
  892. carla_zeroStructs(fMidiEvents, kPluginMaxMidiEvents*2);
  893. // --------------------------------------------------------------------------------------------------------
  894. // Check if needs reset
  895. if (pData->needsReset)
  896. {
  897. if (pData->options & PLUGIN_OPTION_SEND_ALL_SOUND_OFF)
  898. {
  899. fMidiEventCount = MAX_MIDI_CHANNELS*2;
  900. for (uint8_t i=0, k=MAX_MIDI_CHANNELS; i < MAX_MIDI_CHANNELS; ++i)
  901. {
  902. fMidiEvents[k].type = kVstMidiType;
  903. fMidiEvents[k].byteSize = kVstMidiEventSize;
  904. fMidiEvents[k].midiData[0] = char(MIDI_STATUS_CONTROL_CHANGE | (k & MIDI_CHANNEL_BIT));
  905. fMidiEvents[k].midiData[1] = MIDI_CONTROL_ALL_NOTES_OFF;
  906. fMidiEvents[k+i].type = kVstMidiType;
  907. fMidiEvents[k+i].byteSize = kVstMidiEventSize;
  908. fMidiEvents[k+i].midiData[0] = char(MIDI_STATUS_CONTROL_CHANGE | (k & MIDI_CHANNEL_BIT));
  909. fMidiEvents[k+i].midiData[1] = MIDI_CONTROL_ALL_SOUND_OFF;
  910. }
  911. }
  912. else if (pData->ctrlChannel >= 0 && pData->ctrlChannel < MAX_MIDI_CHANNELS)
  913. {
  914. fMidiEventCount = MAX_MIDI_NOTE;
  915. for (uint8_t i=0; i < MAX_MIDI_NOTE; ++i)
  916. {
  917. fMidiEvents[i].type = kVstMidiType;
  918. fMidiEvents[i].byteSize = kVstMidiEventSize;
  919. fMidiEvents[i].midiData[0] = char(MIDI_STATUS_NOTE_OFF | (pData->ctrlChannel & MIDI_CHANNEL_BIT));
  920. fMidiEvents[i].midiData[1] = char(i);
  921. }
  922. }
  923. pData->needsReset = false;
  924. }
  925. // --------------------------------------------------------------------------------------------------------
  926. // Set TimeInfo
  927. const EngineTimeInfo timeInfo(pData->engine->getTimeInfo());
  928. fTimeInfo.flags = 0;
  929. if (fFirstActive || ! fLastTimeInfo.compareIgnoringRollingFrames(timeInfo, fBufferSize))
  930. {
  931. fTimeInfo.flags |= kVstTransportChanged;
  932. fLastTimeInfo = timeInfo;
  933. }
  934. if (timeInfo.playing)
  935. fTimeInfo.flags |= kVstTransportPlaying;
  936. fTimeInfo.samplePos = double(timeInfo.frame);
  937. fTimeInfo.sampleRate = pData->engine->getSampleRate();
  938. if (timeInfo.usecs != 0)
  939. {
  940. fTimeInfo.nanoSeconds = double(timeInfo.usecs)/1000.0;
  941. fTimeInfo.flags |= kVstNanosValid;
  942. }
  943. if (timeInfo.bbt.valid)
  944. {
  945. CARLA_SAFE_ASSERT_INT(timeInfo.bbt.bar > 0, timeInfo.bbt.bar);
  946. CARLA_SAFE_ASSERT_INT(timeInfo.bbt.beat > 0, timeInfo.bbt.beat);
  947. const double ppqBar = static_cast<double>(timeInfo.bbt.beatsPerBar) * (timeInfo.bbt.bar - 1);
  948. // const double ppqBeat = static_cast<double>(timeInfo.bbt.beat - 1);
  949. // const double ppqTick = timeInfo.bbt.tick / timeInfo.bbt.ticksPerBeat;
  950. // PPQ Pos
  951. fTimeInfo.ppqPos = fTimeInfo.samplePos / (fTimeInfo.sampleRate * 60 / fTimeInfo.tempo);
  952. // fTimeInfo.ppqPos = ppqBar + ppqBeat + ppqTick;
  953. fTimeInfo.flags |= kVstPpqPosValid;
  954. // Tempo
  955. fTimeInfo.tempo = timeInfo.bbt.beatsPerMinute;
  956. fTimeInfo.flags |= kVstTempoValid;
  957. // Bars
  958. fTimeInfo.barStartPos = ppqBar;
  959. fTimeInfo.flags |= kVstBarsValid;
  960. // Time Signature
  961. fTimeInfo.timeSigNumerator = static_cast<int32_t>(timeInfo.bbt.beatsPerBar);
  962. fTimeInfo.timeSigDenominator = static_cast<int32_t>(timeInfo.bbt.beatType);
  963. fTimeInfo.flags |= kVstTimeSigValid;
  964. }
  965. else
  966. {
  967. // Tempo
  968. fTimeInfo.tempo = 120.0;
  969. fTimeInfo.flags |= kVstTempoValid;
  970. // Time Signature
  971. fTimeInfo.timeSigNumerator = 4;
  972. fTimeInfo.timeSigDenominator = 4;
  973. fTimeInfo.flags |= kVstTimeSigValid;
  974. // Missing info
  975. fTimeInfo.ppqPos = 0.0;
  976. fTimeInfo.barStartPos = 0.0;
  977. }
  978. // --------------------------------------------------------------------------------------------------------
  979. // Event Input and Processing
  980. if (pData->event.portIn != nullptr)
  981. {
  982. // ----------------------------------------------------------------------------------------------------
  983. // MIDI Input (External)
  984. if (pData->extNotes.mutex.tryLock())
  985. {
  986. ExternalMidiNote note = { 0, 0, 0 };
  987. for (; fMidiEventCount < kPluginMaxMidiEvents*2 && ! pData->extNotes.data.isEmpty();)
  988. {
  989. note = pData->extNotes.data.getFirst(note, true);
  990. CARLA_SAFE_ASSERT_CONTINUE(note.channel >= 0 && note.channel < MAX_MIDI_CHANNELS);
  991. VstMidiEvent& vstMidiEvent(fMidiEvents[fMidiEventCount++]);
  992. vstMidiEvent.type = kVstMidiType;
  993. vstMidiEvent.byteSize = kVstMidiEventSize;
  994. vstMidiEvent.midiData[0] = char((note.velo > 0 ? MIDI_STATUS_NOTE_ON : MIDI_STATUS_NOTE_OFF) | (note.channel & MIDI_CHANNEL_BIT));
  995. vstMidiEvent.midiData[1] = char(note.note);
  996. vstMidiEvent.midiData[2] = char(note.velo);
  997. }
  998. pData->extNotes.mutex.unlock();
  999. } // End of MIDI Input (External)
  1000. // ----------------------------------------------------------------------------------------------------
  1001. // Event Input (System)
  1002. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1003. bool allNotesOffSent = false;
  1004. #endif
  1005. bool isSampleAccurate = (pData->options & PLUGIN_OPTION_FIXED_BUFFERS) == 0;
  1006. uint32_t startTime = 0;
  1007. uint32_t timeOffset = 0;
  1008. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1009. if (cvIn != nullptr && pData->event.cvSourcePorts != nullptr)
  1010. pData->event.cvSourcePorts->initPortBuffers(cvIn, frames, isSampleAccurate, pData->event.portIn);
  1011. #endif
  1012. for (uint32_t i=0, numEvents = pData->event.portIn->getEventCount(); i < numEvents; ++i)
  1013. {
  1014. const EngineEvent& event(pData->event.portIn->getEvent(i));
  1015. uint32_t eventTime = event.time;
  1016. CARLA_SAFE_ASSERT_UINT2_CONTINUE(eventTime < frames, eventTime, frames);
  1017. if (eventTime < timeOffset)
  1018. {
  1019. carla_stderr2("Timing error, eventTime:%u < timeOffset:%u for '%s'",
  1020. eventTime, timeOffset, pData->name);
  1021. eventTime = timeOffset;
  1022. }
  1023. if (isSampleAccurate && eventTime > timeOffset)
  1024. {
  1025. if (processSingle(audioIn, audioOut, eventTime - timeOffset, timeOffset))
  1026. {
  1027. startTime = 0;
  1028. timeOffset = eventTime;
  1029. if (fMidiEventCount > 0)
  1030. {
  1031. carla_zeroStructs(fMidiEvents, fMidiEventCount);
  1032. fMidiEventCount = 0;
  1033. }
  1034. }
  1035. else
  1036. startTime += timeOffset;
  1037. }
  1038. switch (event.type)
  1039. {
  1040. case kEngineEventTypeNull:
  1041. break;
  1042. case kEngineEventTypeControl: {
  1043. const EngineControlEvent& ctrlEvent(event.ctrl);
  1044. switch (ctrlEvent.type)
  1045. {
  1046. case kEngineControlEventTypeNull:
  1047. break;
  1048. case kEngineControlEventTypeParameter: {
  1049. float value;
  1050. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1051. // non-midi
  1052. if (event.channel == kEngineEventNonMidiChannel)
  1053. {
  1054. const uint32_t k = ctrlEvent.param;
  1055. CARLA_SAFE_ASSERT_CONTINUE(k < pData->param.count);
  1056. if (pData->param.data[k].hints & PARAMETER_IS_BOOLEAN)
  1057. {
  1058. value = (ctrlEvent.value < 0.5f) ? pData->param.ranges[k].min : pData->param.ranges[k].max;
  1059. }
  1060. else
  1061. {
  1062. if (pData->param.data[k].hints & PARAMETER_IS_LOGARITHMIC)
  1063. value = pData->param.ranges[k].getUnnormalizedLogValue(ctrlEvent.value);
  1064. else
  1065. value = pData->param.ranges[k].getUnnormalizedValue(ctrlEvent.value);
  1066. if (pData->param.data[k].hints & PARAMETER_IS_INTEGER)
  1067. value = std::rint(value);
  1068. }
  1069. setParameterValueRT(k, value, true);
  1070. continue;
  1071. }
  1072. // Control backend stuff
  1073. if (event.channel == pData->ctrlChannel)
  1074. {
  1075. if (MIDI_IS_CONTROL_BREATH_CONTROLLER(ctrlEvent.param) && (pData->hints & PLUGIN_CAN_DRYWET) != 0)
  1076. {
  1077. value = ctrlEvent.value;
  1078. setDryWetRT(value, true);
  1079. }
  1080. if (MIDI_IS_CONTROL_CHANNEL_VOLUME(ctrlEvent.param) && (pData->hints & PLUGIN_CAN_VOLUME) != 0)
  1081. {
  1082. value = ctrlEvent.value*127.0f/100.0f;
  1083. setVolumeRT(value, true);
  1084. }
  1085. if (MIDI_IS_CONTROL_BALANCE(ctrlEvent.param) && (pData->hints & PLUGIN_CAN_BALANCE) != 0)
  1086. {
  1087. float left, right;
  1088. value = ctrlEvent.value/0.5f - 1.0f;
  1089. if (value < 0.0f)
  1090. {
  1091. left = -1.0f;
  1092. right = (value*2.0f)+1.0f;
  1093. }
  1094. else if (value > 0.0f)
  1095. {
  1096. left = (value*2.0f)-1.0f;
  1097. right = 1.0f;
  1098. }
  1099. else
  1100. {
  1101. left = -1.0f;
  1102. right = 1.0f;
  1103. }
  1104. setBalanceLeftRT(left, true);
  1105. setBalanceRightRT(right, true);
  1106. }
  1107. }
  1108. #endif
  1109. // Control plugin parameters
  1110. uint32_t k;
  1111. for (k=0; k < pData->param.count; ++k)
  1112. {
  1113. if (pData->param.data[k].midiChannel != event.channel)
  1114. continue;
  1115. if (pData->param.data[k].mappedControlIndex != ctrlEvent.param)
  1116. continue;
  1117. if (pData->param.data[k].type != PARAMETER_INPUT)
  1118. continue;
  1119. if ((pData->param.data[k].hints & PARAMETER_IS_AUTOMABLE) == 0)
  1120. continue;
  1121. if (pData->param.data[k].hints & PARAMETER_IS_BOOLEAN)
  1122. {
  1123. value = (ctrlEvent.value < 0.5f) ? pData->param.ranges[k].min : pData->param.ranges[k].max;
  1124. }
  1125. else
  1126. {
  1127. if (pData->param.data[k].hints & PARAMETER_IS_LOGARITHMIC)
  1128. value = pData->param.ranges[k].getUnnormalizedLogValue(ctrlEvent.value);
  1129. else
  1130. value = pData->param.ranges[k].getUnnormalizedValue(ctrlEvent.value);
  1131. if (pData->param.data[k].hints & PARAMETER_IS_INTEGER)
  1132. value = std::rint(value);
  1133. }
  1134. setParameterValueRT(k, value, true);
  1135. }
  1136. if ((pData->options & PLUGIN_OPTION_SEND_CONTROL_CHANGES) != 0 && ctrlEvent.param < MAX_MIDI_CONTROL)
  1137. {
  1138. if (fMidiEventCount >= kPluginMaxMidiEvents*2)
  1139. continue;
  1140. VstMidiEvent& vstMidiEvent(fMidiEvents[fMidiEventCount++]);
  1141. carla_zeroStruct(vstMidiEvent);
  1142. vstMidiEvent.type = kVstMidiType;
  1143. vstMidiEvent.byteSize = kVstMidiEventSize;
  1144. vstMidiEvent.deltaFrames = static_cast<int32_t>(isSampleAccurate ? startTime : eventTime);
  1145. vstMidiEvent.midiData[0] = char(MIDI_STATUS_CONTROL_CHANGE | (event.channel & MIDI_CHANNEL_BIT));
  1146. vstMidiEvent.midiData[1] = char(ctrlEvent.param);
  1147. vstMidiEvent.midiData[2] = char(ctrlEvent.value*127.0f);
  1148. }
  1149. break;
  1150. } // case kEngineControlEventTypeParameter
  1151. case kEngineControlEventTypeMidiBank:
  1152. if ((pData->options & PLUGIN_OPTION_SEND_PROGRAM_CHANGES) != 0)
  1153. {
  1154. if (fMidiEventCount >= kPluginMaxMidiEvents*2)
  1155. continue;
  1156. VstMidiEvent& vstMidiEvent_MSB(fMidiEvents[fMidiEventCount++]);
  1157. carla_zeroStruct(vstMidiEvent_MSB);
  1158. vstMidiEvent_MSB.type = kVstMidiType;
  1159. vstMidiEvent_MSB.byteSize = kVstMidiEventSize;
  1160. vstMidiEvent_MSB.deltaFrames = static_cast<int32_t>(isSampleAccurate ? startTime : event.time);
  1161. vstMidiEvent_MSB.midiData[0] = char(MIDI_STATUS_CONTROL_CHANGE | (event.channel & MIDI_CHANNEL_BIT));
  1162. vstMidiEvent_MSB.midiData[1] = MIDI_CONTROL_BANK_SELECT;
  1163. vstMidiEvent_MSB.midiData[2] = 0;
  1164. VstMidiEvent& vstMidiEvent_LSB(fMidiEvents[fMidiEventCount++]);
  1165. carla_zeroStruct(vstMidiEvent_LSB);
  1166. vstMidiEvent_LSB.type = kVstMidiType;
  1167. vstMidiEvent_LSB.byteSize = kVstMidiEventSize;
  1168. vstMidiEvent_LSB.deltaFrames = static_cast<int32_t>(isSampleAccurate ? startTime : eventTime);
  1169. vstMidiEvent_LSB.midiData[0] = char(MIDI_STATUS_CONTROL_CHANGE | (event.channel & MIDI_CHANNEL_BIT));
  1170. vstMidiEvent_LSB.midiData[1] = MIDI_CONTROL_BANK_SELECT__LSB;
  1171. vstMidiEvent_LSB.midiData[2] = char(ctrlEvent.param);
  1172. }
  1173. break;
  1174. case kEngineControlEventTypeMidiProgram:
  1175. if (event.channel == pData->ctrlChannel && (pData->options & PLUGIN_OPTION_MAP_PROGRAM_CHANGES) != 0)
  1176. {
  1177. if (ctrlEvent.param < pData->prog.count)
  1178. {
  1179. setProgramRT(ctrlEvent.param, true);
  1180. break;
  1181. }
  1182. }
  1183. else if (pData->options & PLUGIN_OPTION_SEND_PROGRAM_CHANGES)
  1184. {
  1185. if (fMidiEventCount >= kPluginMaxMidiEvents*2)
  1186. continue;
  1187. VstMidiEvent& vstMidiEvent(fMidiEvents[fMidiEventCount++]);
  1188. carla_zeroStruct(vstMidiEvent);
  1189. vstMidiEvent.type = kVstMidiType;
  1190. vstMidiEvent.byteSize = kVstMidiEventSize;
  1191. vstMidiEvent.deltaFrames = static_cast<int32_t>(isSampleAccurate ? startTime : eventTime);
  1192. vstMidiEvent.midiData[0] = char(MIDI_STATUS_PROGRAM_CHANGE | (event.channel & MIDI_CHANNEL_BIT));
  1193. vstMidiEvent.midiData[1] = char(ctrlEvent.param);
  1194. }
  1195. break;
  1196. case kEngineControlEventTypeAllSoundOff:
  1197. if (pData->options & PLUGIN_OPTION_SEND_ALL_SOUND_OFF)
  1198. {
  1199. if (fMidiEventCount >= kPluginMaxMidiEvents*2)
  1200. continue;
  1201. VstMidiEvent& vstMidiEvent(fMidiEvents[fMidiEventCount++]);
  1202. carla_zeroStruct(vstMidiEvent);
  1203. vstMidiEvent.type = kVstMidiType;
  1204. vstMidiEvent.byteSize = kVstMidiEventSize;
  1205. vstMidiEvent.deltaFrames = static_cast<int32_t>(isSampleAccurate ? startTime : eventTime);
  1206. vstMidiEvent.midiData[0] = char(MIDI_STATUS_CONTROL_CHANGE | (event.channel & MIDI_CHANNEL_BIT));
  1207. vstMidiEvent.midiData[1] = MIDI_CONTROL_ALL_SOUND_OFF;
  1208. }
  1209. break;
  1210. case kEngineControlEventTypeAllNotesOff:
  1211. if (pData->options & PLUGIN_OPTION_SEND_ALL_SOUND_OFF)
  1212. {
  1213. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1214. if (event.channel == pData->ctrlChannel && ! allNotesOffSent)
  1215. {
  1216. allNotesOffSent = true;
  1217. postponeRtAllNotesOff();
  1218. }
  1219. #endif
  1220. if (fMidiEventCount >= kPluginMaxMidiEvents*2)
  1221. continue;
  1222. VstMidiEvent& vstMidiEvent(fMidiEvents[fMidiEventCount++]);
  1223. carla_zeroStruct(vstMidiEvent);
  1224. vstMidiEvent.type = kVstMidiType;
  1225. vstMidiEvent.byteSize = kVstMidiEventSize;
  1226. vstMidiEvent.deltaFrames = static_cast<int32_t>(isSampleAccurate ? startTime : eventTime);
  1227. vstMidiEvent.midiData[0] = char(MIDI_STATUS_CONTROL_CHANGE | (event.channel & MIDI_CHANNEL_BIT));
  1228. vstMidiEvent.midiData[1] = MIDI_CONTROL_ALL_NOTES_OFF;
  1229. }
  1230. break;
  1231. } // switch (ctrlEvent.type)
  1232. break;
  1233. } // case kEngineEventTypeControl
  1234. case kEngineEventTypeMidi: {
  1235. if (fMidiEventCount >= kPluginMaxMidiEvents*2)
  1236. continue;
  1237. const EngineMidiEvent& midiEvent(event.midi);
  1238. if (midiEvent.size > 3)
  1239. continue;
  1240. #ifdef CARLA_PROPER_CPP11_SUPPORT
  1241. static_assert(3 <= EngineMidiEvent::kDataSize, "Incorrect data");
  1242. #endif
  1243. uint8_t status = uint8_t(MIDI_GET_STATUS_FROM_DATA(midiEvent.data));
  1244. if (status == MIDI_STATUS_CHANNEL_PRESSURE && (pData->options & PLUGIN_OPTION_SEND_CHANNEL_PRESSURE) == 0)
  1245. continue;
  1246. if (status == MIDI_STATUS_CONTROL_CHANGE && (pData->options & PLUGIN_OPTION_SEND_CONTROL_CHANGES) == 0)
  1247. continue;
  1248. if (status == MIDI_STATUS_POLYPHONIC_AFTERTOUCH && (pData->options & PLUGIN_OPTION_SEND_NOTE_AFTERTOUCH) == 0)
  1249. continue;
  1250. if (status == MIDI_STATUS_PITCH_WHEEL_CONTROL && (pData->options & PLUGIN_OPTION_SEND_PITCHBEND) == 0)
  1251. continue;
  1252. // Fix bad note-off
  1253. if (status == MIDI_STATUS_NOTE_ON && midiEvent.data[2] == 0)
  1254. status = MIDI_STATUS_NOTE_OFF;
  1255. VstMidiEvent& vstMidiEvent(fMidiEvents[fMidiEventCount++]);
  1256. carla_zeroStruct(vstMidiEvent);
  1257. vstMidiEvent.type = kVstMidiType;
  1258. vstMidiEvent.byteSize = kVstMidiEventSize;
  1259. vstMidiEvent.deltaFrames = static_cast<int32_t>(isSampleAccurate ? startTime : eventTime);
  1260. vstMidiEvent.midiData[0] = char(status | (event.channel & MIDI_CHANNEL_BIT));
  1261. vstMidiEvent.midiData[1] = char(midiEvent.size >= 2 ? midiEvent.data[1] : 0);
  1262. vstMidiEvent.midiData[2] = char(midiEvent.size >= 3 ? midiEvent.data[2] : 0);
  1263. if (status == MIDI_STATUS_NOTE_ON)
  1264. {
  1265. pData->postponeRtEvent(kPluginPostRtEventNoteOn,
  1266. true,
  1267. event.channel,
  1268. midiEvent.data[1],
  1269. midiEvent.data[2],
  1270. 0.0f);
  1271. }
  1272. else if (status == MIDI_STATUS_NOTE_OFF)
  1273. {
  1274. pData->postponeRtEvent(kPluginPostRtEventNoteOff,
  1275. true,
  1276. event.channel,
  1277. midiEvent.data[1],
  1278. 0, 0.0f);
  1279. }
  1280. } break;
  1281. } // switch (event.type)
  1282. }
  1283. pData->postRtEvents.trySplice();
  1284. if (frames > timeOffset)
  1285. processSingle(audioIn, audioOut, frames - timeOffset, timeOffset);
  1286. } // End of Event Input and Processing
  1287. // --------------------------------------------------------------------------------------------------------
  1288. // Plugin processing (no events)
  1289. else
  1290. {
  1291. processSingle(audioIn, audioOut, frames, 0);
  1292. } // End of Plugin processing (no events)
  1293. // --------------------------------------------------------------------------------------------------------
  1294. // MIDI Output
  1295. if (pData->event.portOut != nullptr)
  1296. {
  1297. // reverse lookup MIDI events
  1298. for (uint32_t k = (kPluginMaxMidiEvents*2)-1; k >= fMidiEventCount; --k)
  1299. {
  1300. if (fMidiEvents[k].type == 0)
  1301. break;
  1302. const VstMidiEvent& vstMidiEvent(fMidiEvents[k]);
  1303. CARLA_SAFE_ASSERT_CONTINUE(vstMidiEvent.deltaFrames >= 0);
  1304. CARLA_SAFE_ASSERT_CONTINUE(vstMidiEvent.midiData[0] != 0);
  1305. uint8_t midiData[3];
  1306. midiData[0] = static_cast<uint8_t>(vstMidiEvent.midiData[0]);
  1307. midiData[1] = static_cast<uint8_t>(vstMidiEvent.midiData[1]);
  1308. midiData[2] = static_cast<uint8_t>(vstMidiEvent.midiData[2]);
  1309. if (! pData->event.portOut->writeMidiEvent(static_cast<uint32_t>(vstMidiEvent.deltaFrames), 3, midiData))
  1310. break;
  1311. }
  1312. } // End of MIDI Output
  1313. fFirstActive = false;
  1314. // --------------------------------------------------------------------------------------------------------
  1315. #ifdef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1316. return;
  1317. // unused
  1318. (void)cvIn;
  1319. #endif
  1320. }
  1321. bool processSingle(const float** const inBuffer, float** const outBuffer, const uint32_t frames, const uint32_t timeOffset)
  1322. {
  1323. CARLA_SAFE_ASSERT_RETURN(frames > 0, false);
  1324. if (pData->audioIn.count > 0)
  1325. {
  1326. CARLA_SAFE_ASSERT_RETURN(inBuffer != nullptr, false);
  1327. }
  1328. if (pData->audioOut.count > 0)
  1329. {
  1330. CARLA_SAFE_ASSERT_RETURN(outBuffer != nullptr, false);
  1331. CARLA_SAFE_ASSERT_RETURN(fAudioOutBuffers != nullptr, false);
  1332. }
  1333. // --------------------------------------------------------------------------------------------------------
  1334. // Try lock, silence otherwise
  1335. #ifndef STOAT_TEST_BUILD
  1336. if (pData->engine->isOffline())
  1337. {
  1338. pData->singleMutex.lock();
  1339. }
  1340. else
  1341. #endif
  1342. if (! pData->singleMutex.tryLock())
  1343. {
  1344. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  1345. {
  1346. for (uint32_t k=0; k < frames; ++k)
  1347. outBuffer[i][k+timeOffset] = 0.0f;
  1348. }
  1349. return false;
  1350. }
  1351. // --------------------------------------------------------------------------------------------------------
  1352. // Set audio buffers
  1353. float* vstInBuffer[pData->audioIn.count];
  1354. for (uint32_t i=0; i < pData->audioIn.count; ++i)
  1355. vstInBuffer[i] = const_cast<float*>(inBuffer[i]+timeOffset);
  1356. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  1357. carla_zeroFloats(fAudioOutBuffers[i], frames);
  1358. // --------------------------------------------------------------------------------------------------------
  1359. // Set MIDI events
  1360. fIsProcessing = true;
  1361. if (fMidiEventCount > 0)
  1362. {
  1363. fEvents.numEvents = static_cast<int32_t>(fMidiEventCount);
  1364. fEvents.reserved = 0;
  1365. dispatcher(effProcessEvents, 0, 0, &fEvents, 0.0f);
  1366. }
  1367. // --------------------------------------------------------------------------------------------------------
  1368. // Run plugin
  1369. if (pData->hints & PLUGIN_CAN_PROCESS_REPLACING)
  1370. {
  1371. fEffect->processReplacing(fEffect,
  1372. (pData->audioIn.count > 0) ? vstInBuffer : nullptr,
  1373. (pData->audioOut.count > 0) ? fAudioOutBuffers : nullptr,
  1374. static_cast<int32_t>(frames));
  1375. }
  1376. else
  1377. {
  1378. #if ! VST_FORCE_DEPRECATED
  1379. fEffect->process(fEffect,
  1380. (pData->audioIn.count > 0) ? vstInBuffer : nullptr,
  1381. (pData->audioOut.count > 0) ? fAudioOutBuffers : nullptr,
  1382. static_cast<int32_t>(frames));
  1383. #endif
  1384. }
  1385. fIsProcessing = false;
  1386. fTimeInfo.samplePos += frames;
  1387. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1388. // --------------------------------------------------------------------------------------------------------
  1389. // Post-processing (dry/wet, volume and balance)
  1390. {
  1391. const bool doDryWet = (pData->hints & PLUGIN_CAN_DRYWET) != 0 && carla_isNotEqual(pData->postProc.dryWet, 1.0f);
  1392. const bool doBalance = (pData->hints & PLUGIN_CAN_BALANCE) != 0 && ! (carla_isEqual(pData->postProc.balanceLeft, -1.0f) && carla_isEqual(pData->postProc.balanceRight, 1.0f));
  1393. const bool isMono = (pData->audioIn.count == 1);
  1394. bool isPair;
  1395. float bufValue, oldBufLeft[doBalance ? frames : 1];
  1396. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  1397. {
  1398. // Dry/Wet
  1399. if (doDryWet)
  1400. {
  1401. const uint32_t c = isMono ? 0 : i;
  1402. for (uint32_t k=0; k < frames; ++k)
  1403. {
  1404. bufValue = inBuffer[c][k+timeOffset];
  1405. fAudioOutBuffers[i][k] = (fAudioOutBuffers[i][k] * pData->postProc.dryWet) + (bufValue * (1.0f - pData->postProc.dryWet));
  1406. }
  1407. }
  1408. // Balance
  1409. if (doBalance)
  1410. {
  1411. isPair = (i % 2 == 0);
  1412. if (isPair)
  1413. {
  1414. CARLA_ASSERT(i+1 < pData->audioOut.count);
  1415. carla_copyFloats(oldBufLeft, fAudioOutBuffers[i], frames);
  1416. }
  1417. float balRangeL = (pData->postProc.balanceLeft + 1.0f)/2.0f;
  1418. float balRangeR = (pData->postProc.balanceRight + 1.0f)/2.0f;
  1419. for (uint32_t k=0; k < frames; ++k)
  1420. {
  1421. if (isPair)
  1422. {
  1423. // left
  1424. fAudioOutBuffers[i][k] = oldBufLeft[k] * (1.0f - balRangeL);
  1425. fAudioOutBuffers[i][k] += fAudioOutBuffers[i+1][k] * (1.0f - balRangeR);
  1426. }
  1427. else
  1428. {
  1429. // right
  1430. fAudioOutBuffers[i][k] = fAudioOutBuffers[i][k] * balRangeR;
  1431. fAudioOutBuffers[i][k] += oldBufLeft[k] * balRangeL;
  1432. }
  1433. }
  1434. }
  1435. // Volume (and buffer copy)
  1436. {
  1437. for (uint32_t k=0; k < frames; ++k)
  1438. outBuffer[i][k+timeOffset] = fAudioOutBuffers[i][k] * pData->postProc.volume;
  1439. }
  1440. }
  1441. } // End of Post-processing
  1442. #else // BUILD_BRIDGE_ALTERNATIVE_ARCH
  1443. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  1444. {
  1445. for (uint32_t k=0; k < frames; ++k)
  1446. outBuffer[i][k+timeOffset] = fAudioOutBuffers[i][k];
  1447. }
  1448. #endif
  1449. // --------------------------------------------------------------------------------------------------------
  1450. pData->singleMutex.unlock();
  1451. return true;
  1452. }
  1453. void bufferSizeChanged(const uint32_t newBufferSize) override
  1454. {
  1455. CARLA_ASSERT_INT(newBufferSize > 0, newBufferSize);
  1456. carla_debug("CarlaPluginVST2::bufferSizeChanged(%i)", newBufferSize);
  1457. fBufferSize = pData->engine->getBufferSize();
  1458. if (pData->active)
  1459. deactivate();
  1460. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  1461. {
  1462. if (fAudioOutBuffers[i] != nullptr)
  1463. delete[] fAudioOutBuffers[i];
  1464. fAudioOutBuffers[i] = new float[newBufferSize];
  1465. }
  1466. #if ! VST_FORCE_DEPRECATED
  1467. dispatcher(effSetBlockSizeAndSampleRate, 0, static_cast<int32_t>(newBufferSize), nullptr, static_cast<float>(pData->engine->getSampleRate()));
  1468. #endif
  1469. dispatcher(effSetBlockSize, 0, static_cast<int32_t>(newBufferSize), nullptr, 0.0f);
  1470. if (pData->active)
  1471. activate();
  1472. }
  1473. void sampleRateChanged(const double newSampleRate) override
  1474. {
  1475. CARLA_ASSERT_INT(newSampleRate > 0.0, newSampleRate);
  1476. carla_debug("CarlaPluginVST2::sampleRateChanged(%g)", newSampleRate);
  1477. if (pData->active)
  1478. deactivate();
  1479. #if ! VST_FORCE_DEPRECATED
  1480. dispatcher(effSetBlockSizeAndSampleRate, 0, static_cast<int32_t>(pData->engine->getBufferSize()), nullptr, static_cast<float>(newSampleRate));
  1481. #endif
  1482. dispatcher(effSetSampleRate, 0, 0, nullptr, static_cast<float>(newSampleRate));
  1483. if (pData->active)
  1484. activate();
  1485. }
  1486. // -------------------------------------------------------------------
  1487. // Plugin buffers
  1488. void clearBuffers() noexcept override
  1489. {
  1490. carla_debug("CarlaPluginVST2::clearBuffers() - start");
  1491. if (fAudioOutBuffers != nullptr)
  1492. {
  1493. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  1494. {
  1495. if (fAudioOutBuffers[i] != nullptr)
  1496. {
  1497. delete[] fAudioOutBuffers[i];
  1498. fAudioOutBuffers[i] = nullptr;
  1499. }
  1500. }
  1501. delete[] fAudioOutBuffers;
  1502. fAudioOutBuffers = nullptr;
  1503. }
  1504. CarlaPlugin::clearBuffers();
  1505. carla_debug("CarlaPluginVST2::clearBuffers() - end");
  1506. }
  1507. // -------------------------------------------------------------------
  1508. // Post-poned UI Stuff
  1509. // nothing
  1510. // -------------------------------------------------------------------
  1511. protected:
  1512. void handlePluginUIClosed() override
  1513. {
  1514. CARLA_SAFE_ASSERT_RETURN(fUI.window != nullptr,);
  1515. carla_debug("CarlaPluginVST2::handlePluginUIClosed()");
  1516. showCustomUI(false);
  1517. pData->engine->callback(true, true,
  1518. ENGINE_CALLBACK_UI_STATE_CHANGED,
  1519. pData->id,
  1520. 0,
  1521. 0, 0, 0.0f, nullptr);
  1522. }
  1523. void handlePluginUIResized(const uint width, const uint height) override
  1524. {
  1525. CARLA_SAFE_ASSERT_RETURN(fUI.window != nullptr,);
  1526. carla_debug("CarlaPluginVST2::handlePluginUIResized(%u, %u)", width, height);
  1527. return; // unused
  1528. (void)width; (void)height;
  1529. }
  1530. // -------------------------------------------------------------------
  1531. intptr_t dispatcher(int32_t opcode, int32_t index = 0, intptr_t value = 0, void* ptr = nullptr, float opt = 0.0f) const noexcept
  1532. {
  1533. CARLA_SAFE_ASSERT_RETURN(fEffect != nullptr, 0);
  1534. #ifdef DEBUG
  1535. if (opcode != effIdle && opcode != effEditIdle && opcode != effProcessEvents)
  1536. carla_debug("CarlaPluginVST2::dispatcher(%02i:%s, %i, " P_INTPTR ", %p, %f)",
  1537. opcode, vstEffectOpcode2str(opcode), index, value, ptr, static_cast<double>(opt));
  1538. #endif
  1539. try {
  1540. return fEffect->dispatcher(fEffect, opcode, index, value, ptr, opt);
  1541. } CARLA_SAFE_EXCEPTION_RETURN("Vst dispatcher", 0);
  1542. }
  1543. intptr_t handleAudioMasterCallback(const int32_t opcode, const int32_t index, const intptr_t value, void* const ptr, const float opt)
  1544. {
  1545. #ifdef DEBUG
  1546. if (opcode != audioMasterGetTime)
  1547. carla_debug("CarlaPluginVST2::handleAudioMasterCallback(%02i:%s, %i, " P_INTPTR ", %p, %f)",
  1548. opcode, vstMasterOpcode2str(opcode), index, value, ptr, static_cast<double>(opt));
  1549. #endif
  1550. intptr_t ret = 0;
  1551. switch (opcode)
  1552. {
  1553. case audioMasterAutomate: {
  1554. if (fIsInitializing) {
  1555. // some plugins can be stupid...
  1556. if (pData->param.count == 0)
  1557. break;
  1558. } else {
  1559. CARLA_SAFE_ASSERT_BREAK(pData->enabled);
  1560. }
  1561. // plugins should never do this:
  1562. CARLA_SAFE_ASSERT_INT2_BREAK(index >= 0 && index < static_cast<int32_t>(pData->param.count),
  1563. index,
  1564. static_cast<int32_t>(pData->param.count));
  1565. const uint32_t uindex(static_cast<uint32_t>(index));
  1566. const float fixedValue(pData->param.getFixedValue(uindex, opt));
  1567. const pthread_t thisThread = pthread_self();
  1568. if (pthread_equal(thisThread, kNullThread))
  1569. {
  1570. carla_stderr("audioMasterAutomate called with null thread!?");
  1571. setParameterValue(uindex, fixedValue, false, true, true);
  1572. }
  1573. // Called from plugin process thread, nasty! (likely MIDI learn)
  1574. else if (pthread_equal(thisThread, fProcThread))
  1575. {
  1576. CARLA_SAFE_ASSERT(fIsProcessing);
  1577. pData->postponeRtEvent(kPluginPostRtEventParameterChange, true, index, 0, 0, fixedValue);
  1578. }
  1579. // Called from effSetChunk or effSetProgram
  1580. else if (pthread_equal(thisThread, fChangingValuesThread))
  1581. {
  1582. carla_debug("audioMasterAutomate called while setting state");
  1583. pData->postponeRtEvent(kPluginPostRtEventParameterChange, true, index, 0, 0, fixedValue);
  1584. }
  1585. // Called from effIdle
  1586. else if (pthread_equal(thisThread, fIdleThread))
  1587. {
  1588. carla_debug("audioMasterAutomate called from idle thread");
  1589. pData->postponeRtEvent(kPluginPostRtEventParameterChange, true, index, 0, 0, fixedValue);
  1590. }
  1591. // Called from UI?
  1592. else if (fUI.isVisible)
  1593. {
  1594. carla_debug("audioMasterAutomate called while UI visible");
  1595. CarlaPlugin::setParameterValue(uindex, fixedValue, false, true, true);
  1596. }
  1597. // Unknown
  1598. else
  1599. {
  1600. carla_stdout("audioMasterAutomate called from unknown source");
  1601. setParameterValue(uindex, fixedValue, false, true, true);
  1602. }
  1603. break;
  1604. }
  1605. case audioMasterCurrentId:
  1606. if (fEffect != nullptr)
  1607. ret = fEffect->uniqueID;
  1608. break;
  1609. case audioMasterIdle:
  1610. CARLA_SAFE_ASSERT_BREAK(pthread_equal(pthread_self(), fMainThread));
  1611. pData->engine->callback(true, false, ENGINE_CALLBACK_IDLE, 0, 0, 0, 0, 0.0f, nullptr);
  1612. if (pData->engine->getType() != kEngineTypePlugin)
  1613. pData->engine->idle();
  1614. break;
  1615. #if ! VST_FORCE_DEPRECATED
  1616. case audioMasterPinConnected:
  1617. // Deprecated in VST SDK 2.4
  1618. // TODO
  1619. break;
  1620. case audioMasterWantMidi:
  1621. // Deprecated in VST SDK 2.4
  1622. pData->hints |= PLUGIN_WANTS_MIDI_INPUT;
  1623. break;
  1624. #endif
  1625. case audioMasterGetTime:
  1626. ret = (intptr_t)&fTimeInfo;
  1627. break;
  1628. case audioMasterProcessEvents:
  1629. CARLA_SAFE_ASSERT_RETURN(pData->enabled, 0);
  1630. CARLA_SAFE_ASSERT_RETURN(fIsProcessing, 0);
  1631. CARLA_SAFE_ASSERT_RETURN(pData->event.portOut != nullptr, 0);
  1632. if (fMidiEventCount >= kPluginMaxMidiEvents*2-1)
  1633. return 0;
  1634. if (const VstEvents* const vstEvents = (const VstEvents*)ptr)
  1635. {
  1636. for (int32_t i=0; i < vstEvents->numEvents && i < kPluginMaxMidiEvents*2; ++i)
  1637. {
  1638. if (vstEvents->events[i] == nullptr)
  1639. break;
  1640. const VstMidiEvent* const vstMidiEvent((const VstMidiEvent*)vstEvents->events[i]);
  1641. if (vstMidiEvent->type != kVstMidiType)
  1642. continue;
  1643. // reverse-find first free event, and put it there
  1644. for (uint32_t j=(kPluginMaxMidiEvents*2)-1; j >= fMidiEventCount; --j)
  1645. {
  1646. if (fMidiEvents[j].type == 0)
  1647. {
  1648. std::memcpy(&fMidiEvents[j], vstMidiEvent, sizeof(VstMidiEvent));
  1649. break;
  1650. }
  1651. }
  1652. }
  1653. }
  1654. ret = 1;
  1655. break;
  1656. #if ! VST_FORCE_DEPRECATED
  1657. case audioMasterSetTime:
  1658. // Deprecated in VST SDK 2.4
  1659. break;
  1660. case audioMasterTempoAt:
  1661. // Deprecated in VST SDK 2.4
  1662. ret = static_cast<intptr_t>(fTimeInfo.tempo * 10000);
  1663. break;
  1664. case audioMasterGetNumAutomatableParameters:
  1665. // Deprecated in VST SDK 2.4
  1666. ret = static_cast<intptr_t>(pData->engine->getOptions().maxParameters);
  1667. ret = carla_minPositive<intptr_t>(ret, fEffect->numParams);
  1668. break;
  1669. case audioMasterGetParameterQuantization:
  1670. // Deprecated in VST SDK 2.4
  1671. ret = 1; // full single float precision
  1672. break;
  1673. #endif
  1674. #if 0
  1675. case audioMasterIOChanged:
  1676. CARLA_ASSERT(pData->enabled);
  1677. // TESTING
  1678. if (! pData->enabled)
  1679. {
  1680. ret = 1;
  1681. break;
  1682. }
  1683. if (x_engine->getOptions().processMode == PROCESS_MODE_CONTINUOUS_RACK)
  1684. {
  1685. carla_stderr2("CarlaPluginVST2::handleAudioMasterIOChanged() - plugin asked IO change, but it's not supported in rack mode");
  1686. return 0;
  1687. }
  1688. engineProcessLock();
  1689. m_enabled = false;
  1690. engineProcessUnlock();
  1691. if (m_active)
  1692. {
  1693. effect->dispatcher(effect, effStopProcess);
  1694. effect->dispatcher(effect, effMainsChanged, 0, 0);
  1695. }
  1696. reload();
  1697. if (m_active)
  1698. {
  1699. effect->dispatcher(effect, effMainsChanged, 0, 1, nullptr, 0.0f);
  1700. effect->dispatcher(effect, effStartProcess);
  1701. }
  1702. x_engine->callback(CALLBACK_RELOAD_ALL, m_id, 0, 0, 0, 0.0, nullptr);
  1703. ret = 1;
  1704. break;
  1705. #endif
  1706. #if ! VST_FORCE_DEPRECATED
  1707. case audioMasterNeedIdle:
  1708. // Deprecated in VST SDK 2.4
  1709. fNeedIdle = true;
  1710. ret = 1;
  1711. break;
  1712. #endif
  1713. case audioMasterSizeWindow:
  1714. CARLA_SAFE_ASSERT_BREAK(fUI.window != nullptr);
  1715. CARLA_SAFE_ASSERT_BREAK(index > 0);
  1716. CARLA_SAFE_ASSERT_BREAK(value > 0);
  1717. fUI.window->setSize(static_cast<uint>(index), static_cast<uint>(value), true);
  1718. ret = 1;
  1719. break;
  1720. case audioMasterGetSampleRate:
  1721. ret = static_cast<intptr_t>(pData->engine->getSampleRate());
  1722. break;
  1723. case audioMasterGetBlockSize:
  1724. ret = static_cast<intptr_t>(pData->engine->getBufferSize());
  1725. break;
  1726. case audioMasterGetInputLatency:
  1727. ret = 0;
  1728. break;
  1729. case audioMasterGetOutputLatency:
  1730. ret = 0;
  1731. break;
  1732. #if ! VST_FORCE_DEPRECATED
  1733. case audioMasterGetPreviousPlug:
  1734. // Deprecated in VST SDK 2.4
  1735. // TODO
  1736. break;
  1737. case audioMasterGetNextPlug:
  1738. // Deprecated in VST SDK 2.4
  1739. // TODO
  1740. break;
  1741. case audioMasterWillReplaceOrAccumulate:
  1742. // Deprecated in VST SDK 2.4
  1743. ret = 1; // replace
  1744. break;
  1745. #endif
  1746. case audioMasterGetCurrentProcessLevel:
  1747. if (pthread_equal(pthread_self(), fProcThread))
  1748. {
  1749. CARLA_SAFE_ASSERT(fIsProcessing);
  1750. if (pData->engine->isOffline())
  1751. ret = kVstProcessLevelOffline;
  1752. else
  1753. ret = kVstProcessLevelRealtime;
  1754. }
  1755. else
  1756. {
  1757. ret = kVstProcessLevelUser;
  1758. }
  1759. break;
  1760. case audioMasterGetAutomationState:
  1761. ret = pData->active ? kVstAutomationReadWrite : kVstAutomationOff;
  1762. break;
  1763. case audioMasterOfflineStart:
  1764. case audioMasterOfflineRead:
  1765. case audioMasterOfflineWrite:
  1766. case audioMasterOfflineGetCurrentPass:
  1767. case audioMasterOfflineGetCurrentMetaPass:
  1768. // TODO
  1769. break;
  1770. #if ! VST_FORCE_DEPRECATED
  1771. case audioMasterSetOutputSampleRate:
  1772. // Deprecated in VST SDK 2.4
  1773. break;
  1774. case audioMasterGetOutputSpeakerArrangement:
  1775. // Deprecated in VST SDK 2.4
  1776. // TODO
  1777. break;
  1778. #endif
  1779. case audioMasterVendorSpecific:
  1780. // TODO - cockos extensions
  1781. break;
  1782. #if ! VST_FORCE_DEPRECATED
  1783. case audioMasterSetIcon:
  1784. // Deprecated in VST SDK 2.4
  1785. break;
  1786. #endif
  1787. #if ! VST_FORCE_DEPRECATED
  1788. case audioMasterOpenWindow:
  1789. case audioMasterCloseWindow:
  1790. // Deprecated in VST SDK 2.4
  1791. // TODO
  1792. break;
  1793. #endif
  1794. case audioMasterGetDirectory:
  1795. // TODO
  1796. break;
  1797. case audioMasterUpdateDisplay:
  1798. // Update current program
  1799. if (pData->prog.count > 1)
  1800. {
  1801. const int32_t current = static_cast<int32_t>(dispatcher(effGetProgram));
  1802. if (current >= 0 && current < static_cast<int32_t>(pData->prog.count))
  1803. {
  1804. char strBuf[STR_MAX+1] = { '\0' };
  1805. dispatcher(effGetProgramName, 0, 0, strBuf);
  1806. if (pData->prog.names[current] != nullptr)
  1807. delete[] pData->prog.names[current];
  1808. pData->prog.names[current] = carla_strdup(strBuf);
  1809. if (pData->prog.current != current)
  1810. {
  1811. pData->prog.current = current;
  1812. pData->engine->callback(true, true,
  1813. ENGINE_CALLBACK_PROGRAM_CHANGED,
  1814. pData->id,
  1815. current,
  1816. 0, 0, 0.0f, nullptr);
  1817. }
  1818. }
  1819. }
  1820. if (! fIsInitializing)
  1821. pData->engine->callback(true, true,
  1822. ENGINE_CALLBACK_RELOAD_PARAMETERS, pData->id, 0, 0, 0, 0.0f, nullptr);
  1823. ret = 1;
  1824. break;
  1825. case audioMasterBeginEdit:
  1826. CARLA_SAFE_ASSERT_BREAK(index >= 0);
  1827. pData->engine->touchPluginParameter(pData->id, static_cast<uint32_t>(index), true);
  1828. break;
  1829. case audioMasterEndEdit:
  1830. CARLA_SAFE_ASSERT_BREAK(index >= 0);
  1831. pData->engine->touchPluginParameter(pData->id, static_cast<uint32_t>(index), false);
  1832. break;
  1833. case audioMasterOpenFileSelector:
  1834. case audioMasterCloseFileSelector:
  1835. // TODO
  1836. break;
  1837. #if ! VST_FORCE_DEPRECATED
  1838. case audioMasterEditFile:
  1839. // Deprecated in VST SDK 2.4
  1840. // TODO
  1841. break;
  1842. case audioMasterGetChunkFile:
  1843. // Deprecated in VST SDK 2.4
  1844. // TODO
  1845. break;
  1846. case audioMasterGetInputSpeakerArrangement:
  1847. // Deprecated in VST SDK 2.4
  1848. // TODO
  1849. break;
  1850. #endif
  1851. default:
  1852. carla_debug("CarlaPluginVST2::handleAudioMasterCallback(%02i:%s, %i, " P_INTPTR ", %p, %f) UNDEF",
  1853. opcode, vstMasterOpcode2str(opcode), index, value, ptr, static_cast<double>(opt));
  1854. break;
  1855. }
  1856. return ret;
  1857. // unused
  1858. (void)opt;
  1859. }
  1860. bool canDo(const char* const feature) const noexcept
  1861. {
  1862. try {
  1863. return (dispatcher(effCanDo, 0, 0, const_cast<char*>(feature)) == 1);
  1864. } CARLA_SAFE_EXCEPTION_RETURN("vstPluginCanDo", false);
  1865. }
  1866. bool hasMidiInput() const noexcept
  1867. {
  1868. return (fEffect->flags & effFlagsIsSynth) != 0 ||
  1869. (pData->hints & PLUGIN_WANTS_MIDI_INPUT) != 0 ||
  1870. canDo("receiveVstEvents") || canDo("receiveVstMidiEvent");
  1871. }
  1872. bool hasMidiOutput() const noexcept
  1873. {
  1874. return canDo("sendVstEvents") || canDo("sendVstMidiEvent");
  1875. }
  1876. // -------------------------------------------------------------------
  1877. const void* getNativeDescriptor() const noexcept override
  1878. {
  1879. return fEffect;
  1880. }
  1881. // -------------------------------------------------------------------
  1882. public:
  1883. bool init(const char* const filename, const char* const name, const int64_t uniqueId, const uint options)
  1884. {
  1885. CARLA_SAFE_ASSERT_RETURN(pData->engine != nullptr, false);
  1886. // ---------------------------------------------------------------
  1887. // first checks
  1888. if (pData->client != nullptr)
  1889. {
  1890. pData->engine->setLastError("Plugin client is already registered");
  1891. return false;
  1892. }
  1893. if (filename == nullptr || filename[0] == '\0')
  1894. {
  1895. pData->engine->setLastError("null filename");
  1896. return false;
  1897. }
  1898. // ---------------------------------------------------------------
  1899. VST_Function vstFn;
  1900. #ifdef CARLA_OS_MAC
  1901. CarlaString filenameCheck(filename);
  1902. filenameCheck.toLower();
  1903. if (filenameCheck.endsWith(".vst") || filenameCheck.endsWith(".vst/"))
  1904. {
  1905. // FIXME assert returns, set engine error
  1906. const CFURLRef urlRef = CFURLCreateFromFileSystemRepresentation(0, (const UInt8*)filename, (CFIndex)strlen(filename), true);
  1907. CARLA_SAFE_ASSERT_RETURN(urlRef != nullptr, false);
  1908. fMacBundleRef = CFBundleCreate(kCFAllocatorDefault, urlRef);
  1909. CFRelease(urlRef);
  1910. CARLA_SAFE_ASSERT_RETURN(fMacBundleRef != nullptr, false);
  1911. if (! CFBundleLoadExecutable(fMacBundleRef))
  1912. {
  1913. CFRelease(fMacBundleRef);
  1914. pData->engine->setLastError("Failed to load VST bundle executable");
  1915. return false;
  1916. }
  1917. vstFn = (VST_Function)CFBundleGetFunctionPointerForName(fMacBundleRef, CFSTR("main_macho"));
  1918. if (vstFn == nullptr)
  1919. vstFn = (VST_Function)CFBundleGetFunctionPointerForName(fMacBundleRef, CFSTR("VSTPluginMain"));
  1920. if (vstFn == nullptr)
  1921. {
  1922. CFBundleUnloadExecutable(fMacBundleRef);
  1923. CFRelease(fMacBundleRef);
  1924. pData->engine->setLastError("Not a VST plugin");
  1925. return false;
  1926. }
  1927. fMacBundleRefNum = CFBundleOpenBundleResourceMap(fMacBundleRef);
  1928. }
  1929. else
  1930. #endif
  1931. {
  1932. // -----------------------------------------------------------
  1933. // open DLL
  1934. if (! pData->libOpen(filename))
  1935. {
  1936. pData->engine->setLastError(pData->libError(filename));
  1937. return false;
  1938. }
  1939. // -----------------------------------------------------------
  1940. // get DLL main entry
  1941. vstFn = pData->libSymbol<VST_Function>("VSTPluginMain");
  1942. if (vstFn == nullptr)
  1943. {
  1944. vstFn = pData->libSymbol<VST_Function>("main");
  1945. if (vstFn == nullptr)
  1946. {
  1947. pData->engine->setLastError("Could not find the VST main entry in the plugin library");
  1948. return false;
  1949. }
  1950. }
  1951. }
  1952. // ---------------------------------------------------------------
  1953. // initialize plugin (part 1)
  1954. sCurrentUniqueId = static_cast<intptr_t>(uniqueId);
  1955. sLastCarlaPluginVST2 = this;
  1956. try {
  1957. fEffect = vstFn(carla_vst_audioMasterCallback);
  1958. } CARLA_SAFE_EXCEPTION_RETURN("Vst init", false);
  1959. sLastCarlaPluginVST2 = nullptr;
  1960. sCurrentUniqueId = 0;
  1961. if (fEffect == nullptr)
  1962. {
  1963. pData->engine->setLastError("Plugin failed to initialize");
  1964. return false;
  1965. }
  1966. if (fEffect->magic != kEffectMagic)
  1967. {
  1968. pData->engine->setLastError("Plugin is not valid (wrong vst effect magic code)");
  1969. return false;
  1970. }
  1971. fEffect->ptr1 = this;
  1972. const int32_t iBufferSize = static_cast<int32_t>(fBufferSize);
  1973. const float fSampleRate = static_cast<float>(pData->engine->getSampleRate());
  1974. dispatcher(effIdentify);
  1975. dispatcher(effSetProcessPrecision, 0, kVstProcessPrecision32);
  1976. dispatcher(effSetBlockSizeAndSampleRate, 0, iBufferSize, nullptr, fSampleRate);
  1977. dispatcher(effSetSampleRate, 0, 0, nullptr, fSampleRate);
  1978. dispatcher(effSetBlockSize, 0, iBufferSize);
  1979. dispatcher(effOpen);
  1980. const bool isShell = (dispatcher(effGetPlugCategory) == kPlugCategShell);
  1981. if (uniqueId == 0 && isShell)
  1982. {
  1983. char strBuf[STR_MAX+1];
  1984. carla_zeroChars(strBuf, STR_MAX+1);
  1985. sCurrentUniqueId = dispatcher(effShellGetNextPlugin, 0, 0, strBuf);
  1986. dispatcher(effClose);
  1987. fEffect = nullptr;
  1988. sLastCarlaPluginVST2 = this;
  1989. try {
  1990. fEffect = vstFn(carla_vst_audioMasterCallback);
  1991. } CARLA_SAFE_EXCEPTION_RETURN("Vst init", false);
  1992. sLastCarlaPluginVST2 = nullptr;
  1993. sCurrentUniqueId = 0;
  1994. dispatcher(effIdentify);
  1995. dispatcher(effSetProcessPrecision, 0, kVstProcessPrecision32);
  1996. dispatcher(effSetBlockSizeAndSampleRate, 0, iBufferSize, nullptr, fSampleRate);
  1997. dispatcher(effSetSampleRate, 0, 0, nullptr, fSampleRate);
  1998. dispatcher(effSetBlockSize, 0, iBufferSize);
  1999. dispatcher(effOpen);
  2000. }
  2001. if (fEffect->uniqueID == 0 && !isShell)
  2002. {
  2003. dispatcher(effClose);
  2004. fEffect = nullptr;
  2005. pData->engine->setLastError("Plugin is not valid (no unique ID after being open)");
  2006. return false;
  2007. }
  2008. // ---------------------------------------------------------------
  2009. // get info
  2010. if (name != nullptr && name[0] != '\0')
  2011. {
  2012. pData->name = pData->engine->getUniquePluginName(name);
  2013. }
  2014. else
  2015. {
  2016. char strBuf[STR_MAX+1];
  2017. carla_zeroChars(strBuf, STR_MAX+1);
  2018. dispatcher(effGetEffectName, 0, 0, strBuf);
  2019. if (strBuf[0] != '\0')
  2020. pData->name = pData->engine->getUniquePluginName(strBuf);
  2021. else if (const char* const shortname = std::strrchr(filename, CARLA_OS_SEP))
  2022. pData->name = pData->engine->getUniquePluginName(shortname+1);
  2023. else
  2024. pData->name = pData->engine->getUniquePluginName("unknown");
  2025. }
  2026. pData->filename = carla_strdup(filename);
  2027. // ---------------------------------------------------------------
  2028. // register client
  2029. pData->client = pData->engine->addClient(this);
  2030. if (pData->client == nullptr || ! pData->client->isOk())
  2031. {
  2032. pData->engine->setLastError("Failed to register plugin client");
  2033. return false;
  2034. }
  2035. // ---------------------------------------------------------------
  2036. // initialize plugin (part 2)
  2037. for (int i = fEffect->numInputs; --i >= 0;) dispatcher(effConnectInput, i, 1);
  2038. for (int i = fEffect->numOutputs; --i >= 0;) dispatcher(effConnectOutput, i, 1);
  2039. if (dispatcher(effGetVstVersion) < kVstVersion)
  2040. pData->hints |= PLUGIN_USES_OLD_VSTSDK;
  2041. static const char kHasCockosExtensions[] = "hasCockosExtensions";
  2042. if (static_cast<uintptr_t>(dispatcher(effCanDo, 0, 0, const_cast<char*>(kHasCockosExtensions))) == 0xbeef0000)
  2043. pData->hints |= PLUGIN_HAS_COCKOS_EXTENSIONS;
  2044. // ---------------------------------------------------------------
  2045. // set default options
  2046. pData->options = 0x0;
  2047. if (pData->latency.frames != 0 || hasMidiOutput() || isPluginOptionEnabled(options, PLUGIN_OPTION_FIXED_BUFFERS))
  2048. pData->options |= PLUGIN_OPTION_FIXED_BUFFERS;
  2049. if (fEffect->flags & effFlagsProgramChunks)
  2050. if (isPluginOptionEnabled(options, PLUGIN_OPTION_USE_CHUNKS))
  2051. pData->options |= PLUGIN_OPTION_USE_CHUNKS;
  2052. if (hasMidiInput())
  2053. {
  2054. if (isPluginOptionEnabled(options, PLUGIN_OPTION_SEND_CONTROL_CHANGES))
  2055. pData->options |= PLUGIN_OPTION_SEND_CONTROL_CHANGES;
  2056. if (isPluginOptionEnabled(options, PLUGIN_OPTION_SEND_CHANNEL_PRESSURE))
  2057. pData->options |= PLUGIN_OPTION_SEND_CHANNEL_PRESSURE;
  2058. if (isPluginOptionEnabled(options, PLUGIN_OPTION_SEND_NOTE_AFTERTOUCH))
  2059. pData->options |= PLUGIN_OPTION_SEND_NOTE_AFTERTOUCH;
  2060. if (isPluginOptionEnabled(options, PLUGIN_OPTION_SEND_PITCHBEND))
  2061. pData->options |= PLUGIN_OPTION_SEND_PITCHBEND;
  2062. if (isPluginOptionEnabled(options, PLUGIN_OPTION_SEND_ALL_SOUND_OFF))
  2063. pData->options |= PLUGIN_OPTION_SEND_ALL_SOUND_OFF;
  2064. if (isPluginOptionEnabled(options, PLUGIN_OPTION_SEND_PROGRAM_CHANGES))
  2065. pData->options |= PLUGIN_OPTION_SEND_PROGRAM_CHANGES;
  2066. }
  2067. if (fEffect->numPrograms > 1 && (pData->options & PLUGIN_OPTION_SEND_PROGRAM_CHANGES) == 0)
  2068. if (isPluginOptionEnabled(options, PLUGIN_OPTION_MAP_PROGRAM_CHANGES))
  2069. pData->options |= PLUGIN_OPTION_MAP_PROGRAM_CHANGES;
  2070. return true;
  2071. }
  2072. private:
  2073. int fUnique1;
  2074. AEffect* fEffect;
  2075. uint32_t fMidiEventCount;
  2076. VstMidiEvent fMidiEvents[kPluginMaxMidiEvents*2];
  2077. VstTimeInfo fTimeInfo;
  2078. bool fNeedIdle;
  2079. void* fLastChunk;
  2080. bool fIsInitializing;
  2081. bool fIsProcessing;
  2082. pthread_t fChangingValuesThread;
  2083. pthread_t fIdleThread;
  2084. pthread_t fMainThread;
  2085. pthread_t fProcThread;
  2086. #ifdef CARLA_OS_MAC
  2087. CFBundleRef fMacBundleRef;
  2088. CFBundleRefNum fMacBundleRefNum;
  2089. #endif
  2090. bool fFirstActive; // first process() call after activate()
  2091. uint32_t fBufferSize;
  2092. float** fAudioOutBuffers;
  2093. EngineTimeInfo fLastTimeInfo;
  2094. struct FixedVstEvents {
  2095. int32_t numEvents;
  2096. intptr_t reserved;
  2097. VstEvent* data[kPluginMaxMidiEvents*2];
  2098. FixedVstEvents() noexcept
  2099. : numEvents(0),
  2100. reserved(0)
  2101. {
  2102. carla_zeroPointers(data, kPluginMaxMidiEvents*2);
  2103. }
  2104. CARLA_DECLARE_NON_COPY_STRUCT(FixedVstEvents);
  2105. } fEvents;
  2106. struct UI {
  2107. bool isOpen;
  2108. bool isVisible;
  2109. CarlaPluginUI* window;
  2110. UI() noexcept
  2111. : isOpen(false),
  2112. isVisible(false),
  2113. window(nullptr) {}
  2114. ~UI()
  2115. {
  2116. CARLA_ASSERT(! isVisible);
  2117. if (window != nullptr)
  2118. {
  2119. delete window;
  2120. window = nullptr;
  2121. }
  2122. }
  2123. CARLA_DECLARE_NON_COPY_STRUCT(UI);
  2124. } fUI;
  2125. int fUnique2;
  2126. static intptr_t sCurrentUniqueId;
  2127. static CarlaPluginVST2* sLastCarlaPluginVST2;
  2128. // -------------------------------------------------------------------
  2129. static bool compareMagic(int32_t magic, const char* name) noexcept
  2130. {
  2131. return magic == (int32_t)ByteOrder::littleEndianInt (name)
  2132. || magic == (int32_t)ByteOrder::bigEndianInt (name);
  2133. }
  2134. static int32_t fxbSwap(const int32_t x) noexcept
  2135. {
  2136. return (int32_t)ByteOrder::swapIfLittleEndian ((uint32_t) x);
  2137. }
  2138. bool loadJuceSaveFormat(const void* const data, const std::size_t dataSize)
  2139. {
  2140. if (dataSize < 28)
  2141. return false;
  2142. const int32_t* const set = (const int32_t*)data;
  2143. if (set[1] != 0)
  2144. return false;
  2145. if (! compareMagic(set[0], "CcnK"))
  2146. return false;
  2147. if (! compareMagic(set[2], "FBCh") && ! compareMagic(set[2], "FJuc"))
  2148. return false;
  2149. if (fxbSwap(set[3]) > 1)
  2150. return false;
  2151. const int32_t chunkSize = fxbSwap(set[39]);
  2152. CARLA_SAFE_ASSERT_RETURN(chunkSize > 0, false);
  2153. if (static_cast<std::size_t>(chunkSize + 160) > dataSize)
  2154. return false;
  2155. carla_stdout("NOTE: Loading plugin state in VST2/JUCE compatibility mode");
  2156. setChunkData(&set[40], static_cast<std::size_t>(chunkSize));
  2157. return true;
  2158. }
  2159. static intptr_t carla_vst_hostCanDo(const char* const feature)
  2160. {
  2161. carla_debug("carla_vst_hostCanDo(\"%s\")", feature);
  2162. if (std::strcmp(feature, "supplyIdle") == 0)
  2163. return 1;
  2164. if (std::strcmp(feature, "sendVstEvents") == 0)
  2165. return 1;
  2166. if (std::strcmp(feature, "sendVstMidiEvent") == 0)
  2167. return 1;
  2168. if (std::strcmp(feature, "sendVstMidiEventFlagIsRealtime") == 0)
  2169. return 1;
  2170. if (std::strcmp(feature, "sendVstTimeInfo") == 0)
  2171. return 1;
  2172. if (std::strcmp(feature, "receiveVstEvents") == 0)
  2173. return 1;
  2174. if (std::strcmp(feature, "receiveVstMidiEvent") == 0)
  2175. return 1;
  2176. if (std::strcmp(feature, "receiveVstTimeInfo") == 0)
  2177. return -1;
  2178. if (std::strcmp(feature, "reportConnectionChanges") == 0)
  2179. return -1;
  2180. if (std::strcmp(feature, "acceptIOChanges") == 0)
  2181. return 1;
  2182. if (std::strcmp(feature, "sizeWindow") == 0)
  2183. return 1;
  2184. if (std::strcmp(feature, "offline") == 0)
  2185. return -1;
  2186. if (std::strcmp(feature, "openFileSelector") == 0)
  2187. return -1;
  2188. if (std::strcmp(feature, "closeFileSelector") == 0)
  2189. return -1;
  2190. if (std::strcmp(feature, "startStopProcess") == 0)
  2191. return 1;
  2192. if (std::strcmp(feature, "supportShell") == 0)
  2193. return 1;
  2194. if (std::strcmp(feature, "shellCategory") == 0)
  2195. return 1;
  2196. if (std::strcmp(feature, "NIMKPIVendorSpecificCallbacks") == 0)
  2197. return -1;
  2198. // unimplemented
  2199. carla_stderr("carla_vst_hostCanDo(\"%s\") - unknown feature", feature);
  2200. return 0;
  2201. }
  2202. static intptr_t VSTCALLBACK carla_vst_audioMasterCallback(AEffect* effect, int32_t opcode, int32_t index, intptr_t value, void* ptr, float opt)
  2203. {
  2204. #if defined(DEBUG) && ! defined(CARLA_OS_WIN)
  2205. if (opcode != audioMasterGetTime && opcode != audioMasterProcessEvents && opcode != audioMasterGetCurrentProcessLevel && opcode != audioMasterGetOutputLatency)
  2206. carla_debug("carla_vst_audioMasterCallback(%p, %02i:%s, %i, " P_INTPTR ", %p, %f)",
  2207. effect, opcode, vstMasterOpcode2str(opcode), index, value, ptr, static_cast<double>(opt));
  2208. #endif
  2209. switch (opcode)
  2210. {
  2211. case audioMasterVersion:
  2212. return kVstVersion;
  2213. case audioMasterCurrentId:
  2214. if (sCurrentUniqueId != 0)
  2215. return sCurrentUniqueId;
  2216. break;
  2217. case audioMasterGetVendorString:
  2218. CARLA_SAFE_ASSERT_RETURN(ptr != nullptr, 0);
  2219. std::strcpy((char*)ptr, "falkTX");
  2220. return 1;
  2221. case audioMasterGetProductString:
  2222. CARLA_SAFE_ASSERT_RETURN(ptr != nullptr, 0);
  2223. std::strcpy((char*)ptr, "Carla");
  2224. return 1;
  2225. case audioMasterGetVendorVersion:
  2226. return CARLA_VERSION_HEX;
  2227. case audioMasterCanDo:
  2228. CARLA_SAFE_ASSERT_RETURN(ptr != nullptr, 0);
  2229. return carla_vst_hostCanDo((const char*)ptr);
  2230. case audioMasterGetLanguage:
  2231. return kVstLangEnglish;
  2232. }
  2233. // Check if 'resvd1' points to us, otherwise register ourselves if possible
  2234. CarlaPluginVST2* self = nullptr;
  2235. if (effect != nullptr)
  2236. {
  2237. if (effect->ptr1 != nullptr)
  2238. {
  2239. self = (CarlaPluginVST2*)effect->ptr1;
  2240. if (self->fUnique1 != self->fUnique2)
  2241. self = nullptr;
  2242. }
  2243. if (self != nullptr)
  2244. {
  2245. if (self->fEffect == nullptr)
  2246. self->fEffect = effect;
  2247. if (self->fEffect != effect)
  2248. {
  2249. carla_stderr2("carla_vst_audioMasterCallback() - host pointer mismatch: %p != %p", self->fEffect, effect);
  2250. self = nullptr;
  2251. }
  2252. }
  2253. else if (sLastCarlaPluginVST2 != nullptr)
  2254. {
  2255. effect->ptr1 = sLastCarlaPluginVST2;
  2256. self = sLastCarlaPluginVST2;
  2257. }
  2258. }
  2259. return (self != nullptr) ? self->handleAudioMasterCallback(opcode, index, value, ptr, opt) : 0;
  2260. }
  2261. CARLA_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(CarlaPluginVST2)
  2262. };
  2263. intptr_t CarlaPluginVST2::sCurrentUniqueId = 0;
  2264. CarlaPluginVST2* CarlaPluginVST2::sLastCarlaPluginVST2 = nullptr;
  2265. CARLA_BACKEND_END_NAMESPACE
  2266. // -------------------------------------------------------------------------------------------------------------------
  2267. CARLA_BACKEND_START_NAMESPACE
  2268. CarlaPlugin* CarlaPlugin::newVST2(const Initializer& init)
  2269. {
  2270. carla_debug("CarlaPlugin::newVST2({%p, \"%s\", \"%s\", " P_INT64 "})", init.engine, init.filename, init.name, init.uniqueId);
  2271. #ifdef USE_JUCE_FOR_VST2
  2272. if (std::getenv("CARLA_DO_NOT_USE_JUCE_FOR_VST2") == nullptr)
  2273. return newJuce(init, "VST2");
  2274. #endif
  2275. CarlaPluginVST2* const plugin(new CarlaPluginVST2(init.engine, init.id));
  2276. if (! plugin->init(init.filename, init.name, init.uniqueId, init.options))
  2277. {
  2278. delete plugin;
  2279. return nullptr;
  2280. }
  2281. return plugin;
  2282. }
  2283. // -------------------------------------------------------------------------------------------------------------------
  2284. CARLA_BACKEND_END_NAMESPACE