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.

2744 lines
101KB

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