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.

2442 lines
82KB

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