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.

2733 lines
93KB

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