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.

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