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.

2597 lines
87KB

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