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.

2596 lines
87KB

  1. /*
  2. * Carla VST Plugin
  3. * Copyright (C) 2011-2014 Filipe Coelho <falktx@falktx.com>
  4. *
  5. * This program is free software; you can redistribute it and/or
  6. * modify it under the terms of the GNU General Public License as
  7. * published by the Free Software Foundation; either version 2 of
  8. * the License, or any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * For a full copy of the GNU General Public License see the doc/GPL.txt file.
  16. */
  17. #include "CarlaPluginInternal.hpp"
  18. #include "CarlaEngine.hpp"
  19. #if defined(CARLA_OS_LINUX) || defined(VESTIGE_HEADER)
  20. # define USE_JUCE_FOR_VST 0
  21. #else
  22. # define USE_JUCE_FOR_VST 1
  23. #endif
  24. #if defined(WANT_VST) && ! (defined(HAVE_JUCE_UI) && USE_JUCE_FOR_VST)
  25. #include "CarlaVstUtils.hpp"
  26. #include "CarlaMathUtils.hpp"
  27. #include "CarlaPluginUi.hpp"
  28. // FIXME
  29. #include <QtCore/QFile>
  30. #include <pthread.h>
  31. #undef VST_FORCE_DEPRECATED
  32. #define VST_FORCE_DEPRECATED 0
  33. // -----------------------------------------------------
  34. CARLA_BACKEND_START_NAMESPACE
  35. #if 0
  36. }
  37. #endif
  38. // -----------------------------------------------------
  39. const uint PLUGIN_CAN_PROCESS_REPLACING = 0x1000;
  40. const uint PLUGIN_HAS_COCKOS_EXTENSIONS = 0x2000;
  41. const uint PLUGIN_USES_OLD_VSTSDK = 0x4000;
  42. const uint PLUGIN_WANTS_MIDI_INPUT = 0x8000;
  43. // -----------------------------------------------------
  44. class VstPlugin : public CarlaPlugin,
  45. CarlaPluginUi::CloseCallback
  46. {
  47. public:
  48. VstPlugin(CarlaEngine* const engine, const uint id)
  49. : CarlaPlugin(engine, id),
  50. fUnique1(1),
  51. fEffect(nullptr),
  52. fMidiEventCount(0),
  53. fNeedIdle(false),
  54. fLastChunk(nullptr),
  55. fIsProcessing(false),
  56. fUnique2(2)
  57. {
  58. carla_debug("VstPlugin::VstPlugin(%p, %i)", engine, id);
  59. carla_zeroStruct<VstMidiEvent>(fMidiEvents, kPluginMaxMidiEvents*2);
  60. carla_zeroStruct<VstTimeInfo>(fTimeInfo);
  61. for (ushort i=0; i < kPluginMaxMidiEvents*2; ++i)
  62. fEvents.data[i] = (VstEvent*)&fMidiEvents[i];
  63. pData->osc.thread.setMode(CarlaPluginThread::PLUGIN_THREAD_VST_GUI);
  64. #ifdef CARLA_OS_WIN
  65. fProcThread.p = nullptr;
  66. fProcThread.x = 0;
  67. #else
  68. fProcThread = 0;
  69. #endif
  70. // make plugin valid
  71. srand(id);
  72. fUnique1 = fUnique2 = rand();
  73. }
  74. ~VstPlugin() override
  75. {
  76. carla_debug("VstPlugin::~VstPlugin()");
  77. // close UI
  78. if (pData->hints & PLUGIN_HAS_CUSTOM_UI)
  79. {
  80. showCustomUI(false);
  81. if (fUi.type == UI::UI_OSC)
  82. pData->osc.thread.stopThread(static_cast<int>(pData->engine->getOptions().uiBridgesTimeout * 2));
  83. }
  84. pData->singleMutex.lock();
  85. pData->masterMutex.lock();
  86. if (pData->client != nullptr && pData->client->isActive())
  87. pData->client->deactivate();
  88. CARLA_ASSERT(! fIsProcessing);
  89. if (pData->active)
  90. {
  91. deactivate();
  92. pData->active = false;
  93. }
  94. if (fEffect != nullptr)
  95. {
  96. dispatcher(effClose, 0, 0, nullptr, 0.0f);
  97. fEffect = nullptr;
  98. }
  99. // make plugin invalid
  100. fUnique2 += 1;
  101. if (fLastChunk != nullptr)
  102. {
  103. std::free(fLastChunk);
  104. fLastChunk = nullptr;
  105. }
  106. clearBuffers();
  107. }
  108. // -------------------------------------------------------------------
  109. // Information (base)
  110. PluginType getType() const noexcept override
  111. {
  112. return PLUGIN_VST;
  113. }
  114. PluginCategory getCategory() const noexcept override
  115. {
  116. CARLA_SAFE_ASSERT_RETURN(fEffect != nullptr, CarlaPlugin::getCategory());
  117. const intptr_t category(dispatcher(effGetPlugCategory, 0, 0, nullptr, 0.0f));
  118. switch (category)
  119. {
  120. case kPlugCategSynth:
  121. return PLUGIN_CATEGORY_SYNTH;
  122. case kPlugCategAnalysis:
  123. return PLUGIN_CATEGORY_UTILITY;
  124. case kPlugCategMastering:
  125. return PLUGIN_CATEGORY_DYNAMICS;
  126. case kPlugCategRoomFx:
  127. return PLUGIN_CATEGORY_DELAY;
  128. case kPlugCategRestoration:
  129. return PLUGIN_CATEGORY_UTILITY;
  130. case kPlugCategGenerator:
  131. return PLUGIN_CATEGORY_SYNTH;
  132. }
  133. if (fEffect->flags & effFlagsIsSynth)
  134. return PLUGIN_CATEGORY_SYNTH;
  135. return CarlaPlugin::getCategory();
  136. }
  137. int64_t getUniqueId() const noexcept override
  138. {
  139. CARLA_SAFE_ASSERT_RETURN(fEffect != nullptr, 0);
  140. return static_cast<int64_t>(fEffect->uniqueID);
  141. }
  142. // -------------------------------------------------------------------
  143. // Information (count)
  144. // nothing
  145. // -------------------------------------------------------------------
  146. // Information (current data)
  147. int32_t getChunkData(void** const dataPtr) const noexcept override
  148. {
  149. CARLA_SAFE_ASSERT_RETURN(pData->options & PLUGIN_OPTION_USE_CHUNKS, 0);
  150. CARLA_SAFE_ASSERT_RETURN(fEffect != nullptr, 0);
  151. CARLA_SAFE_ASSERT_RETURN(dataPtr != nullptr, 0);
  152. int32_t ret = 0;
  153. try {
  154. ret = static_cast<int32_t>(dispatcher(effGetChunk, 0 /* bank */, 0, dataPtr, 0.0f));
  155. } catch(...) {}
  156. return ret;
  157. }
  158. // -------------------------------------------------------------------
  159. // Information (per-plugin data)
  160. uint getOptionsAvailable() const noexcept override
  161. {
  162. CARLA_SAFE_ASSERT_RETURN(fEffect != nullptr, 0);
  163. uint options = 0x0;
  164. options |= PLUGIN_OPTION_MAP_PROGRAM_CHANGES;
  165. if (fEffect->flags & effFlagsProgramChunks)
  166. options |= PLUGIN_OPTION_USE_CHUNKS;
  167. if (getMidiInCount() == 0)
  168. {
  169. options |= PLUGIN_OPTION_FIXED_BUFFERS;
  170. }
  171. else
  172. {
  173. options |= PLUGIN_OPTION_SEND_CONTROL_CHANGES;
  174. options |= PLUGIN_OPTION_SEND_CHANNEL_PRESSURE;
  175. options |= PLUGIN_OPTION_SEND_NOTE_AFTERTOUCH;
  176. options |= PLUGIN_OPTION_SEND_PITCHBEND;
  177. options |= PLUGIN_OPTION_SEND_ALL_SOUND_OFF;
  178. }
  179. return options;
  180. }
  181. float getParameterValue(const uint32_t parameterId) const noexcept override
  182. {
  183. CARLA_SAFE_ASSERT_RETURN(fEffect != nullptr, 0.0f);
  184. CARLA_SAFE_ASSERT_RETURN(parameterId < pData->param.count, 0.0f);
  185. return fEffect->getParameter(fEffect, static_cast<int32_t>(parameterId));
  186. }
  187. void getLabel(char* const strBuf) const noexcept override
  188. {
  189. CARLA_SAFE_ASSERT_RETURN(fEffect != nullptr,);
  190. strBuf[0] = '\0';
  191. dispatcher(effGetProductString, 0, 0, strBuf, 0.0f);
  192. }
  193. void getMaker(char* const strBuf) const noexcept override
  194. {
  195. CARLA_SAFE_ASSERT_RETURN(fEffect != nullptr,);
  196. strBuf[0] = '\0';
  197. dispatcher(effGetVendorString, 0, 0, strBuf, 0.0f);
  198. }
  199. void getCopyright(char* const strBuf) const noexcept override
  200. {
  201. getMaker(strBuf);
  202. }
  203. void getRealName(char* const strBuf) const noexcept override
  204. {
  205. CARLA_SAFE_ASSERT_RETURN(fEffect != nullptr,);
  206. strBuf[0] = '\0';
  207. dispatcher(effGetEffectName, 0, 0, strBuf, 0.0f);
  208. }
  209. void getParameterName(const uint32_t parameterId, char* const strBuf) const noexcept override
  210. {
  211. CARLA_SAFE_ASSERT_RETURN(fEffect != nullptr,);
  212. CARLA_SAFE_ASSERT_RETURN(parameterId < pData->param.count,);
  213. strBuf[0] = '\0';
  214. dispatcher(effGetParamName, static_cast<int32_t>(parameterId), 0, strBuf, 0.0f);
  215. }
  216. void getParameterText(const uint32_t parameterId, char* const strBuf) const noexcept override
  217. {
  218. CARLA_SAFE_ASSERT_RETURN(fEffect != nullptr,);
  219. CARLA_SAFE_ASSERT_RETURN(parameterId < pData->param.count,);
  220. strBuf[0] = '\0';
  221. dispatcher(effGetParamDisplay, static_cast<int32_t>(parameterId), 0, strBuf, 0.0f);
  222. if (strBuf[0] == '\0')
  223. std::snprintf(strBuf, STR_MAX, "%f", getParameterValue(parameterId));
  224. }
  225. void getParameterUnit(const uint32_t parameterId, char* const strBuf) const noexcept override
  226. {
  227. CARLA_SAFE_ASSERT_RETURN(fEffect != nullptr,);
  228. CARLA_SAFE_ASSERT_RETURN(parameterId < pData->param.count,);
  229. strBuf[0] = '\0';
  230. dispatcher(effGetParamLabel, static_cast<int32_t>(parameterId), 0, strBuf, 0.0f);
  231. }
  232. // -------------------------------------------------------------------
  233. // Set data (state)
  234. // nothing
  235. // -------------------------------------------------------------------
  236. // Set data (internal stuff)
  237. void setName(const char* const newName) override
  238. {
  239. CarlaPlugin::setName(newName);
  240. if (fUi.window != nullptr)
  241. {
  242. QString guiTitle(QString("%1 (GUI)").arg(pData->name));
  243. fUi.window->setTitle(guiTitle.toUtf8().constData());
  244. }
  245. }
  246. // -------------------------------------------------------------------
  247. // Set data (plugin-specific stuff)
  248. void setParameterValue(const uint32_t parameterId, const float value, const bool sendGui, const bool sendOsc, const bool sendCallback) noexcept override
  249. {
  250. CARLA_SAFE_ASSERT_RETURN(fEffect != nullptr,);
  251. CARLA_SAFE_ASSERT_RETURN(parameterId < pData->param.count,);
  252. const float fixedValue(pData->param.getFixedValue(parameterId, value));
  253. fEffect->setParameter(fEffect, static_cast<int32_t>(parameterId), fixedValue);
  254. CarlaPlugin::setParameterValue(parameterId, fixedValue, sendGui, sendOsc, sendCallback);
  255. }
  256. void setChunkData(const char* const stringData) override
  257. {
  258. CARLA_SAFE_ASSERT_RETURN(pData->options & PLUGIN_OPTION_USE_CHUNKS,);
  259. CARLA_SAFE_ASSERT_RETURN(fEffect != nullptr,);
  260. CARLA_SAFE_ASSERT_RETURN(stringData != nullptr,);
  261. if (fLastChunk != nullptr)
  262. {
  263. std::free(fLastChunk);
  264. fLastChunk = nullptr;
  265. }
  266. QByteArray chunk(QByteArray::fromBase64(stringData));
  267. CARLA_SAFE_ASSERT_RETURN(chunk.size() > 0,);
  268. fLastChunk = std::malloc(static_cast<size_t>(chunk.size()));
  269. CARLA_SAFE_ASSERT_RETURN(fLastChunk != nullptr,);
  270. std::memcpy(fLastChunk, chunk.constData(), static_cast<size_t>(chunk.size()));
  271. {
  272. const ScopedSingleProcessLocker spl(this, true);
  273. dispatcher(effSetChunk, 0 /* bank */, chunk.size(), fLastChunk, 0.0f);
  274. }
  275. // simulate an updateDisplay callback
  276. handleAudioMasterCallback(audioMasterUpdateDisplay, 0, 0, nullptr, 0.0f);
  277. #ifdef BUILD_BRIDGE
  278. const bool sendOsc(false);
  279. #else
  280. const bool sendOsc(pData->engine->isOscControlRegistered());
  281. #endif
  282. pData->updateParameterValues(this, sendOsc, true, false);
  283. }
  284. void setProgram(const int32_t index, const bool sendGui, const bool sendOsc, const bool sendCallback) noexcept override
  285. {
  286. CARLA_SAFE_ASSERT_RETURN(fEffect != nullptr,);
  287. CARLA_SAFE_ASSERT_RETURN(index >= -1 && index < static_cast<int32_t>(pData->prog.count),);
  288. if (index >= 0)
  289. {
  290. try {
  291. dispatcher(effBeginSetProgram, 0, 0, nullptr, 0.0f);
  292. } catch (...) {
  293. return;
  294. }
  295. {
  296. const ScopedSingleProcessLocker spl(this, (sendGui || sendOsc || sendCallback));
  297. try {
  298. dispatcher(effSetProgram, 0, index, nullptr, 0.0f);
  299. } catch(...) {}
  300. }
  301. try {
  302. dispatcher(effEndSetProgram, 0, 0, nullptr, 0.0f);
  303. } catch(...) {}
  304. }
  305. CarlaPlugin::setProgram(index, sendGui, sendOsc, sendCallback);
  306. }
  307. // -------------------------------------------------------------------
  308. // Set ui stuff
  309. void showCustomUI(const bool yesNo) override
  310. {
  311. if (fUi.type == UI::UI_OSC)
  312. {
  313. if (yesNo)
  314. {
  315. pData->osc.data.free();
  316. pData->osc.thread.startThread();
  317. }
  318. else
  319. {
  320. pData->transientTryCounter = 0;
  321. if (pData->osc.data.target != nullptr)
  322. {
  323. osc_send_hide(pData->osc.data);
  324. osc_send_quit(pData->osc.data);
  325. pData->osc.data.free();
  326. }
  327. pData->osc.thread.stopThread(static_cast<int>(pData->engine->getOptions().uiBridgesTimeout * 2));
  328. }
  329. return;
  330. }
  331. if (fUi.isVisible == yesNo)
  332. return;
  333. if (yesNo)
  334. {
  335. QString uiTitle(QString("%1 (GUI)").arg(pData->name));
  336. void* vstPtr;
  337. if (fUi.window == nullptr && fUi.type == UI::UI_EMBED)
  338. {
  339. const char* msg = nullptr;
  340. const uintptr_t frontendWinId(pData->engine->getOptions().frontendWinId);
  341. #if defined(CARLA_OS_LINUX)
  342. # ifdef HAVE_X11
  343. fUi.window = CarlaPluginUi::newX11(this, frontendWinId);
  344. # else
  345. msg = "UI is only for systems with X11";
  346. # endif
  347. #elif defined(CARLA_OS_MAC)
  348. # ifdef __LP64__
  349. fUi.window = CarlaPluginUi::newCocoa(this, frontendWinId);
  350. # endif
  351. #elif defined(CARLA_OS_WIN)
  352. fUi.window = CarlaPluginUi::newWindows(this, frontendWinId);
  353. #else
  354. msg = "Unknown UI type";
  355. #endif
  356. if (fUi.window == nullptr)
  357. return pData->engine->callback(ENGINE_CALLBACK_UI_STATE_CHANGED, pData->id, -1, 0, 0.0f, msg);
  358. fUi.window->setTitle(uiTitle.toUtf8().constData());
  359. }
  360. if (fUi.type == UI::UI_EMBED)
  361. vstPtr = fUi.window->getPtr();
  362. else
  363. vstPtr = uiTitle.toUtf8().data();
  364. if (dispatcher(effEditOpen, 0, 0, vstPtr, 0.0f) != 0)
  365. {
  366. if (fUi.type == UI::UI_EMBED)
  367. {
  368. ERect* vstRect = nullptr;
  369. dispatcher(effEditGetRect, 0, 0, &vstRect, 0.0f);
  370. if (vstRect != nullptr)
  371. {
  372. const int width(vstRect->right - vstRect->left);
  373. const int height(vstRect->bottom - vstRect->top);
  374. CARLA_SAFE_ASSERT_INT2(width > 1 && height > 1, width, height);
  375. if (width > 1 && height > 1)
  376. fUi.window->setSize(static_cast<uint>(width), static_cast<uint>(height), false);
  377. }
  378. fUi.window->show();
  379. }
  380. else
  381. {
  382. if (pData->engine->getOptions().frontendWinId)
  383. pData->transientTryCounter = 1;
  384. }
  385. fUi.isVisible = true;
  386. }
  387. else
  388. {
  389. if (fUi.type == UI::UI_EMBED)
  390. {
  391. delete fUi.window;
  392. fUi.window = nullptr;
  393. }
  394. return pData->engine->callback(ENGINE_CALLBACK_UI_STATE_CHANGED, pData->id, -1, 0, 0.0f, "Plugin refused to open its own UI");
  395. }
  396. }
  397. else
  398. {
  399. fUi.isVisible = false;
  400. if (fUi.type == UI::UI_EMBED)
  401. {
  402. CARLA_SAFE_ASSERT_RETURN(fUi.window != nullptr,);
  403. fUi.window->hide();
  404. }
  405. else
  406. {
  407. pData->transientTryCounter = 0;
  408. }
  409. dispatcher(effEditClose, 0, 0, nullptr, 0.0f);
  410. }
  411. }
  412. void idle() override
  413. {
  414. if (fNeedIdle)
  415. dispatcher(effIdle, 0, 0, nullptr, 0.0f);
  416. if (fUi.window != nullptr)
  417. {
  418. fUi.window->idle();
  419. if (fUi.isVisible)
  420. dispatcher(effEditIdle, 0, 0, nullptr, 0.0f);
  421. }
  422. CarlaPlugin::idle();
  423. }
  424. // -------------------------------------------------------------------
  425. // Plugin state
  426. void reload() override
  427. {
  428. CARLA_SAFE_ASSERT_RETURN(pData->engine != nullptr,);
  429. CARLA_SAFE_ASSERT_RETURN(fEffect != nullptr,);
  430. carla_debug("VstPlugin::reload() - start");
  431. const EngineProcessMode processMode(pData->engine->getProccessMode());
  432. // Safely disable plugin for reload
  433. const ScopedDisabler sd(this);
  434. if (pData->active)
  435. deactivate();
  436. clearBuffers();
  437. uint32_t aIns, aOuts, mIns, mOuts, params;
  438. bool needsCtrlIn, needsCtrlOut;
  439. needsCtrlIn = needsCtrlOut = false;
  440. aIns = (fEffect->numInputs > 0) ? static_cast<uint32_t>(fEffect->numInputs) : 0;
  441. aOuts = (fEffect->numOutputs > 0) ? static_cast<uint32_t>(fEffect->numOutputs) : 0;
  442. params = (fEffect->numParams > 0) ? static_cast<uint32_t>(fEffect->numParams) : 0;
  443. if (hasMidiInput())
  444. {
  445. mIns = 1;
  446. needsCtrlIn = true;
  447. }
  448. else
  449. mIns = 0;
  450. if (hasMidiOutput())
  451. {
  452. mOuts = 1;
  453. needsCtrlOut = true;
  454. }
  455. else
  456. mOuts = 0;
  457. if (aIns > 0)
  458. {
  459. pData->audioIn.createNew(aIns);
  460. }
  461. if (aOuts > 0)
  462. {
  463. pData->audioOut.createNew(aOuts);
  464. needsCtrlIn = true;
  465. }
  466. if (params > 0)
  467. {
  468. pData->param.createNew(params, false);
  469. needsCtrlIn = true;
  470. }
  471. const uint portNameSize(pData->engine->getMaxPortNameSize());
  472. CarlaString portName;
  473. // Audio Ins
  474. for (uint32_t j=0; j < aIns; ++j)
  475. {
  476. portName.clear();
  477. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  478. {
  479. portName = pData->name;
  480. portName += ":";
  481. }
  482. if (aIns > 1)
  483. {
  484. portName += "input_";
  485. portName += CarlaString(j+1);
  486. }
  487. else
  488. portName += "input";
  489. portName.truncate(portNameSize);
  490. pData->audioIn.ports[j].port = (CarlaEngineAudioPort*)pData->client->addPort(kEnginePortTypeAudio, portName, true);
  491. pData->audioIn.ports[j].rindex = j;
  492. }
  493. // Audio Outs
  494. for (uint32_t j=0; j < aOuts; ++j)
  495. {
  496. portName.clear();
  497. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  498. {
  499. portName = pData->name;
  500. portName += ":";
  501. }
  502. if (aOuts > 1)
  503. {
  504. portName += "output_";
  505. portName += CarlaString(j+1);
  506. }
  507. else
  508. portName += "output";
  509. portName.truncate(portNameSize);
  510. pData->audioOut.ports[j].port = (CarlaEngineAudioPort*)pData->client->addPort(kEnginePortTypeAudio, portName, false);
  511. pData->audioOut.ports[j].rindex = j;
  512. }
  513. for (uint32_t j=0; j < params; ++j)
  514. {
  515. pData->param.data[j].type = PARAMETER_INPUT;
  516. pData->param.data[j].index = static_cast<int32_t>(j);
  517. pData->param.data[j].rindex = static_cast<int32_t>(j);
  518. float min, max, def, step, stepSmall, stepLarge;
  519. VstParameterProperties prop;
  520. carla_zeroStruct<VstParameterProperties>(prop);
  521. if (pData->hints & PLUGIN_HAS_COCKOS_EXTENSIONS)
  522. {
  523. double vrange[2] = { 0.0, 1.0 };
  524. bool isInteger = false;
  525. if (static_cast<uintptr_t>(dispatcher(effVendorSpecific, static_cast<int32_t>(0xdeadbef0), static_cast<int32_t>(j), vrange, 0.0f)) >= 0xbeef)
  526. {
  527. min = static_cast<float>(vrange[0]);
  528. max = static_cast<float>(vrange[1]);
  529. if (min > max)
  530. {
  531. carla_stderr2("WARNING - Broken plugin parameter min > max (with cockos extensions)");
  532. min = max - 0.1f;
  533. }
  534. else if (min == max)
  535. {
  536. carla_stderr2("WARNING - Broken plugin parameter min == max (with cockos extensions)");
  537. max = min + 0.1f;
  538. }
  539. // only use values as integer if we have a proper range
  540. if (max - min >= 1.0f)
  541. isInteger = dispatcher(effVendorSpecific, kVstParameterUsesIntStep, static_cast<int32_t>(j), nullptr, 0.0f) >= 0xbeef;
  542. }
  543. else
  544. {
  545. min = 0.0f;
  546. max = 1.0f;
  547. }
  548. if (isInteger)
  549. {
  550. step = 1.0f;
  551. stepSmall = 1.0f;
  552. stepLarge = 10.0f;
  553. }
  554. else
  555. {
  556. const float range = max - min;
  557. step = range/100.0f;
  558. stepSmall = range/1000.0f;
  559. stepLarge = range/10.0f;
  560. }
  561. }
  562. else if (dispatcher(effGetParameterProperties, static_cast<int32_t>(j), 0, &prop, 0) == 1)
  563. {
  564. if (prop.flags & kVstParameterUsesIntegerMinMax)
  565. {
  566. min = static_cast<float>(prop.minInteger);
  567. max = static_cast<float>(prop.maxInteger);
  568. if (min > max)
  569. {
  570. carla_stderr2("WARNING - Broken plugin parameter min > max");
  571. min = max - 0.1f;
  572. }
  573. else if (min == max)
  574. {
  575. carla_stderr2("WARNING - Broken plugin parameter min == max");
  576. max = min + 0.1f;
  577. }
  578. }
  579. else
  580. {
  581. min = 0.0f;
  582. max = 1.0f;
  583. }
  584. if (prop.flags & kVstParameterIsSwitch)
  585. {
  586. step = max - min;
  587. stepSmall = step;
  588. stepLarge = step;
  589. pData->param.data[j].hints |= PARAMETER_IS_BOOLEAN;
  590. }
  591. else if (prop.flags & kVstParameterUsesIntStep)
  592. {
  593. step = static_cast<float>(prop.stepInteger);
  594. stepSmall = static_cast<float>(prop.stepInteger)/10.0f;
  595. stepLarge = static_cast<float>(prop.largeStepInteger);
  596. pData->param.data[j].hints |= PARAMETER_IS_INTEGER;
  597. }
  598. else if (prop.flags & kVstParameterUsesFloatStep)
  599. {
  600. step = prop.stepFloat;
  601. stepSmall = prop.smallStepFloat;
  602. stepLarge = prop.largeStepFloat;
  603. }
  604. else
  605. {
  606. const float range = max - min;
  607. step = range/100.0f;
  608. stepSmall = range/1000.0f;
  609. stepLarge = range/10.0f;
  610. }
  611. if (prop.flags & kVstParameterCanRamp)
  612. pData->param.data[j].hints |= PARAMETER_IS_LOGARITHMIC;
  613. }
  614. else
  615. {
  616. min = 0.0f;
  617. max = 1.0f;
  618. step = 0.001f;
  619. stepSmall = 0.0001f;
  620. stepLarge = 0.1f;
  621. }
  622. pData->param.data[j].hints |= PARAMETER_IS_ENABLED;
  623. #ifndef BUILD_BRIDGE
  624. pData->param.data[j].hints |= PARAMETER_USES_CUSTOM_TEXT;
  625. #endif
  626. if ((pData->hints & PLUGIN_USES_OLD_VSTSDK) != 0 || dispatcher(effCanBeAutomated, static_cast<int32_t>(j), 0, nullptr, 0.0f) == 1)
  627. pData->param.data[j].hints |= PARAMETER_IS_AUTOMABLE;
  628. // no such thing as VST default parameters
  629. def = fEffect->getParameter(fEffect, static_cast<int32_t>(j));
  630. if (def < min)
  631. def = min;
  632. else if (def > max)
  633. def = max;
  634. pData->param.ranges[j].min = min;
  635. pData->param.ranges[j].max = max;
  636. pData->param.ranges[j].def = def;
  637. pData->param.ranges[j].step = step;
  638. pData->param.ranges[j].stepSmall = stepSmall;
  639. pData->param.ranges[j].stepLarge = stepLarge;
  640. }
  641. if (needsCtrlIn)
  642. {
  643. portName.clear();
  644. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  645. {
  646. portName = pData->name;
  647. portName += ":";
  648. }
  649. portName += "events-in";
  650. portName.truncate(portNameSize);
  651. pData->event.portIn = (CarlaEngineEventPort*)pData->client->addPort(kEnginePortTypeEvent, portName, true);
  652. }
  653. if (needsCtrlOut)
  654. {
  655. portName.clear();
  656. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  657. {
  658. portName = pData->name;
  659. portName += ":";
  660. }
  661. portName += "events-out";
  662. portName.truncate(portNameSize);
  663. pData->event.portOut = (CarlaEngineEventPort*)pData->client->addPort(kEnginePortTypeEvent, portName, false);
  664. }
  665. // plugin hints
  666. const intptr_t vstCategory = dispatcher(effGetPlugCategory, 0, 0, nullptr, 0.0f);
  667. pData->hints = 0x0;
  668. if (vstCategory == kPlugCategSynth || vstCategory == kPlugCategGenerator)
  669. pData->hints |= PLUGIN_IS_SYNTH;
  670. if (fEffect->flags & effFlagsHasEditor)
  671. {
  672. pData->hints |= PLUGIN_HAS_CUSTOM_UI;
  673. if (fUi.type == UI::UI_EMBED)
  674. pData->hints |= PLUGIN_NEEDS_SINGLE_THREAD;
  675. }
  676. if (dispatcher(effGetVstVersion, 0, 0, nullptr, 0.0f) < kVstVersion)
  677. pData->hints |= PLUGIN_USES_OLD_VSTSDK;
  678. if ((fEffect->flags & effFlagsCanReplacing) != 0 && fEffect->processReplacing != fEffect->process)
  679. pData->hints |= PLUGIN_CAN_PROCESS_REPLACING;
  680. if (static_cast<uintptr_t>(dispatcher(effCanDo, 0, 0, const_cast<char*>("hasCockosExtensions"), 0.0f)) == 0xbeef0000)
  681. pData->hints |= PLUGIN_HAS_COCKOS_EXTENSIONS;
  682. if (aOuts > 0 && (aIns == aOuts || aIns == 1))
  683. pData->hints |= PLUGIN_CAN_DRYWET;
  684. if (aOuts > 0)
  685. pData->hints |= PLUGIN_CAN_VOLUME;
  686. if (aOuts >= 2 && aOuts % 2 == 0)
  687. pData->hints |= PLUGIN_CAN_BALANCE;
  688. // extra plugin hints
  689. pData->extraHints = 0x0;
  690. if (mIns > 0)
  691. pData->extraHints |= PLUGIN_EXTRA_HINT_HAS_MIDI_IN;
  692. if (mOuts > 0)
  693. pData->extraHints |= PLUGIN_EXTRA_HINT_HAS_MIDI_OUT;
  694. if (aIns <= 2 && aOuts <= 2 && (aIns == aOuts || aIns == 0 || aOuts == 0))
  695. pData->extraHints |= PLUGIN_EXTRA_HINT_CAN_RUN_RACK;
  696. // dummy pre-start to get latency and wantEvents() on old plugins
  697. {
  698. activate();
  699. deactivate();
  700. }
  701. // check latency
  702. if (pData->hints & PLUGIN_CAN_DRYWET)
  703. {
  704. #ifdef VESTIGE_HEADER
  705. char* const empty3Ptr = &fEffect->empty3[0];
  706. int32_t initialDelay = *(int32_t*)empty3Ptr;
  707. pData->latency = (initialDelay > 0) ? static_cast<uint32_t>(initialDelay) : 0;
  708. #else
  709. pData->latency = (fEffect->initialDelay > 0) ? static_cast<uint32_t>(fEffect->initialDelay) : 0;
  710. #endif
  711. pData->client->setLatency(pData->latency);
  712. #ifndef BUILD_BRIDGE
  713. pData->recreateLatencyBuffers();
  714. #endif
  715. }
  716. // special plugin fixes
  717. // 1. IL Harmless - disable threaded processing
  718. if (fEffect->uniqueID == 1229484653)
  719. {
  720. char strBuf[STR_MAX+1] = { '\0' };
  721. getLabel(strBuf);
  722. if (std::strcmp(strBuf, "IL Harmless") == 0)
  723. {
  724. // TODO - disable threaded processing
  725. }
  726. }
  727. //bufferSizeChanged(pData->engine->getBufferSize());
  728. reloadPrograms(true);
  729. if (pData->active)
  730. activate();
  731. carla_debug("VstPlugin::reload() - end");
  732. }
  733. void reloadPrograms(const bool doInit) override
  734. {
  735. carla_debug("VstPlugin::reloadPrograms(%s)", bool2str(doInit));
  736. const uint32_t oldCount = pData->prog.count;
  737. const int32_t current = pData->prog.current;
  738. // Delete old programs
  739. pData->prog.clear();
  740. // Query new programs
  741. uint32_t newCount = (fEffect->numPrograms > 0) ? static_cast<uint32_t>(fEffect->numPrograms) : 0;
  742. if (newCount > 0)
  743. {
  744. pData->prog.createNew(newCount);
  745. // Update names
  746. for (int32_t i=0; i < fEffect->numPrograms; ++i)
  747. {
  748. char strBuf[STR_MAX+1] = { '\0' };
  749. if (dispatcher(effGetProgramNameIndexed, i, 0, strBuf, 0.0f) != 1)
  750. {
  751. // program will be [re-]changed later
  752. dispatcher(effSetProgram, 0, i, nullptr, 0.0f);
  753. dispatcher(effGetProgramName, 0, 0, strBuf, 0.0f);
  754. }
  755. pData->prog.names[i] = carla_strdup(strBuf);
  756. }
  757. }
  758. #ifndef BUILD_BRIDGE
  759. // Update OSC Names
  760. if (pData->engine->isOscControlRegistered())
  761. {
  762. pData->engine->oscSend_control_set_program_count(pData->id, newCount);
  763. for (uint32_t i=0; i < newCount; ++i)
  764. pData->engine->oscSend_control_set_program_name(pData->id, i, pData->prog.names[i]);
  765. }
  766. #endif
  767. if (doInit)
  768. {
  769. if (newCount > 0)
  770. setProgram(0, false, false, false);
  771. }
  772. else
  773. {
  774. // Check if current program is invalid
  775. bool programChanged = false;
  776. if (newCount == oldCount+1)
  777. {
  778. // one program added, probably created by user
  779. pData->prog.current = static_cast<int32_t>(oldCount);
  780. programChanged = true;
  781. }
  782. else if (current < 0 && newCount > 0)
  783. {
  784. // programs exist now, but not before
  785. pData->prog.current = 0;
  786. programChanged = true;
  787. }
  788. else if (current >= 0 && newCount == 0)
  789. {
  790. // programs existed before, but not anymore
  791. pData->prog.current = -1;
  792. programChanged = true;
  793. }
  794. else if (current >= static_cast<int32_t>(newCount))
  795. {
  796. // current program > count
  797. pData->prog.current = 0;
  798. programChanged = true;
  799. }
  800. else
  801. {
  802. // no change
  803. pData->prog.current = current;
  804. }
  805. if (programChanged)
  806. {
  807. setProgram(pData->prog.current, true, true, true);
  808. }
  809. else
  810. {
  811. // Program was changed during update, re-set it
  812. if (pData->prog.current >= 0)
  813. dispatcher(effSetProgram, 0, pData->prog.current, nullptr, 0.0f);
  814. }
  815. pData->engine->callback(ENGINE_CALLBACK_RELOAD_PROGRAMS, pData->id, 0, 0, 0.0f, nullptr);
  816. }
  817. }
  818. // -------------------------------------------------------------------
  819. // Plugin processing
  820. void activate() noexcept override
  821. {
  822. CARLA_SAFE_ASSERT_RETURN(fEffect != nullptr,);
  823. try {
  824. dispatcher(effMainsChanged, 0, 1, nullptr, 0.0f);
  825. } catch(...) {}
  826. try {
  827. dispatcher(effStartProcess, 0, 0, nullptr, 0.0f);
  828. } catch(...) {}
  829. }
  830. void deactivate() noexcept override
  831. {
  832. CARLA_SAFE_ASSERT_RETURN(fEffect != nullptr,);
  833. try {
  834. dispatcher(effStopProcess, 0, 0, nullptr, 0.0f);
  835. } catch(...) {}
  836. try {
  837. dispatcher(effMainsChanged, 0, 0, nullptr, 0.0f);
  838. } catch(...) {}
  839. }
  840. void process(float** const inBuffer, float** const outBuffer, const uint32_t frames) override
  841. {
  842. fProcThread = pthread_self();
  843. // --------------------------------------------------------------------------------------------------------
  844. // Check if active
  845. if (! pData->active)
  846. {
  847. // disable any output sound
  848. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  849. FloatVectorOperations::clear(outBuffer[i], frames);
  850. return;
  851. }
  852. fMidiEventCount = 0;
  853. carla_zeroStruct<VstMidiEvent>(fMidiEvents, kPluginMaxMidiEvents*2);
  854. // --------------------------------------------------------------------------------------------------------
  855. // Check if needs reset
  856. if (pData->needsReset)
  857. {
  858. if (pData->options & PLUGIN_OPTION_SEND_ALL_SOUND_OFF)
  859. {
  860. fMidiEventCount = MAX_MIDI_CHANNELS*2;
  861. for (uint8_t i=0, k=MAX_MIDI_CHANNELS; i < MAX_MIDI_CHANNELS; ++i)
  862. {
  863. fMidiEvents[k].type = kVstMidiType;
  864. fMidiEvents[k].byteSize = static_cast<int32_t>(sizeof(VstMidiEvent));
  865. fMidiEvents[k].midiData[0] = static_cast<char>(MIDI_STATUS_CONTROL_CHANGE + k);
  866. fMidiEvents[k].midiData[1] = MIDI_CONTROL_ALL_NOTES_OFF;
  867. fMidiEvents[k+i].type = kVstMidiType;
  868. fMidiEvents[k+i].byteSize = static_cast<int32_t>(sizeof(VstMidiEvent));
  869. fMidiEvents[k+i].midiData[0] = static_cast<char>(MIDI_STATUS_CONTROL_CHANGE + k);
  870. fMidiEvents[k+i].midiData[1] = MIDI_CONTROL_ALL_SOUND_OFF;
  871. }
  872. }
  873. else if (pData->ctrlChannel >= 0 && pData->ctrlChannel < MAX_MIDI_CHANNELS)
  874. {
  875. fMidiEventCount = MAX_MIDI_NOTE;
  876. for (uint8_t i=0; i < MAX_MIDI_NOTE; ++i)
  877. {
  878. fMidiEvents[i].type = kVstMidiType;
  879. fMidiEvents[i].byteSize = static_cast<int32_t>(sizeof(VstMidiEvent));
  880. fMidiEvents[i].midiData[0] = static_cast<char>(MIDI_STATUS_NOTE_OFF + pData->ctrlChannel);
  881. fMidiEvents[i].midiData[1] = static_cast<char>(i);
  882. }
  883. }
  884. #ifndef BUILD_BRIDGE
  885. if (pData->latency > 0)
  886. {
  887. for (uint32_t i=0; i < pData->audioIn.count; ++i)
  888. FloatVectorOperations::clear(pData->latencyBuffers[i], pData->latency);
  889. }
  890. #endif
  891. pData->needsReset = false;
  892. }
  893. // --------------------------------------------------------------------------------------------------------
  894. // Set TimeInfo
  895. const EngineTimeInfo& timeInfo(pData->engine->getTimeInfo());
  896. fTimeInfo.flags = kVstTransportChanged;
  897. if (timeInfo.playing)
  898. fTimeInfo.flags |= kVstTransportPlaying;
  899. fTimeInfo.samplePos = double(timeInfo.frame);
  900. fTimeInfo.sampleRate = pData->engine->getSampleRate();
  901. if (timeInfo.usecs != 0)
  902. {
  903. fTimeInfo.nanoSeconds = double(timeInfo.usecs)/1000.0;
  904. fTimeInfo.flags |= kVstNanosValid;
  905. }
  906. if (timeInfo.valid & EngineTimeInfo::kValidBBT)
  907. {
  908. double ppqBar = double(timeInfo.bbt.bar - 1) * timeInfo.bbt.beatsPerBar;
  909. double ppqBeat = double(timeInfo.bbt.beat - 1);
  910. double ppqTick = double(timeInfo.bbt.tick) / timeInfo.bbt.ticksPerBeat;
  911. // PPQ Pos
  912. fTimeInfo.ppqPos = ppqBar + ppqBeat + ppqTick;
  913. fTimeInfo.flags |= kVstPpqPosValid;
  914. // Tempo
  915. fTimeInfo.tempo = timeInfo.bbt.beatsPerMinute;
  916. fTimeInfo.flags |= kVstTempoValid;
  917. // Bars
  918. fTimeInfo.barStartPos = ppqBar;
  919. fTimeInfo.flags |= kVstBarsValid;
  920. // Time Signature
  921. fTimeInfo.timeSigNumerator = static_cast<int32_t>(timeInfo.bbt.beatsPerBar);
  922. fTimeInfo.timeSigDenominator = static_cast<int32_t>(timeInfo.bbt.beatType);
  923. fTimeInfo.flags |= kVstTimeSigValid;
  924. }
  925. else
  926. {
  927. // Tempo
  928. fTimeInfo.tempo = 120.0;
  929. fTimeInfo.flags |= kVstTempoValid;
  930. // Time Signature
  931. fTimeInfo.timeSigNumerator = 4;
  932. fTimeInfo.timeSigDenominator = 4;
  933. fTimeInfo.flags |= kVstTimeSigValid;
  934. // Missing info
  935. fTimeInfo.ppqPos = 0.0;
  936. fTimeInfo.barStartPos = 0.0;
  937. }
  938. // --------------------------------------------------------------------------------------------------------
  939. // Event Input and Processing
  940. if (pData->event.portIn != nullptr)
  941. {
  942. // ----------------------------------------------------------------------------------------------------
  943. // MIDI Input (External)
  944. if (pData->extNotes.mutex.tryLock())
  945. {
  946. ExternalMidiNote note = { 0, 0, 0 };
  947. for (; fMidiEventCount < kPluginMaxMidiEvents*2 && ! pData->extNotes.data.isEmpty();)
  948. {
  949. note = pData->extNotes.data.getFirst(note, true);
  950. CARLA_SAFE_ASSERT_CONTINUE(note.channel >= 0 && note.channel < MAX_MIDI_CHANNELS);
  951. fMidiEvents[fMidiEventCount].type = kVstMidiType;
  952. fMidiEvents[fMidiEventCount].byteSize = static_cast<int32_t>(sizeof(VstMidiEvent));
  953. fMidiEvents[fMidiEventCount].midiData[0] = static_cast<char>((note.velo > 0 ? MIDI_STATUS_NOTE_ON : MIDI_STATUS_NOTE_OFF) | (note.channel & MIDI_CHANNEL_BIT));
  954. fMidiEvents[fMidiEventCount].midiData[1] = static_cast<char>(note.note);
  955. fMidiEvents[fMidiEventCount].midiData[2] = static_cast<char>(note.velo);
  956. ++fMidiEventCount;
  957. }
  958. pData->extNotes.mutex.unlock();
  959. } // End of MIDI Input (External)
  960. // ----------------------------------------------------------------------------------------------------
  961. // Event Input (System)
  962. bool allNotesOffSent = false;
  963. bool isSampleAccurate = (pData->options & PLUGIN_OPTION_FIXED_BUFFERS) == 0;
  964. uint32_t numEvents = pData->event.portIn->getEventCount();
  965. uint32_t startTime = 0;
  966. uint32_t timeOffset = 0;
  967. for (uint32_t i=0; i < numEvents; ++i)
  968. {
  969. const EngineEvent& event(pData->event.portIn->getEvent(i));
  970. if (event.time >= frames)
  971. continue;
  972. CARLA_ASSERT_INT2(event.time >= timeOffset, event.time, timeOffset);
  973. if (isSampleAccurate && event.time > timeOffset)
  974. {
  975. if (processSingle(inBuffer, outBuffer, event.time - timeOffset, timeOffset))
  976. {
  977. startTime = 0;
  978. timeOffset = event.time;
  979. if (fMidiEventCount > 0)
  980. {
  981. carla_zeroStruct<VstMidiEvent>(fMidiEvents, fMidiEventCount);
  982. fMidiEventCount = 0;
  983. }
  984. }
  985. else
  986. startTime += timeOffset;
  987. }
  988. switch (event.type)
  989. {
  990. case kEngineEventTypeNull:
  991. break;
  992. case kEngineEventTypeControl: {
  993. const EngineControlEvent& ctrlEvent(event.ctrl);
  994. switch (ctrlEvent.type)
  995. {
  996. case kEngineControlEventTypeNull:
  997. break;
  998. case kEngineControlEventTypeParameter: {
  999. #ifndef BUILD_BRIDGE
  1000. // Control backend stuff
  1001. if (event.channel == pData->ctrlChannel)
  1002. {
  1003. float value;
  1004. if (MIDI_IS_CONTROL_BREATH_CONTROLLER(ctrlEvent.param) && (pData->hints & PLUGIN_CAN_DRYWET) != 0)
  1005. {
  1006. value = ctrlEvent.value;
  1007. setDryWet(value, false, false);
  1008. pData->postponeRtEvent(kPluginPostRtEventParameterChange, PARAMETER_DRYWET, 0, value);
  1009. break;
  1010. }
  1011. if (MIDI_IS_CONTROL_CHANNEL_VOLUME(ctrlEvent.param) && (pData->hints & PLUGIN_CAN_VOLUME) != 0)
  1012. {
  1013. value = ctrlEvent.value*127.0f/100.0f;
  1014. setVolume(value, false, false);
  1015. pData->postponeRtEvent(kPluginPostRtEventParameterChange, PARAMETER_VOLUME, 0, value);
  1016. break;
  1017. }
  1018. if (MIDI_IS_CONTROL_BALANCE(ctrlEvent.param) && (pData->hints & PLUGIN_CAN_BALANCE) != 0)
  1019. {
  1020. float left, right;
  1021. value = ctrlEvent.value/0.5f - 1.0f;
  1022. if (value < 0.0f)
  1023. {
  1024. left = -1.0f;
  1025. right = (value*2.0f)+1.0f;
  1026. }
  1027. else if (value > 0.0f)
  1028. {
  1029. left = (value*2.0f)-1.0f;
  1030. right = 1.0f;
  1031. }
  1032. else
  1033. {
  1034. left = -1.0f;
  1035. right = 1.0f;
  1036. }
  1037. setBalanceLeft(left, false, false);
  1038. setBalanceRight(right, false, false);
  1039. pData->postponeRtEvent(kPluginPostRtEventParameterChange, PARAMETER_BALANCE_LEFT, 0, left);
  1040. pData->postponeRtEvent(kPluginPostRtEventParameterChange, PARAMETER_BALANCE_RIGHT, 0, right);
  1041. break;
  1042. }
  1043. }
  1044. #endif
  1045. // Control plugin parameters
  1046. uint32_t k;
  1047. for (k=0; k < pData->param.count; ++k)
  1048. {
  1049. if (pData->param.data[k].midiChannel != event.channel)
  1050. continue;
  1051. if (pData->param.data[k].midiCC != ctrlEvent.param)
  1052. continue;
  1053. if (pData->param.data[k].type != PARAMETER_INPUT)
  1054. continue;
  1055. if ((pData->param.data[k].hints & PARAMETER_IS_AUTOMABLE) == 0)
  1056. continue;
  1057. float value;
  1058. if (pData->param.data[k].hints & PARAMETER_IS_BOOLEAN)
  1059. {
  1060. value = (ctrlEvent.value < 0.5f) ? pData->param.ranges[k].min : pData->param.ranges[k].max;
  1061. }
  1062. else
  1063. {
  1064. value = pData->param.ranges[k].getUnnormalizedValue(ctrlEvent.value);
  1065. if (pData->param.data[k].hints & PARAMETER_IS_INTEGER)
  1066. value = std::rint(value);
  1067. }
  1068. setParameterValue(k, value, false, false, false);
  1069. pData->postponeRtEvent(kPluginPostRtEventParameterChange, static_cast<int32_t>(k), 0, value);
  1070. break;
  1071. }
  1072. // check if event is already handled
  1073. if (k != pData->param.count)
  1074. break;
  1075. if ((pData->options & PLUGIN_OPTION_SEND_CONTROL_CHANGES) != 0 && ctrlEvent.param <= 0x5F)
  1076. {
  1077. if (fMidiEventCount >= kPluginMaxMidiEvents*2)
  1078. continue;
  1079. carla_zeroStruct<VstMidiEvent>(fMidiEvents[fMidiEventCount]);
  1080. fMidiEvents[fMidiEventCount].type = kVstMidiType;
  1081. fMidiEvents[fMidiEventCount].byteSize = static_cast<int32_t>(sizeof(VstMidiEvent));
  1082. fMidiEvents[fMidiEventCount].midiData[0] = static_cast<char>(MIDI_STATUS_CONTROL_CHANGE + event.channel);
  1083. fMidiEvents[fMidiEventCount].midiData[1] = static_cast<char>(ctrlEvent.param);
  1084. fMidiEvents[fMidiEventCount].midiData[2] = char(ctrlEvent.value*127.0f);
  1085. fMidiEvents[fMidiEventCount].deltaFrames = static_cast<int32_t>(isSampleAccurate ? startTime : event.time);
  1086. ++fMidiEventCount;
  1087. }
  1088. break;
  1089. } // case kEngineControlEventTypeParameter
  1090. case kEngineControlEventTypeMidiBank:
  1091. break;
  1092. case kEngineControlEventTypeMidiProgram:
  1093. if (event.channel == pData->ctrlChannel && (pData->options & PLUGIN_OPTION_MAP_PROGRAM_CHANGES) != 0)
  1094. {
  1095. if (ctrlEvent.param < pData->prog.count)
  1096. {
  1097. setProgram(ctrlEvent.param, false, false, false);
  1098. pData->postponeRtEvent(kPluginPostRtEventProgramChange, ctrlEvent.param, 0, 0.0f);
  1099. break;
  1100. }
  1101. }
  1102. break;
  1103. case kEngineControlEventTypeAllSoundOff:
  1104. if (pData->options & PLUGIN_OPTION_SEND_ALL_SOUND_OFF)
  1105. {
  1106. if (fMidiEventCount >= kPluginMaxMidiEvents*2)
  1107. continue;
  1108. carla_zeroStruct<VstMidiEvent>(fMidiEvents[fMidiEventCount]);
  1109. fMidiEvents[fMidiEventCount].type = kVstMidiType;
  1110. fMidiEvents[fMidiEventCount].byteSize = static_cast<int32_t>(sizeof(VstMidiEvent));
  1111. fMidiEvents[fMidiEventCount].midiData[0] = static_cast<char>(MIDI_STATUS_CONTROL_CHANGE + event.channel);
  1112. fMidiEvents[fMidiEventCount].midiData[1] = MIDI_CONTROL_ALL_SOUND_OFF;
  1113. fMidiEvents[fMidiEventCount].deltaFrames = static_cast<int32_t>(isSampleAccurate ? startTime : event.time);
  1114. ++fMidiEventCount;
  1115. }
  1116. break;
  1117. case kEngineControlEventTypeAllNotesOff:
  1118. if (pData->options & PLUGIN_OPTION_SEND_ALL_SOUND_OFF)
  1119. {
  1120. if (event.channel == pData->ctrlChannel && ! allNotesOffSent)
  1121. {
  1122. allNotesOffSent = true;
  1123. sendMidiAllNotesOffToCallback();
  1124. }
  1125. if (fMidiEventCount >= kPluginMaxMidiEvents*2)
  1126. continue;
  1127. carla_zeroStruct<VstMidiEvent>(fMidiEvents[fMidiEventCount]);
  1128. fMidiEvents[fMidiEventCount].type = kVstMidiType;
  1129. fMidiEvents[fMidiEventCount].byteSize = static_cast<int32_t>(sizeof(VstMidiEvent));
  1130. fMidiEvents[fMidiEventCount].midiData[0] = static_cast<char>(MIDI_STATUS_CONTROL_CHANGE + event.channel);
  1131. fMidiEvents[fMidiEventCount].midiData[1] = MIDI_CONTROL_ALL_NOTES_OFF;
  1132. fMidiEvents[fMidiEventCount].deltaFrames = static_cast<int32_t>(isSampleAccurate ? startTime : event.time);
  1133. ++fMidiEventCount;
  1134. }
  1135. break;
  1136. } // switch (ctrlEvent.type)
  1137. break;
  1138. } // case kEngineEventTypeControl
  1139. case kEngineEventTypeMidi: {
  1140. if (fMidiEventCount >= kPluginMaxMidiEvents*2)
  1141. continue;
  1142. const EngineMidiEvent& midiEvent(event.midi);
  1143. uint8_t status = static_cast<uint8_t>(MIDI_GET_STATUS_FROM_DATA(midiEvent.data));
  1144. uint8_t channel = event.channel;
  1145. // Fix bad note-off (per VST spec)
  1146. if (MIDI_IS_STATUS_NOTE_ON(status) && midiEvent.data[2] == 0)
  1147. status = MIDI_STATUS_NOTE_OFF;
  1148. if (status == MIDI_STATUS_CHANNEL_PRESSURE && (pData->options & PLUGIN_OPTION_SEND_CHANNEL_PRESSURE) == 0)
  1149. continue;
  1150. if (status == MIDI_STATUS_CONTROL_CHANGE && (pData->options & PLUGIN_OPTION_SEND_CONTROL_CHANGES) == 0)
  1151. continue;
  1152. if (status == MIDI_STATUS_POLYPHONIC_AFTERTOUCH && (pData->options & PLUGIN_OPTION_SEND_NOTE_AFTERTOUCH) == 0)
  1153. continue;
  1154. if (status == MIDI_STATUS_PITCH_WHEEL_CONTROL && (pData->options & PLUGIN_OPTION_SEND_PITCHBEND) == 0)
  1155. continue;
  1156. carla_zeroStruct<VstMidiEvent>(fMidiEvents[fMidiEventCount]);
  1157. fMidiEvents[fMidiEventCount].type = kVstMidiType;
  1158. fMidiEvents[fMidiEventCount].byteSize = static_cast<int32_t>(sizeof(VstMidiEvent));
  1159. fMidiEvents[fMidiEventCount].midiData[0] = static_cast<char>(status + channel);
  1160. fMidiEvents[fMidiEventCount].midiData[1] = static_cast<char>(midiEvent.data[1]);
  1161. fMidiEvents[fMidiEventCount].midiData[2] = static_cast<char>(midiEvent.data[2]);
  1162. fMidiEvents[fMidiEventCount].deltaFrames = static_cast<int32_t>(isSampleAccurate ? startTime : event.time);
  1163. ++fMidiEventCount;
  1164. if (status == MIDI_STATUS_NOTE_ON)
  1165. pData->postponeRtEvent(kPluginPostRtEventNoteOn, channel, midiEvent.data[1], midiEvent.data[2]);
  1166. else if (status == MIDI_STATUS_NOTE_OFF)
  1167. pData->postponeRtEvent(kPluginPostRtEventNoteOff, channel, midiEvent.data[1], 0.0f);
  1168. break;
  1169. } // case kEngineEventTypeMidi
  1170. } // switch (event.type)
  1171. }
  1172. pData->postRtEvents.trySplice();
  1173. if (frames > timeOffset)
  1174. processSingle(inBuffer, outBuffer, frames - timeOffset, timeOffset);
  1175. } // End of Event Input and Processing
  1176. // --------------------------------------------------------------------------------------------------------
  1177. // Plugin processing (no events)
  1178. else
  1179. {
  1180. processSingle(inBuffer, outBuffer, frames, 0);
  1181. } // End of Plugin processing (no events)
  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. FloatVectorOperations::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. FloatVectorOperations::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 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_UI) && 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_UI) && 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. // -------------------------------------------------------------------------------------------------------------------