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.

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