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.

2802 lines
96KB

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