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.

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