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.

2751 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:
  1331. {
  1332. if ((processContext.frameRate.flags & Vst::FrameRate::kPullDownRate) != 0)
  1333. info.frameRate = AudioPlayHead::fps23976;
  1334. else
  1335. info.frameRate = AudioPlayHead::fps24;
  1336. }
  1337. break;
  1338. case 25: info.frameRate = AudioPlayHead::fps25; break;
  1339. case 29: info.frameRate = AudioPlayHead::fps30drop; break;
  1340. case 30:
  1341. {
  1342. if ((processContext.frameRate.flags & Vst::FrameRate::kDropRate) != 0)
  1343. info.frameRate = AudioPlayHead::fps30drop;
  1344. else
  1345. info.frameRate = AudioPlayHead::fps30;
  1346. }
  1347. break;
  1348. default: break;
  1349. }
  1350. }
  1351. return true;
  1352. }
  1353. //==============================================================================
  1354. int getNumAudioBuses (bool isInput) const
  1355. {
  1356. int busCount = pluginInstance->getBusCount (isInput);
  1357. #ifdef JucePlugin_PreferredChannelConfigurations
  1358. short configs[][2] = {JucePlugin_PreferredChannelConfigurations};
  1359. const int numConfigs = sizeof (configs) / sizeof (short[2]);
  1360. bool hasOnlyZeroChannels = true;
  1361. for (int i = 0; i < numConfigs && hasOnlyZeroChannels == true; ++i)
  1362. if (configs[i][isInput ? 0 : 1] != 0)
  1363. hasOnlyZeroChannels = false;
  1364. busCount = jmin (busCount, hasOnlyZeroChannels ? 0 : 1);
  1365. #endif
  1366. return busCount;
  1367. }
  1368. //==============================================================================
  1369. Steinberg::int32 PLUGIN_API getBusCount (Vst::MediaType type, Vst::BusDirection dir) override
  1370. {
  1371. if (type == Vst::kAudio)
  1372. return getNumAudioBuses (dir == Vst::kInput);
  1373. if (type == Vst::kEvent)
  1374. {
  1375. if (dir == Vst::kInput)
  1376. return isMidiInputBusEnabled ? 1 : 0;
  1377. if (dir == Vst::kOutput)
  1378. return isMidiOutputBusEnabled ? 1 : 0;
  1379. }
  1380. return 0;
  1381. }
  1382. tresult PLUGIN_API getBusInfo (Vst::MediaType type, Vst::BusDirection dir,
  1383. Steinberg::int32 index, Vst::BusInfo& info) override
  1384. {
  1385. if (type == Vst::kAudio)
  1386. {
  1387. if (index < 0 || index >= getNumAudioBuses (dir == Vst::kInput))
  1388. return kResultFalse;
  1389. if (auto* bus = pluginInstance->getBus (dir == Vst::kInput, index))
  1390. {
  1391. info.mediaType = Vst::kAudio;
  1392. info.direction = dir;
  1393. info.channelCount = bus->getLastEnabledLayout().size();
  1394. toString128 (info.name, bus->getName());
  1395. #if JucePlugin_IsSynth
  1396. info.busType = (dir == Vst::kInput && index > 0 ? Vst::kAux : Vst::kMain);
  1397. #else
  1398. info.busType = (index == 0 ? Vst::kMain : Vst::kAux);
  1399. #endif
  1400. info.flags = (bus->isEnabledByDefault()) ? Vst::BusInfo::kDefaultActive : 0;
  1401. return kResultTrue;
  1402. }
  1403. }
  1404. if (type == Vst::kEvent)
  1405. {
  1406. info.flags = Vst::BusInfo::kDefaultActive;
  1407. #if JucePlugin_WantsMidiInput
  1408. if (dir == Vst::kInput && index == 0)
  1409. {
  1410. info.mediaType = Vst::kEvent;
  1411. info.direction = dir;
  1412. info.channelCount = 16;
  1413. toString128 (info.name, TRANS("MIDI Input"));
  1414. info.busType = Vst::kMain;
  1415. return kResultTrue;
  1416. }
  1417. #endif
  1418. #if JucePlugin_ProducesMidiOutput
  1419. if (dir == Vst::kOutput && index == 0)
  1420. {
  1421. info.mediaType = Vst::kEvent;
  1422. info.direction = dir;
  1423. info.channelCount = 16;
  1424. toString128 (info.name, TRANS("MIDI Output"));
  1425. info.busType = Vst::kMain;
  1426. return kResultTrue;
  1427. }
  1428. #endif
  1429. }
  1430. zerostruct (info);
  1431. return kResultFalse;
  1432. }
  1433. tresult PLUGIN_API activateBus (Vst::MediaType type, Vst::BusDirection dir, Steinberg::int32 index, TBool state) override
  1434. {
  1435. if (type == Vst::kEvent)
  1436. {
  1437. if (index != 0)
  1438. return kResultFalse;
  1439. if (dir == Vst::kInput)
  1440. isMidiInputBusEnabled = (state != 0);
  1441. else
  1442. isMidiOutputBusEnabled = (state != 0);
  1443. return kResultTrue;
  1444. }
  1445. if (type == Vst::kAudio)
  1446. {
  1447. if (index < 0 || index >= getNumAudioBuses (dir == Vst::kInput))
  1448. return kResultFalse;
  1449. if (auto* bus = pluginInstance->getBus (dir == Vst::kInput, index))
  1450. {
  1451. #ifdef JucePlugin_PreferredChannelConfigurations
  1452. auto newLayout = pluginInstance->getBusesLayout();
  1453. auto targetLayout = (state != 0 ? bus->getLastEnabledLayout() : AudioChannelSet::disabled());
  1454. (dir == Vst::kInput ? newLayout.inputBuses : newLayout.outputBuses).getReference (index) = targetLayout;
  1455. short configs[][2] = { JucePlugin_PreferredChannelConfigurations };
  1456. auto compLayout = pluginInstance->getNextBestLayoutInLayoutList (newLayout, configs);
  1457. if ((dir == Vst::kInput ? compLayout.inputBuses : compLayout.outputBuses).getReference (index) != targetLayout)
  1458. return kResultFalse;
  1459. #endif
  1460. return bus->enable (state != 0) ? kResultTrue : kResultFalse;
  1461. }
  1462. }
  1463. return kResultFalse;
  1464. }
  1465. bool checkBusFormatsAreNotDiscrete()
  1466. {
  1467. auto numInputBuses = pluginInstance->getBusCount (true);
  1468. auto numOutputBuses = pluginInstance->getBusCount (false);
  1469. for (int i = 0; i < numInputBuses; ++i)
  1470. if (pluginInstance->getChannelLayoutOfBus (true, i).isDiscreteLayout())
  1471. return false;
  1472. for (int i = 0; i < numOutputBuses; ++i)
  1473. if (pluginInstance->getChannelLayoutOfBus (false, i).isDiscreteLayout())
  1474. return false;
  1475. return true;
  1476. }
  1477. tresult PLUGIN_API setBusArrangements (Vst::SpeakerArrangement* inputs, Steinberg::int32 numIns,
  1478. Vst::SpeakerArrangement* outputs, Steinberg::int32 numOuts) override
  1479. {
  1480. auto numInputBuses = pluginInstance->getBusCount (true);
  1481. auto numOutputBuses = pluginInstance->getBusCount (false);
  1482. if (numIns > numInputBuses || numOuts > numOutputBuses)
  1483. return false;
  1484. auto requested = pluginInstance->getBusesLayout();
  1485. for (int i = 0; i < numIns; ++i)
  1486. requested.getChannelSet (true, i) = getChannelSetForSpeakerArrangement (inputs[i]);
  1487. for (int i = 0; i < numOuts; ++i)
  1488. requested.getChannelSet (false, i) = getChannelSetForSpeakerArrangement (outputs[i]);
  1489. #ifdef JucePlugin_PreferredChannelConfigurations
  1490. short configs[][2] = { JucePlugin_PreferredChannelConfigurations };
  1491. if (! AudioProcessor::containsLayout (requested, configs))
  1492. return kResultFalse;
  1493. #endif
  1494. return pluginInstance->setBusesLayoutWithoutEnabling (requested) ? kResultTrue : kResultFalse;
  1495. }
  1496. tresult PLUGIN_API getBusArrangement (Vst::BusDirection dir, Steinberg::int32 index, Vst::SpeakerArrangement& arr) override
  1497. {
  1498. if (auto* bus = pluginInstance->getBus (dir == Vst::kInput, index))
  1499. {
  1500. arr = getVst3SpeakerArrangement (bus->getLastEnabledLayout());
  1501. return kResultTrue;
  1502. }
  1503. return kResultFalse;
  1504. }
  1505. //==============================================================================
  1506. tresult PLUGIN_API canProcessSampleSize (Steinberg::int32 symbolicSampleSize) override
  1507. {
  1508. return (symbolicSampleSize == Vst::kSample32
  1509. || (getPluginInstance().supportsDoublePrecisionProcessing()
  1510. && symbolicSampleSize == Vst::kSample64)) ? kResultTrue : kResultFalse;
  1511. }
  1512. Steinberg::uint32 PLUGIN_API getLatencySamples() override
  1513. {
  1514. return (Steinberg::uint32) jmax (0, getPluginInstance().getLatencySamples());
  1515. }
  1516. tresult PLUGIN_API setupProcessing (Vst::ProcessSetup& newSetup) override
  1517. {
  1518. if (canProcessSampleSize (newSetup.symbolicSampleSize) != kResultTrue)
  1519. return kResultFalse;
  1520. processSetup = newSetup;
  1521. processContext.sampleRate = processSetup.sampleRate;
  1522. getPluginInstance().setProcessingPrecision (newSetup.symbolicSampleSize == Vst::kSample64
  1523. ? AudioProcessor::doublePrecision
  1524. : AudioProcessor::singlePrecision);
  1525. preparePlugin (processSetup.sampleRate, processSetup.maxSamplesPerBlock);
  1526. return kResultTrue;
  1527. }
  1528. tresult PLUGIN_API setProcessing (TBool state) override
  1529. {
  1530. if (! state)
  1531. getPluginInstance().reset();
  1532. return kResultTrue;
  1533. }
  1534. Steinberg::uint32 PLUGIN_API getTailSamples() override
  1535. {
  1536. auto tailLengthSeconds = getPluginInstance().getTailLengthSeconds();
  1537. if (tailLengthSeconds <= 0.0 || processSetup.sampleRate > 0.0)
  1538. return Vst::kNoTail;
  1539. return (Steinberg::uint32) roundToIntAccurate (tailLengthSeconds * processSetup.sampleRate);
  1540. }
  1541. //==============================================================================
  1542. void processParameterChanges (Vst::IParameterChanges& paramChanges)
  1543. {
  1544. jassert (pluginInstance != nullptr);
  1545. auto numParamsChanged = paramChanges.getParameterCount();
  1546. for (Steinberg::int32 i = 0; i < numParamsChanged; ++i)
  1547. {
  1548. if (auto* paramQueue = paramChanges.getParameterData (i))
  1549. {
  1550. auto numPoints = paramQueue->getPointCount();
  1551. Steinberg::int32 offsetSamples = 0;
  1552. double value = 0.0;
  1553. if (paramQueue->getPoint (numPoints - 1, offsetSamples, value) == kResultTrue)
  1554. {
  1555. auto vstParamID = paramQueue->getParameterId();
  1556. if (vstParamID == vstBypassParameterId)
  1557. setBypassed (static_cast<float> (value) != 0.0f);
  1558. #if JUCE_VST3_EMULATE_MIDI_CC_WITH_PARAMETERS
  1559. else if (juceVST3EditController->isMidiControllerParamID (vstParamID))
  1560. addParameterChangeToMidiBuffer (offsetSamples, vstParamID, value);
  1561. #endif
  1562. else if (vstParamID == JuceVST3EditController::paramPreset)
  1563. {
  1564. auto numPrograms = pluginInstance->getNumPrograms();
  1565. auto programValue = roundToInt (value * (jmax (0, numPrograms - 1)));
  1566. if (numPrograms > 1 && isPositiveAndBelow (programValue, numPrograms)
  1567. && programValue != pluginInstance->getCurrentProgram())
  1568. pluginInstance->setCurrentProgram (programValue);
  1569. }
  1570. else
  1571. {
  1572. auto index = getJuceIndexForVSTParamID (vstParamID);
  1573. if (isPositiveAndBelow (index, pluginInstance->getNumParameters()))
  1574. pluginInstance->setParameter (index, static_cast<float> (value));
  1575. }
  1576. }
  1577. }
  1578. }
  1579. }
  1580. void addParameterChangeToMidiBuffer (const Steinberg::int32 offsetSamples, const Vst::ParamID id, const double value)
  1581. {
  1582. // If the parameter is mapped to a MIDI CC message then insert it into the midiBuffer.
  1583. int channel, ctrlNumber;
  1584. if (juceVST3EditController->getMidiControllerForParameter (id, channel, ctrlNumber))
  1585. {
  1586. if (ctrlNumber == Vst::kAfterTouch)
  1587. midiBuffer.addEvent (MidiMessage::channelPressureChange (channel,
  1588. jlimit (0, 127, (int) (value * 128.0))), offsetSamples);
  1589. else if (ctrlNumber == Vst::kPitchBend)
  1590. midiBuffer.addEvent (MidiMessage::pitchWheel (channel,
  1591. jlimit (0, 0x3fff, (int) (value * 0x4000))), offsetSamples);
  1592. else
  1593. midiBuffer.addEvent (MidiMessage::controllerEvent (channel,
  1594. jlimit (0, 127, ctrlNumber),
  1595. jlimit (0, 127, (int) (value * 128.0))), offsetSamples);
  1596. }
  1597. }
  1598. tresult PLUGIN_API process (Vst::ProcessData& data) override
  1599. {
  1600. if (pluginInstance == nullptr)
  1601. return kResultFalse;
  1602. if ((processSetup.symbolicSampleSize == Vst::kSample64) != pluginInstance->isUsingDoublePrecision())
  1603. return kResultFalse;
  1604. if (data.processContext != nullptr)
  1605. processContext = *data.processContext;
  1606. else
  1607. zerostruct (processContext);
  1608. midiBuffer.clear();
  1609. #if JucePlugin_WantsMidiInput
  1610. if (data.inputEvents != nullptr)
  1611. MidiEventList::toMidiBuffer (midiBuffer, *data.inputEvents);
  1612. #endif
  1613. if (getHostType().isWavelab())
  1614. {
  1615. const int numInputChans = (data.inputs != nullptr && data.inputs[0].channelBuffers32 != nullptr) ? (int) data.inputs[0].numChannels : 0;
  1616. const int numOutputChans = (data.outputs != nullptr && data.outputs[0].channelBuffers32 != nullptr) ? (int) data.outputs[0].numChannels : 0;
  1617. if ((pluginInstance->getTotalNumInputChannels() + pluginInstance->getTotalNumOutputChannels()) > 0
  1618. && (numInputChans + numOutputChans) == 0)
  1619. return kResultFalse;
  1620. }
  1621. if (processSetup.symbolicSampleSize == Vst::kSample32) processAudio<float> (data, channelListFloat);
  1622. else if (processSetup.symbolicSampleSize == Vst::kSample64) processAudio<double> (data, channelListDouble);
  1623. else jassertfalse;
  1624. #if JucePlugin_ProducesMidiOutput
  1625. if (data.outputEvents != nullptr)
  1626. MidiEventList::toEventList (*data.outputEvents, midiBuffer);
  1627. #endif
  1628. return kResultTrue;
  1629. }
  1630. private:
  1631. //==============================================================================
  1632. Atomic<int> refCount { 1 };
  1633. AudioProcessor* pluginInstance;
  1634. ComSmartPtr<Vst::IHostApplication> host;
  1635. ComSmartPtr<JuceAudioProcessor> comPluginInstance;
  1636. ComSmartPtr<JuceVST3EditController> juceVST3EditController;
  1637. /**
  1638. Since VST3 does not provide a way of knowing the buffer size and sample rate at any point,
  1639. this object needs to be copied on every call to process() to be up-to-date...
  1640. */
  1641. Vst::ProcessContext processContext;
  1642. Vst::ProcessSetup processSetup;
  1643. MidiBuffer midiBuffer;
  1644. Array<float*> channelListFloat;
  1645. Array<double*> channelListDouble;
  1646. AudioBuffer<float> emptyBufferFloat;
  1647. AudioBuffer<double> emptyBufferDouble;
  1648. #if JucePlugin_WantsMidiInput
  1649. bool isMidiInputBusEnabled = true;
  1650. #else
  1651. bool isMidiInputBusEnabled = false;
  1652. #endif
  1653. #if JucePlugin_ProducesMidiOutput
  1654. bool isMidiOutputBusEnabled = true;
  1655. #else
  1656. bool isMidiOutputBusEnabled = false;
  1657. #endif
  1658. ScopedJuceInitialiser_GUI libraryInitialiser;
  1659. #if ! JUCE_FORCE_USE_LEGACY_PARAM_IDS
  1660. bool usingManagedParameter;
  1661. Array<Vst::ParamID> vstParamIDs;
  1662. HashMap<int32, int> paramMap;
  1663. #endif
  1664. Vst::ParamID vstBypassParameterId;
  1665. static const char* kJucePrivateDataIdentifier;
  1666. //==============================================================================
  1667. template <typename FloatType>
  1668. void processAudio (Vst::ProcessData& data, Array<FloatType*>& channelList)
  1669. {
  1670. int totalInputChans = 0, totalOutputChans = 0;
  1671. bool tmpBufferNeedsClearing = false;
  1672. auto plugInInputChannels = pluginInstance->getTotalNumInputChannels();
  1673. auto plugInOutputChannels = pluginInstance->getTotalNumOutputChannels();
  1674. // Wavelab workaround: wave-lab lies on the number of inputs/outputs so re-count here
  1675. int vstInputs;
  1676. for (vstInputs = 0; vstInputs < data.numInputs; ++vstInputs)
  1677. if (getPointerForAudioBus<FloatType> (data.inputs[vstInputs]) == nullptr
  1678. && data.inputs[vstInputs].numChannels > 0)
  1679. break;
  1680. int vstOutputs;
  1681. for (vstOutputs = 0; vstOutputs < data.numOutputs; ++vstOutputs)
  1682. if (getPointerForAudioBus<FloatType> (data.outputs[vstOutputs]) == nullptr
  1683. && data.outputs[vstOutputs].numChannels > 0)
  1684. break;
  1685. {
  1686. auto n = jmax (vstOutputs, getNumAudioBuses (false));
  1687. for (int bus = 0; bus < n && totalOutputChans < plugInOutputChannels; ++bus)
  1688. {
  1689. if (bus < vstOutputs)
  1690. {
  1691. if (auto** const busChannels = getPointerForAudioBus<FloatType> (data.outputs[bus]))
  1692. {
  1693. auto numChans = jmin ((int) data.outputs[bus].numChannels, plugInOutputChannels - totalOutputChans);
  1694. for (int i = 0; i < numChans; ++i)
  1695. {
  1696. if (auto dst = busChannels[i])
  1697. {
  1698. if (totalOutputChans >= plugInInputChannels)
  1699. FloatVectorOperations::clear (dst, (int) data.numSamples);
  1700. channelList.set (totalOutputChans++, busChannels[i]);
  1701. }
  1702. }
  1703. }
  1704. }
  1705. else
  1706. {
  1707. const int numChans = jmin (pluginInstance->getChannelCountOfBus (false, bus), plugInOutputChannels - totalOutputChans);
  1708. for (int i = 0; i < numChans; ++i)
  1709. {
  1710. if (auto* tmpBuffer = getTmpBufferForChannel<FloatType> (totalOutputChans, data.numSamples))\
  1711. {
  1712. tmpBufferNeedsClearing = true;
  1713. channelList.set (totalOutputChans++, tmpBuffer);
  1714. }
  1715. else
  1716. return;
  1717. }
  1718. }
  1719. }
  1720. }
  1721. {
  1722. auto n = jmax (vstInputs, getNumAudioBuses (true));
  1723. for (int bus = 0; bus < n && totalInputChans < plugInInputChannels; ++bus)
  1724. {
  1725. if (bus < vstInputs)
  1726. {
  1727. if (auto** const busChannels = getPointerForAudioBus<FloatType> (data.inputs[bus]))
  1728. {
  1729. const int numChans = jmin ((int) data.inputs[bus].numChannels, plugInInputChannels - totalInputChans);
  1730. for (int i = 0; i < numChans; ++i)
  1731. {
  1732. if (busChannels[i] != nullptr)
  1733. {
  1734. if (totalInputChans >= totalOutputChans)
  1735. channelList.set (totalInputChans, busChannels[i]);
  1736. else
  1737. {
  1738. auto* dst = channelList.getReference (totalInputChans);
  1739. auto* src = busChannels[i];
  1740. if (dst != src)
  1741. FloatVectorOperations::copy (dst, src, (int) data.numSamples);
  1742. }
  1743. }
  1744. ++totalInputChans;
  1745. }
  1746. }
  1747. }
  1748. else
  1749. {
  1750. auto numChans = jmin (pluginInstance->getChannelCountOfBus (true, bus), plugInInputChannels - totalInputChans);
  1751. for (int i = 0; i < numChans; ++i)
  1752. {
  1753. if (auto* tmpBuffer = getTmpBufferForChannel<FloatType> (totalInputChans, data.numSamples))
  1754. {
  1755. tmpBufferNeedsClearing = true;
  1756. channelList.set (totalInputChans++, tmpBuffer);
  1757. }
  1758. else
  1759. return;
  1760. }
  1761. }
  1762. }
  1763. }
  1764. if (tmpBufferNeedsClearing)
  1765. ChooseBufferHelper<FloatType>::impl (emptyBufferFloat, emptyBufferDouble).clear();
  1766. AudioBuffer<FloatType> buffer;
  1767. if (int totalChans = jmax (totalOutputChans, totalInputChans))
  1768. buffer.setDataToReferTo (channelList.getRawDataPointer(), totalChans, (int) data.numSamples);
  1769. {
  1770. const ScopedLock sl (pluginInstance->getCallbackLock());
  1771. pluginInstance->setNonRealtime (data.processMode == Vst::kOffline);
  1772. if (data.inputParameterChanges != nullptr)
  1773. processParameterChanges (*data.inputParameterChanges);
  1774. #if JUCE_DEBUG && ! JucePlugin_ProducesMidiOutput
  1775. const int numMidiEventsComingIn = midiBuffer.getNumEvents();
  1776. #endif
  1777. if (pluginInstance->isSuspended())
  1778. {
  1779. buffer.clear();
  1780. }
  1781. else
  1782. {
  1783. if (totalInputChans == pluginInstance->getTotalNumInputChannels()
  1784. && totalOutputChans == pluginInstance->getTotalNumOutputChannels())
  1785. {
  1786. if (isBypassed())
  1787. pluginInstance->processBlockBypassed (buffer, midiBuffer);
  1788. else
  1789. pluginInstance->processBlock (buffer, midiBuffer);
  1790. }
  1791. }
  1792. #if JUCE_DEBUG && (! JucePlugin_ProducesMidiOutput)
  1793. /* This assertion is caused when you've added some events to the
  1794. midiMessages array in your processBlock() method, which usually means
  1795. that you're trying to send them somewhere. But in this case they're
  1796. getting thrown away.
  1797. If your plugin does want to send MIDI messages, you'll need to set
  1798. the JucePlugin_ProducesMidiOutput macro to 1 in your
  1799. JucePluginCharacteristics.h file.
  1800. If you don't want to produce any MIDI output, then you should clear the
  1801. midiMessages array at the end of your processBlock() method, to
  1802. indicate that you don't want any of the events to be passed through
  1803. to the output.
  1804. */
  1805. jassert (midiBuffer.getNumEvents() <= numMidiEventsComingIn);
  1806. #endif
  1807. }
  1808. }
  1809. //==============================================================================
  1810. template <typename FloatType>
  1811. void allocateChannelListAndBuffers (Array<FloatType*>& channelList, AudioBuffer<FloatType>& buffer)
  1812. {
  1813. channelList.clearQuick();
  1814. channelList.insertMultiple (0, nullptr, 128);
  1815. auto& p = getPluginInstance();
  1816. buffer.setSize (jmax (p.getTotalNumInputChannels(), p.getTotalNumOutputChannels()), p.getBlockSize() * 4);
  1817. buffer.clear();
  1818. }
  1819. template <typename FloatType>
  1820. void deallocateChannelListAndBuffers (Array<FloatType*>& channelList, AudioBuffer<FloatType>& buffer)
  1821. {
  1822. channelList.clearQuick();
  1823. channelList.resize (0);
  1824. buffer.setSize (0, 0);
  1825. }
  1826. template <typename FloatType>
  1827. static FloatType** getPointerForAudioBus (Vst::AudioBusBuffers& data) noexcept
  1828. {
  1829. return AudioBusPointerHelper<FloatType>::impl (data);
  1830. }
  1831. template <typename FloatType>
  1832. FloatType* getTmpBufferForChannel (int channel, int numSamples) noexcept
  1833. {
  1834. auto& buffer = ChooseBufferHelper<FloatType>::impl (emptyBufferFloat, emptyBufferDouble);
  1835. // we can't do anything if the host requests to render many more samples than the
  1836. // block size, we need to bail out
  1837. if (numSamples > buffer.getNumSamples() || channel >= buffer.getNumChannels())
  1838. return nullptr;
  1839. return buffer.getWritePointer (channel);
  1840. }
  1841. void preparePlugin (double sampleRate, int bufferSize)
  1842. {
  1843. auto& p = getPluginInstance();
  1844. p.setRateAndBufferSizeDetails (sampleRate, bufferSize);
  1845. p.prepareToPlay (sampleRate, bufferSize);
  1846. }
  1847. //==============================================================================
  1848. #if JUCE_FORCE_USE_LEGACY_PARAM_IDS
  1849. inline Vst::ParamID getVSTParamIDForIndex (int paramIndex) const noexcept { return static_cast<Vst::ParamID> (paramIndex); }
  1850. inline int getJuceIndexForVSTParamID (Vst::ParamID paramID) const noexcept { return static_cast<int> (paramID); }
  1851. #else
  1852. void cacheParameterIDs()
  1853. {
  1854. const int numParameters = pluginInstance->getNumParameters();
  1855. usingManagedParameter = (pluginInstance->getParameters().size() == numParameters);
  1856. vstBypassParameterId = static_cast<Vst::ParamID> (usingManagedParameter ? JuceVST3EditController::paramBypass : numParameters);
  1857. for (int i = 0; i < numParameters; ++i)
  1858. {
  1859. auto paramID = JuceVST3EditController::generateVSTParamIDForIndex (pluginInstance, i);
  1860. // Consider yourself very unlucky if you hit this assertion. The hash code of your
  1861. // parameter ids are not unique.
  1862. jassert (! vstParamIDs.contains (paramID));
  1863. vstParamIDs.add (paramID);
  1864. paramMap.set (static_cast<int32> (paramID), i);
  1865. }
  1866. }
  1867. inline Vst::ParamID getVSTParamIDForIndex (int paramIndex) const noexcept
  1868. {
  1869. return usingManagedParameter ? vstParamIDs.getReference (paramIndex)
  1870. : static_cast<Vst::ParamID> (paramIndex);
  1871. }
  1872. inline int getJuceIndexForVSTParamID (Vst::ParamID paramID) const noexcept
  1873. {
  1874. return usingManagedParameter ? paramMap[static_cast<int32> (paramID)]
  1875. : static_cast<int> (paramID);
  1876. }
  1877. #endif
  1878. //==============================================================================
  1879. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (JuceVST3Component)
  1880. };
  1881. const char* JuceVST3Component::kJucePrivateDataIdentifier = "JUCEPrivateData";
  1882. //==============================================================================
  1883. #if JUCE_MSVC
  1884. #pragma warning (push, 0)
  1885. #pragma warning (disable: 4310)
  1886. #elif JUCE_CLANG
  1887. #pragma clang diagnostic push
  1888. #pragma clang diagnostic ignored "-Wall"
  1889. #endif
  1890. DECLARE_CLASS_IID (JuceAudioProcessor, 0x0101ABAB, 0xABCDEF01, JucePlugin_ManufacturerCode, JucePlugin_PluginCode)
  1891. DEF_CLASS_IID (JuceAudioProcessor)
  1892. #if JUCE_VST3_CAN_REPLACE_VST2
  1893. FUID getFUIDForVST2ID (bool forControllerUID)
  1894. {
  1895. TUID uuid;
  1896. extern JUCE_API void getUUIDForVST2ID (bool, uint8[16]);
  1897. getUUIDForVST2ID (forControllerUID, (uint8*) uuid);
  1898. return FUID (uuid);
  1899. }
  1900. const Steinberg::FUID JuceVST3Component ::iid (getFUIDForVST2ID (false));
  1901. const Steinberg::FUID JuceVST3EditController::iid (getFUIDForVST2ID (true));
  1902. #else
  1903. DECLARE_CLASS_IID (JuceVST3EditController, 0xABCDEF01, 0x1234ABCD, JucePlugin_ManufacturerCode, JucePlugin_PluginCode)
  1904. DEF_CLASS_IID (JuceVST3EditController)
  1905. DECLARE_CLASS_IID (JuceVST3Component, 0xABCDEF01, 0x9182FAEB, JucePlugin_ManufacturerCode, JucePlugin_PluginCode)
  1906. DEF_CLASS_IID (JuceVST3Component)
  1907. #endif
  1908. #if JUCE_MSVC
  1909. #pragma warning (pop)
  1910. #elif JUCE_CLANG
  1911. #pragma clang diagnostic pop
  1912. #endif
  1913. //==============================================================================
  1914. bool initModule()
  1915. {
  1916. #if JUCE_MAC
  1917. initialiseMacVST();
  1918. #endif
  1919. return true;
  1920. }
  1921. bool shutdownModule()
  1922. {
  1923. return true;
  1924. }
  1925. #undef JUCE_EXPORTED_FUNCTION
  1926. #if JUCE_WINDOWS
  1927. extern "C" __declspec (dllexport) bool InitDll() { return initModule(); }
  1928. extern "C" __declspec (dllexport) bool ExitDll() { return shutdownModule(); }
  1929. #define JUCE_EXPORTED_FUNCTION
  1930. #else
  1931. #define JUCE_EXPORTED_FUNCTION extern "C" __attribute__ ((visibility ("default")))
  1932. CFBundleRef globalBundleInstance = nullptr;
  1933. juce::uint32 numBundleRefs = 0;
  1934. juce::Array<CFBundleRef> bundleRefs;
  1935. enum { MaxPathLength = 2048 };
  1936. char modulePath[MaxPathLength] = { 0 };
  1937. void* moduleHandle = nullptr;
  1938. JUCE_EXPORTED_FUNCTION bool bundleEntry (CFBundleRef ref)
  1939. {
  1940. if (ref != nullptr)
  1941. {
  1942. ++numBundleRefs;
  1943. CFRetain (ref);
  1944. bundleRefs.add (ref);
  1945. if (moduleHandle == nullptr)
  1946. {
  1947. globalBundleInstance = ref;
  1948. moduleHandle = ref;
  1949. CFURLRef tempURL = CFBundleCopyBundleURL (ref);
  1950. CFURLGetFileSystemRepresentation (tempURL, true, (UInt8*) modulePath, MaxPathLength);
  1951. CFRelease (tempURL);
  1952. }
  1953. }
  1954. return initModule();
  1955. }
  1956. JUCE_EXPORTED_FUNCTION bool bundleExit()
  1957. {
  1958. if (shutdownModule())
  1959. {
  1960. if (--numBundleRefs == 0)
  1961. {
  1962. for (int i = 0; i < bundleRefs.size(); ++i)
  1963. CFRelease (bundleRefs.getUnchecked (i));
  1964. bundleRefs.clear();
  1965. }
  1966. return true;
  1967. }
  1968. return false;
  1969. }
  1970. #endif
  1971. //==============================================================================
  1972. /** This typedef represents VST3's createInstance() function signature */
  1973. typedef FUnknown* (*CreateFunction) (Vst::IHostApplication*);
  1974. static FUnknown* createComponentInstance (Vst::IHostApplication* host)
  1975. {
  1976. return static_cast<Vst::IAudioProcessor*> (new JuceVST3Component (host));
  1977. }
  1978. static FUnknown* createControllerInstance (Vst::IHostApplication* host)
  1979. {
  1980. return static_cast<Vst::IEditController*> (new JuceVST3EditController (host));
  1981. }
  1982. //==============================================================================
  1983. struct JucePluginFactory;
  1984. static JucePluginFactory* globalFactory = nullptr;
  1985. //==============================================================================
  1986. struct JucePluginFactory : public IPluginFactory3
  1987. {
  1988. JucePluginFactory()
  1989. : factoryInfo (JucePlugin_Manufacturer, JucePlugin_ManufacturerWebsite,
  1990. JucePlugin_ManufacturerEmail, Vst::kDefaultFactoryFlags)
  1991. {
  1992. }
  1993. virtual ~JucePluginFactory()
  1994. {
  1995. if (globalFactory == this)
  1996. globalFactory = nullptr;
  1997. }
  1998. //==============================================================================
  1999. bool registerClass (const PClassInfo2& info, CreateFunction createFunction)
  2000. {
  2001. if (createFunction == nullptr)
  2002. {
  2003. jassertfalse;
  2004. return false;
  2005. }
  2006. auto* entry = classes.add (new ClassEntry (info, createFunction));
  2007. entry->infoW.fromAscii (info);
  2008. return true;
  2009. }
  2010. bool isClassRegistered (const FUID& cid) const
  2011. {
  2012. for (int i = 0; i < classes.size(); ++i)
  2013. if (classes.getUnchecked (i)->infoW.cid == cid)
  2014. return true;
  2015. return false;
  2016. }
  2017. //==============================================================================
  2018. JUCE_DECLARE_VST3_COM_REF_METHODS
  2019. tresult PLUGIN_API queryInterface (const TUID targetIID, void** obj) override
  2020. {
  2021. TEST_FOR_AND_RETURN_IF_VALID (targetIID, IPluginFactory3)
  2022. TEST_FOR_AND_RETURN_IF_VALID (targetIID, IPluginFactory2)
  2023. TEST_FOR_AND_RETURN_IF_VALID (targetIID, IPluginFactory)
  2024. TEST_FOR_AND_RETURN_IF_VALID (targetIID, FUnknown)
  2025. jassertfalse; // Something new?
  2026. *obj = nullptr;
  2027. return kNotImplemented;
  2028. }
  2029. //==============================================================================
  2030. Steinberg::int32 PLUGIN_API countClasses() override
  2031. {
  2032. return (Steinberg::int32) classes.size();
  2033. }
  2034. tresult PLUGIN_API getFactoryInfo (PFactoryInfo* info) override
  2035. {
  2036. if (info == nullptr)
  2037. return kInvalidArgument;
  2038. memcpy (info, &factoryInfo, sizeof (PFactoryInfo));
  2039. return kResultOk;
  2040. }
  2041. tresult PLUGIN_API getClassInfo (Steinberg::int32 index, PClassInfo* info) override
  2042. {
  2043. return getPClassInfo<PClassInfo> (index, info);
  2044. }
  2045. tresult PLUGIN_API getClassInfo2 (Steinberg::int32 index, PClassInfo2* info) override
  2046. {
  2047. return getPClassInfo<PClassInfo2> (index, info);
  2048. }
  2049. tresult PLUGIN_API getClassInfoUnicode (Steinberg::int32 index, PClassInfoW* info) override
  2050. {
  2051. if (info != nullptr)
  2052. {
  2053. if (auto* entry = classes[(int) index])
  2054. {
  2055. memcpy (info, &entry->infoW, sizeof (PClassInfoW));
  2056. return kResultOk;
  2057. }
  2058. }
  2059. return kInvalidArgument;
  2060. }
  2061. tresult PLUGIN_API createInstance (FIDString cid, FIDString sourceIid, void** obj) override
  2062. {
  2063. *obj = nullptr;
  2064. FUID sourceFuid = sourceIid;
  2065. if (cid == nullptr || sourceIid == nullptr || ! sourceFuid.isValid())
  2066. {
  2067. jassertfalse; // The host you're running in has severe implementation issues!
  2068. return kInvalidArgument;
  2069. }
  2070. TUID iidToQuery;
  2071. sourceFuid.toTUID (iidToQuery);
  2072. for (auto* entry : classes)
  2073. {
  2074. if (doUIDsMatch (entry->infoW.cid, cid))
  2075. {
  2076. if (auto* instance = entry->createFunction (host))
  2077. {
  2078. const FReleaser releaser (instance);
  2079. if (instance->queryInterface (iidToQuery, obj) == kResultOk)
  2080. return kResultOk;
  2081. }
  2082. break;
  2083. }
  2084. }
  2085. return kNoInterface;
  2086. }
  2087. tresult PLUGIN_API setHostContext (FUnknown* context) override
  2088. {
  2089. host.loadFrom (context);
  2090. if (host != nullptr)
  2091. {
  2092. Vst::String128 name;
  2093. host->getName (name);
  2094. return kResultTrue;
  2095. }
  2096. return kNotImplemented;
  2097. }
  2098. private:
  2099. //==============================================================================
  2100. ScopedJuceInitialiser_GUI libraryInitialiser;
  2101. Atomic<int> refCount { 1 };
  2102. const PFactoryInfo factoryInfo;
  2103. ComSmartPtr<Vst::IHostApplication> host;
  2104. //==============================================================================
  2105. struct ClassEntry
  2106. {
  2107. ClassEntry() noexcept {}
  2108. ClassEntry (const PClassInfo2& info, CreateFunction fn) noexcept
  2109. : info2 (info), createFunction (fn) {}
  2110. PClassInfo2 info2;
  2111. PClassInfoW infoW;
  2112. CreateFunction createFunction = {};
  2113. bool isUnicode = false;
  2114. private:
  2115. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ClassEntry)
  2116. };
  2117. OwnedArray<ClassEntry> classes;
  2118. //==============================================================================
  2119. template<class PClassInfoType>
  2120. tresult PLUGIN_API getPClassInfo (Steinberg::int32 index, PClassInfoType* info)
  2121. {
  2122. if (info != nullptr)
  2123. {
  2124. zerostruct (*info);
  2125. if (auto* entry = classes[(int) index])
  2126. {
  2127. if (entry->isUnicode)
  2128. return kResultFalse;
  2129. memcpy (info, &entry->info2, sizeof (PClassInfoType));
  2130. return kResultOk;
  2131. }
  2132. }
  2133. jassertfalse;
  2134. return kInvalidArgument;
  2135. }
  2136. //==============================================================================
  2137. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (JucePluginFactory)
  2138. };
  2139. } // juce namespace
  2140. //==============================================================================
  2141. #ifndef JucePlugin_Vst3ComponentFlags
  2142. #if JucePlugin_IsSynth
  2143. #define JucePlugin_Vst3ComponentFlags Vst::kSimpleModeSupported
  2144. #else
  2145. #define JucePlugin_Vst3ComponentFlags 0
  2146. #endif
  2147. #endif
  2148. #ifndef JucePlugin_Vst3Category
  2149. #if JucePlugin_IsSynth
  2150. #define JucePlugin_Vst3Category Vst::PlugType::kInstrumentSynth
  2151. #else
  2152. #define JucePlugin_Vst3Category Vst::PlugType::kFx
  2153. #endif
  2154. #endif
  2155. //==============================================================================
  2156. // The VST3 plugin entry point.
  2157. JUCE_EXPORTED_FUNCTION IPluginFactory* PLUGIN_API GetPluginFactory()
  2158. {
  2159. PluginHostType::jucePlugInClientCurrentWrapperType = AudioProcessor::wrapperType_VST3;
  2160. #if JUCE_WINDOWS
  2161. // Cunning trick to force this function to be exported. Life's too short to
  2162. // faff around creating .def files for this kind of thing.
  2163. #pragma comment(linker, "/EXPORT:" __FUNCTION__ "=" __FUNCDNAME__)
  2164. #endif
  2165. if (globalFactory == nullptr)
  2166. {
  2167. globalFactory = new JucePluginFactory();
  2168. static const PClassInfo2 componentClass (JuceVST3Component::iid,
  2169. PClassInfo::kManyInstances,
  2170. kVstAudioEffectClass,
  2171. JucePlugin_Name,
  2172. JucePlugin_Vst3ComponentFlags,
  2173. JucePlugin_Vst3Category,
  2174. JucePlugin_Manufacturer,
  2175. JucePlugin_VersionString,
  2176. kVstVersionString);
  2177. globalFactory->registerClass (componentClass, createComponentInstance);
  2178. static const PClassInfo2 controllerClass (JuceVST3EditController::iid,
  2179. PClassInfo::kManyInstances,
  2180. kVstComponentControllerClass,
  2181. JucePlugin_Name,
  2182. JucePlugin_Vst3ComponentFlags,
  2183. JucePlugin_Vst3Category,
  2184. JucePlugin_Manufacturer,
  2185. JucePlugin_VersionString,
  2186. kVstVersionString);
  2187. globalFactory->registerClass (controllerClass, createControllerInstance);
  2188. }
  2189. else
  2190. {
  2191. globalFactory->addRef();
  2192. }
  2193. return dynamic_cast<IPluginFactory*> (globalFactory);
  2194. }
  2195. //==============================================================================
  2196. #if _MSC_VER || JUCE_MINGW
  2197. extern "C" BOOL WINAPI DllMain (HINSTANCE instance, DWORD reason, LPVOID) { if (reason == DLL_PROCESS_ATTACH) Process::setCurrentModuleInstanceHandle (instance); return true; }
  2198. #endif
  2199. #endif //JucePlugin_Build_VST3