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.

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