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.

2433 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. #ifdef BUILD_BRIDGE
  277. const bool sendOsc(false);
  278. #else
  279. const bool sendOsc(pData->engine->isOscControlRegistered());
  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. if (fUI.window != nullptr)
  381. {
  382. fUI.window->idle();
  383. if (fUI.isVisible)
  384. dispatcher(effEditIdle, 0, 0, nullptr, 0.0f);
  385. }
  386. CarlaPlugin::idle();
  387. }
  388. // -------------------------------------------------------------------
  389. // Plugin state
  390. void reload() override
  391. {
  392. CARLA_SAFE_ASSERT_RETURN(pData->engine != nullptr,);
  393. CARLA_SAFE_ASSERT_RETURN(fEffect != nullptr,);
  394. carla_debug("CarlaPluginVST2::reload() - start");
  395. const EngineProcessMode processMode(pData->engine->getProccessMode());
  396. // Safely disable plugin for reload
  397. const ScopedDisabler sd(this);
  398. if (pData->active)
  399. deactivate();
  400. clearBuffers();
  401. uint32_t aIns, aOuts, mIns, mOuts, params;
  402. bool needsCtrlIn, needsCtrlOut;
  403. needsCtrlIn = needsCtrlOut = false;
  404. aIns = (fEffect->numInputs > 0) ? static_cast<uint32_t>(fEffect->numInputs) : 0;
  405. aOuts = (fEffect->numOutputs > 0) ? static_cast<uint32_t>(fEffect->numOutputs) : 0;
  406. params = (fEffect->numParams > 0) ? static_cast<uint32_t>(fEffect->numParams) : 0;
  407. if (hasMidiInput())
  408. {
  409. mIns = 1;
  410. needsCtrlIn = true;
  411. }
  412. else
  413. mIns = 0;
  414. if (hasMidiOutput())
  415. {
  416. mOuts = 1;
  417. needsCtrlOut = true;
  418. }
  419. else
  420. mOuts = 0;
  421. if (aIns > 0)
  422. {
  423. pData->audioIn.createNew(aIns);
  424. }
  425. if (aOuts > 0)
  426. {
  427. pData->audioOut.createNew(aOuts);
  428. needsCtrlIn = true;
  429. }
  430. if (params > 0)
  431. {
  432. pData->param.createNew(params, false);
  433. needsCtrlIn = true;
  434. }
  435. const uint portNameSize(pData->engine->getMaxPortNameSize());
  436. CarlaString portName;
  437. // Audio Ins
  438. for (uint32_t j=0; j < aIns; ++j)
  439. {
  440. portName.clear();
  441. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  442. {
  443. portName = pData->name;
  444. portName += ":";
  445. }
  446. if (aIns > 1)
  447. {
  448. portName += "input_";
  449. portName += CarlaString(j+1);
  450. }
  451. else
  452. portName += "input";
  453. portName.truncate(portNameSize);
  454. pData->audioIn.ports[j].port = (CarlaEngineAudioPort*)pData->client->addPort(kEnginePortTypeAudio, portName, true);
  455. pData->audioIn.ports[j].rindex = j;
  456. }
  457. // Audio Outs
  458. for (uint32_t j=0; j < aOuts; ++j)
  459. {
  460. portName.clear();
  461. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  462. {
  463. portName = pData->name;
  464. portName += ":";
  465. }
  466. if (aOuts > 1)
  467. {
  468. portName += "output_";
  469. portName += CarlaString(j+1);
  470. }
  471. else
  472. portName += "output";
  473. portName.truncate(portNameSize);
  474. pData->audioOut.ports[j].port = (CarlaEngineAudioPort*)pData->client->addPort(kEnginePortTypeAudio, portName, false);
  475. pData->audioOut.ports[j].rindex = j;
  476. }
  477. for (uint32_t j=0; j < params; ++j)
  478. {
  479. pData->param.data[j].type = PARAMETER_INPUT;
  480. pData->param.data[j].index = static_cast<int32_t>(j);
  481. pData->param.data[j].rindex = static_cast<int32_t>(j);
  482. float min, max, def, step, stepSmall, stepLarge;
  483. VstParameterProperties prop;
  484. carla_zeroStruct<VstParameterProperties>(prop);
  485. if (pData->hints & PLUGIN_HAS_COCKOS_EXTENSIONS)
  486. {
  487. double vrange[2] = { 0.0, 1.0 };
  488. bool isInteger = false;
  489. if (static_cast<uintptr_t>(dispatcher(effVendorSpecific, static_cast<int32_t>(0xdeadbef0), static_cast<int32_t>(j), vrange, 0.0f)) >= 0xbeef)
  490. {
  491. min = static_cast<float>(vrange[0]);
  492. max = static_cast<float>(vrange[1]);
  493. if (min > max)
  494. {
  495. carla_stderr2("WARNING - Broken plugin parameter min > max (with cockos extensions)");
  496. min = max - 0.1f;
  497. }
  498. else if (carla_compareFloats(min, max))
  499. {
  500. carla_stderr2("WARNING - Broken plugin parameter min == max (with cockos extensions)");
  501. max = min + 0.1f;
  502. }
  503. // only use values as integer if we have a proper range
  504. if (max - min >= 1.0f)
  505. isInteger = dispatcher(effVendorSpecific, kVstParameterUsesIntStep, static_cast<int32_t>(j), nullptr, 0.0f) >= 0xbeef;
  506. }
  507. else
  508. {
  509. min = 0.0f;
  510. max = 1.0f;
  511. }
  512. if (isInteger)
  513. {
  514. step = 1.0f;
  515. stepSmall = 1.0f;
  516. stepLarge = 10.0f;
  517. }
  518. else
  519. {
  520. const float range = max - min;
  521. step = range/100.0f;
  522. stepSmall = range/1000.0f;
  523. stepLarge = range/10.0f;
  524. }
  525. }
  526. else if (dispatcher(effGetParameterProperties, static_cast<int32_t>(j), 0, &prop, 0) == 1)
  527. {
  528. if (prop.flags & kVstParameterUsesIntegerMinMax)
  529. {
  530. min = static_cast<float>(prop.minInteger);
  531. max = static_cast<float>(prop.maxInteger);
  532. if (min > max)
  533. {
  534. carla_stderr2("WARNING - Broken plugin parameter min > max");
  535. min = max - 0.1f;
  536. }
  537. else if (carla_compareFloats(min, max))
  538. {
  539. carla_stderr2("WARNING - Broken plugin parameter min == max");
  540. max = min + 0.1f;
  541. }
  542. }
  543. else
  544. {
  545. min = 0.0f;
  546. max = 1.0f;
  547. }
  548. if (prop.flags & kVstParameterIsSwitch)
  549. {
  550. step = max - min;
  551. stepSmall = step;
  552. stepLarge = step;
  553. pData->param.data[j].hints |= PARAMETER_IS_BOOLEAN;
  554. }
  555. else if (prop.flags & kVstParameterUsesIntStep)
  556. {
  557. step = static_cast<float>(prop.stepInteger);
  558. stepSmall = static_cast<float>(prop.stepInteger)/10.0f;
  559. stepLarge = static_cast<float>(prop.largeStepInteger);
  560. pData->param.data[j].hints |= PARAMETER_IS_INTEGER;
  561. }
  562. else if (prop.flags & kVstParameterUsesFloatStep)
  563. {
  564. step = prop.stepFloat;
  565. stepSmall = prop.smallStepFloat;
  566. stepLarge = prop.largeStepFloat;
  567. }
  568. else
  569. {
  570. const float range = max - min;
  571. step = range/100.0f;
  572. stepSmall = range/1000.0f;
  573. stepLarge = range/10.0f;
  574. }
  575. if (prop.flags & kVstParameterCanRamp)
  576. pData->param.data[j].hints |= PARAMETER_IS_LOGARITHMIC;
  577. }
  578. else
  579. {
  580. min = 0.0f;
  581. max = 1.0f;
  582. step = 0.001f;
  583. stepSmall = 0.0001f;
  584. stepLarge = 0.1f;
  585. }
  586. pData->param.data[j].hints |= PARAMETER_IS_ENABLED;
  587. #ifndef BUILD_BRIDGE
  588. pData->param.data[j].hints |= PARAMETER_USES_CUSTOM_TEXT;
  589. #endif
  590. if ((pData->hints & PLUGIN_USES_OLD_VSTSDK) != 0 || dispatcher(effCanBeAutomated, static_cast<int32_t>(j), 0, nullptr, 0.0f) == 1)
  591. pData->param.data[j].hints |= PARAMETER_IS_AUTOMABLE;
  592. // no such thing as VST default parameters
  593. def = fEffect->getParameter(fEffect, static_cast<int32_t>(j));
  594. if (def < min)
  595. def = min;
  596. else if (def > max)
  597. def = max;
  598. pData->param.ranges[j].min = min;
  599. pData->param.ranges[j].max = max;
  600. pData->param.ranges[j].def = def;
  601. pData->param.ranges[j].step = step;
  602. pData->param.ranges[j].stepSmall = stepSmall;
  603. pData->param.ranges[j].stepLarge = stepLarge;
  604. }
  605. if (needsCtrlIn)
  606. {
  607. portName.clear();
  608. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  609. {
  610. portName = pData->name;
  611. portName += ":";
  612. }
  613. portName += "events-in";
  614. portName.truncate(portNameSize);
  615. pData->event.portIn = (CarlaEngineEventPort*)pData->client->addPort(kEnginePortTypeEvent, portName, true);
  616. }
  617. if (needsCtrlOut)
  618. {
  619. portName.clear();
  620. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  621. {
  622. portName = pData->name;
  623. portName += ":";
  624. }
  625. portName += "events-out";
  626. portName.truncate(portNameSize);
  627. pData->event.portOut = (CarlaEngineEventPort*)pData->client->addPort(kEnginePortTypeEvent, portName, false);
  628. }
  629. // plugin hints
  630. const intptr_t vstCategory = dispatcher(effGetPlugCategory, 0, 0, nullptr, 0.0f);
  631. pData->hints = 0x0;
  632. if (vstCategory == kPlugCategSynth || vstCategory == kPlugCategGenerator)
  633. pData->hints |= PLUGIN_IS_SYNTH;
  634. if (fEffect->flags & effFlagsHasEditor)
  635. {
  636. pData->hints |= PLUGIN_HAS_CUSTOM_UI;
  637. pData->hints |= PLUGIN_NEEDS_SINGLE_THREAD;
  638. }
  639. if (dispatcher(effGetVstVersion, 0, 0, nullptr, 0.0f) < kVstVersion)
  640. pData->hints |= PLUGIN_USES_OLD_VSTSDK;
  641. if ((fEffect->flags & effFlagsCanReplacing) != 0 && fEffect->processReplacing != fEffect->process)
  642. pData->hints |= PLUGIN_CAN_PROCESS_REPLACING;
  643. if (static_cast<uintptr_t>(dispatcher(effCanDo, 0, 0, const_cast<char*>("hasCockosExtensions"), 0.0f)) == 0xbeef0000)
  644. pData->hints |= PLUGIN_HAS_COCKOS_EXTENSIONS;
  645. if (aOuts > 0 && (aIns == aOuts || aIns == 1))
  646. pData->hints |= PLUGIN_CAN_DRYWET;
  647. if (aOuts > 0)
  648. pData->hints |= PLUGIN_CAN_VOLUME;
  649. if (aOuts >= 2 && aOuts % 2 == 0)
  650. pData->hints |= PLUGIN_CAN_BALANCE;
  651. // extra plugin hints
  652. pData->extraHints = 0x0;
  653. if (mIns > 0)
  654. pData->extraHints |= PLUGIN_EXTRA_HINT_HAS_MIDI_IN;
  655. if (mOuts > 0)
  656. pData->extraHints |= PLUGIN_EXTRA_HINT_HAS_MIDI_OUT;
  657. if (aIns <= 2 && aOuts <= 2 && (aIns == aOuts || aIns == 0 || aOuts == 0))
  658. pData->extraHints |= PLUGIN_EXTRA_HINT_CAN_RUN_RACK;
  659. // dummy pre-start to get latency and wantEvents() on old plugins
  660. {
  661. activate();
  662. deactivate();
  663. }
  664. // check latency
  665. if (pData->hints & PLUGIN_CAN_DRYWET)
  666. {
  667. #ifdef VESTIGE_HEADER
  668. char* const empty3Ptr = &fEffect->empty3[0];
  669. int32_t initialDelay = *(int32_t*)empty3Ptr;
  670. pData->latency = (initialDelay > 0) ? static_cast<uint32_t>(initialDelay) : 0;
  671. #else
  672. pData->latency = (fEffect->initialDelay > 0) ? static_cast<uint32_t>(fEffect->initialDelay) : 0;
  673. #endif
  674. pData->client->setLatency(pData->latency);
  675. #ifndef BUILD_BRIDGE
  676. pData->recreateLatencyBuffers();
  677. #endif
  678. }
  679. // special plugin fixes
  680. // 1. IL Harmless - disable threaded processing
  681. if (fEffect->uniqueID == 1229484653)
  682. {
  683. char strBuf[STR_MAX+1] = { '\0' };
  684. getLabel(strBuf);
  685. if (std::strcmp(strBuf, "IL Harmless") == 0)
  686. {
  687. // TODO - disable threaded processing
  688. }
  689. }
  690. //bufferSizeChanged(pData->engine->getBufferSize());
  691. reloadPrograms(true);
  692. if (pData->active)
  693. activate();
  694. carla_debug("CarlaPluginVST2::reload() - end");
  695. }
  696. void reloadPrograms(const bool doInit) override
  697. {
  698. carla_debug("CarlaPluginVST2::reloadPrograms(%s)", bool2str(doInit));
  699. const uint32_t oldCount = pData->prog.count;
  700. const int32_t current = pData->prog.current;
  701. // Delete old programs
  702. pData->prog.clear();
  703. // Query new programs
  704. uint32_t newCount = (fEffect->numPrograms > 0) ? static_cast<uint32_t>(fEffect->numPrograms) : 0;
  705. if (newCount > 0)
  706. {
  707. pData->prog.createNew(newCount);
  708. // Update names
  709. for (int32_t i=0; i < fEffect->numPrograms; ++i)
  710. {
  711. char strBuf[STR_MAX+1] = { '\0' };
  712. if (dispatcher(effGetProgramNameIndexed, i, 0, strBuf, 0.0f) != 1)
  713. {
  714. // program will be [re-]changed later
  715. dispatcher(effSetProgram, 0, i, nullptr, 0.0f);
  716. dispatcher(effGetProgramName, 0, 0, strBuf, 0.0f);
  717. }
  718. pData->prog.names[i] = carla_strdup(strBuf);
  719. }
  720. }
  721. #ifndef BUILD_BRIDGE
  722. // Update OSC Names
  723. if (pData->engine->isOscControlRegistered())
  724. {
  725. pData->engine->oscSend_control_set_program_count(pData->id, newCount);
  726. for (uint32_t i=0; i < newCount; ++i)
  727. pData->engine->oscSend_control_set_program_name(pData->id, i, pData->prog.names[i]);
  728. }
  729. #endif
  730. if (doInit)
  731. {
  732. if (newCount > 0)
  733. setProgram(0, false, false, false);
  734. }
  735. else
  736. {
  737. // Check if current program is invalid
  738. bool programChanged = false;
  739. if (newCount == oldCount+1)
  740. {
  741. // one program added, probably created by user
  742. pData->prog.current = static_cast<int32_t>(oldCount);
  743. programChanged = true;
  744. }
  745. else if (current < 0 && newCount > 0)
  746. {
  747. // programs exist now, but not before
  748. pData->prog.current = 0;
  749. programChanged = true;
  750. }
  751. else if (current >= 0 && newCount == 0)
  752. {
  753. // programs existed before, but not anymore
  754. pData->prog.current = -1;
  755. programChanged = true;
  756. }
  757. else if (current >= static_cast<int32_t>(newCount))
  758. {
  759. // current program > count
  760. pData->prog.current = 0;
  761. programChanged = true;
  762. }
  763. else
  764. {
  765. // no change
  766. pData->prog.current = current;
  767. }
  768. if (programChanged)
  769. {
  770. setProgram(pData->prog.current, true, true, true);
  771. }
  772. else
  773. {
  774. // Program was changed during update, re-set it
  775. if (pData->prog.current >= 0)
  776. dispatcher(effSetProgram, 0, pData->prog.current, nullptr, 0.0f);
  777. }
  778. pData->engine->callback(ENGINE_CALLBACK_RELOAD_PROGRAMS, pData->id, 0, 0, 0.0f, nullptr);
  779. }
  780. }
  781. // -------------------------------------------------------------------
  782. // Plugin processing
  783. void activate() noexcept override
  784. {
  785. CARLA_SAFE_ASSERT_RETURN(fEffect != nullptr,);
  786. try {
  787. dispatcher(effMainsChanged, 0, 1, nullptr, 0.0f);
  788. } catch(...) {}
  789. try {
  790. dispatcher(effStartProcess, 0, 0, nullptr, 0.0f);
  791. } catch(...) {}
  792. }
  793. void deactivate() noexcept override
  794. {
  795. CARLA_SAFE_ASSERT_RETURN(fEffect != nullptr,);
  796. try {
  797. dispatcher(effStopProcess, 0, 0, nullptr, 0.0f);
  798. } catch(...) {}
  799. try {
  800. dispatcher(effMainsChanged, 0, 0, nullptr, 0.0f);
  801. } catch(...) {}
  802. }
  803. void process(const float** const audioIn, float** const audioOut, const float** const, float** const, const uint32_t frames) override
  804. {
  805. fProcThread = pthread_self();
  806. // --------------------------------------------------------------------------------------------------------
  807. // Check if active
  808. if (! pData->active)
  809. {
  810. // disable any output sound
  811. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  812. FloatVectorOperations::clear(audioOut[i], static_cast<int>(frames));
  813. return;
  814. }
  815. fMidiEventCount = 0;
  816. carla_zeroStruct<VstMidiEvent>(fMidiEvents, kPluginMaxMidiEvents*2);
  817. // --------------------------------------------------------------------------------------------------------
  818. // Check if needs reset
  819. if (pData->needsReset)
  820. {
  821. if (pData->options & PLUGIN_OPTION_SEND_ALL_SOUND_OFF)
  822. {
  823. fMidiEventCount = MAX_MIDI_CHANNELS*2;
  824. for (uint8_t i=0, k=MAX_MIDI_CHANNELS; i < MAX_MIDI_CHANNELS; ++i)
  825. {
  826. fMidiEvents[k].type = kVstMidiType;
  827. fMidiEvents[k].byteSize = kVstMidiEventSize;
  828. fMidiEvents[k].midiData[0] = char(MIDI_STATUS_CONTROL_CHANGE | (k & MIDI_CHANNEL_BIT));
  829. fMidiEvents[k].midiData[1] = MIDI_CONTROL_ALL_NOTES_OFF;
  830. fMidiEvents[k+i].type = kVstMidiType;
  831. fMidiEvents[k+i].byteSize = kVstMidiEventSize;
  832. fMidiEvents[k+i].midiData[0] = char(MIDI_STATUS_CONTROL_CHANGE | (k & MIDI_CHANNEL_BIT));
  833. fMidiEvents[k+i].midiData[1] = MIDI_CONTROL_ALL_SOUND_OFF;
  834. }
  835. }
  836. else if (pData->ctrlChannel >= 0 && pData->ctrlChannel < MAX_MIDI_CHANNELS)
  837. {
  838. fMidiEventCount = MAX_MIDI_NOTE;
  839. for (uint8_t i=0; i < MAX_MIDI_NOTE; ++i)
  840. {
  841. fMidiEvents[i].type = kVstMidiType;
  842. fMidiEvents[i].byteSize = kVstMidiEventSize;
  843. fMidiEvents[i].midiData[0] = char(MIDI_STATUS_NOTE_OFF | (pData->ctrlChannel & MIDI_CHANNEL_BIT));
  844. fMidiEvents[i].midiData[1] = char(i);
  845. }
  846. }
  847. #ifndef BUILD_BRIDGE
  848. if (pData->latency > 0)
  849. {
  850. for (uint32_t i=0; i < pData->audioIn.count; ++i)
  851. FloatVectorOperations::clear(pData->latencyBuffers[i], static_cast<int>(pData->latency));
  852. }
  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_zeroStruct<VstMidiEvent>(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), MIDI_GET_CHANNEL_FROM_DATA(midiData), 0, 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_compareFloats(pData->postProc.volume, 1.0f);
  1233. const bool doDryWet = (pData->hints & PLUGIN_CAN_DRYWET) != 0 && ! carla_compareFloats(pData->postProc.dryWet, 1.0f);
  1234. const bool doBalance = (pData->hints & PLUGIN_CAN_BALANCE) != 0 && ! (carla_compareFloats(pData->postProc.balanceLeft, -1.0f) && carla_compareFloats(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. // TODO
  1388. // if using old sdk, return effect->uniqueID
  1389. break;
  1390. case audioMasterIdle:
  1391. //pData->engine->callback(ENGINE_CALLBACK_IDLE, 0, 0, 0, 0.0f, nullptr);
  1392. //pData->engine->idle();
  1393. break;
  1394. #if ! VST_FORCE_DEPRECATED
  1395. case audioMasterPinConnected:
  1396. // Deprecated in VST SDK 2.4
  1397. // TODO
  1398. break;
  1399. case audioMasterWantMidi:
  1400. // Deprecated in VST SDK 2.4
  1401. pData->hints |= PLUGIN_WANTS_MIDI_INPUT;
  1402. break;
  1403. #endif
  1404. case audioMasterGetTime:
  1405. ret = (intptr_t)&fTimeInfo;
  1406. break;
  1407. case audioMasterProcessEvents:
  1408. CARLA_SAFE_ASSERT_RETURN(pData->enabled, 0);
  1409. CARLA_SAFE_ASSERT_RETURN(fIsProcessing, 0);
  1410. CARLA_SAFE_ASSERT_RETURN(pData->event.portOut != nullptr, 0);
  1411. if (fMidiEventCount >= kPluginMaxMidiEvents*2)
  1412. return 0;
  1413. if (const VstEvents* const vstEvents = (const VstEvents*)ptr)
  1414. {
  1415. for (int32_t i=0; i < vstEvents->numEvents && i < kPluginMaxMidiEvents*2; ++i)
  1416. {
  1417. if (vstEvents->events[i] == nullptr)
  1418. break;
  1419. const VstMidiEvent* const vstMidiEvent((const VstMidiEvent*)vstEvents->events[i]);
  1420. if (vstMidiEvent->type != kVstMidiType)
  1421. continue;
  1422. // reverse-find first free event, and put it there
  1423. for (uint32_t j=(kPluginMaxMidiEvents*2)-1; j >= fMidiEventCount; --j)
  1424. {
  1425. if (fMidiEvents[j].type == 0)
  1426. {
  1427. std::memcpy(&fMidiEvents[j], vstMidiEvent, sizeof(VstMidiEvent));
  1428. break;
  1429. }
  1430. }
  1431. }
  1432. }
  1433. ret = 1;
  1434. break;
  1435. #if ! VST_FORCE_DEPRECATED
  1436. case audioMasterSetTime:
  1437. // Deprecated in VST SDK 2.4
  1438. break;
  1439. case audioMasterTempoAt:
  1440. // Deprecated in VST SDK 2.4
  1441. ret = static_cast<intptr_t>(fTimeInfo.tempo * 10000);
  1442. break;
  1443. case audioMasterGetNumAutomatableParameters:
  1444. // Deprecated in VST SDK 2.4
  1445. ret = carla_fixValue<intptr_t>(0, static_cast<intptr_t>(pData->engine->getOptions().maxParameters), fEffect->numParams);
  1446. break;
  1447. case audioMasterGetParameterQuantization:
  1448. // Deprecated in VST SDK 2.4
  1449. ret = 1; // full single float precision
  1450. break;
  1451. #endif
  1452. #if 0
  1453. case audioMasterIOChanged:
  1454. CARLA_ASSERT(pData->enabled);
  1455. // TESTING
  1456. if (! pData->enabled)
  1457. {
  1458. ret = 1;
  1459. break;
  1460. }
  1461. if (x_engine->getOptions().processMode == PROCESS_MODE_CONTINUOUS_RACK)
  1462. {
  1463. carla_stderr2("CarlaPluginVST2::handleAudioMasterIOChanged() - plugin asked IO change, but it's not supported in rack mode");
  1464. return 0;
  1465. }
  1466. engineProcessLock();
  1467. m_enabled = false;
  1468. engineProcessUnlock();
  1469. if (m_active)
  1470. {
  1471. effect->dispatcher(effect, effStopProcess, 0, 0, nullptr, 0.0f);
  1472. effect->dispatcher(effect, effMainsChanged, 0, 0, nullptr, 0.0f);
  1473. }
  1474. reload();
  1475. if (m_active)
  1476. {
  1477. effect->dispatcher(effect, effMainsChanged, 0, 1, nullptr, 0.0f);
  1478. effect->dispatcher(effect, effStartProcess, 0, 0, nullptr, 0.0f);
  1479. }
  1480. x_engine->callback(CALLBACK_RELOAD_ALL, m_id, 0, 0, 0.0, nullptr);
  1481. ret = 1;
  1482. break;
  1483. #endif
  1484. #if ! VST_FORCE_DEPRECATED
  1485. case audioMasterNeedIdle:
  1486. // Deprecated in VST SDK 2.4
  1487. fNeedIdle = true;
  1488. ret = 1;
  1489. break;
  1490. #endif
  1491. case audioMasterSizeWindow:
  1492. CARLA_SAFE_ASSERT_BREAK(fUI.window != nullptr);
  1493. CARLA_SAFE_ASSERT_BREAK(index > 0);
  1494. CARLA_SAFE_ASSERT_BREAK(value > 0);
  1495. fUI.window->setSize(static_cast<uint>(index), static_cast<uint>(value), true);
  1496. ret = 1;
  1497. break;
  1498. case audioMasterGetSampleRate:
  1499. ret = static_cast<intptr_t>(pData->engine->getSampleRate());
  1500. break;
  1501. case audioMasterGetBlockSize:
  1502. ret = static_cast<intptr_t>(pData->engine->getBufferSize());
  1503. break;
  1504. case audioMasterGetInputLatency:
  1505. ret = 0;
  1506. break;
  1507. case audioMasterGetOutputLatency:
  1508. ret = 0;
  1509. break;
  1510. #if ! VST_FORCE_DEPRECATED
  1511. case audioMasterGetPreviousPlug:
  1512. // Deprecated in VST SDK 2.4
  1513. // TODO
  1514. break;
  1515. case audioMasterGetNextPlug:
  1516. // Deprecated in VST SDK 2.4
  1517. // TODO
  1518. break;
  1519. case audioMasterWillReplaceOrAccumulate:
  1520. // Deprecated in VST SDK 2.4
  1521. ret = 1; // replace
  1522. break;
  1523. #endif
  1524. case audioMasterGetCurrentProcessLevel:
  1525. if (pthread_equal(pthread_self(), fProcThread))
  1526. {
  1527. CARLA_SAFE_ASSERT(fIsProcessing);
  1528. if (pData->engine->isOffline())
  1529. ret = kVstProcessLevelOffline;
  1530. else
  1531. ret = kVstProcessLevelRealtime;
  1532. }
  1533. else
  1534. ret = kVstProcessLevelUser;
  1535. break;
  1536. case audioMasterGetAutomationState:
  1537. ret = pData->active ? kVstAutomationReadWrite : kVstAutomationOff;
  1538. break;
  1539. case audioMasterOfflineStart:
  1540. case audioMasterOfflineRead:
  1541. case audioMasterOfflineWrite:
  1542. case audioMasterOfflineGetCurrentPass:
  1543. case audioMasterOfflineGetCurrentMetaPass:
  1544. // TODO
  1545. break;
  1546. #if ! VST_FORCE_DEPRECATED
  1547. case audioMasterSetOutputSampleRate:
  1548. // Deprecated in VST SDK 2.4
  1549. break;
  1550. case audioMasterGetOutputSpeakerArrangement:
  1551. // Deprecated in VST SDK 2.4
  1552. // TODO
  1553. break;
  1554. #endif
  1555. case audioMasterVendorSpecific:
  1556. // TODO - cockos extensions
  1557. break;
  1558. #if ! VST_FORCE_DEPRECATED
  1559. case audioMasterSetIcon:
  1560. // Deprecated in VST SDK 2.4
  1561. break;
  1562. #endif
  1563. #if ! VST_FORCE_DEPRECATED
  1564. case audioMasterOpenWindow:
  1565. case audioMasterCloseWindow:
  1566. // Deprecated in VST SDK 2.4
  1567. // TODO
  1568. break;
  1569. #endif
  1570. case audioMasterGetDirectory:
  1571. // TODO
  1572. break;
  1573. case audioMasterUpdateDisplay:
  1574. // Idle UI if visible
  1575. if (fUI.isVisible)
  1576. dispatcher(effEditIdle, 0, 0, nullptr, 0.0f);
  1577. // Update current program
  1578. if (pData->prog.count > 0)
  1579. {
  1580. const int32_t current = static_cast<int32_t>(dispatcher(effGetProgram, 0, 0, nullptr, 0.0f));
  1581. if (current >= 0 && current < static_cast<int32_t>(pData->prog.count))
  1582. {
  1583. char strBuf[STR_MAX+1] = { '\0' };
  1584. dispatcher(effGetProgramName, 0, 0, strBuf, 0.0f);
  1585. if (pData->prog.names[current] != nullptr)
  1586. delete[] pData->prog.names[current];
  1587. pData->prog.names[current] = carla_strdup(strBuf);
  1588. if (pData->prog.current != current)
  1589. {
  1590. pData->prog.current = current;
  1591. pData->engine->callback(ENGINE_CALLBACK_PROGRAM_CHANGED, pData->id, current, 0, 0.0f, nullptr);
  1592. }
  1593. }
  1594. }
  1595. pData->engine->callback(ENGINE_CALLBACK_UPDATE, pData->id, 0, 0, 0.0f, nullptr);
  1596. ret = 1;
  1597. break;
  1598. case audioMasterBeginEdit:
  1599. case audioMasterEndEdit:
  1600. // TODO
  1601. break;
  1602. case audioMasterOpenFileSelector:
  1603. case audioMasterCloseFileSelector:
  1604. // TODO
  1605. break;
  1606. #if ! VST_FORCE_DEPRECATED
  1607. case audioMasterEditFile:
  1608. // Deprecated in VST SDK 2.4
  1609. // TODO
  1610. break;
  1611. case audioMasterGetChunkFile:
  1612. // Deprecated in VST SDK 2.4
  1613. // TODO
  1614. break;
  1615. case audioMasterGetInputSpeakerArrangement:
  1616. // Deprecated in VST SDK 2.4
  1617. // TODO
  1618. break;
  1619. #endif
  1620. default:
  1621. carla_debug("CarlaPluginVST2::handleAudioMasterCallback(%02i:%s, %i, " P_INTPTR ", %p, %f) UNDEF", opcode, vstMasterOpcode2str(opcode), index, value, ptr, opt);
  1622. break;
  1623. }
  1624. return ret;
  1625. // unused
  1626. (void)opt;
  1627. }
  1628. bool canDo(const char* const feature) const noexcept
  1629. {
  1630. try {
  1631. return (fEffect->dispatcher(fEffect, effCanDo, 0, 0, const_cast<char*>(feature), 0.0f) == 1);
  1632. } CARLA_SAFE_EXCEPTION_RETURN("vstPluginCanDo", false);
  1633. }
  1634. bool hasMidiInput() const noexcept
  1635. {
  1636. return (canDo("receiveVstEvents") || canDo("receiveVstMidiEvent") || (fEffect->flags & effFlagsIsSynth) > 0 || (pData->hints & PLUGIN_WANTS_MIDI_INPUT));
  1637. }
  1638. bool hasMidiOutput() const noexcept
  1639. {
  1640. return (canDo("sendVstEvents") || canDo("sendVstMidiEvent"));
  1641. }
  1642. // -------------------------------------------------------------------
  1643. const void* getNativeDescriptor() const noexcept override
  1644. {
  1645. return fEffect;
  1646. }
  1647. // -------------------------------------------------------------------
  1648. public:
  1649. bool init(const char* const filename, const char* const name, const int64_t uniqueId)
  1650. {
  1651. CARLA_SAFE_ASSERT_RETURN(pData->engine != nullptr, false);
  1652. // ---------------------------------------------------------------
  1653. // first checks
  1654. if (pData->client != nullptr)
  1655. {
  1656. pData->engine->setLastError("Plugin client is already registered");
  1657. return false;
  1658. }
  1659. if (filename == nullptr || filename[0] == '\0')
  1660. {
  1661. pData->engine->setLastError("null filename");
  1662. return false;
  1663. }
  1664. // ---------------------------------------------------------------
  1665. // open DLL
  1666. if (! pData->libOpen(filename))
  1667. {
  1668. pData->engine->setLastError(pData->libError(filename));
  1669. return false;
  1670. }
  1671. // ---------------------------------------------------------------
  1672. // get DLL main entry
  1673. VST_Function vstFn = pData->libSymbol<VST_Function>("VSTPluginMain");
  1674. if (vstFn == nullptr)
  1675. {
  1676. vstFn = pData->libSymbol<VST_Function>("main");
  1677. if (vstFn == nullptr)
  1678. {
  1679. pData->engine->setLastError("Could not find the VST main entry in the plugin library");
  1680. return false;
  1681. }
  1682. }
  1683. // ---------------------------------------------------------------
  1684. // initialize plugin (part 1)
  1685. sLastCarlaPluginVST2 = this;
  1686. fEffect = vstFn(carla_vst_audioMasterCallback);
  1687. sLastCarlaPluginVST2 = nullptr;
  1688. if (fEffect == nullptr)
  1689. {
  1690. pData->engine->setLastError("Plugin failed to initialize");
  1691. return false;
  1692. }
  1693. if (fEffect->magic != kEffectMagic)
  1694. {
  1695. pData->engine->setLastError("Plugin is not valid (wrong vst effect magic code)");
  1696. return false;
  1697. }
  1698. #ifdef VESTIGE_HEADER
  1699. fEffect->ptr1 = this;
  1700. #else
  1701. fEffect->resvd1 = (intptr_t)this;
  1702. #endif
  1703. dispatcher(effOpen, 0, 0, nullptr, 0.0f);
  1704. // ---------------------------------------------------------------
  1705. // get info
  1706. if (name != nullptr && name[0] != '\0')
  1707. {
  1708. pData->name = pData->engine->getUniquePluginName(name);
  1709. }
  1710. else
  1711. {
  1712. char strBuf[STR_MAX+1];
  1713. carla_zeroChar(strBuf, STR_MAX+1);
  1714. dispatcher(effGetEffectName, 0, 0, strBuf, 0.0f);
  1715. if (strBuf[0] != '\0')
  1716. pData->name = pData->engine->getUniquePluginName(strBuf);
  1717. else if (const char* const shortname = std::strrchr(filename, CARLA_OS_SEP))
  1718. pData->name = pData->engine->getUniquePluginName(shortname+1);
  1719. else
  1720. pData->name = pData->engine->getUniquePluginName("unknown");
  1721. }
  1722. pData->filename = carla_strdup(filename);
  1723. // ---------------------------------------------------------------
  1724. // register client
  1725. pData->client = pData->engine->addClient(this);
  1726. if (pData->client == nullptr || ! pData->client->isOk())
  1727. {
  1728. pData->engine->setLastError("Failed to register plugin client");
  1729. return false;
  1730. }
  1731. // ---------------------------------------------------------------
  1732. // initialize plugin (part 2)
  1733. #if ! VST_FORCE_DEPRECATED
  1734. dispatcher(effSetBlockSizeAndSampleRate, 0, static_cast<int32_t>(pData->engine->getBufferSize()), nullptr, static_cast<float>(pData->engine->getSampleRate()));
  1735. #endif
  1736. dispatcher(effSetSampleRate, 0, 0, nullptr, static_cast<float>(pData->engine->getSampleRate()));
  1737. dispatcher(effSetBlockSize, 0, static_cast<int32_t>(pData->engine->getBufferSize()), nullptr, 0.0f);
  1738. dispatcher(effSetProcessPrecision, 0, kVstProcessPrecision32, nullptr, 0.0f);
  1739. if (dispatcher(effGetVstVersion, 0, 0, nullptr, 0.0f) < kVstVersion)
  1740. pData->hints |= PLUGIN_USES_OLD_VSTSDK;
  1741. if (static_cast<uintptr_t>(dispatcher(effCanDo, 0, 0, const_cast<char*>("hasCockosExtensions"), 0.0f)) == 0xbeef0000)
  1742. pData->hints |= PLUGIN_HAS_COCKOS_EXTENSIONS;
  1743. // ---------------------------------------------------------------
  1744. // set default options
  1745. pData->options = 0x0;
  1746. pData->options |= PLUGIN_OPTION_MAP_PROGRAM_CHANGES;
  1747. if (fEffect->flags & effFlagsProgramChunks)
  1748. pData->options |= PLUGIN_OPTION_USE_CHUNKS;
  1749. if (hasMidiInput())
  1750. {
  1751. pData->options |= PLUGIN_OPTION_FIXED_BUFFERS;
  1752. pData->options |= PLUGIN_OPTION_SEND_CHANNEL_PRESSURE;
  1753. pData->options |= PLUGIN_OPTION_SEND_NOTE_AFTERTOUCH;
  1754. pData->options |= PLUGIN_OPTION_SEND_PITCHBEND;
  1755. pData->options |= PLUGIN_OPTION_SEND_ALL_SOUND_OFF;
  1756. }
  1757. return true;
  1758. // unused
  1759. (void)uniqueId;
  1760. }
  1761. private:
  1762. int fUnique1;
  1763. AEffect* fEffect;
  1764. uint32_t fMidiEventCount;
  1765. VstMidiEvent fMidiEvents[kPluginMaxMidiEvents*2];
  1766. VstTimeInfo fTimeInfo;
  1767. bool fNeedIdle;
  1768. void* fLastChunk;
  1769. bool fIsProcessing;
  1770. pthread_t fProcThread;
  1771. struct FixedVstEvents {
  1772. int32_t numEvents;
  1773. intptr_t reserved;
  1774. VstEvent* data[kPluginMaxMidiEvents*2];
  1775. FixedVstEvents() noexcept
  1776. : numEvents(0),
  1777. reserved(0)
  1778. {
  1779. carla_fill<VstEvent*>(data, nullptr, kPluginMaxMidiEvents*2);
  1780. }
  1781. CARLA_DECLARE_NON_COPY_STRUCT(FixedVstEvents);
  1782. } fEvents;
  1783. struct UI {
  1784. bool isVisible;
  1785. CarlaPluginUI* window;
  1786. UI() noexcept
  1787. : isVisible(false),
  1788. window(nullptr) {}
  1789. ~UI()
  1790. {
  1791. CARLA_ASSERT(! isVisible);
  1792. if (window != nullptr)
  1793. {
  1794. delete window;
  1795. window = nullptr;
  1796. }
  1797. }
  1798. CARLA_DECLARE_NON_COPY_STRUCT(UI);
  1799. } fUI;
  1800. int fUnique2;
  1801. static CarlaPluginVST2* sLastCarlaPluginVST2;
  1802. // -------------------------------------------------------------------
  1803. static intptr_t carla_vst_hostCanDo(const char* const feature)
  1804. {
  1805. carla_debug("carla_vst_hostCanDo(\"%s\")", feature);
  1806. if (std::strcmp(feature, "supplyIdle") == 0)
  1807. return 1;
  1808. if (std::strcmp(feature, "sendVstEvents") == 0)
  1809. return 1;
  1810. if (std::strcmp(feature, "sendVstMidiEvent") == 0)
  1811. return 1;
  1812. if (std::strcmp(feature, "sendVstMidiEventFlagIsRealtime") == 0)
  1813. return 1;
  1814. if (std::strcmp(feature, "sendVstTimeInfo") == 0)
  1815. return 1;
  1816. if (std::strcmp(feature, "receiveVstEvents") == 0)
  1817. return 1;
  1818. if (std::strcmp(feature, "receiveVstMidiEvent") == 0)
  1819. return 1;
  1820. if (std::strcmp(feature, "receiveVstTimeInfo") == 0)
  1821. return -1;
  1822. if (std::strcmp(feature, "reportConnectionChanges") == 0)
  1823. return -1;
  1824. if (std::strcmp(feature, "acceptIOChanges") == 0)
  1825. return 1;
  1826. if (std::strcmp(feature, "sizeWindow") == 0)
  1827. return 1;
  1828. if (std::strcmp(feature, "offline") == 0)
  1829. return -1;
  1830. if (std::strcmp(feature, "openFileSelector") == 0)
  1831. return -1;
  1832. if (std::strcmp(feature, "closeFileSelector") == 0)
  1833. return -1;
  1834. if (std::strcmp(feature, "startStopProcess") == 0)
  1835. return 1;
  1836. if (std::strcmp(feature, "supportShell") == 0)
  1837. return -1;
  1838. if (std::strcmp(feature, "shellCategory") == 0)
  1839. return -1;
  1840. // unimplemented
  1841. carla_stderr("carla_vst_hostCanDo(\"%s\") - unknown feature", feature);
  1842. return 0;
  1843. }
  1844. static intptr_t VSTCALLBACK carla_vst_audioMasterCallback(AEffect* effect, int32_t opcode, int32_t index, intptr_t value, void* ptr, float opt)
  1845. {
  1846. #if defined(DEBUG) && ! defined(CARLA_OS_WIN)
  1847. if (opcode != audioMasterGetTime && opcode != audioMasterProcessEvents && opcode != audioMasterGetCurrentProcessLevel && opcode != audioMasterGetOutputLatency)
  1848. carla_debug("carla_vst_audioMasterCallback(%p, %02i:%s, %i, " P_INTPTR ", %p, %f)", effect, opcode, vstMasterOpcode2str(opcode), index, value, ptr, opt);
  1849. #endif
  1850. switch (opcode)
  1851. {
  1852. case audioMasterVersion:
  1853. return kVstVersion;
  1854. case audioMasterGetVendorString:
  1855. CARLA_SAFE_ASSERT_RETURN(ptr != nullptr, 0);
  1856. std::strcpy((char*)ptr, "falkTX");
  1857. return 1;
  1858. case audioMasterGetProductString:
  1859. CARLA_SAFE_ASSERT_RETURN(ptr != nullptr, 0);
  1860. std::strcpy((char*)ptr, "Carla");
  1861. return 1;
  1862. case audioMasterGetVendorVersion:
  1863. return 0x110; // 1.1.0
  1864. case audioMasterCanDo:
  1865. CARLA_SAFE_ASSERT_RETURN(ptr != nullptr, 0);
  1866. return carla_vst_hostCanDo((const char*)ptr);
  1867. case audioMasterGetLanguage:
  1868. return kVstLangEnglish;
  1869. }
  1870. // Check if 'resvd1' points to us, otherwise register ourselfs if possible
  1871. CarlaPluginVST2* self = nullptr;
  1872. if (effect != nullptr)
  1873. {
  1874. #ifdef VESTIGE_HEADER
  1875. if (effect->ptr1 != nullptr)
  1876. {
  1877. self = (CarlaPluginVST2*)effect->ptr1;
  1878. if (self->fUnique1 != self->fUnique2)
  1879. self = nullptr;
  1880. }
  1881. #else
  1882. if (effect->resvd1 != 0)
  1883. {
  1884. self = (CarlaPluginVST2*)effect->resvd1;
  1885. if (self->fUnique1 != self->fUnique2)
  1886. self = nullptr;
  1887. }
  1888. #endif
  1889. if (self != nullptr)
  1890. {
  1891. if (self->fEffect == nullptr)
  1892. self->fEffect = effect;
  1893. if (self->fEffect != effect)
  1894. {
  1895. carla_stderr2("carla_vst_audioMasterCallback() - host pointer mismatch: %p != %p", self->fEffect, effect);
  1896. self = nullptr;
  1897. }
  1898. }
  1899. else if (sLastCarlaPluginVST2 != nullptr)
  1900. {
  1901. #ifdef VESTIGE_HEADER
  1902. effect->ptr1 = sLastCarlaPluginVST2;
  1903. #else
  1904. effect->resvd1 = (intptr_t)sLastCarlaPluginVST2;
  1905. #endif
  1906. self = sLastCarlaPluginVST2;
  1907. }
  1908. }
  1909. return (self != nullptr) ? self->handleAudioMasterCallback(opcode, index, value, ptr, opt) : 0;
  1910. }
  1911. CARLA_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(CarlaPluginVST2)
  1912. };
  1913. CarlaPluginVST2* CarlaPluginVST2::sLastCarlaPluginVST2 = nullptr;
  1914. CARLA_BACKEND_END_NAMESPACE
  1915. #endif // ! USE_JUCE_FOR_VST
  1916. // -------------------------------------------------------------------------------------------------------------------
  1917. CARLA_BACKEND_START_NAMESPACE
  1918. CarlaPlugin* CarlaPlugin::newVST2(const Initializer& init)
  1919. {
  1920. carla_debug("CarlaPlugin::newVST2({%p, \"%s\", \"%s\", " P_INT64 "})", init.engine, init.filename, init.name, init.uniqueId);
  1921. #ifdef USE_JUCE_FOR_VST
  1922. return newJuce(init, "VST");
  1923. #else
  1924. CarlaPluginVST2* const plugin(new CarlaPluginVST2(init.engine, init.id));
  1925. if (! plugin->init(init.filename, init.name, init.uniqueId))
  1926. {
  1927. delete plugin;
  1928. return nullptr;
  1929. }
  1930. plugin->reload();
  1931. if (init.engine->getProccessMode() == ENGINE_PROCESS_MODE_CONTINUOUS_RACK && ! plugin->canRunInRack())
  1932. {
  1933. init.engine->setLastError("Carla's rack mode can only work with Stereo VST plugins, sorry!");
  1934. delete plugin;
  1935. return nullptr;
  1936. }
  1937. return plugin;
  1938. #endif
  1939. }
  1940. // -------------------------------------------------------------------------------------------------------------------
  1941. CARLA_BACKEND_END_NAMESPACE