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.

2603 lines
87KB

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