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.

2858 lines
98KB

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