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.

2427 lines
83KB

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