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.

2817 lines
103KB

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