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.

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