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.

2566 lines
86KB

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