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.

2780 lines
102KB

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