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.

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