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.

2781 lines
102KB

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