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.

2398 lines
81KB

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