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.

2499 lines
85KB

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