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