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.

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