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.

2898 lines
100KB

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