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.

2539 lines
86KB

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