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.

2567 lines
86KB

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