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.

2833 lines
97KB

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