Audio plugin host https://kx.studio/carla
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2516 lines
85KB

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