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.

2762 lines
101KB

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