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.

2497 lines
84KB

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