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.

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