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.

2810 lines
96KB

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