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.

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