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.

2516 lines
84KB

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