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.

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