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.

2572 lines
87KB

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