The JUCE cross-platform C++ framework, with DISTRHO/KXStudio specific changes
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.

2827 lines
103KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2017 - ROLI Ltd.
  5. JUCE is an open source library subject to commercial or open-source
  6. licensing.
  7. By using JUCE, you agree to the terms of both the JUCE 5 End-User License
  8. Agreement and JUCE 5 Privacy Policy (both updated and effective as of the
  9. 27th April 2017).
  10. End User License Agreement: www.juce.com/juce-5-licence
  11. Privacy Policy: www.juce.com/juce-5-privacy-policy
  12. Or: You may also use this code under the terms of the GPL v3 (see
  13. www.gnu.org/licenses).
  14. JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
  15. EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
  16. DISCLAIMED.
  17. ==============================================================================
  18. */
  19. #include "../../juce_core/system/juce_TargetPlatform.h"
  20. //==============================================================================
  21. #if JucePlugin_Build_VST3 && (__APPLE_CPP__ || __APPLE_CC__ || _WIN32 || _WIN64)
  22. #if JUCE_PLUGINHOST_VST3 && (JUCE_MAC || JUCE_WINDOWS)
  23. #undef JUCE_VST3HEADERS_INCLUDE_HEADERS_ONLY
  24. #define JUCE_VST3HEADERS_INCLUDE_HEADERS_ONLY 1
  25. #endif
  26. #include "../../juce_audio_processors/format_types/juce_VST3Headers.h"
  27. #undef JUCE_VST3HEADERS_INCLUDE_HEADERS_ONLY
  28. #include "../utility/juce_CheckSettingMacros.h"
  29. #include "../utility/juce_IncludeModuleHeaders.h"
  30. #include "../utility/juce_WindowsHooks.h"
  31. #include "../utility/juce_FakeMouseMoveGenerator.h"
  32. #include "../../juce_audio_processors/format_types/juce_LegacyAudioParameter.cpp"
  33. #include "../../juce_audio_processors/format_types/juce_VST3Common.h"
  34. #ifndef JUCE_VST3_CAN_REPLACE_VST2
  35. #define JUCE_VST3_CAN_REPLACE_VST2 1
  36. #endif
  37. #if JUCE_VST3_CAN_REPLACE_VST2
  38. namespace Vst2
  39. {
  40. #include "../../juce_audio_processors/format_types/VST3_SDK/pluginterfaces/vst2.x/vstfxstore.h"
  41. }
  42. #endif
  43. #ifndef JUCE_VST3_EMULATE_MIDI_CC_WITH_PARAMETERS
  44. #define JUCE_VST3_EMULATE_MIDI_CC_WITH_PARAMETERS 1
  45. #endif
  46. #if JUCE_VST3_CAN_REPLACE_VST2
  47. #if JUCE_MSVC
  48. #pragma warning (push)
  49. #pragma warning (disable: 4514 4996)
  50. #endif
  51. #if JUCE_MSVC
  52. #pragma warning (pop)
  53. #endif
  54. #endif
  55. namespace juce
  56. {
  57. using namespace Steinberg;
  58. //==============================================================================
  59. #if JUCE_MAC
  60. extern void initialiseMacVST();
  61. #if ! JUCE_64BIT
  62. extern void updateEditorCompBoundsVST (Component*);
  63. #endif
  64. extern JUCE_API void* attachComponentToWindowRefVST (Component*, void* parentWindowOrView, bool isNSView);
  65. extern JUCE_API void detachComponentFromWindowRefVST (Component*, void* nsWindow, bool isNSView);
  66. extern JUCE_API void setNativeHostWindowSizeVST (void* window, Component*, int newWidth, int newHeight, bool isNSView);
  67. #endif
  68. //==============================================================================
  69. class JuceAudioProcessor : public FUnknown
  70. {
  71. public:
  72. JuceAudioProcessor (AudioProcessor* source) noexcept
  73. : audioProcessor (source)
  74. {
  75. setupParameters();
  76. }
  77. virtual ~JuceAudioProcessor() {}
  78. AudioProcessor* get() const noexcept { return audioProcessor.get(); }
  79. JUCE_DECLARE_VST3_COM_QUERY_METHODS
  80. JUCE_DECLARE_VST3_COM_REF_METHODS
  81. //==============================================================================
  82. inline Vst::ParamID getVSTParamIDForIndex (int paramIndex) const noexcept
  83. {
  84. #if JUCE_FORCE_USE_LEGACY_PARAM_IDS
  85. return static_cast<Vst::ParamID> (paramIndex);
  86. #else
  87. return vstParamIDs.getReference (paramIndex);
  88. #endif
  89. }
  90. AudioProcessorParameter* getParamForVSTParamID (Vst::ParamID paramID) const noexcept
  91. {
  92. return paramMap[static_cast<int32> (paramID)];
  93. }
  94. AudioProcessorParameter* getBypassParameter() const noexcept
  95. {
  96. return getParamForVSTParamID (bypassParamID);
  97. }
  98. int getNumParameters() const noexcept { return vstParamIDs.size(); }
  99. bool isUsingManagedParameters() const noexcept { return juceParameters.isUsingManagedParameters(); }
  100. //==============================================================================
  101. static const FUID iid;
  102. Array<Vst::ParamID> vstParamIDs;
  103. Vst::ParamID bypassParamID = 0;
  104. bool bypassIsRegularParameter = false;
  105. private:
  106. enum InternalParameters
  107. {
  108. paramBypass = 0x62797073 // 'byps'
  109. };
  110. //==============================================================================
  111. bool isBypassPartOfRegularParemeters() const
  112. {
  113. int n = juceParameters.getNumParameters();
  114. if (auto* bypassParam = audioProcessor->getBypassParameter())
  115. for (int i = 0; i < n; ++i)
  116. if (juceParameters.getParamForIndex (i) == bypassParam)
  117. return true;
  118. return false;
  119. }
  120. void setupParameters()
  121. {
  122. #if JUCE_FORCE_USE_LEGACY_PARAM_IDS
  123. const bool forceLegacyParamIDs = true;
  124. #else
  125. const bool forceLegacyParamIDs = false;
  126. #endif
  127. juceParameters.update (*audioProcessor, forceLegacyParamIDs);
  128. auto numParameters = juceParameters.getNumParameters();
  129. bool vst3WrapperProvidedBypassParam = false;
  130. auto* bypassParameter = audioProcessor->getBypassParameter();
  131. if (bypassParameter == nullptr)
  132. {
  133. vst3WrapperProvidedBypassParam = true;
  134. ownedBypassParameter.reset (new AudioParameterBool ("byps", "Bypass", false, {}, {}, {}));
  135. bypassParameter = ownedBypassParameter.get();
  136. }
  137. // if the bypass parameter is not part of the exported parameters that the plug-in supports
  138. // then add it to the end of the list as VST3 requires the bypass parameter to be exported!
  139. bypassIsRegularParameter = isBypassPartOfRegularParemeters();
  140. if (! bypassIsRegularParameter)
  141. juceParameters.params.add (bypassParameter);
  142. int i = 0;
  143. for (auto* juceParam : juceParameters.params)
  144. {
  145. bool isBypassParameter = (juceParam == bypassParameter);
  146. Vst::ParamID vstParamID = forceLegacyParamIDs ? static_cast<Vst::ParamID> (i++)
  147. : generateVSTParamIDForParam (juceParam);
  148. if (isBypassParameter)
  149. {
  150. // we need to remain backward compatible with the old bypass id
  151. if (vst3WrapperProvidedBypassParam)
  152. vstParamID = static_cast<Vst::ParamID> (isUsingManagedParameters() ? paramBypass : numParameters);
  153. bypassParamID = vstParamID;
  154. }
  155. vstParamIDs.add (vstParamID);
  156. paramMap.set (static_cast<int32> (vstParamID), juceParam);
  157. }
  158. }
  159. Vst::ParamID generateVSTParamIDForParam (AudioProcessorParameter* param)
  160. {
  161. auto juceParamID = LegacyAudioParameter::getParamID (param, false);
  162. #if JUCE_FORCE_USE_LEGACY_PARAM_IDS
  163. return static_cast<Vst::ParamID> (juceParamID.getIntValue());
  164. #else
  165. auto paramHash = static_cast<Vst::ParamID> (juceParamID.hashCode());
  166. #if JUCE_USE_STUDIO_ONE_COMPATIBLE_PARAMETERS
  167. // studio one doesn't like negative parameters
  168. paramHash &= ~(1 << (sizeof (Vst::ParamID) * 8 - 1));
  169. #endif
  170. return paramHash;
  171. #endif
  172. }
  173. //==============================================================================
  174. Atomic<int> refCount;
  175. std::unique_ptr<AudioProcessor> audioProcessor;
  176. ScopedJuceInitialiser_GUI libraryInitialiser;
  177. //==============================================================================
  178. LegacyAudioParametersWrapper juceParameters;
  179. HashMap<int32, AudioProcessorParameter*> paramMap;
  180. std::unique_ptr<AudioProcessorParameter> ownedBypassParameter;
  181. JuceAudioProcessor() = delete;
  182. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (JuceAudioProcessor)
  183. };
  184. class JuceVST3Component;
  185. static ThreadLocalValue<bool> inParameterChangedCallback;
  186. //==============================================================================
  187. class JuceVST3EditController : public Vst::EditController,
  188. public Vst::IMidiMapping,
  189. public Vst::ChannelContext::IInfoListener,
  190. public AudioProcessorListener,
  191. private AudioProcessorParameter::Listener
  192. {
  193. public:
  194. JuceVST3EditController (Vst::IHostApplication* host)
  195. {
  196. if (host != nullptr)
  197. host->queryInterface (FUnknown::iid, (void**) &hostContext);
  198. }
  199. //==============================================================================
  200. static const FUID iid;
  201. //==============================================================================
  202. #if JUCE_CLANG
  203. #pragma clang diagnostic push
  204. #pragma clang diagnostic ignored "-Winconsistent-missing-override"
  205. #endif
  206. REFCOUNT_METHODS (ComponentBase)
  207. #if JUCE_CLANG
  208. #pragma clang diagnostic pop
  209. #endif
  210. tresult PLUGIN_API queryInterface (const TUID targetIID, void** obj) override
  211. {
  212. TEST_FOR_AND_RETURN_IF_VALID (targetIID, FObject)
  213. TEST_FOR_AND_RETURN_IF_VALID (targetIID, JuceVST3EditController)
  214. TEST_FOR_AND_RETURN_IF_VALID (targetIID, Vst::IEditController)
  215. TEST_FOR_AND_RETURN_IF_VALID (targetIID, Vst::IEditController2)
  216. TEST_FOR_AND_RETURN_IF_VALID (targetIID, Vst::IConnectionPoint)
  217. TEST_FOR_AND_RETURN_IF_VALID (targetIID, Vst::IMidiMapping)
  218. TEST_FOR_AND_RETURN_IF_VALID (targetIID, Vst::ChannelContext::IInfoListener)
  219. TEST_FOR_COMMON_BASE_AND_RETURN_IF_VALID (targetIID, IPluginBase, Vst::IEditController)
  220. TEST_FOR_COMMON_BASE_AND_RETURN_IF_VALID (targetIID, IDependent, Vst::IEditController)
  221. TEST_FOR_COMMON_BASE_AND_RETURN_IF_VALID (targetIID, FUnknown, Vst::IEditController)
  222. if (doUIDsMatch (targetIID, JuceAudioProcessor::iid))
  223. {
  224. audioProcessor->addRef();
  225. *obj = audioProcessor;
  226. return kResultOk;
  227. }
  228. *obj = nullptr;
  229. return kNoInterface;
  230. }
  231. //==============================================================================
  232. tresult PLUGIN_API initialize (FUnknown* context) override
  233. {
  234. if (hostContext != context)
  235. {
  236. if (hostContext != nullptr)
  237. hostContext->release();
  238. hostContext = context;
  239. if (hostContext != nullptr)
  240. hostContext->addRef();
  241. }
  242. return kResultTrue;
  243. }
  244. tresult PLUGIN_API terminate() override
  245. {
  246. if (auto* pluginInstance = getPluginInstance())
  247. pluginInstance->removeListener (this);
  248. audioProcessor = nullptr;
  249. return EditController::terminate();
  250. }
  251. //==============================================================================
  252. enum InternalParameters
  253. {
  254. paramPreset = 0x70727374, // 'prst'
  255. paramMidiControllerOffset = 0x6d636d00 // 'mdm*'
  256. };
  257. struct Param : public Vst::Parameter
  258. {
  259. Param (JuceVST3EditController& editController, AudioProcessorParameter& p,
  260. Vst::ParamID vstParamID, bool isBypassParameter, bool forceLegacyParamIDs)
  261. : owner (editController), param (p)
  262. {
  263. info.id = vstParamID;
  264. toString128 (info.title, param.getName (128));
  265. toString128 (info.shortTitle, param.getName (8));
  266. toString128 (info.units, param.getLabel());
  267. info.stepCount = (Steinberg::int32) 0;
  268. if (! forceLegacyParamIDs && param.isDiscrete())
  269. {
  270. const int numSteps = param.getNumSteps();
  271. info.stepCount = (Steinberg::int32) (numSteps > 0 && numSteps < 0x7fffffff ? numSteps - 1 : 0);
  272. }
  273. info.defaultNormalizedValue = param.getDefaultValue();
  274. jassert (info.defaultNormalizedValue >= 0 && info.defaultNormalizedValue <= 1.0f);
  275. info.unitId = Vst::kRootUnitId;
  276. // Is this a meter?
  277. if (((param.getCategory() & 0xffff0000) >> 16) == 2)
  278. info.flags = Vst::ParameterInfo::kIsReadOnly;
  279. else
  280. info.flags = param.isAutomatable() ? Vst::ParameterInfo::kCanAutomate : 0;
  281. if (isBypassParameter)
  282. info.flags |= Vst::ParameterInfo::kIsBypass;
  283. valueNormalized = info.defaultNormalizedValue;
  284. }
  285. virtual ~Param() {}
  286. bool setNormalized (Vst::ParamValue v) override
  287. {
  288. v = jlimit (0.0, 1.0, v);
  289. if (v != valueNormalized)
  290. {
  291. valueNormalized = v;
  292. // Only update the AudioProcessor here if we're not playing,
  293. // otherwise we get parallel streams of parameter value updates
  294. // during playback
  295. if (owner.vst3IsPlaying.get() == 0)
  296. {
  297. auto value = static_cast<float> (v);
  298. param.setValue (value);
  299. inParameterChangedCallback = true;
  300. param.sendValueChangedMessageToListeners (value);
  301. }
  302. changed();
  303. return true;
  304. }
  305. return false;
  306. }
  307. void toString (Vst::ParamValue value, Vst::String128 result) const override
  308. {
  309. if (LegacyAudioParameter::isLegacy (&param))
  310. // remain backward-compatible with old JUCE code
  311. toString128 (result, param.getCurrentValueAsText());
  312. else
  313. toString128 (result, param.getText ((float) value, 128));
  314. }
  315. bool fromString (const Vst::TChar* text, Vst::ParamValue& outValueNormalized) const override
  316. {
  317. if (! LegacyAudioParameter::isLegacy (&param))
  318. {
  319. outValueNormalized = param.getValueForText (getStringFromVstTChars (text));
  320. return true;
  321. }
  322. return false;
  323. }
  324. static String getStringFromVstTChars (const Vst::TChar* text)
  325. {
  326. return juce::String (juce::CharPointer_UTF16 (reinterpret_cast<const juce::CharPointer_UTF16::CharType*> (text)));
  327. }
  328. Vst::ParamValue toPlain (Vst::ParamValue v) const override { return v; }
  329. Vst::ParamValue toNormalized (Vst::ParamValue v) const override { return v; }
  330. private:
  331. JuceVST3EditController& owner;
  332. AudioProcessorParameter& param;
  333. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Param)
  334. };
  335. //==============================================================================
  336. struct ProgramChangeParameter : public Vst::Parameter
  337. {
  338. ProgramChangeParameter (AudioProcessor& p) : owner (p)
  339. {
  340. jassert (owner.getNumPrograms() > 1);
  341. info.id = paramPreset;
  342. toString128 (info.title, "Program");
  343. toString128 (info.shortTitle, "Program");
  344. toString128 (info.units, "");
  345. info.stepCount = owner.getNumPrograms() - 1;
  346. info.defaultNormalizedValue = static_cast<Vst::ParamValue> (owner.getCurrentProgram())
  347. / static_cast<Vst::ParamValue> (info.stepCount);
  348. info.unitId = Vst::kRootUnitId;
  349. info.flags = Vst::ParameterInfo::kIsProgramChange | Vst::ParameterInfo::kCanAutomate;
  350. }
  351. virtual ~ProgramChangeParameter() {}
  352. bool setNormalized (Vst::ParamValue v) override
  353. {
  354. Vst::ParamValue program = v * info.stepCount;
  355. if (! isPositiveAndBelow ((int) program, owner.getNumPrograms()))
  356. return false;
  357. if (valueNormalized != v)
  358. {
  359. valueNormalized = v;
  360. changed();
  361. return true;
  362. }
  363. return false;
  364. }
  365. void toString (Vst::ParamValue value, Vst::String128 result) const override
  366. {
  367. toString128 (result, owner.getProgramName (static_cast<int> (value * info.stepCount)));
  368. }
  369. bool fromString (const Vst::TChar* text, Vst::ParamValue& outValueNormalized) const override
  370. {
  371. auto paramValueString = getStringFromVstTChars (text);
  372. auto n = owner.getNumPrograms();
  373. for (int i = 0; i < n; ++i)
  374. {
  375. if (paramValueString == owner.getProgramName (i))
  376. {
  377. outValueNormalized = static_cast<Vst::ParamValue> (i) / info.stepCount;
  378. return true;
  379. }
  380. }
  381. return false;
  382. }
  383. static String getStringFromVstTChars (const Vst::TChar* text)
  384. {
  385. return String (CharPointer_UTF16 (reinterpret_cast<const CharPointer_UTF16::CharType*> (text)));
  386. }
  387. Vst::ParamValue toPlain (Vst::ParamValue v) const override { return v * info.stepCount; }
  388. Vst::ParamValue toNormalized (Vst::ParamValue v) const override { return v / info.stepCount; }
  389. private:
  390. AudioProcessor& owner;
  391. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ProgramChangeParameter)
  392. };
  393. //==============================================================================
  394. tresult PLUGIN_API setChannelContextInfos (Vst::IAttributeList* list) override
  395. {
  396. if (auto* instance = getPluginInstance())
  397. {
  398. if (list != nullptr)
  399. {
  400. AudioProcessor::TrackProperties trackProperties;
  401. {
  402. Vst::String128 channelName;
  403. if (list->getString (Vst::ChannelContext::kChannelNameKey, channelName, sizeof (channelName)) == kResultTrue)
  404. trackProperties.name = toString (channelName);
  405. }
  406. {
  407. int64 colour;
  408. if (list->getInt (Vst::ChannelContext::kChannelColorKey, colour) == kResultTrue)
  409. trackProperties.colour = Colour (Vst::ChannelContext::GetRed ((uint32) colour), Vst::ChannelContext::GetGreen ((uint32) colour),
  410. Vst::ChannelContext::GetBlue ((uint32) colour), Vst::ChannelContext::GetAlpha ((uint32) colour));
  411. }
  412. if (MessageManager::getInstance()->isThisTheMessageThread())
  413. instance->updateTrackProperties (trackProperties);
  414. else
  415. MessageManager::callAsync ([trackProperties, instance]
  416. { instance->updateTrackProperties (trackProperties); });
  417. }
  418. }
  419. return kResultOk;
  420. }
  421. //==============================================================================
  422. tresult PLUGIN_API setComponentState (IBStream* stream) override
  423. {
  424. // Cubase and Nuendo need to inform the host of the current parameter values
  425. if (auto* pluginInstance = getPluginInstance())
  426. {
  427. for (auto vstParamId : audioProcessor->vstParamIDs)
  428. setParamNormalized (vstParamId, audioProcessor->getParamForVSTParamID (vstParamId)->getValue());
  429. auto numPrograms = pluginInstance->getNumPrograms();
  430. if (numPrograms > 1)
  431. setParamNormalized (paramPreset, static_cast<Vst::ParamValue> (pluginInstance->getCurrentProgram())
  432. / static_cast<Vst::ParamValue> (numPrograms - 1));
  433. }
  434. if (auto* handler = getComponentHandler())
  435. handler->restartComponent (Vst::kParamValuesChanged);
  436. return Vst::EditController::setComponentState (stream);
  437. }
  438. void setAudioProcessor (JuceAudioProcessor* audioProc)
  439. {
  440. if (audioProcessor != audioProc)
  441. {
  442. audioProcessor = audioProc;
  443. setupParameters();
  444. }
  445. }
  446. tresult PLUGIN_API connect (IConnectionPoint* other) override
  447. {
  448. if (other != nullptr && audioProcessor == nullptr)
  449. {
  450. auto result = ComponentBase::connect (other);
  451. if (! audioProcessor.loadFrom (other))
  452. sendIntMessage ("JuceVST3EditController", (Steinberg::int64) (pointer_sized_int) this);
  453. else
  454. setupParameters();
  455. return result;
  456. }
  457. jassertfalse;
  458. return kResultFalse;
  459. }
  460. //==============================================================================
  461. tresult PLUGIN_API getMidiControllerAssignment (Steinberg::int32 /*busIndex*/, Steinberg::int16 channel,
  462. Vst::CtrlNumber midiControllerNumber, Vst::ParamID& resultID) override
  463. {
  464. resultID = midiControllerToParameter[channel][midiControllerNumber];
  465. return kResultTrue; // Returning false makes some hosts stop asking for further MIDI Controller Assignments
  466. }
  467. // Converts an incoming parameter index to a MIDI controller:
  468. bool getMidiControllerForParameter (Vst::ParamID index, int& channel, int& ctrlNumber)
  469. {
  470. auto mappedIndex = static_cast<int> (index - parameterToMidiControllerOffset);
  471. if (isPositiveAndBelow (mappedIndex, numElementsInArray (parameterToMidiController)))
  472. {
  473. auto& mc = parameterToMidiController[mappedIndex];
  474. if (mc.channel != -1 && mc.ctrlNumber != -1)
  475. {
  476. channel = jlimit (1, 16, mc.channel + 1);
  477. ctrlNumber = mc.ctrlNumber;
  478. return true;
  479. }
  480. }
  481. return false;
  482. }
  483. inline bool isMidiControllerParamID (Vst::ParamID paramID) const noexcept
  484. {
  485. return (paramID >= parameterToMidiControllerOffset
  486. && isPositiveAndBelow (paramID - parameterToMidiControllerOffset,
  487. static_cast<Vst::ParamID> (numElementsInArray (parameterToMidiController))));
  488. }
  489. //==============================================================================
  490. IPlugView* PLUGIN_API createView (const char* name) override
  491. {
  492. if (auto* pluginInstance = getPluginInstance())
  493. {
  494. if (pluginInstance->hasEditor() && name != nullptr
  495. && strcmp (name, Vst::ViewType::kEditor) == 0)
  496. {
  497. return new JuceVST3Editor (*this, *pluginInstance);
  498. }
  499. }
  500. return nullptr;
  501. }
  502. //==============================================================================
  503. void paramChanged (Vst::ParamID vstParamId, float newValue)
  504. {
  505. if (inParameterChangedCallback.get())
  506. {
  507. inParameterChangedCallback = false;
  508. return;
  509. }
  510. // NB: Cubase has problems if performEdit is called without setParamNormalized
  511. EditController::setParamNormalized (vstParamId, (double) newValue);
  512. performEdit (vstParamId, (double) newValue);
  513. }
  514. //==============================================================================
  515. void audioProcessorParameterChangeGestureBegin (AudioProcessor*, int index) override { beginEdit (audioProcessor->getVSTParamIDForIndex (index)); }
  516. void audioProcessorParameterChangeGestureEnd (AudioProcessor*, int index) override { endEdit (audioProcessor->getVSTParamIDForIndex (index)); }
  517. void audioProcessorParameterChanged (AudioProcessor*, int index, float newValue) override
  518. {
  519. paramChanged (audioProcessor->getVSTParamIDForIndex (index), newValue);
  520. }
  521. void audioProcessorChanged (AudioProcessor*) override
  522. {
  523. if (auto* pluginInstance = getPluginInstance())
  524. {
  525. if (pluginInstance->getNumPrograms() > 1)
  526. EditController::setParamNormalized (paramPreset, static_cast<Vst::ParamValue> (pluginInstance->getCurrentProgram())
  527. / static_cast<Vst::ParamValue> (pluginInstance->getNumPrograms() - 1));
  528. }
  529. if (componentHandler != nullptr)
  530. componentHandler->restartComponent (Vst::kLatencyChanged | Vst::kParamValuesChanged);
  531. }
  532. void parameterValueChanged (int, float newValue) override
  533. {
  534. // this can only come from the bypass parameter
  535. paramChanged (audioProcessor->bypassParamID, newValue);
  536. }
  537. void parameterGestureChanged (int, bool gestureIsStarting) override
  538. {
  539. // this can only come from the bypass parameter
  540. if (gestureIsStarting) beginEdit (audioProcessor->bypassParamID);
  541. else endEdit (audioProcessor->bypassParamID);
  542. }
  543. //==============================================================================
  544. AudioProcessor* getPluginInstance() const noexcept
  545. {
  546. if (audioProcessor != nullptr)
  547. return audioProcessor->get();
  548. return nullptr;
  549. }
  550. private:
  551. friend class JuceVST3Component;
  552. friend struct Param;
  553. //==============================================================================
  554. ComSmartPtr<JuceAudioProcessor> audioProcessor;
  555. ScopedJuceInitialiser_GUI libraryInitialiser;
  556. struct MidiController
  557. {
  558. int channel = -1, ctrlNumber = -1;
  559. };
  560. enum { numMIDIChannels = 16 };
  561. Vst::ParamID parameterToMidiControllerOffset;
  562. MidiController parameterToMidiController[numMIDIChannels * Vst::kCountCtrlNumber];
  563. Vst::ParamID midiControllerToParameter[numMIDIChannels][Vst::kCountCtrlNumber];
  564. //==============================================================================
  565. Atomic<int> vst3IsPlaying { 0 };
  566. void setupParameters()
  567. {
  568. if (auto* pluginInstance = getPluginInstance())
  569. {
  570. pluginInstance->addListener (this);
  571. // as the bypass is not part of the regular parameters
  572. // we need to listen for it explicitly
  573. if (! audioProcessor->bypassIsRegularParameter)
  574. audioProcessor->getBypassParameter()->addListener (this);
  575. if (parameters.getParameterCount() <= 0)
  576. {
  577. #if JUCE_FORCE_USE_LEGACY_PARAM_IDS
  578. const bool forceLegacyParamIDs = true;
  579. #else
  580. const bool forceLegacyParamIDs = false;
  581. #endif
  582. auto n = audioProcessor->getNumParameters();
  583. for (int i = 0; i < n; ++i)
  584. {
  585. auto vstParamID = audioProcessor->getVSTParamIDForIndex (i);
  586. auto* juceParam = audioProcessor->getParamForVSTParamID (vstParamID);
  587. parameters.addParameter (new Param (*this, *juceParam, vstParamID,
  588. (vstParamID == audioProcessor->bypassParamID), forceLegacyParamIDs));
  589. }
  590. if (pluginInstance->getNumPrograms() > 1)
  591. parameters.addParameter (new ProgramChangeParameter (*pluginInstance));
  592. }
  593. #if JUCE_VST3_EMULATE_MIDI_CC_WITH_PARAMETERS
  594. parameterToMidiControllerOffset = static_cast<Vst::ParamID> (audioProcessor->isUsingManagedParameters() ? paramMidiControllerOffset
  595. : parameters.getParameterCount());
  596. initialiseMidiControllerMappings();
  597. #endif
  598. audioProcessorChanged (pluginInstance);
  599. }
  600. }
  601. void initialiseMidiControllerMappings()
  602. {
  603. for (int c = 0, p = 0; c < numMIDIChannels; ++c)
  604. {
  605. for (int i = 0; i < Vst::kCountCtrlNumber; ++i, ++p)
  606. {
  607. midiControllerToParameter[c][i] = static_cast<Vst::ParamID> (p) + parameterToMidiControllerOffset;
  608. parameterToMidiController[p].channel = c;
  609. parameterToMidiController[p].ctrlNumber = i;
  610. parameters.addParameter (new Vst::Parameter (toString ("MIDI CC " + String (c) + "|" + String (i)),
  611. static_cast<Vst::ParamID> (p) + parameterToMidiControllerOffset, 0, 0, 0,
  612. 0, Vst::kRootUnitId));
  613. }
  614. }
  615. }
  616. void sendIntMessage (const char* idTag, const Steinberg::int64 value)
  617. {
  618. jassert (hostContext != nullptr);
  619. if (auto* message = allocateMessage())
  620. {
  621. const FReleaser releaser (message);
  622. message->setMessageID (idTag);
  623. message->getAttributes()->setInt (idTag, value);
  624. sendMessage (message);
  625. }
  626. }
  627. //==============================================================================
  628. class JuceVST3Editor : public Vst::EditorView,
  629. public Steinberg::IPlugViewContentScaleSupport,
  630. private Timer
  631. {
  632. public:
  633. JuceVST3Editor (JuceVST3EditController& ec, AudioProcessor& p)
  634. : Vst::EditorView (&ec, nullptr),
  635. owner (&ec), pluginInstance (p)
  636. {
  637. component.reset (new ContentWrapperComponent (*this, p));
  638. }
  639. tresult PLUGIN_API queryInterface (const TUID targetIID, void** obj) override
  640. {
  641. TEST_FOR_AND_RETURN_IF_VALID (targetIID, Steinberg::IPlugViewContentScaleSupport)
  642. return Vst::EditorView::queryInterface (targetIID, obj);
  643. }
  644. REFCOUNT_METHODS (Vst::EditorView)
  645. //==============================================================================
  646. tresult PLUGIN_API isPlatformTypeSupported (FIDString type) override
  647. {
  648. if (type != nullptr && pluginInstance.hasEditor())
  649. {
  650. #if JUCE_WINDOWS
  651. if (strcmp (type, kPlatformTypeHWND) == 0)
  652. #else
  653. if (strcmp (type, kPlatformTypeNSView) == 0 || strcmp (type, kPlatformTypeHIView) == 0)
  654. #endif
  655. return kResultTrue;
  656. }
  657. return kResultFalse;
  658. }
  659. tresult PLUGIN_API attached (void* parent, FIDString type) override
  660. {
  661. if (parent == nullptr || isPlatformTypeSupported (type) == kResultFalse)
  662. return kResultFalse;
  663. if (component == nullptr)
  664. component.reset (new ContentWrapperComponent (*this, pluginInstance));
  665. #if JUCE_WINDOWS
  666. component->addToDesktop (0, parent);
  667. component->setOpaque (true);
  668. component->setVisible (true);
  669. #else
  670. isNSView = (strcmp (type, kPlatformTypeNSView) == 0);
  671. macHostWindow = juce::attachComponentToWindowRefVST (component.get(), parent, isNSView);
  672. #endif
  673. component->resizeHostWindow();
  674. systemWindow = parent;
  675. attachedToParent();
  676. // Life's too short to faff around with wave lab
  677. if (getHostType().isWavelab())
  678. startTimer (200);
  679. return kResultTrue;
  680. }
  681. tresult PLUGIN_API removed() override
  682. {
  683. if (component != nullptr)
  684. {
  685. #if JUCE_WINDOWS
  686. component->removeFromDesktop();
  687. #else
  688. if (macHostWindow != nullptr)
  689. {
  690. juce::detachComponentFromWindowRefVST (component.get(), macHostWindow, isNSView);
  691. macHostWindow = nullptr;
  692. }
  693. #endif
  694. component = nullptr;
  695. }
  696. return CPluginView::removed();
  697. }
  698. tresult PLUGIN_API onSize (ViewRect* newSize) override
  699. {
  700. if (newSize != nullptr)
  701. {
  702. rect = *newSize;
  703. if (component != nullptr)
  704. {
  705. component->setSize (rect.getWidth(), rect.getHeight());
  706. if (auto* peer = component->getPeer())
  707. peer->updateBounds();
  708. }
  709. return kResultTrue;
  710. }
  711. jassertfalse;
  712. return kResultFalse;
  713. }
  714. tresult PLUGIN_API getSize (ViewRect* size) override
  715. {
  716. if (size != nullptr && component != nullptr)
  717. {
  718. *size = ViewRect (0, 0, component->getWidth(), component->getHeight());
  719. return kResultTrue;
  720. }
  721. return kResultFalse;
  722. }
  723. tresult PLUGIN_API canResize() override
  724. {
  725. if (component != nullptr)
  726. if (auto* editor = component->pluginEditor.get())
  727. return editor->isResizable() ? kResultTrue : kResultFalse;
  728. return kResultFalse;
  729. }
  730. tresult PLUGIN_API checkSizeConstraint (ViewRect* rectToCheck) override
  731. {
  732. if (rectToCheck != nullptr && component != nullptr)
  733. {
  734. if (auto* editor = component->pluginEditor.get())
  735. {
  736. // checkSizeConstraint
  737. auto juceRect = editor->getLocalArea (component.get(), Rectangle<int>::leftTopRightBottom (rectToCheck->left, rectToCheck->top,
  738. rectToCheck->right, rectToCheck->bottom));
  739. if (auto* constrainer = editor->getConstrainer())
  740. {
  741. Rectangle<int> limits (0, 0, constrainer->getMaximumWidth(), constrainer->getMaximumHeight());
  742. constrainer->checkBounds (juceRect, editor->getBounds(), limits, false, false, false, false);
  743. juceRect = component->getLocalArea (editor, juceRect);
  744. rectToCheck->right = rectToCheck->left + juceRect.getWidth();
  745. rectToCheck->bottom = rectToCheck->top + juceRect.getHeight();
  746. }
  747. }
  748. return kResultTrue;
  749. }
  750. jassertfalse;
  751. return kResultFalse;
  752. }
  753. tresult PLUGIN_API setContentScaleFactor (Steinberg::IPlugViewContentScaleSupport::ScaleFactor factor) override
  754. {
  755. #if (JUCE_MAC || JUCE_IOS)
  756. ignoreUnused (factor);
  757. #else
  758. if (auto* editor = component->pluginEditor.get())
  759. {
  760. editor->setScaleFactor (factor);
  761. return kResultTrue;
  762. }
  763. #endif
  764. return kResultFalse;
  765. }
  766. private:
  767. void timerCallback() override
  768. {
  769. stopTimer();
  770. ViewRect viewRect;
  771. getSize (&viewRect);
  772. onSize (&viewRect);
  773. }
  774. //==============================================================================
  775. struct ContentWrapperComponent : public Component
  776. {
  777. ContentWrapperComponent (JuceVST3Editor& editor, AudioProcessor& plugin)
  778. : pluginEditor (plugin.createEditorIfNeeded()),
  779. owner (editor)
  780. {
  781. setOpaque (true);
  782. setBroughtToFrontOnMouseClick (true);
  783. // if hasEditor() returns true then createEditorIfNeeded has to return a valid editor
  784. jassert (pluginEditor != nullptr);
  785. if (pluginEditor != nullptr)
  786. {
  787. addAndMakeVisible (pluginEditor.get());
  788. pluginEditor->setTopLeftPosition (0, 0);
  789. lastBounds = getSizeToContainChild();
  790. isResizingParentToFitChild = true;
  791. setBounds (lastBounds);
  792. isResizingParentToFitChild = false;
  793. resizeHostWindow();
  794. }
  795. ignoreUnused (fakeMouseGenerator);
  796. }
  797. ~ContentWrapperComponent()
  798. {
  799. if (pluginEditor != nullptr)
  800. {
  801. PopupMenu::dismissAllActiveMenus();
  802. pluginEditor->processor.editorBeingDeleted (pluginEditor.get());
  803. }
  804. }
  805. void paint (Graphics& g) override
  806. {
  807. g.fillAll (Colours::black);
  808. }
  809. juce::Rectangle<int> getSizeToContainChild()
  810. {
  811. if (pluginEditor != nullptr)
  812. return getLocalArea (pluginEditor.get(), pluginEditor->getLocalBounds());
  813. return {};
  814. }
  815. void childBoundsChanged (Component*) override
  816. {
  817. if (isResizingChildToFitParent)
  818. return;
  819. auto b = getSizeToContainChild();
  820. if (lastBounds != b)
  821. {
  822. lastBounds = b;
  823. isResizingParentToFitChild = true;
  824. resizeHostWindow();
  825. isResizingParentToFitChild = false;
  826. }
  827. }
  828. void resized() override
  829. {
  830. if (pluginEditor != nullptr)
  831. {
  832. if (! isResizingParentToFitChild)
  833. {
  834. lastBounds = getLocalBounds();
  835. isResizingChildToFitParent = true;
  836. if (auto* constrainer = pluginEditor->getConstrainer())
  837. {
  838. auto aspectRatio = constrainer->getFixedAspectRatio();
  839. auto width = (double) lastBounds.getWidth();
  840. auto height = (double) lastBounds.getHeight();
  841. if (aspectRatio != 0)
  842. {
  843. if (width / height > aspectRatio)
  844. setBounds ({ 0, 0, roundToInt (height * aspectRatio), lastBounds.getHeight() });
  845. else
  846. setBounds ({ 0, 0, lastBounds.getWidth(), roundToInt (width / aspectRatio) });
  847. }
  848. }
  849. pluginEditor->setTopLeftPosition (0, 0);
  850. pluginEditor->setBounds (pluginEditor->getLocalArea (this, getLocalBounds()));
  851. isResizingChildToFitParent = false;
  852. }
  853. }
  854. }
  855. void resizeHostWindow()
  856. {
  857. if (pluginEditor != nullptr)
  858. {
  859. auto b = getSizeToContainChild();
  860. auto w = b.getWidth();
  861. auto h = b.getHeight();
  862. auto host = getHostType();
  863. #if JUCE_WINDOWS
  864. setSize (w, h);
  865. #else
  866. if (owner.macHostWindow != nullptr && ! (host.isWavelab() || host.isReaper() || host.isBitwigStudio()))
  867. juce::setNativeHostWindowSizeVST (owner.macHostWindow, this, w, h, owner.isNSView);
  868. #endif
  869. if (owner.plugFrame != nullptr)
  870. {
  871. ViewRect newSize (0, 0, w, h);
  872. isResizingParentToFitChild = true;
  873. owner.plugFrame->resizeView (&owner, &newSize);
  874. isResizingParentToFitChild = false;
  875. #if JUCE_MAC
  876. if (host.isWavelab() || host.isReaper())
  877. #else
  878. if (host.isWavelab())
  879. #endif
  880. setBounds (0, 0, w, h);
  881. }
  882. }
  883. }
  884. std::unique_ptr<AudioProcessorEditor> pluginEditor;
  885. private:
  886. JuceVST3Editor& owner;
  887. FakeMouseMoveGenerator fakeMouseGenerator;
  888. Rectangle<int> lastBounds;
  889. bool isResizingChildToFitParent = false;
  890. bool isResizingParentToFitChild = false;
  891. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ContentWrapperComponent)
  892. };
  893. //==============================================================================
  894. ComSmartPtr<JuceVST3EditController> owner;
  895. AudioProcessor& pluginInstance;
  896. std::unique_ptr<ContentWrapperComponent> component;
  897. friend struct ContentWrapperComponent;
  898. #if JUCE_MAC
  899. void* macHostWindow = nullptr;
  900. bool isNSView = false;
  901. #endif
  902. #if JUCE_WINDOWS
  903. WindowsHooks hooks;
  904. #endif
  905. ScopedJuceInitialiser_GUI libraryInitialiser;
  906. //==============================================================================
  907. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (JuceVST3Editor)
  908. };
  909. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (JuceVST3EditController)
  910. };
  911. namespace
  912. {
  913. template <typename FloatType> struct AudioBusPointerHelper {};
  914. template <> struct AudioBusPointerHelper<float> { static inline float** impl (Vst::AudioBusBuffers& data) noexcept { return data.channelBuffers32; } };
  915. template <> struct AudioBusPointerHelper<double> { static inline double** impl (Vst::AudioBusBuffers& data) noexcept { return data.channelBuffers64; } };
  916. template <typename FloatType> struct ChooseBufferHelper {};
  917. template <> struct ChooseBufferHelper<float> { static inline AudioBuffer<float>& impl (AudioBuffer<float>& f, AudioBuffer<double>& ) noexcept { return f; } };
  918. template <> struct ChooseBufferHelper<double> { static inline AudioBuffer<double>& impl (AudioBuffer<float>& , AudioBuffer<double>& d) noexcept { return d; } };
  919. }
  920. //==============================================================================
  921. class JuceVST3Component : public Vst::IComponent,
  922. public Vst::IAudioProcessor,
  923. public Vst::IUnitInfo,
  924. public Vst::IConnectionPoint,
  925. public AudioPlayHead
  926. {
  927. public:
  928. JuceVST3Component (Vst::IHostApplication* h)
  929. : pluginInstance (createPluginFilterOfType (AudioProcessor::wrapperType_VST3)),
  930. host (h)
  931. {
  932. inParameterChangedCallback = false;
  933. #ifdef JucePlugin_PreferredChannelConfigurations
  934. short configs[][2] = { JucePlugin_PreferredChannelConfigurations };
  935. const int numConfigs = sizeof (configs) / sizeof (short[2]);
  936. jassert (numConfigs > 0 && (configs[0][0] > 0 || configs[0][1] > 0));
  937. pluginInstance->setPlayConfigDetails (configs[0][0], configs[0][1], 44100.0, 1024);
  938. #endif
  939. // VST-3 requires your default layout to be non-discrete!
  940. // For example, your default layout must be mono, stereo, quadrophonic
  941. // and not AudioChannelSet::discreteChannels (2) etc.
  942. jassert (checkBusFormatsAreNotDiscrete());
  943. comPluginInstance = new JuceAudioProcessor (pluginInstance);
  944. zerostruct (processContext);
  945. processSetup.maxSamplesPerBlock = 1024;
  946. processSetup.processMode = Vst::kRealtime;
  947. processSetup.sampleRate = 44100.0;
  948. processSetup.symbolicSampleSize = Vst::kSample32;
  949. pluginInstance->setPlayHead (this);
  950. }
  951. ~JuceVST3Component()
  952. {
  953. if (juceVST3EditController != nullptr)
  954. juceVST3EditController->vst3IsPlaying = 0;
  955. if (pluginInstance != nullptr)
  956. if (pluginInstance->getPlayHead() == this)
  957. pluginInstance->setPlayHead (nullptr);
  958. }
  959. //==============================================================================
  960. AudioProcessor& getPluginInstance() const noexcept { return *pluginInstance; }
  961. //==============================================================================
  962. static const FUID iid;
  963. JUCE_DECLARE_VST3_COM_REF_METHODS
  964. tresult PLUGIN_API queryInterface (const TUID targetIID, void** obj) override
  965. {
  966. TEST_FOR_AND_RETURN_IF_VALID (targetIID, IPluginBase)
  967. TEST_FOR_AND_RETURN_IF_VALID (targetIID, JuceVST3Component)
  968. TEST_FOR_AND_RETURN_IF_VALID (targetIID, Vst::IComponent)
  969. TEST_FOR_AND_RETURN_IF_VALID (targetIID, Vst::IAudioProcessor)
  970. TEST_FOR_AND_RETURN_IF_VALID (targetIID, Vst::IUnitInfo)
  971. TEST_FOR_AND_RETURN_IF_VALID (targetIID, Vst::IConnectionPoint)
  972. TEST_FOR_COMMON_BASE_AND_RETURN_IF_VALID (targetIID, FUnknown, Vst::IComponent)
  973. if (doUIDsMatch (targetIID, JuceAudioProcessor::iid))
  974. {
  975. comPluginInstance->addRef();
  976. *obj = comPluginInstance;
  977. return kResultOk;
  978. }
  979. *obj = nullptr;
  980. return kNoInterface;
  981. }
  982. //==============================================================================
  983. tresult PLUGIN_API initialize (FUnknown* hostContext) override
  984. {
  985. if (host != hostContext)
  986. host.loadFrom (hostContext);
  987. processContext.sampleRate = processSetup.sampleRate;
  988. preparePlugin (processSetup.sampleRate, (int) processSetup.maxSamplesPerBlock);
  989. return kResultTrue;
  990. }
  991. tresult PLUGIN_API terminate() override
  992. {
  993. getPluginInstance().releaseResources();
  994. return kResultTrue;
  995. }
  996. //==============================================================================
  997. tresult PLUGIN_API connect (IConnectionPoint* other) override
  998. {
  999. if (other != nullptr && juceVST3EditController == nullptr)
  1000. juceVST3EditController.loadFrom (other);
  1001. return kResultTrue;
  1002. }
  1003. tresult PLUGIN_API disconnect (IConnectionPoint*) override
  1004. {
  1005. if (juceVST3EditController != nullptr)
  1006. juceVST3EditController->vst3IsPlaying = 0;
  1007. juceVST3EditController = nullptr;
  1008. return kResultTrue;
  1009. }
  1010. tresult PLUGIN_API notify (Vst::IMessage* message) override
  1011. {
  1012. if (message != nullptr && juceVST3EditController == nullptr)
  1013. {
  1014. Steinberg::int64 value = 0;
  1015. if (message->getAttributes()->getInt ("JuceVST3EditController", value) == kResultTrue)
  1016. {
  1017. juceVST3EditController = (JuceVST3EditController*) (pointer_sized_int) value;
  1018. if (juceVST3EditController != nullptr)
  1019. juceVST3EditController->setAudioProcessor (comPluginInstance);
  1020. else
  1021. jassertfalse;
  1022. }
  1023. }
  1024. return kResultTrue;
  1025. }
  1026. tresult PLUGIN_API getControllerClassId (TUID classID) override
  1027. {
  1028. memcpy (classID, JuceVST3EditController::iid, sizeof (TUID));
  1029. return kResultTrue;
  1030. }
  1031. //==============================================================================
  1032. tresult PLUGIN_API setActive (TBool state) override
  1033. {
  1034. if (! state)
  1035. {
  1036. getPluginInstance().releaseResources();
  1037. deallocateChannelListAndBuffers (channelListFloat, emptyBufferFloat);
  1038. deallocateChannelListAndBuffers (channelListDouble, emptyBufferDouble);
  1039. }
  1040. else
  1041. {
  1042. auto sampleRate = getPluginInstance().getSampleRate();
  1043. auto bufferSize = getPluginInstance().getBlockSize();
  1044. sampleRate = processSetup.sampleRate > 0.0
  1045. ? processSetup.sampleRate
  1046. : sampleRate;
  1047. bufferSize = processSetup.maxSamplesPerBlock > 0
  1048. ? (int) processSetup.maxSamplesPerBlock
  1049. : bufferSize;
  1050. allocateChannelListAndBuffers (channelListFloat, emptyBufferFloat);
  1051. allocateChannelListAndBuffers (channelListDouble, emptyBufferDouble);
  1052. preparePlugin (sampleRate, bufferSize);
  1053. }
  1054. return kResultOk;
  1055. }
  1056. tresult PLUGIN_API setIoMode (Vst::IoMode) override { return kNotImplemented; }
  1057. tresult PLUGIN_API getRoutingInfo (Vst::RoutingInfo&, Vst::RoutingInfo&) override { return kNotImplemented; }
  1058. //==============================================================================
  1059. bool isBypassed()
  1060. {
  1061. if (auto* bypassParam = comPluginInstance->getBypassParameter())
  1062. return (bypassParam->getValue() != 0.0f);
  1063. return false;
  1064. }
  1065. void setBypassed (bool shouldBeBypassed)
  1066. {
  1067. if (auto* bypassParam = comPluginInstance->getBypassParameter())
  1068. {
  1069. auto floatValue = (shouldBeBypassed ? 1.0f : 0.0f);
  1070. bypassParam->setValue (floatValue);
  1071. inParameterChangedCallback = true;
  1072. bypassParam->sendValueChangedMessageToListeners (floatValue);
  1073. }
  1074. }
  1075. //==============================================================================
  1076. void writeJucePrivateStateInformation (MemoryOutputStream& out)
  1077. {
  1078. if (pluginInstance->getBypassParameter() == nullptr)
  1079. {
  1080. ValueTree privateData (kJucePrivateDataIdentifier);
  1081. // for now we only store the bypass value
  1082. privateData.setProperty ("Bypass", var (isBypassed()), nullptr);
  1083. privateData.writeToStream (out);
  1084. }
  1085. }
  1086. void setJucePrivateStateInformation (const void* data, int sizeInBytes)
  1087. {
  1088. if (pluginInstance->getBypassParameter() == nullptr)
  1089. {
  1090. if (auto* bypassParam = comPluginInstance->getBypassParameter())
  1091. {
  1092. auto privateData = ValueTree::readFromData (data, static_cast<size_t> (sizeInBytes));
  1093. setBypassed (static_cast<bool> (privateData.getProperty ("Bypass", var (false))));
  1094. }
  1095. }
  1096. }
  1097. void getStateInformation (MemoryBlock& destData)
  1098. {
  1099. pluginInstance->getStateInformation (destData);
  1100. // With bypass support, JUCE now needs to store private state data.
  1101. // Put this at the end of the plug-in state and add a few null characters
  1102. // so that plug-ins built with older versions of JUCE will hopefully ignore
  1103. // this data. Additionally, we need to add some sort of magic identifier
  1104. // at the very end of the private data so that JUCE has some sort of
  1105. // way to figure out if the data was stored with a newer JUCE version.
  1106. MemoryOutputStream extraData;
  1107. extraData.writeInt64 (0);
  1108. writeJucePrivateStateInformation (extraData);
  1109. auto privateDataSize = (int64) (extraData.getDataSize() - sizeof (int64));
  1110. extraData.writeInt64 (privateDataSize);
  1111. extraData << kJucePrivateDataIdentifier;
  1112. // write magic string
  1113. destData.append (extraData.getData(), extraData.getDataSize());
  1114. }
  1115. void setStateInformation (const void* data, int sizeAsInt)
  1116. {
  1117. int64 size = sizeAsInt;
  1118. // Check if this data was written with a newer JUCE version
  1119. // and if it has the JUCE private data magic code at the end
  1120. auto jucePrivDataIdentifierSize = std::strlen (kJucePrivateDataIdentifier);
  1121. if ((size_t) size >= jucePrivDataIdentifierSize + sizeof (int64))
  1122. {
  1123. auto buffer = static_cast<const char*> (data);
  1124. String magic (CharPointer_UTF8 (buffer + size - jucePrivDataIdentifierSize),
  1125. CharPointer_UTF8 (buffer + size));
  1126. if (magic == kJucePrivateDataIdentifier)
  1127. {
  1128. // found a JUCE private data section
  1129. uint64 privateDataSize;
  1130. std::memcpy (&privateDataSize,
  1131. buffer + ((size_t) size - jucePrivDataIdentifierSize - sizeof (uint64)),
  1132. sizeof (uint64));
  1133. privateDataSize = ByteOrder::swapIfBigEndian (privateDataSize);
  1134. size -= privateDataSize + jucePrivDataIdentifierSize + sizeof (uint64);
  1135. if (privateDataSize > 0)
  1136. setJucePrivateStateInformation (buffer + size, static_cast<int> (privateDataSize));
  1137. size -= sizeof (uint64);
  1138. }
  1139. }
  1140. if (size >= 0)
  1141. pluginInstance->setStateInformation (data, static_cast<int> (size));
  1142. }
  1143. //==============================================================================
  1144. #if JUCE_VST3_CAN_REPLACE_VST2
  1145. bool loadVST2VstWBlock (const char* data, int size)
  1146. {
  1147. jassert ('VstW' == htonl (*(juce::int32*) data));
  1148. jassert (1 == htonl (*(juce::int32*) (data + 8))); // version should be 1 according to Steinberg's docs
  1149. auto headerLen = (int) htonl (*(juce::int32*) (data + 4)) + 8;
  1150. return loadVST2CcnKBlock (data + headerLen, size - headerLen);
  1151. }
  1152. bool loadVST2CcnKBlock (const char* data, int size)
  1153. {
  1154. auto bank = (const Vst2::fxBank*) data;
  1155. jassert ('CcnK' == htonl (bank->chunkMagic));
  1156. jassert ('FBCh' == htonl (bank->fxMagic));
  1157. jassert (htonl (bank->version) == 1 || htonl (bank->version) == 2);
  1158. jassert (JucePlugin_VSTUniqueID == htonl (bank->fxID));
  1159. setStateInformation (bank->content.data.chunk,
  1160. jmin ((int) (size - (bank->content.data.chunk - data)),
  1161. (int) htonl (bank->content.data.size)));
  1162. return true;
  1163. }
  1164. bool loadVST3PresetFile (const char* data, int size)
  1165. {
  1166. if (size < 48)
  1167. return false;
  1168. // At offset 4 there's a little-endian version number which seems to typically be 1
  1169. // At offset 8 there's 32 bytes the SDK calls "ASCII-encoded class id"
  1170. auto chunkListOffset = (int) ByteOrder::littleEndianInt (data + 40);
  1171. jassert (memcmp (data + chunkListOffset, "List", 4) == 0);
  1172. auto entryCount = (int) ByteOrder::littleEndianInt (data + chunkListOffset + 4);
  1173. jassert (entryCount > 0);
  1174. for (int i = 0; i < entryCount; ++i)
  1175. {
  1176. auto entryOffset = chunkListOffset + 8 + 20 * i;
  1177. if (entryOffset + 20 > size)
  1178. return false;
  1179. if (memcmp (data + entryOffset, "Comp", 4) == 0)
  1180. {
  1181. // "Comp" entries seem to contain the data.
  1182. auto chunkOffset = ByteOrder::littleEndianInt64 (data + entryOffset + 4);
  1183. auto chunkSize = ByteOrder::littleEndianInt64 (data + entryOffset + 12);
  1184. if (chunkOffset + chunkSize > static_cast<juce::uint64> (size))
  1185. {
  1186. jassertfalse;
  1187. return false;
  1188. }
  1189. loadVST2VstWBlock (data + chunkOffset, (int) chunkSize);
  1190. }
  1191. }
  1192. return true;
  1193. }
  1194. bool loadVST2CompatibleState (const char* data, int size)
  1195. {
  1196. if (size < 4)
  1197. return false;
  1198. auto header = htonl (*(juce::int32*) data);
  1199. if (header == 'VstW')
  1200. return loadVST2VstWBlock (data, size);
  1201. if (header == 'CcnK')
  1202. return loadVST2CcnKBlock (data, size);
  1203. if (memcmp (data, "VST3", 4) == 0)
  1204. {
  1205. // In Cubase 5, when loading VST3 .vstpreset files,
  1206. // we get the whole content of the files to load.
  1207. // In Cubase 7 we get just the contents within and
  1208. // we go directly to the loadVST2VstW codepath instead.
  1209. return loadVST3PresetFile (data, size);
  1210. }
  1211. return false;
  1212. }
  1213. #endif
  1214. bool loadStateData (const void* data, int size)
  1215. {
  1216. #if JUCE_VST3_CAN_REPLACE_VST2
  1217. return loadVST2CompatibleState ((const char*) data, size);
  1218. #else
  1219. setStateInformation (data, size);
  1220. return true;
  1221. #endif
  1222. }
  1223. bool readFromMemoryStream (IBStream* state)
  1224. {
  1225. FUnknownPtr<ISizeableStream> s (state);
  1226. Steinberg::int64 size = 0;
  1227. if (s != nullptr
  1228. && s->getStreamSize (size) == kResultOk
  1229. && size > 0
  1230. && size < 1024 * 1024 * 100) // (some hosts seem to return junk for the size)
  1231. {
  1232. MemoryBlock block (static_cast<size_t> (size));
  1233. // turns out that Cubase 9 might give you the incorrect stream size :-(
  1234. Steinberg::int32 bytesRead = 1;
  1235. int len;
  1236. for (len = 0; bytesRead > 0 && len < static_cast<int> (block.getSize()); len += bytesRead)
  1237. if (state->read (block.getData(), static_cast<int32> (block.getSize()), &bytesRead) != kResultOk)
  1238. break;
  1239. if (len == 0)
  1240. return false;
  1241. block.setSize (static_cast<size_t> (len));
  1242. // Adobe Audition CS6 hack to avoid trying to use corrupted streams:
  1243. if (getHostType().isAdobeAudition())
  1244. if (block.getSize() >= 5 && memcmp (block.getData(), "VC2!E", 5) == 0)
  1245. return false;
  1246. return loadStateData (block.getData(), (int) block.getSize());
  1247. }
  1248. return false;
  1249. }
  1250. bool readFromUnknownStream (IBStream* state)
  1251. {
  1252. MemoryOutputStream allData;
  1253. {
  1254. const size_t bytesPerBlock = 4096;
  1255. HeapBlock<char> buffer (bytesPerBlock);
  1256. for (;;)
  1257. {
  1258. Steinberg::int32 bytesRead = 0;
  1259. auto status = state->read (buffer, (Steinberg::int32) bytesPerBlock, &bytesRead);
  1260. if (bytesRead <= 0 || (status != kResultTrue && ! getHostType().isWavelab()))
  1261. break;
  1262. allData.write (buffer, static_cast<size_t> (bytesRead));
  1263. }
  1264. }
  1265. const size_t dataSize = allData.getDataSize();
  1266. return dataSize > 0 && dataSize < 0x7fffffff
  1267. && loadStateData (allData.getData(), (int) dataSize);
  1268. }
  1269. tresult PLUGIN_API setState (IBStream* state) override
  1270. {
  1271. if (state == nullptr)
  1272. return kInvalidArgument;
  1273. FUnknownPtr<IBStream> stateRefHolder (state); // just in case the caller hasn't properly ref-counted the stream object
  1274. if (state->seek (0, IBStream::kIBSeekSet, nullptr) == kResultTrue)
  1275. {
  1276. if (! getHostType().isFruityLoops() && readFromMemoryStream (state))
  1277. return kResultTrue;
  1278. if (readFromUnknownStream (state))
  1279. return kResultTrue;
  1280. }
  1281. return kResultFalse;
  1282. }
  1283. #if JUCE_VST3_CAN_REPLACE_VST2
  1284. static tresult writeVST2Int (IBStream* state, int n)
  1285. {
  1286. juce::int32 t = (juce::int32) htonl (n);
  1287. return state->write (&t, 4);
  1288. }
  1289. static tresult writeVST2Header (IBStream* state, bool bypassed)
  1290. {
  1291. tresult status = writeVST2Int (state, 'VstW');
  1292. if (status == kResultOk) status = writeVST2Int (state, 8); // header size
  1293. if (status == kResultOk) status = writeVST2Int (state, 1); // version
  1294. if (status == kResultOk) status = writeVST2Int (state, bypassed ? 1 : 0); // bypass
  1295. return status;
  1296. }
  1297. #endif
  1298. tresult PLUGIN_API getState (IBStream* state) override
  1299. {
  1300. if (state == nullptr)
  1301. return kInvalidArgument;
  1302. juce::MemoryBlock mem;
  1303. getStateInformation (mem);
  1304. #if JUCE_VST3_CAN_REPLACE_VST2
  1305. tresult status = writeVST2Header (state, isBypassed());
  1306. if (status != kResultOk)
  1307. return status;
  1308. const int bankBlockSize = 160;
  1309. Vst2::fxBank bank;
  1310. zerostruct (bank);
  1311. bank.chunkMagic = (int32) htonl ('CcnK');
  1312. bank.byteSize = (int32) htonl (bankBlockSize - 8 + (unsigned int) mem.getSize());
  1313. bank.fxMagic = (int32) htonl ('FBCh');
  1314. bank.version = (int32) htonl (2);
  1315. bank.fxID = (int32) htonl (JucePlugin_VSTUniqueID);
  1316. bank.fxVersion = (int32) htonl (JucePlugin_VersionCode);
  1317. bank.content.data.size = (int32) htonl ((unsigned int) mem.getSize());
  1318. status = state->write (&bank, bankBlockSize);
  1319. if (status != kResultOk)
  1320. return status;
  1321. #endif
  1322. return state->write (mem.getData(), (Steinberg::int32) mem.getSize());
  1323. }
  1324. //==============================================================================
  1325. Steinberg::int32 PLUGIN_API getUnitCount() override
  1326. {
  1327. return 1;
  1328. }
  1329. tresult PLUGIN_API getUnitInfo (Steinberg::int32 unitIndex, Vst::UnitInfo& info) override
  1330. {
  1331. if (unitIndex == 0)
  1332. {
  1333. info.id = Vst::kRootUnitId;
  1334. info.parentUnitId = Vst::kNoParentUnitId;
  1335. info.programListId = Vst::kNoProgramListId;
  1336. toString128 (info.name, TRANS("Root Unit"));
  1337. return kResultTrue;
  1338. }
  1339. zerostruct (info);
  1340. return kResultFalse;
  1341. }
  1342. Steinberg::int32 PLUGIN_API getProgramListCount() override
  1343. {
  1344. if (getPluginInstance().getNumPrograms() > 0)
  1345. return 1;
  1346. return 0;
  1347. }
  1348. tresult PLUGIN_API getProgramListInfo (Steinberg::int32 listIndex, Vst::ProgramListInfo& info) override
  1349. {
  1350. if (listIndex == 0)
  1351. {
  1352. info.id = JuceVST3EditController::paramPreset;
  1353. info.programCount = (Steinberg::int32) getPluginInstance().getNumPrograms();
  1354. toString128 (info.name, TRANS("Factory Presets"));
  1355. return kResultTrue;
  1356. }
  1357. jassertfalse;
  1358. zerostruct (info);
  1359. return kResultFalse;
  1360. }
  1361. tresult PLUGIN_API getProgramName (Vst::ProgramListID listId, Steinberg::int32 programIndex, Vst::String128 name) override
  1362. {
  1363. if (listId == JuceVST3EditController::paramPreset
  1364. && isPositiveAndBelow ((int) programIndex, getPluginInstance().getNumPrograms()))
  1365. {
  1366. toString128 (name, getPluginInstance().getProgramName ((int) programIndex));
  1367. return kResultTrue;
  1368. }
  1369. jassertfalse;
  1370. toString128 (name, juce::String());
  1371. return kResultFalse;
  1372. }
  1373. tresult PLUGIN_API getProgramInfo (Vst::ProgramListID, Steinberg::int32, Vst::CString, Vst::String128) override { return kNotImplemented; }
  1374. tresult PLUGIN_API hasProgramPitchNames (Vst::ProgramListID, Steinberg::int32) override { return kNotImplemented; }
  1375. tresult PLUGIN_API getProgramPitchName (Vst::ProgramListID, Steinberg::int32, Steinberg::int16, Vst::String128) override { return kNotImplemented; }
  1376. tresult PLUGIN_API selectUnit (Vst::UnitID) override { return kNotImplemented; }
  1377. tresult PLUGIN_API setUnitProgramData (Steinberg::int32, Steinberg::int32, IBStream*) override { return kNotImplemented; }
  1378. Vst::UnitID PLUGIN_API getSelectedUnit() override { return Vst::kRootUnitId; }
  1379. tresult PLUGIN_API getUnitByBus (Vst::MediaType, Vst::BusDirection, Steinberg::int32, Steinberg::int32, Vst::UnitID& unitId) override
  1380. {
  1381. zerostruct (unitId);
  1382. return kNotImplemented;
  1383. }
  1384. //==============================================================================
  1385. bool getCurrentPosition (CurrentPositionInfo& info) override
  1386. {
  1387. info.timeInSamples = jmax ((juce::int64) 0, processContext.projectTimeSamples);
  1388. info.timeInSeconds = static_cast<double> (info.timeInSamples) / processContext.sampleRate;
  1389. info.bpm = jmax (1.0, processContext.tempo);
  1390. info.timeSigNumerator = jmax (1, (int) processContext.timeSigNumerator);
  1391. info.timeSigDenominator = jmax (1, (int) processContext.timeSigDenominator);
  1392. info.ppqPositionOfLastBarStart = processContext.barPositionMusic;
  1393. info.ppqPosition = processContext.projectTimeMusic;
  1394. info.ppqLoopStart = processContext.cycleStartMusic;
  1395. info.ppqLoopEnd = processContext.cycleEndMusic;
  1396. info.isRecording = (processContext.state & Vst::ProcessContext::kRecording) != 0;
  1397. info.isPlaying = (processContext.state & Vst::ProcessContext::kPlaying) != 0;
  1398. info.isLooping = (processContext.state & Vst::ProcessContext::kCycleActive) != 0;
  1399. info.editOriginTime = 0.0;
  1400. info.frameRate = AudioPlayHead::fpsUnknown;
  1401. if ((processContext.state & Vst::ProcessContext::kSmpteValid) != 0)
  1402. {
  1403. switch (processContext.frameRate.framesPerSecond)
  1404. {
  1405. case 24:
  1406. {
  1407. if ((processContext.frameRate.flags & Vst::FrameRate::kPullDownRate) != 0)
  1408. info.frameRate = AudioPlayHead::fps23976;
  1409. else
  1410. info.frameRate = AudioPlayHead::fps24;
  1411. }
  1412. break;
  1413. case 25: info.frameRate = AudioPlayHead::fps25; break;
  1414. case 29: info.frameRate = AudioPlayHead::fps30drop; break;
  1415. case 30:
  1416. {
  1417. if ((processContext.frameRate.flags & Vst::FrameRate::kDropRate) != 0)
  1418. info.frameRate = AudioPlayHead::fps30drop;
  1419. else
  1420. info.frameRate = AudioPlayHead::fps30;
  1421. }
  1422. break;
  1423. default: break;
  1424. }
  1425. }
  1426. return true;
  1427. }
  1428. //==============================================================================
  1429. int getNumAudioBuses (bool isInput) const
  1430. {
  1431. int busCount = pluginInstance->getBusCount (isInput);
  1432. #ifdef JucePlugin_PreferredChannelConfigurations
  1433. short configs[][2] = {JucePlugin_PreferredChannelConfigurations};
  1434. const int numConfigs = sizeof (configs) / sizeof (short[2]);
  1435. bool hasOnlyZeroChannels = true;
  1436. for (int i = 0; i < numConfigs && hasOnlyZeroChannels == true; ++i)
  1437. if (configs[i][isInput ? 0 : 1] != 0)
  1438. hasOnlyZeroChannels = false;
  1439. busCount = jmin (busCount, hasOnlyZeroChannels ? 0 : 1);
  1440. #endif
  1441. return busCount;
  1442. }
  1443. //==============================================================================
  1444. Steinberg::int32 PLUGIN_API getBusCount (Vst::MediaType type, Vst::BusDirection dir) override
  1445. {
  1446. if (type == Vst::kAudio)
  1447. return getNumAudioBuses (dir == Vst::kInput);
  1448. if (type == Vst::kEvent)
  1449. {
  1450. if (dir == Vst::kInput)
  1451. return isMidiInputBusEnabled ? 1 : 0;
  1452. if (dir == Vst::kOutput)
  1453. return isMidiOutputBusEnabled ? 1 : 0;
  1454. }
  1455. return 0;
  1456. }
  1457. tresult PLUGIN_API getBusInfo (Vst::MediaType type, Vst::BusDirection dir,
  1458. Steinberg::int32 index, Vst::BusInfo& info) override
  1459. {
  1460. if (type == Vst::kAudio)
  1461. {
  1462. if (index < 0 || index >= getNumAudioBuses (dir == Vst::kInput))
  1463. return kResultFalse;
  1464. if (auto* bus = pluginInstance->getBus (dir == Vst::kInput, index))
  1465. {
  1466. info.mediaType = Vst::kAudio;
  1467. info.direction = dir;
  1468. info.channelCount = bus->getLastEnabledLayout().size();
  1469. toString128 (info.name, bus->getName());
  1470. #if JucePlugin_IsSynth
  1471. info.busType = (dir == Vst::kInput && index > 0 ? Vst::kAux : Vst::kMain);
  1472. #else
  1473. info.busType = (index == 0 ? Vst::kMain : Vst::kAux);
  1474. #endif
  1475. info.flags = (bus->isEnabledByDefault()) ? Vst::BusInfo::kDefaultActive : 0;
  1476. return kResultTrue;
  1477. }
  1478. }
  1479. if (type == Vst::kEvent)
  1480. {
  1481. info.flags = Vst::BusInfo::kDefaultActive;
  1482. #if JucePlugin_WantsMidiInput
  1483. if (dir == Vst::kInput && index == 0)
  1484. {
  1485. info.mediaType = Vst::kEvent;
  1486. info.direction = dir;
  1487. info.channelCount = 16;
  1488. toString128 (info.name, TRANS("MIDI Input"));
  1489. info.busType = Vst::kMain;
  1490. return kResultTrue;
  1491. }
  1492. #endif
  1493. #if JucePlugin_ProducesMidiOutput
  1494. if (dir == Vst::kOutput && index == 0)
  1495. {
  1496. info.mediaType = Vst::kEvent;
  1497. info.direction = dir;
  1498. info.channelCount = 16;
  1499. toString128 (info.name, TRANS("MIDI Output"));
  1500. info.busType = Vst::kMain;
  1501. return kResultTrue;
  1502. }
  1503. #endif
  1504. }
  1505. zerostruct (info);
  1506. return kResultFalse;
  1507. }
  1508. tresult PLUGIN_API activateBus (Vst::MediaType type, Vst::BusDirection dir, Steinberg::int32 index, TBool state) override
  1509. {
  1510. if (type == Vst::kEvent)
  1511. {
  1512. if (index != 0)
  1513. return kResultFalse;
  1514. if (dir == Vst::kInput)
  1515. isMidiInputBusEnabled = (state != 0);
  1516. else
  1517. isMidiOutputBusEnabled = (state != 0);
  1518. return kResultTrue;
  1519. }
  1520. if (type == Vst::kAudio)
  1521. {
  1522. if (index < 0 || index >= getNumAudioBuses (dir == Vst::kInput))
  1523. return kResultFalse;
  1524. if (auto* bus = pluginInstance->getBus (dir == Vst::kInput, index))
  1525. {
  1526. #ifdef JucePlugin_PreferredChannelConfigurations
  1527. auto newLayout = pluginInstance->getBusesLayout();
  1528. auto targetLayout = (state != 0 ? bus->getLastEnabledLayout() : AudioChannelSet::disabled());
  1529. (dir == Vst::kInput ? newLayout.inputBuses : newLayout.outputBuses).getReference (index) = targetLayout;
  1530. short configs[][2] = { JucePlugin_PreferredChannelConfigurations };
  1531. auto compLayout = pluginInstance->getNextBestLayoutInLayoutList (newLayout, configs);
  1532. if ((dir == Vst::kInput ? compLayout.inputBuses : compLayout.outputBuses).getReference (index) != targetLayout)
  1533. return kResultFalse;
  1534. #endif
  1535. return bus->enable (state != 0) ? kResultTrue : kResultFalse;
  1536. }
  1537. }
  1538. return kResultFalse;
  1539. }
  1540. bool checkBusFormatsAreNotDiscrete()
  1541. {
  1542. auto numInputBuses = pluginInstance->getBusCount (true);
  1543. auto numOutputBuses = pluginInstance->getBusCount (false);
  1544. for (int i = 0; i < numInputBuses; ++i)
  1545. {
  1546. auto layout = pluginInstance->getChannelLayoutOfBus (true, i);
  1547. if (layout.isDiscreteLayout() && ! layout.isDisabled())
  1548. return false;
  1549. }
  1550. for (int i = 0; i < numOutputBuses; ++i)
  1551. {
  1552. auto layout = pluginInstance->getChannelLayoutOfBus (false, i);
  1553. if (layout.isDiscreteLayout() && ! layout.isDisabled())
  1554. return false;
  1555. }
  1556. return true;
  1557. }
  1558. tresult PLUGIN_API setBusArrangements (Vst::SpeakerArrangement* inputs, Steinberg::int32 numIns,
  1559. Vst::SpeakerArrangement* outputs, Steinberg::int32 numOuts) override
  1560. {
  1561. auto numInputBuses = pluginInstance->getBusCount (true);
  1562. auto numOutputBuses = pluginInstance->getBusCount (false);
  1563. if (numIns > numInputBuses || numOuts > numOutputBuses)
  1564. return false;
  1565. auto requested = pluginInstance->getBusesLayout();
  1566. for (int i = 0; i < numIns; ++i)
  1567. requested.getChannelSet (true, i) = getChannelSetForSpeakerArrangement (inputs[i]);
  1568. for (int i = 0; i < numOuts; ++i)
  1569. requested.getChannelSet (false, i) = getChannelSetForSpeakerArrangement (outputs[i]);
  1570. #ifdef JucePlugin_PreferredChannelConfigurations
  1571. short configs[][2] = { JucePlugin_PreferredChannelConfigurations };
  1572. if (! AudioProcessor::containsLayout (requested, configs))
  1573. return kResultFalse;
  1574. #endif
  1575. return pluginInstance->setBusesLayoutWithoutEnabling (requested) ? kResultTrue : kResultFalse;
  1576. }
  1577. tresult PLUGIN_API getBusArrangement (Vst::BusDirection dir, Steinberg::int32 index, Vst::SpeakerArrangement& arr) override
  1578. {
  1579. if (auto* bus = pluginInstance->getBus (dir == Vst::kInput, index))
  1580. {
  1581. arr = getVst3SpeakerArrangement (bus->getLastEnabledLayout());
  1582. return kResultTrue;
  1583. }
  1584. return kResultFalse;
  1585. }
  1586. //==============================================================================
  1587. tresult PLUGIN_API canProcessSampleSize (Steinberg::int32 symbolicSampleSize) override
  1588. {
  1589. return (symbolicSampleSize == Vst::kSample32
  1590. || (getPluginInstance().supportsDoublePrecisionProcessing()
  1591. && symbolicSampleSize == Vst::kSample64)) ? kResultTrue : kResultFalse;
  1592. }
  1593. Steinberg::uint32 PLUGIN_API getLatencySamples() override
  1594. {
  1595. return (Steinberg::uint32) jmax (0, getPluginInstance().getLatencySamples());
  1596. }
  1597. tresult PLUGIN_API setupProcessing (Vst::ProcessSetup& newSetup) override
  1598. {
  1599. if (canProcessSampleSize (newSetup.symbolicSampleSize) != kResultTrue)
  1600. return kResultFalse;
  1601. processSetup = newSetup;
  1602. processContext.sampleRate = processSetup.sampleRate;
  1603. getPluginInstance().setProcessingPrecision (newSetup.symbolicSampleSize == Vst::kSample64
  1604. ? AudioProcessor::doublePrecision
  1605. : AudioProcessor::singlePrecision);
  1606. getPluginInstance().setNonRealtime (newSetup.processMode == Vst::kOffline);
  1607. preparePlugin (processSetup.sampleRate, processSetup.maxSamplesPerBlock);
  1608. return kResultTrue;
  1609. }
  1610. tresult PLUGIN_API setProcessing (TBool state) override
  1611. {
  1612. if (! state)
  1613. getPluginInstance().reset();
  1614. return kResultTrue;
  1615. }
  1616. Steinberg::uint32 PLUGIN_API getTailSamples() override
  1617. {
  1618. auto tailLengthSeconds = getPluginInstance().getTailLengthSeconds();
  1619. if (tailLengthSeconds <= 0.0 || processSetup.sampleRate <= 0.0)
  1620. return Vst::kNoTail;
  1621. if (tailLengthSeconds == std::numeric_limits<double>::infinity())
  1622. return Vst::kInfiniteTail;
  1623. return (Steinberg::uint32) roundToIntAccurate (tailLengthSeconds * processSetup.sampleRate);
  1624. }
  1625. //==============================================================================
  1626. void processParameterChanges (Vst::IParameterChanges& paramChanges)
  1627. {
  1628. jassert (pluginInstance != nullptr);
  1629. auto numParamsChanged = paramChanges.getParameterCount();
  1630. for (Steinberg::int32 i = 0; i < numParamsChanged; ++i)
  1631. {
  1632. if (auto* paramQueue = paramChanges.getParameterData (i))
  1633. {
  1634. auto numPoints = paramQueue->getPointCount();
  1635. Steinberg::int32 offsetSamples = 0;
  1636. double value = 0.0;
  1637. if (paramQueue->getPoint (numPoints - 1, offsetSamples, value) == kResultTrue)
  1638. {
  1639. auto vstParamID = paramQueue->getParameterId();
  1640. if (vstParamID == JuceVST3EditController::paramPreset)
  1641. {
  1642. auto numPrograms = pluginInstance->getNumPrograms();
  1643. auto programValue = roundToInt (value * (jmax (0, numPrograms - 1)));
  1644. if (numPrograms > 1 && isPositiveAndBelow (programValue, numPrograms)
  1645. && programValue != pluginInstance->getCurrentProgram())
  1646. pluginInstance->setCurrentProgram (programValue);
  1647. }
  1648. #if JUCE_VST3_EMULATE_MIDI_CC_WITH_PARAMETERS
  1649. else if (juceVST3EditController->isMidiControllerParamID (vstParamID))
  1650. addParameterChangeToMidiBuffer (offsetSamples, vstParamID, value);
  1651. #endif
  1652. else
  1653. {
  1654. auto floatValue = static_cast<float> (value);
  1655. if (auto* param = comPluginInstance->getParamForVSTParamID (vstParamID))
  1656. {
  1657. param->setValue (floatValue);
  1658. inParameterChangedCallback = true;
  1659. param->sendValueChangedMessageToListeners (floatValue);
  1660. }
  1661. }
  1662. }
  1663. }
  1664. }
  1665. }
  1666. void addParameterChangeToMidiBuffer (const Steinberg::int32 offsetSamples, const Vst::ParamID id, const double value)
  1667. {
  1668. // If the parameter is mapped to a MIDI CC message then insert it into the midiBuffer.
  1669. int channel, ctrlNumber;
  1670. if (juceVST3EditController->getMidiControllerForParameter (id, channel, ctrlNumber))
  1671. {
  1672. if (ctrlNumber == Vst::kAfterTouch)
  1673. midiBuffer.addEvent (MidiMessage::channelPressureChange (channel,
  1674. jlimit (0, 127, (int) (value * 128.0))), offsetSamples);
  1675. else if (ctrlNumber == Vst::kPitchBend)
  1676. midiBuffer.addEvent (MidiMessage::pitchWheel (channel,
  1677. jlimit (0, 0x3fff, (int) (value * 0x4000))), offsetSamples);
  1678. else
  1679. midiBuffer.addEvent (MidiMessage::controllerEvent (channel,
  1680. jlimit (0, 127, ctrlNumber),
  1681. jlimit (0, 127, (int) (value * 128.0))), offsetSamples);
  1682. }
  1683. }
  1684. tresult PLUGIN_API process (Vst::ProcessData& data) override
  1685. {
  1686. if (pluginInstance == nullptr)
  1687. return kResultFalse;
  1688. if ((processSetup.symbolicSampleSize == Vst::kSample64) != pluginInstance->isUsingDoublePrecision())
  1689. return kResultFalse;
  1690. if (data.processContext != nullptr)
  1691. {
  1692. processContext = *data.processContext;
  1693. if (juceVST3EditController != nullptr)
  1694. juceVST3EditController->vst3IsPlaying = processContext.state & Vst::ProcessContext::kPlaying;
  1695. }
  1696. else
  1697. {
  1698. zerostruct (processContext);
  1699. if (juceVST3EditController != nullptr)
  1700. juceVST3EditController->vst3IsPlaying = 0;
  1701. }
  1702. midiBuffer.clear();
  1703. if (data.inputParameterChanges != nullptr)
  1704. processParameterChanges (*data.inputParameterChanges);
  1705. #if JucePlugin_WantsMidiInput
  1706. if (data.inputEvents != nullptr)
  1707. MidiEventList::toMidiBuffer (midiBuffer, *data.inputEvents);
  1708. #endif
  1709. if (getHostType().isWavelab())
  1710. {
  1711. const int numInputChans = (data.inputs != nullptr && data.inputs[0].channelBuffers32 != nullptr) ? (int) data.inputs[0].numChannels : 0;
  1712. const int numOutputChans = (data.outputs != nullptr && data.outputs[0].channelBuffers32 != nullptr) ? (int) data.outputs[0].numChannels : 0;
  1713. if ((pluginInstance->getTotalNumInputChannels() + pluginInstance->getTotalNumOutputChannels()) > 0
  1714. && (numInputChans + numOutputChans) == 0)
  1715. return kResultFalse;
  1716. }
  1717. if (processSetup.symbolicSampleSize == Vst::kSample32) processAudio<float> (data, channelListFloat);
  1718. else if (processSetup.symbolicSampleSize == Vst::kSample64) processAudio<double> (data, channelListDouble);
  1719. else jassertfalse;
  1720. #if JucePlugin_ProducesMidiOutput
  1721. if (data.outputEvents != nullptr)
  1722. MidiEventList::toEventList (*data.outputEvents, midiBuffer);
  1723. #endif
  1724. return kResultTrue;
  1725. }
  1726. private:
  1727. //==============================================================================
  1728. Atomic<int> refCount { 1 };
  1729. AudioProcessor* pluginInstance;
  1730. ComSmartPtr<Vst::IHostApplication> host;
  1731. ComSmartPtr<JuceAudioProcessor> comPluginInstance;
  1732. ComSmartPtr<JuceVST3EditController> juceVST3EditController;
  1733. /**
  1734. Since VST3 does not provide a way of knowing the buffer size and sample rate at any point,
  1735. this object needs to be copied on every call to process() to be up-to-date...
  1736. */
  1737. Vst::ProcessContext processContext;
  1738. Vst::ProcessSetup processSetup;
  1739. MidiBuffer midiBuffer;
  1740. Array<float*> channelListFloat;
  1741. Array<double*> channelListDouble;
  1742. AudioBuffer<float> emptyBufferFloat;
  1743. AudioBuffer<double> emptyBufferDouble;
  1744. #if JucePlugin_WantsMidiInput
  1745. bool isMidiInputBusEnabled = true;
  1746. #else
  1747. bool isMidiInputBusEnabled = false;
  1748. #endif
  1749. #if JucePlugin_ProducesMidiOutput
  1750. bool isMidiOutputBusEnabled = true;
  1751. #else
  1752. bool isMidiOutputBusEnabled = false;
  1753. #endif
  1754. ScopedJuceInitialiser_GUI libraryInitialiser;
  1755. static const char* kJucePrivateDataIdentifier;
  1756. //==============================================================================
  1757. template <typename FloatType>
  1758. void processAudio (Vst::ProcessData& data, Array<FloatType*>& channelList)
  1759. {
  1760. int totalInputChans = 0, totalOutputChans = 0;
  1761. bool tmpBufferNeedsClearing = false;
  1762. auto plugInInputChannels = pluginInstance->getTotalNumInputChannels();
  1763. auto plugInOutputChannels = pluginInstance->getTotalNumOutputChannels();
  1764. // Wavelab workaround: wave-lab lies on the number of inputs/outputs so re-count here
  1765. int vstInputs;
  1766. for (vstInputs = 0; vstInputs < data.numInputs; ++vstInputs)
  1767. if (getPointerForAudioBus<FloatType> (data.inputs[vstInputs]) == nullptr
  1768. && data.inputs[vstInputs].numChannels > 0)
  1769. break;
  1770. int vstOutputs;
  1771. for (vstOutputs = 0; vstOutputs < data.numOutputs; ++vstOutputs)
  1772. if (getPointerForAudioBus<FloatType> (data.outputs[vstOutputs]) == nullptr
  1773. && data.outputs[vstOutputs].numChannels > 0)
  1774. break;
  1775. {
  1776. auto n = jmax (vstOutputs, getNumAudioBuses (false));
  1777. for (int bus = 0; bus < n && totalOutputChans < plugInOutputChannels; ++bus)
  1778. {
  1779. if (bus < vstOutputs)
  1780. {
  1781. if (auto** const busChannels = getPointerForAudioBus<FloatType> (data.outputs[bus]))
  1782. {
  1783. auto numChans = jmin ((int) data.outputs[bus].numChannels, plugInOutputChannels - totalOutputChans);
  1784. for (int i = 0; i < numChans; ++i)
  1785. {
  1786. if (auto dst = busChannels[i])
  1787. {
  1788. if (totalOutputChans >= plugInInputChannels)
  1789. FloatVectorOperations::clear (dst, (int) data.numSamples);
  1790. channelList.set (totalOutputChans++, busChannels[i]);
  1791. }
  1792. }
  1793. }
  1794. }
  1795. else
  1796. {
  1797. const int numChans = jmin (pluginInstance->getChannelCountOfBus (false, bus), plugInOutputChannels - totalOutputChans);
  1798. for (int i = 0; i < numChans; ++i)
  1799. {
  1800. if (auto* tmpBuffer = getTmpBufferForChannel<FloatType> (totalOutputChans, data.numSamples))\
  1801. {
  1802. tmpBufferNeedsClearing = true;
  1803. channelList.set (totalOutputChans++, tmpBuffer);
  1804. }
  1805. else
  1806. return;
  1807. }
  1808. }
  1809. }
  1810. }
  1811. {
  1812. auto n = jmax (vstInputs, getNumAudioBuses (true));
  1813. for (int bus = 0; bus < n && totalInputChans < plugInInputChannels; ++bus)
  1814. {
  1815. if (bus < vstInputs)
  1816. {
  1817. if (auto** const busChannels = getPointerForAudioBus<FloatType> (data.inputs[bus]))
  1818. {
  1819. const int numChans = jmin ((int) data.inputs[bus].numChannels, plugInInputChannels - totalInputChans);
  1820. for (int i = 0; i < numChans; ++i)
  1821. {
  1822. if (busChannels[i] != nullptr)
  1823. {
  1824. if (totalInputChans >= totalOutputChans)
  1825. channelList.set (totalInputChans, busChannels[i]);
  1826. else
  1827. {
  1828. auto* dst = channelList.getReference (totalInputChans);
  1829. auto* src = busChannels[i];
  1830. if (dst != src)
  1831. FloatVectorOperations::copy (dst, src, (int) data.numSamples);
  1832. }
  1833. }
  1834. ++totalInputChans;
  1835. }
  1836. }
  1837. }
  1838. else
  1839. {
  1840. auto numChans = jmin (pluginInstance->getChannelCountOfBus (true, bus), plugInInputChannels - totalInputChans);
  1841. for (int i = 0; i < numChans; ++i)
  1842. {
  1843. if (auto* tmpBuffer = getTmpBufferForChannel<FloatType> (totalInputChans, data.numSamples))
  1844. {
  1845. tmpBufferNeedsClearing = true;
  1846. channelList.set (totalInputChans++, tmpBuffer);
  1847. }
  1848. else
  1849. return;
  1850. }
  1851. }
  1852. }
  1853. }
  1854. if (tmpBufferNeedsClearing)
  1855. ChooseBufferHelper<FloatType>::impl (emptyBufferFloat, emptyBufferDouble).clear();
  1856. AudioBuffer<FloatType> buffer;
  1857. if (int totalChans = jmax (totalOutputChans, totalInputChans))
  1858. buffer.setDataToReferTo (channelList.getRawDataPointer(), totalChans, (int) data.numSamples);
  1859. {
  1860. const ScopedLock sl (pluginInstance->getCallbackLock());
  1861. pluginInstance->setNonRealtime (data.processMode == Vst::kOffline);
  1862. #if JUCE_DEBUG && ! JucePlugin_ProducesMidiOutput
  1863. const int numMidiEventsComingIn = midiBuffer.getNumEvents();
  1864. #endif
  1865. if (pluginInstance->isSuspended())
  1866. {
  1867. buffer.clear();
  1868. }
  1869. else
  1870. {
  1871. if (totalInputChans == pluginInstance->getTotalNumInputChannels()
  1872. && totalOutputChans == pluginInstance->getTotalNumOutputChannels())
  1873. {
  1874. if (isBypassed())
  1875. pluginInstance->processBlockBypassed (buffer, midiBuffer);
  1876. else
  1877. pluginInstance->processBlock (buffer, midiBuffer);
  1878. }
  1879. }
  1880. #if JUCE_DEBUG && (! JucePlugin_ProducesMidiOutput)
  1881. /* This assertion is caused when you've added some events to the
  1882. midiMessages array in your processBlock() method, which usually means
  1883. that you're trying to send them somewhere. But in this case they're
  1884. getting thrown away.
  1885. If your plugin does want to send MIDI messages, you'll need to set
  1886. the JucePlugin_ProducesMidiOutput macro to 1 in your
  1887. JucePluginCharacteristics.h file.
  1888. If you don't want to produce any MIDI output, then you should clear the
  1889. midiMessages array at the end of your processBlock() method, to
  1890. indicate that you don't want any of the events to be passed through
  1891. to the output.
  1892. */
  1893. jassert (midiBuffer.getNumEvents() <= numMidiEventsComingIn);
  1894. #endif
  1895. }
  1896. }
  1897. //==============================================================================
  1898. template <typename FloatType>
  1899. void allocateChannelListAndBuffers (Array<FloatType*>& channelList, AudioBuffer<FloatType>& buffer)
  1900. {
  1901. channelList.clearQuick();
  1902. channelList.insertMultiple (0, nullptr, 128);
  1903. auto& p = getPluginInstance();
  1904. buffer.setSize (jmax (p.getTotalNumInputChannels(), p.getTotalNumOutputChannels()), p.getBlockSize() * 4);
  1905. buffer.clear();
  1906. }
  1907. template <typename FloatType>
  1908. void deallocateChannelListAndBuffers (Array<FloatType*>& channelList, AudioBuffer<FloatType>& buffer)
  1909. {
  1910. channelList.clearQuick();
  1911. channelList.resize (0);
  1912. buffer.setSize (0, 0);
  1913. }
  1914. template <typename FloatType>
  1915. static FloatType** getPointerForAudioBus (Vst::AudioBusBuffers& data) noexcept
  1916. {
  1917. return AudioBusPointerHelper<FloatType>::impl (data);
  1918. }
  1919. template <typename FloatType>
  1920. FloatType* getTmpBufferForChannel (int channel, int numSamples) noexcept
  1921. {
  1922. auto& buffer = ChooseBufferHelper<FloatType>::impl (emptyBufferFloat, emptyBufferDouble);
  1923. // we can't do anything if the host requests to render many more samples than the
  1924. // block size, we need to bail out
  1925. if (numSamples > buffer.getNumSamples() || channel >= buffer.getNumChannels())
  1926. return nullptr;
  1927. return buffer.getWritePointer (channel);
  1928. }
  1929. void preparePlugin (double sampleRate, int bufferSize)
  1930. {
  1931. auto& p = getPluginInstance();
  1932. p.setRateAndBufferSizeDetails (sampleRate, bufferSize);
  1933. p.prepareToPlay (sampleRate, bufferSize);
  1934. midiBuffer.ensureSize (2048);
  1935. midiBuffer.clear();
  1936. }
  1937. //==============================================================================
  1938. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (JuceVST3Component)
  1939. };
  1940. const char* JuceVST3Component::kJucePrivateDataIdentifier = "JUCEPrivateData";
  1941. //==============================================================================
  1942. #if JUCE_MSVC
  1943. #pragma warning (push, 0)
  1944. #pragma warning (disable: 4310)
  1945. #elif JUCE_CLANG
  1946. #pragma clang diagnostic push
  1947. #pragma clang diagnostic ignored "-Wall"
  1948. #endif
  1949. DECLARE_CLASS_IID (JuceAudioProcessor, 0x0101ABAB, 0xABCDEF01, JucePlugin_ManufacturerCode, JucePlugin_PluginCode)
  1950. DEF_CLASS_IID (JuceAudioProcessor)
  1951. #if JUCE_VST3_CAN_REPLACE_VST2
  1952. FUID getFUIDForVST2ID (bool forControllerUID)
  1953. {
  1954. TUID uuid;
  1955. extern JUCE_API void getUUIDForVST2ID (bool, uint8[16]);
  1956. getUUIDForVST2ID (forControllerUID, (uint8*) uuid);
  1957. return FUID (uuid);
  1958. }
  1959. const Steinberg::FUID JuceVST3Component ::iid (getFUIDForVST2ID (false));
  1960. const Steinberg::FUID JuceVST3EditController::iid (getFUIDForVST2ID (true));
  1961. #else
  1962. DECLARE_CLASS_IID (JuceVST3EditController, 0xABCDEF01, 0x1234ABCD, JucePlugin_ManufacturerCode, JucePlugin_PluginCode)
  1963. DEF_CLASS_IID (JuceVST3EditController)
  1964. DECLARE_CLASS_IID (JuceVST3Component, 0xABCDEF01, 0x9182FAEB, JucePlugin_ManufacturerCode, JucePlugin_PluginCode)
  1965. DEF_CLASS_IID (JuceVST3Component)
  1966. #endif
  1967. #if JUCE_MSVC
  1968. #pragma warning (pop)
  1969. #elif JUCE_CLANG
  1970. #pragma clang diagnostic pop
  1971. #endif
  1972. //==============================================================================
  1973. bool initModule()
  1974. {
  1975. #if JUCE_MAC
  1976. initialiseMacVST();
  1977. #endif
  1978. return true;
  1979. }
  1980. bool shutdownModule()
  1981. {
  1982. return true;
  1983. }
  1984. #undef JUCE_EXPORTED_FUNCTION
  1985. #if JUCE_WINDOWS
  1986. extern "C" __declspec (dllexport) bool InitDll() { return initModule(); }
  1987. extern "C" __declspec (dllexport) bool ExitDll() { return shutdownModule(); }
  1988. #define JUCE_EXPORTED_FUNCTION
  1989. #else
  1990. #define JUCE_EXPORTED_FUNCTION extern "C" __attribute__ ((visibility ("default")))
  1991. CFBundleRef globalBundleInstance = nullptr;
  1992. juce::uint32 numBundleRefs = 0;
  1993. juce::Array<CFBundleRef> bundleRefs;
  1994. enum { MaxPathLength = 2048 };
  1995. char modulePath[MaxPathLength] = { 0 };
  1996. void* moduleHandle = nullptr;
  1997. JUCE_EXPORTED_FUNCTION bool bundleEntry (CFBundleRef ref)
  1998. {
  1999. if (ref != nullptr)
  2000. {
  2001. ++numBundleRefs;
  2002. CFRetain (ref);
  2003. bundleRefs.add (ref);
  2004. if (moduleHandle == nullptr)
  2005. {
  2006. globalBundleInstance = ref;
  2007. moduleHandle = ref;
  2008. CFURLRef tempURL = CFBundleCopyBundleURL (ref);
  2009. CFURLGetFileSystemRepresentation (tempURL, true, (UInt8*) modulePath, MaxPathLength);
  2010. CFRelease (tempURL);
  2011. }
  2012. }
  2013. return initModule();
  2014. }
  2015. JUCE_EXPORTED_FUNCTION bool bundleExit()
  2016. {
  2017. if (shutdownModule())
  2018. {
  2019. if (--numBundleRefs == 0)
  2020. {
  2021. for (int i = 0; i < bundleRefs.size(); ++i)
  2022. CFRelease (bundleRefs.getUnchecked (i));
  2023. bundleRefs.clear();
  2024. }
  2025. return true;
  2026. }
  2027. return false;
  2028. }
  2029. #endif
  2030. //==============================================================================
  2031. /** This typedef represents VST3's createInstance() function signature */
  2032. using CreateFunction = FUnknown* (*)(Vst::IHostApplication*);
  2033. static FUnknown* createComponentInstance (Vst::IHostApplication* host)
  2034. {
  2035. return static_cast<Vst::IAudioProcessor*> (new JuceVST3Component (host));
  2036. }
  2037. static FUnknown* createControllerInstance (Vst::IHostApplication* host)
  2038. {
  2039. return static_cast<Vst::IEditController*> (new JuceVST3EditController (host));
  2040. }
  2041. //==============================================================================
  2042. struct JucePluginFactory;
  2043. static JucePluginFactory* globalFactory = nullptr;
  2044. //==============================================================================
  2045. struct JucePluginFactory : public IPluginFactory3
  2046. {
  2047. JucePluginFactory()
  2048. : factoryInfo (JucePlugin_Manufacturer, JucePlugin_ManufacturerWebsite,
  2049. JucePlugin_ManufacturerEmail, Vst::kDefaultFactoryFlags)
  2050. {
  2051. }
  2052. virtual ~JucePluginFactory()
  2053. {
  2054. if (globalFactory == this)
  2055. globalFactory = nullptr;
  2056. }
  2057. //==============================================================================
  2058. bool registerClass (const PClassInfo2& info, CreateFunction createFunction)
  2059. {
  2060. if (createFunction == nullptr)
  2061. {
  2062. jassertfalse;
  2063. return false;
  2064. }
  2065. auto* entry = classes.add (new ClassEntry (info, createFunction));
  2066. entry->infoW.fromAscii (info);
  2067. return true;
  2068. }
  2069. //==============================================================================
  2070. JUCE_DECLARE_VST3_COM_REF_METHODS
  2071. tresult PLUGIN_API queryInterface (const TUID targetIID, void** obj) override
  2072. {
  2073. TEST_FOR_AND_RETURN_IF_VALID (targetIID, IPluginFactory3)
  2074. TEST_FOR_AND_RETURN_IF_VALID (targetIID, IPluginFactory2)
  2075. TEST_FOR_AND_RETURN_IF_VALID (targetIID, IPluginFactory)
  2076. TEST_FOR_AND_RETURN_IF_VALID (targetIID, FUnknown)
  2077. jassertfalse; // Something new?
  2078. *obj = nullptr;
  2079. return kNotImplemented;
  2080. }
  2081. //==============================================================================
  2082. Steinberg::int32 PLUGIN_API countClasses() override
  2083. {
  2084. return (Steinberg::int32) classes.size();
  2085. }
  2086. tresult PLUGIN_API getFactoryInfo (PFactoryInfo* info) override
  2087. {
  2088. if (info == nullptr)
  2089. return kInvalidArgument;
  2090. memcpy (info, &factoryInfo, sizeof (PFactoryInfo));
  2091. return kResultOk;
  2092. }
  2093. tresult PLUGIN_API getClassInfo (Steinberg::int32 index, PClassInfo* info) override
  2094. {
  2095. return getPClassInfo<PClassInfo> (index, info);
  2096. }
  2097. tresult PLUGIN_API getClassInfo2 (Steinberg::int32 index, PClassInfo2* info) override
  2098. {
  2099. return getPClassInfo<PClassInfo2> (index, info);
  2100. }
  2101. tresult PLUGIN_API getClassInfoUnicode (Steinberg::int32 index, PClassInfoW* info) override
  2102. {
  2103. if (info != nullptr)
  2104. {
  2105. if (auto* entry = classes[(int) index])
  2106. {
  2107. memcpy (info, &entry->infoW, sizeof (PClassInfoW));
  2108. return kResultOk;
  2109. }
  2110. }
  2111. return kInvalidArgument;
  2112. }
  2113. tresult PLUGIN_API createInstance (FIDString cid, FIDString sourceIid, void** obj) override
  2114. {
  2115. *obj = nullptr;
  2116. TUID tuid;
  2117. memcpy (tuid, sourceIid, sizeof (TUID));
  2118. #if VST_VERSION >= 0x030608
  2119. auto sourceFuid = FUID::fromTUID (tuid);
  2120. #else
  2121. FUID sourceFuid;
  2122. sourceFuid = tuid;
  2123. #endif
  2124. if (cid == nullptr || sourceIid == nullptr || ! sourceFuid.isValid())
  2125. {
  2126. jassertfalse; // The host you're running in has severe implementation issues!
  2127. return kInvalidArgument;
  2128. }
  2129. TUID iidToQuery;
  2130. sourceFuid.toTUID (iidToQuery);
  2131. for (auto* entry : classes)
  2132. {
  2133. if (doUIDsMatch (entry->infoW.cid, cid))
  2134. {
  2135. if (auto* instance = entry->createFunction (host))
  2136. {
  2137. const FReleaser releaser (instance);
  2138. if (instance->queryInterface (iidToQuery, obj) == kResultOk)
  2139. return kResultOk;
  2140. }
  2141. break;
  2142. }
  2143. }
  2144. return kNoInterface;
  2145. }
  2146. tresult PLUGIN_API setHostContext (FUnknown* context) override
  2147. {
  2148. host.loadFrom (context);
  2149. if (host != nullptr)
  2150. {
  2151. Vst::String128 name;
  2152. host->getName (name);
  2153. return kResultTrue;
  2154. }
  2155. return kNotImplemented;
  2156. }
  2157. private:
  2158. //==============================================================================
  2159. ScopedJuceInitialiser_GUI libraryInitialiser;
  2160. Atomic<int> refCount { 1 };
  2161. const PFactoryInfo factoryInfo;
  2162. ComSmartPtr<Vst::IHostApplication> host;
  2163. //==============================================================================
  2164. struct ClassEntry
  2165. {
  2166. ClassEntry() noexcept {}
  2167. ClassEntry (const PClassInfo2& info, CreateFunction fn) noexcept
  2168. : info2 (info), createFunction (fn) {}
  2169. PClassInfo2 info2;
  2170. PClassInfoW infoW;
  2171. CreateFunction createFunction = {};
  2172. bool isUnicode = false;
  2173. private:
  2174. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ClassEntry)
  2175. };
  2176. OwnedArray<ClassEntry> classes;
  2177. //==============================================================================
  2178. template<class PClassInfoType>
  2179. tresult PLUGIN_API getPClassInfo (Steinberg::int32 index, PClassInfoType* info)
  2180. {
  2181. if (info != nullptr)
  2182. {
  2183. zerostruct (*info);
  2184. if (auto* entry = classes[(int) index])
  2185. {
  2186. if (entry->isUnicode)
  2187. return kResultFalse;
  2188. memcpy (info, &entry->info2, sizeof (PClassInfoType));
  2189. return kResultOk;
  2190. }
  2191. }
  2192. jassertfalse;
  2193. return kInvalidArgument;
  2194. }
  2195. //==============================================================================
  2196. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (JucePluginFactory)
  2197. };
  2198. } // juce namespace
  2199. //==============================================================================
  2200. #ifndef JucePlugin_Vst3ComponentFlags
  2201. #if JucePlugin_IsSynth
  2202. #define JucePlugin_Vst3ComponentFlags Vst::kSimpleModeSupported
  2203. #else
  2204. #define JucePlugin_Vst3ComponentFlags 0
  2205. #endif
  2206. #endif
  2207. #ifndef JucePlugin_Vst3Category
  2208. #if JucePlugin_IsSynth
  2209. #define JucePlugin_Vst3Category Vst::PlugType::kInstrumentSynth
  2210. #else
  2211. #define JucePlugin_Vst3Category Vst::PlugType::kFx
  2212. #endif
  2213. #endif
  2214. using namespace juce;
  2215. //==============================================================================
  2216. // The VST3 plugin entry point.
  2217. JUCE_EXPORTED_FUNCTION IPluginFactory* PLUGIN_API GetPluginFactory()
  2218. {
  2219. PluginHostType::jucePlugInClientCurrentWrapperType = AudioProcessor::wrapperType_VST3;
  2220. #if JUCE_WINDOWS
  2221. // Cunning trick to force this function to be exported. Life's too short to
  2222. // faff around creating .def files for this kind of thing.
  2223. #pragma comment(linker, "/EXPORT:" __FUNCTION__ "=" __FUNCDNAME__)
  2224. #endif
  2225. if (globalFactory == nullptr)
  2226. {
  2227. globalFactory = new JucePluginFactory();
  2228. static const PClassInfo2 componentClass (JuceVST3Component::iid,
  2229. PClassInfo::kManyInstances,
  2230. kVstAudioEffectClass,
  2231. JucePlugin_Name,
  2232. JucePlugin_Vst3ComponentFlags,
  2233. JucePlugin_Vst3Category,
  2234. JucePlugin_Manufacturer,
  2235. JucePlugin_VersionString,
  2236. kVstVersionString);
  2237. globalFactory->registerClass (componentClass, createComponentInstance);
  2238. static const PClassInfo2 controllerClass (JuceVST3EditController::iid,
  2239. PClassInfo::kManyInstances,
  2240. kVstComponentControllerClass,
  2241. JucePlugin_Name,
  2242. JucePlugin_Vst3ComponentFlags,
  2243. JucePlugin_Vst3Category,
  2244. JucePlugin_Manufacturer,
  2245. JucePlugin_VersionString,
  2246. kVstVersionString);
  2247. globalFactory->registerClass (controllerClass, createControllerInstance);
  2248. }
  2249. else
  2250. {
  2251. globalFactory->addRef();
  2252. }
  2253. return dynamic_cast<IPluginFactory*> (globalFactory);
  2254. }
  2255. //==============================================================================
  2256. #if _MSC_VER || JUCE_MINGW
  2257. extern "C" BOOL WINAPI DllMain (HINSTANCE instance, DWORD reason, LPVOID) { if (reason == DLL_PROCESS_ATTACH) Process::setCurrentModuleInstanceHandle (instance); return true; }
  2258. #endif
  2259. #endif //JucePlugin_Build_VST3