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.

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