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.

2400 lines
81KB

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