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.

2811 lines
103KB

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