The JUCE cross-platform C++ framework, with DISTRHO/KXStudio specific changes
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2810 lines
103KB

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