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.

2857 lines
99KB

  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 main thread, why?
  1592. else if (pthread_equal(thisThread, fMainThread))
  1593. {
  1594. if (fFirstActive) {
  1595. carla_stdout("audioMasterAutomate called while loading, nasty!");
  1596. } else {
  1597. carla_debug("audioMasterAutomate called from main thread");
  1598. }
  1599. CarlaPlugin::setParameterValue(uindex, fixedValue, false, true, true);
  1600. }
  1601. // Called from UI?
  1602. else if (fUI.isVisible)
  1603. {
  1604. carla_debug("audioMasterAutomate called while UI visible");
  1605. CarlaPlugin::setParameterValue(uindex, fixedValue, false, true, true);
  1606. }
  1607. // Unknown
  1608. else
  1609. {
  1610. carla_stdout("audioMasterAutomate called from unknown source");
  1611. setParameterValue(uindex, fixedValue, false, true, true);
  1612. }
  1613. break;
  1614. }
  1615. case audioMasterCurrentId:
  1616. if (fEffect != nullptr)
  1617. ret = fEffect->uniqueID;
  1618. break;
  1619. case audioMasterIdle:
  1620. CARLA_SAFE_ASSERT_BREAK(pthread_equal(pthread_self(), fMainThread));
  1621. pData->engine->callback(true, false, ENGINE_CALLBACK_IDLE, 0, 0, 0, 0, 0.0f, nullptr);
  1622. if (pData->engine->getType() != kEngineTypePlugin)
  1623. pData->engine->idle();
  1624. break;
  1625. #if ! VST_FORCE_DEPRECATED
  1626. case audioMasterPinConnected:
  1627. // Deprecated in VST SDK 2.4
  1628. // TODO
  1629. break;
  1630. case audioMasterWantMidi:
  1631. // Deprecated in VST SDK 2.4
  1632. pData->hints |= PLUGIN_WANTS_MIDI_INPUT;
  1633. break;
  1634. #endif
  1635. case audioMasterGetTime:
  1636. ret = (intptr_t)&fTimeInfo;
  1637. break;
  1638. case audioMasterProcessEvents:
  1639. CARLA_SAFE_ASSERT_RETURN(pData->enabled, 0);
  1640. CARLA_SAFE_ASSERT_RETURN(fIsProcessing, 0);
  1641. CARLA_SAFE_ASSERT_RETURN(pData->event.portOut != nullptr, 0);
  1642. if (fMidiEventCount >= kPluginMaxMidiEvents*2-1)
  1643. return 0;
  1644. if (const VstEvents* const vstEvents = (const VstEvents*)ptr)
  1645. {
  1646. for (int32_t i=0; i < vstEvents->numEvents && i < kPluginMaxMidiEvents*2; ++i)
  1647. {
  1648. if (vstEvents->events[i] == nullptr)
  1649. break;
  1650. const VstMidiEvent* const vstMidiEvent((const VstMidiEvent*)vstEvents->events[i]);
  1651. if (vstMidiEvent->type != kVstMidiType)
  1652. continue;
  1653. // reverse-find first free event, and put it there
  1654. for (uint32_t j=(kPluginMaxMidiEvents*2)-1; j >= fMidiEventCount; --j)
  1655. {
  1656. if (fMidiEvents[j].type == 0)
  1657. {
  1658. std::memcpy(&fMidiEvents[j], vstMidiEvent, sizeof(VstMidiEvent));
  1659. break;
  1660. }
  1661. }
  1662. }
  1663. }
  1664. ret = 1;
  1665. break;
  1666. #if ! VST_FORCE_DEPRECATED
  1667. case audioMasterSetTime:
  1668. // Deprecated in VST SDK 2.4
  1669. break;
  1670. case audioMasterTempoAt:
  1671. // Deprecated in VST SDK 2.4
  1672. ret = static_cast<intptr_t>(fTimeInfo.tempo * 10000);
  1673. break;
  1674. case audioMasterGetNumAutomatableParameters:
  1675. // Deprecated in VST SDK 2.4
  1676. ret = static_cast<intptr_t>(pData->engine->getOptions().maxParameters);
  1677. ret = carla_minPositive<intptr_t>(ret, fEffect->numParams);
  1678. break;
  1679. case audioMasterGetParameterQuantization:
  1680. // Deprecated in VST SDK 2.4
  1681. ret = 1; // full single float precision
  1682. break;
  1683. #endif
  1684. #if 0
  1685. case audioMasterIOChanged:
  1686. CARLA_ASSERT(pData->enabled);
  1687. // TESTING
  1688. if (! pData->enabled)
  1689. {
  1690. ret = 1;
  1691. break;
  1692. }
  1693. if (x_engine->getOptions().processMode == PROCESS_MODE_CONTINUOUS_RACK)
  1694. {
  1695. carla_stderr2("CarlaPluginVST2::handleAudioMasterIOChanged() - plugin asked IO change, but it's not supported in rack mode");
  1696. return 0;
  1697. }
  1698. engineProcessLock();
  1699. m_enabled = false;
  1700. engineProcessUnlock();
  1701. if (m_active)
  1702. {
  1703. effect->dispatcher(effect, effStopProcess);
  1704. effect->dispatcher(effect, effMainsChanged, 0, 0);
  1705. }
  1706. reload();
  1707. if (m_active)
  1708. {
  1709. effect->dispatcher(effect, effMainsChanged, 0, 1, nullptr, 0.0f);
  1710. effect->dispatcher(effect, effStartProcess);
  1711. }
  1712. x_engine->callback(CALLBACK_RELOAD_ALL, m_id, 0, 0, 0, 0.0, nullptr);
  1713. ret = 1;
  1714. break;
  1715. #endif
  1716. #if ! VST_FORCE_DEPRECATED
  1717. case audioMasterNeedIdle:
  1718. // Deprecated in VST SDK 2.4
  1719. fNeedIdle = true;
  1720. ret = 1;
  1721. break;
  1722. #endif
  1723. case audioMasterSizeWindow:
  1724. CARLA_SAFE_ASSERT_BREAK(fUI.window != nullptr);
  1725. CARLA_SAFE_ASSERT_BREAK(index > 0);
  1726. CARLA_SAFE_ASSERT_BREAK(value > 0);
  1727. fUI.window->setSize(static_cast<uint>(index), static_cast<uint>(value), true);
  1728. ret = 1;
  1729. break;
  1730. case audioMasterGetSampleRate:
  1731. ret = static_cast<intptr_t>(pData->engine->getSampleRate());
  1732. break;
  1733. case audioMasterGetBlockSize:
  1734. ret = static_cast<intptr_t>(pData->engine->getBufferSize());
  1735. break;
  1736. case audioMasterGetInputLatency:
  1737. ret = 0;
  1738. break;
  1739. case audioMasterGetOutputLatency:
  1740. ret = 0;
  1741. break;
  1742. #if ! VST_FORCE_DEPRECATED
  1743. case audioMasterGetPreviousPlug:
  1744. // Deprecated in VST SDK 2.4
  1745. // TODO
  1746. break;
  1747. case audioMasterGetNextPlug:
  1748. // Deprecated in VST SDK 2.4
  1749. // TODO
  1750. break;
  1751. case audioMasterWillReplaceOrAccumulate:
  1752. // Deprecated in VST SDK 2.4
  1753. ret = 1; // replace
  1754. break;
  1755. #endif
  1756. case audioMasterGetCurrentProcessLevel:
  1757. if (pthread_equal(pthread_self(), fProcThread))
  1758. {
  1759. CARLA_SAFE_ASSERT(fIsProcessing);
  1760. if (pData->engine->isOffline())
  1761. ret = kVstProcessLevelOffline;
  1762. else
  1763. ret = kVstProcessLevelRealtime;
  1764. }
  1765. else
  1766. {
  1767. ret = kVstProcessLevelUser;
  1768. }
  1769. break;
  1770. case audioMasterGetAutomationState:
  1771. ret = pData->active ? kVstAutomationReadWrite : kVstAutomationOff;
  1772. break;
  1773. case audioMasterOfflineStart:
  1774. case audioMasterOfflineRead:
  1775. case audioMasterOfflineWrite:
  1776. case audioMasterOfflineGetCurrentPass:
  1777. case audioMasterOfflineGetCurrentMetaPass:
  1778. // TODO
  1779. break;
  1780. #if ! VST_FORCE_DEPRECATED
  1781. case audioMasterSetOutputSampleRate:
  1782. // Deprecated in VST SDK 2.4
  1783. break;
  1784. case audioMasterGetOutputSpeakerArrangement:
  1785. // Deprecated in VST SDK 2.4
  1786. // TODO
  1787. break;
  1788. #endif
  1789. case audioMasterVendorSpecific:
  1790. // TODO - cockos extensions
  1791. break;
  1792. #if ! VST_FORCE_DEPRECATED
  1793. case audioMasterSetIcon:
  1794. // Deprecated in VST SDK 2.4
  1795. break;
  1796. #endif
  1797. #if ! VST_FORCE_DEPRECATED
  1798. case audioMasterOpenWindow:
  1799. case audioMasterCloseWindow:
  1800. // Deprecated in VST SDK 2.4
  1801. // TODO
  1802. break;
  1803. #endif
  1804. case audioMasterGetDirectory:
  1805. // TODO
  1806. break;
  1807. case audioMasterUpdateDisplay:
  1808. // Update current program
  1809. if (pData->prog.count > 1)
  1810. {
  1811. const int32_t current = static_cast<int32_t>(dispatcher(effGetProgram));
  1812. if (current >= 0 && current < static_cast<int32_t>(pData->prog.count))
  1813. {
  1814. char strBuf[STR_MAX+1] = { '\0' };
  1815. dispatcher(effGetProgramName, 0, 0, strBuf);
  1816. if (pData->prog.names[current] != nullptr)
  1817. delete[] pData->prog.names[current];
  1818. pData->prog.names[current] = carla_strdup(strBuf);
  1819. if (pData->prog.current != current)
  1820. {
  1821. pData->prog.current = current;
  1822. pData->engine->callback(true, true,
  1823. ENGINE_CALLBACK_PROGRAM_CHANGED,
  1824. pData->id,
  1825. current,
  1826. 0, 0, 0.0f, nullptr);
  1827. }
  1828. }
  1829. }
  1830. if (! fIsInitializing)
  1831. pData->engine->callback(true, true,
  1832. ENGINE_CALLBACK_RELOAD_PARAMETERS, pData->id, 0, 0, 0, 0.0f, nullptr);
  1833. ret = 1;
  1834. break;
  1835. case audioMasterBeginEdit:
  1836. CARLA_SAFE_ASSERT_BREAK(index >= 0);
  1837. pData->engine->touchPluginParameter(pData->id, static_cast<uint32_t>(index), true);
  1838. break;
  1839. case audioMasterEndEdit:
  1840. CARLA_SAFE_ASSERT_BREAK(index >= 0);
  1841. pData->engine->touchPluginParameter(pData->id, static_cast<uint32_t>(index), false);
  1842. break;
  1843. case audioMasterOpenFileSelector:
  1844. case audioMasterCloseFileSelector:
  1845. // TODO
  1846. break;
  1847. #if ! VST_FORCE_DEPRECATED
  1848. case audioMasterEditFile:
  1849. // Deprecated in VST SDK 2.4
  1850. // TODO
  1851. break;
  1852. case audioMasterGetChunkFile:
  1853. // Deprecated in VST SDK 2.4
  1854. // TODO
  1855. break;
  1856. case audioMasterGetInputSpeakerArrangement:
  1857. // Deprecated in VST SDK 2.4
  1858. // TODO
  1859. break;
  1860. #endif
  1861. default:
  1862. carla_debug("CarlaPluginVST2::handleAudioMasterCallback(%02i:%s, %i, " P_INTPTR ", %p, %f) UNDEF",
  1863. opcode, vstMasterOpcode2str(opcode), index, value, ptr, static_cast<double>(opt));
  1864. break;
  1865. }
  1866. return ret;
  1867. // unused
  1868. (void)opt;
  1869. }
  1870. bool canDo(const char* const feature) const noexcept
  1871. {
  1872. try {
  1873. return (dispatcher(effCanDo, 0, 0, const_cast<char*>(feature)) == 1);
  1874. } CARLA_SAFE_EXCEPTION_RETURN("vstPluginCanDo", false);
  1875. }
  1876. bool hasMidiInput() const noexcept
  1877. {
  1878. return (fEffect->flags & effFlagsIsSynth) != 0 ||
  1879. (pData->hints & PLUGIN_WANTS_MIDI_INPUT) != 0 ||
  1880. canDo("receiveVstEvents") || canDo("receiveVstMidiEvent");
  1881. }
  1882. bool hasMidiOutput() const noexcept
  1883. {
  1884. return canDo("sendVstEvents") || canDo("sendVstMidiEvent");
  1885. }
  1886. // -------------------------------------------------------------------
  1887. const void* getNativeDescriptor() const noexcept override
  1888. {
  1889. return fEffect;
  1890. }
  1891. // -------------------------------------------------------------------
  1892. public:
  1893. bool init(const char* const filename, const char* const name, const int64_t uniqueId, const uint options)
  1894. {
  1895. CARLA_SAFE_ASSERT_RETURN(pData->engine != nullptr, false);
  1896. // ---------------------------------------------------------------
  1897. // first checks
  1898. if (pData->client != nullptr)
  1899. {
  1900. pData->engine->setLastError("Plugin client is already registered");
  1901. return false;
  1902. }
  1903. if (filename == nullptr || filename[0] == '\0')
  1904. {
  1905. pData->engine->setLastError("null filename");
  1906. return false;
  1907. }
  1908. // ---------------------------------------------------------------
  1909. VST_Function vstFn;
  1910. #ifdef CARLA_OS_MAC
  1911. CarlaString filenameCheck(filename);
  1912. filenameCheck.toLower();
  1913. if (filenameCheck.endsWith(".vst") || filenameCheck.endsWith(".vst/"))
  1914. {
  1915. // FIXME assert returns, set engine error
  1916. const CFURLRef urlRef = CFURLCreateFromFileSystemRepresentation(0, (const UInt8*)filename, (CFIndex)strlen(filename), true);
  1917. CARLA_SAFE_ASSERT_RETURN(urlRef != nullptr, false);
  1918. fMacBundleRef = CFBundleCreate(kCFAllocatorDefault, urlRef);
  1919. CFRelease(urlRef);
  1920. CARLA_SAFE_ASSERT_RETURN(fMacBundleRef != nullptr, false);
  1921. if (! CFBundleLoadExecutable(fMacBundleRef))
  1922. {
  1923. CFRelease(fMacBundleRef);
  1924. pData->engine->setLastError("Failed to load VST bundle executable");
  1925. return false;
  1926. }
  1927. vstFn = (VST_Function)CFBundleGetFunctionPointerForName(fMacBundleRef, CFSTR("main_macho"));
  1928. if (vstFn == nullptr)
  1929. vstFn = (VST_Function)CFBundleGetFunctionPointerForName(fMacBundleRef, CFSTR("VSTPluginMain"));
  1930. if (vstFn == nullptr)
  1931. {
  1932. CFBundleUnloadExecutable(fMacBundleRef);
  1933. CFRelease(fMacBundleRef);
  1934. pData->engine->setLastError("Not a VST plugin");
  1935. return false;
  1936. }
  1937. fMacBundleRefNum = CFBundleOpenBundleResourceMap(fMacBundleRef);
  1938. }
  1939. else
  1940. #endif
  1941. {
  1942. // -----------------------------------------------------------
  1943. // open DLL
  1944. if (! pData->libOpen(filename))
  1945. {
  1946. pData->engine->setLastError(pData->libError(filename));
  1947. return false;
  1948. }
  1949. // -----------------------------------------------------------
  1950. // get DLL main entry
  1951. vstFn = pData->libSymbol<VST_Function>("VSTPluginMain");
  1952. if (vstFn == nullptr)
  1953. {
  1954. vstFn = pData->libSymbol<VST_Function>("main");
  1955. if (vstFn == nullptr)
  1956. {
  1957. pData->engine->setLastError("Could not find the VST main entry in the plugin library");
  1958. return false;
  1959. }
  1960. }
  1961. }
  1962. // ---------------------------------------------------------------
  1963. // initialize plugin (part 1)
  1964. sCurrentUniqueId = static_cast<intptr_t>(uniqueId);
  1965. sLastCarlaPluginVST2 = this;
  1966. try {
  1967. fEffect = vstFn(carla_vst_audioMasterCallback);
  1968. } CARLA_SAFE_EXCEPTION_RETURN("Vst init", false);
  1969. sLastCarlaPluginVST2 = nullptr;
  1970. sCurrentUniqueId = 0;
  1971. if (fEffect == nullptr)
  1972. {
  1973. pData->engine->setLastError("Plugin failed to initialize");
  1974. return false;
  1975. }
  1976. if (fEffect->magic != kEffectMagic)
  1977. {
  1978. pData->engine->setLastError("Plugin is not valid (wrong vst effect magic code)");
  1979. return false;
  1980. }
  1981. fEffect->ptr1 = this;
  1982. const int32_t iBufferSize = static_cast<int32_t>(fBufferSize);
  1983. const float fSampleRate = static_cast<float>(pData->engine->getSampleRate());
  1984. dispatcher(effIdentify);
  1985. dispatcher(effSetProcessPrecision, 0, kVstProcessPrecision32);
  1986. dispatcher(effSetBlockSizeAndSampleRate, 0, iBufferSize, nullptr, fSampleRate);
  1987. dispatcher(effSetSampleRate, 0, 0, nullptr, fSampleRate);
  1988. dispatcher(effSetBlockSize, 0, iBufferSize);
  1989. dispatcher(effOpen);
  1990. const bool isShell = (dispatcher(effGetPlugCategory) == kPlugCategShell);
  1991. if (uniqueId == 0 && isShell)
  1992. {
  1993. char strBuf[STR_MAX+1];
  1994. carla_zeroChars(strBuf, STR_MAX+1);
  1995. sCurrentUniqueId = dispatcher(effShellGetNextPlugin, 0, 0, strBuf);
  1996. dispatcher(effClose);
  1997. fEffect = nullptr;
  1998. sLastCarlaPluginVST2 = this;
  1999. try {
  2000. fEffect = vstFn(carla_vst_audioMasterCallback);
  2001. } CARLA_SAFE_EXCEPTION_RETURN("Vst init", false);
  2002. sLastCarlaPluginVST2 = nullptr;
  2003. sCurrentUniqueId = 0;
  2004. dispatcher(effIdentify);
  2005. dispatcher(effSetProcessPrecision, 0, kVstProcessPrecision32);
  2006. dispatcher(effSetBlockSizeAndSampleRate, 0, iBufferSize, nullptr, fSampleRate);
  2007. dispatcher(effSetSampleRate, 0, 0, nullptr, fSampleRate);
  2008. dispatcher(effSetBlockSize, 0, iBufferSize);
  2009. dispatcher(effOpen);
  2010. }
  2011. if (fEffect->uniqueID == 0 && !isShell)
  2012. {
  2013. dispatcher(effClose);
  2014. fEffect = nullptr;
  2015. pData->engine->setLastError("Plugin is not valid (no unique ID after being open)");
  2016. return false;
  2017. }
  2018. // ---------------------------------------------------------------
  2019. // get info
  2020. if (name != nullptr && name[0] != '\0')
  2021. {
  2022. pData->name = pData->engine->getUniquePluginName(name);
  2023. }
  2024. else
  2025. {
  2026. char strBuf[STR_MAX+1];
  2027. carla_zeroChars(strBuf, STR_MAX+1);
  2028. dispatcher(effGetEffectName, 0, 0, strBuf);
  2029. if (strBuf[0] != '\0')
  2030. pData->name = pData->engine->getUniquePluginName(strBuf);
  2031. else if (const char* const shortname = std::strrchr(filename, CARLA_OS_SEP))
  2032. pData->name = pData->engine->getUniquePluginName(shortname+1);
  2033. else
  2034. pData->name = pData->engine->getUniquePluginName("unknown");
  2035. }
  2036. pData->filename = carla_strdup(filename);
  2037. // ---------------------------------------------------------------
  2038. // register client
  2039. pData->client = pData->engine->addClient(this);
  2040. if (pData->client == nullptr || ! pData->client->isOk())
  2041. {
  2042. pData->engine->setLastError("Failed to register plugin client");
  2043. return false;
  2044. }
  2045. // ---------------------------------------------------------------
  2046. // initialize plugin (part 2)
  2047. for (int i = fEffect->numInputs; --i >= 0;) dispatcher(effConnectInput, i, 1);
  2048. for (int i = fEffect->numOutputs; --i >= 0;) dispatcher(effConnectOutput, i, 1);
  2049. if (dispatcher(effGetVstVersion) < kVstVersion)
  2050. pData->hints |= PLUGIN_USES_OLD_VSTSDK;
  2051. static const char kHasCockosExtensions[] = "hasCockosExtensions";
  2052. if (static_cast<uintptr_t>(dispatcher(effCanDo, 0, 0, const_cast<char*>(kHasCockosExtensions))) == 0xbeef0000)
  2053. pData->hints |= PLUGIN_HAS_COCKOS_EXTENSIONS;
  2054. // ---------------------------------------------------------------
  2055. // set default options
  2056. pData->options = 0x0;
  2057. if (pData->latency.frames != 0 || hasMidiOutput() || isPluginOptionEnabled(options, PLUGIN_OPTION_FIXED_BUFFERS))
  2058. pData->options |= PLUGIN_OPTION_FIXED_BUFFERS;
  2059. if (fEffect->flags & effFlagsProgramChunks)
  2060. if (isPluginOptionEnabled(options, PLUGIN_OPTION_USE_CHUNKS))
  2061. pData->options |= PLUGIN_OPTION_USE_CHUNKS;
  2062. if (hasMidiInput())
  2063. {
  2064. if (isPluginOptionEnabled(options, PLUGIN_OPTION_SEND_CONTROL_CHANGES))
  2065. pData->options |= PLUGIN_OPTION_SEND_CONTROL_CHANGES;
  2066. if (isPluginOptionEnabled(options, PLUGIN_OPTION_SEND_CHANNEL_PRESSURE))
  2067. pData->options |= PLUGIN_OPTION_SEND_CHANNEL_PRESSURE;
  2068. if (isPluginOptionEnabled(options, PLUGIN_OPTION_SEND_NOTE_AFTERTOUCH))
  2069. pData->options |= PLUGIN_OPTION_SEND_NOTE_AFTERTOUCH;
  2070. if (isPluginOptionEnabled(options, PLUGIN_OPTION_SEND_PITCHBEND))
  2071. pData->options |= PLUGIN_OPTION_SEND_PITCHBEND;
  2072. if (isPluginOptionEnabled(options, PLUGIN_OPTION_SEND_ALL_SOUND_OFF))
  2073. pData->options |= PLUGIN_OPTION_SEND_ALL_SOUND_OFF;
  2074. if (isPluginOptionEnabled(options, PLUGIN_OPTION_SEND_PROGRAM_CHANGES))
  2075. pData->options |= PLUGIN_OPTION_SEND_PROGRAM_CHANGES;
  2076. }
  2077. if (fEffect->numPrograms > 1 && (pData->options & PLUGIN_OPTION_SEND_PROGRAM_CHANGES) == 0)
  2078. if (isPluginOptionEnabled(options, PLUGIN_OPTION_MAP_PROGRAM_CHANGES))
  2079. pData->options |= PLUGIN_OPTION_MAP_PROGRAM_CHANGES;
  2080. return true;
  2081. }
  2082. private:
  2083. int fUnique1;
  2084. AEffect* fEffect;
  2085. uint32_t fMidiEventCount;
  2086. VstMidiEvent fMidiEvents[kPluginMaxMidiEvents*2];
  2087. VstTimeInfo fTimeInfo;
  2088. bool fNeedIdle;
  2089. void* fLastChunk;
  2090. bool fIsInitializing;
  2091. bool fIsProcessing;
  2092. pthread_t fChangingValuesThread;
  2093. pthread_t fIdleThread;
  2094. pthread_t fMainThread;
  2095. pthread_t fProcThread;
  2096. #ifdef CARLA_OS_MAC
  2097. CFBundleRef fMacBundleRef;
  2098. CFBundleRefNum fMacBundleRefNum;
  2099. #endif
  2100. bool fFirstActive; // first process() call after activate()
  2101. uint32_t fBufferSize;
  2102. float** fAudioOutBuffers;
  2103. EngineTimeInfo fLastTimeInfo;
  2104. struct FixedVstEvents {
  2105. int32_t numEvents;
  2106. intptr_t reserved;
  2107. VstEvent* data[kPluginMaxMidiEvents*2];
  2108. FixedVstEvents() noexcept
  2109. : numEvents(0),
  2110. reserved(0)
  2111. {
  2112. carla_zeroPointers(data, kPluginMaxMidiEvents*2);
  2113. }
  2114. CARLA_DECLARE_NON_COPY_STRUCT(FixedVstEvents);
  2115. } fEvents;
  2116. struct UI {
  2117. bool isOpen;
  2118. bool isVisible;
  2119. CarlaPluginUI* window;
  2120. UI() noexcept
  2121. : isOpen(false),
  2122. isVisible(false),
  2123. window(nullptr) {}
  2124. ~UI()
  2125. {
  2126. CARLA_ASSERT(! isVisible);
  2127. if (window != nullptr)
  2128. {
  2129. delete window;
  2130. window = nullptr;
  2131. }
  2132. }
  2133. CARLA_DECLARE_NON_COPY_STRUCT(UI);
  2134. } fUI;
  2135. int fUnique2;
  2136. static intptr_t sCurrentUniqueId;
  2137. static CarlaPluginVST2* sLastCarlaPluginVST2;
  2138. // -------------------------------------------------------------------
  2139. static bool compareMagic(int32_t magic, const char* name) noexcept
  2140. {
  2141. return magic == (int32_t)ByteOrder::littleEndianInt (name)
  2142. || magic == (int32_t)ByteOrder::bigEndianInt (name);
  2143. }
  2144. static int32_t fxbSwap(const int32_t x) noexcept
  2145. {
  2146. return (int32_t)ByteOrder::swapIfLittleEndian ((uint32_t) x);
  2147. }
  2148. bool loadJuceSaveFormat(const void* const data, const std::size_t dataSize)
  2149. {
  2150. if (dataSize < 28)
  2151. return false;
  2152. const int32_t* const set = (const int32_t*)data;
  2153. if (set[1] != 0)
  2154. return false;
  2155. if (! compareMagic(set[0], "CcnK"))
  2156. return false;
  2157. if (! compareMagic(set[2], "FBCh") && ! compareMagic(set[2], "FJuc"))
  2158. return false;
  2159. if (fxbSwap(set[3]) > 1)
  2160. return false;
  2161. const int32_t chunkSize = fxbSwap(set[39]);
  2162. CARLA_SAFE_ASSERT_RETURN(chunkSize > 0, false);
  2163. if (static_cast<std::size_t>(chunkSize + 160) > dataSize)
  2164. return false;
  2165. carla_stdout("NOTE: Loading plugin state in VST2/JUCE compatibility mode");
  2166. setChunkData(&set[40], static_cast<std::size_t>(chunkSize));
  2167. return true;
  2168. }
  2169. static intptr_t carla_vst_hostCanDo(const char* const feature)
  2170. {
  2171. carla_debug("carla_vst_hostCanDo(\"%s\")", feature);
  2172. if (std::strcmp(feature, "supplyIdle") == 0)
  2173. return 1;
  2174. if (std::strcmp(feature, "sendVstEvents") == 0)
  2175. return 1;
  2176. if (std::strcmp(feature, "sendVstMidiEvent") == 0)
  2177. return 1;
  2178. if (std::strcmp(feature, "sendVstMidiEventFlagIsRealtime") == 0)
  2179. return 1;
  2180. if (std::strcmp(feature, "sendVstTimeInfo") == 0)
  2181. return 1;
  2182. if (std::strcmp(feature, "receiveVstEvents") == 0)
  2183. return 1;
  2184. if (std::strcmp(feature, "receiveVstMidiEvent") == 0)
  2185. return 1;
  2186. if (std::strcmp(feature, "receiveVstTimeInfo") == 0)
  2187. return -1;
  2188. if (std::strcmp(feature, "reportConnectionChanges") == 0)
  2189. return -1;
  2190. if (std::strcmp(feature, "acceptIOChanges") == 0)
  2191. return 1;
  2192. if (std::strcmp(feature, "sizeWindow") == 0)
  2193. return 1;
  2194. if (std::strcmp(feature, "offline") == 0)
  2195. return -1;
  2196. if (std::strcmp(feature, "openFileSelector") == 0)
  2197. return -1;
  2198. if (std::strcmp(feature, "closeFileSelector") == 0)
  2199. return -1;
  2200. if (std::strcmp(feature, "startStopProcess") == 0)
  2201. return 1;
  2202. if (std::strcmp(feature, "supportShell") == 0)
  2203. return 1;
  2204. if (std::strcmp(feature, "shellCategory") == 0)
  2205. return 1;
  2206. if (std::strcmp(feature, "NIMKPIVendorSpecificCallbacks") == 0)
  2207. return -1;
  2208. // unimplemented
  2209. carla_stderr("carla_vst_hostCanDo(\"%s\") - unknown feature", feature);
  2210. return 0;
  2211. }
  2212. static intptr_t VSTCALLBACK carla_vst_audioMasterCallback(AEffect* effect, int32_t opcode, int32_t index, intptr_t value, void* ptr, float opt)
  2213. {
  2214. #if defined(DEBUG) && ! defined(CARLA_OS_WIN)
  2215. if (opcode != audioMasterGetTime && opcode != audioMasterProcessEvents && opcode != audioMasterGetCurrentProcessLevel && opcode != audioMasterGetOutputLatency)
  2216. carla_debug("carla_vst_audioMasterCallback(%p, %02i:%s, %i, " P_INTPTR ", %p, %f)",
  2217. effect, opcode, vstMasterOpcode2str(opcode), index, value, ptr, static_cast<double>(opt));
  2218. #endif
  2219. switch (opcode)
  2220. {
  2221. case audioMasterVersion:
  2222. return kVstVersion;
  2223. case audioMasterCurrentId:
  2224. if (sCurrentUniqueId != 0)
  2225. return sCurrentUniqueId;
  2226. break;
  2227. case audioMasterGetVendorString:
  2228. CARLA_SAFE_ASSERT_RETURN(ptr != nullptr, 0);
  2229. std::strcpy((char*)ptr, "falkTX");
  2230. return 1;
  2231. case audioMasterGetProductString:
  2232. CARLA_SAFE_ASSERT_RETURN(ptr != nullptr, 0);
  2233. std::strcpy((char*)ptr, "Carla");
  2234. return 1;
  2235. case audioMasterGetVendorVersion:
  2236. return CARLA_VERSION_HEX;
  2237. case audioMasterCanDo:
  2238. CARLA_SAFE_ASSERT_RETURN(ptr != nullptr, 0);
  2239. return carla_vst_hostCanDo((const char*)ptr);
  2240. case audioMasterGetLanguage:
  2241. return kVstLangEnglish;
  2242. }
  2243. // Check if 'resvd1' points to us, otherwise register ourselves if possible
  2244. CarlaPluginVST2* self = nullptr;
  2245. if (effect != nullptr)
  2246. {
  2247. if (effect->ptr1 != nullptr)
  2248. {
  2249. self = (CarlaPluginVST2*)effect->ptr1;
  2250. if (self->fUnique1 != self->fUnique2)
  2251. self = nullptr;
  2252. }
  2253. if (self != nullptr)
  2254. {
  2255. if (self->fEffect == nullptr)
  2256. self->fEffect = effect;
  2257. if (self->fEffect != effect)
  2258. {
  2259. carla_stderr2("carla_vst_audioMasterCallback() - host pointer mismatch: %p != %p", self->fEffect, effect);
  2260. self = nullptr;
  2261. }
  2262. }
  2263. else if (sLastCarlaPluginVST2 != nullptr)
  2264. {
  2265. effect->ptr1 = sLastCarlaPluginVST2;
  2266. self = sLastCarlaPluginVST2;
  2267. }
  2268. }
  2269. return (self != nullptr) ? self->handleAudioMasterCallback(opcode, index, value, ptr, opt) : 0;
  2270. }
  2271. CARLA_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(CarlaPluginVST2)
  2272. };
  2273. intptr_t CarlaPluginVST2::sCurrentUniqueId = 0;
  2274. CarlaPluginVST2* CarlaPluginVST2::sLastCarlaPluginVST2 = nullptr;
  2275. CARLA_BACKEND_END_NAMESPACE
  2276. // -------------------------------------------------------------------------------------------------------------------
  2277. CARLA_BACKEND_START_NAMESPACE
  2278. CarlaPlugin* CarlaPlugin::newVST2(const Initializer& init)
  2279. {
  2280. carla_debug("CarlaPlugin::newVST2({%p, \"%s\", \"%s\", " P_INT64 "})", init.engine, init.filename, init.name, init.uniqueId);
  2281. #ifdef USE_JUCE_FOR_VST2
  2282. if (std::getenv("CARLA_DO_NOT_USE_JUCE_FOR_VST2") == nullptr)
  2283. return newJuce(init, "VST2");
  2284. #endif
  2285. CarlaPluginVST2* const plugin(new CarlaPluginVST2(init.engine, init.id));
  2286. if (! plugin->init(init.filename, init.name, init.uniqueId, init.options))
  2287. {
  2288. delete plugin;
  2289. return nullptr;
  2290. }
  2291. return plugin;
  2292. }
  2293. // -------------------------------------------------------------------------------------------------------------------
  2294. CARLA_BACKEND_END_NAMESPACE