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.

2768 lines
101KB

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