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.

2702 lines
99KB

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