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.

2438 lines
82KB

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