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.

2744 lines
93KB

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