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.

2831 lines
97KB

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