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.

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