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.

2729 lines
92KB

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