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.

2707 lines
92KB

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