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.

2916 lines
100KB

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