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.

2749 lines
93KB

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