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.

2523 lines
85KB

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