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.

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