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.

2706 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 (JUCE_MAC || JUCE_IOS)
  691. ignoreUnused (factor);
  692. #else
  693. if (auto* editor = component->pluginEditor.get())
  694. {
  695. editor->setScaleFactor (factor);
  696. return kResultTrue;
  697. }
  698. #endif
  699. return kResultFalse;
  700. }
  701. private:
  702. void timerCallback() override
  703. {
  704. stopTimer();
  705. ViewRect viewRect;
  706. getSize (&viewRect);
  707. onSize (&viewRect);
  708. }
  709. //==============================================================================
  710. struct ContentWrapperComponent : public Component
  711. {
  712. ContentWrapperComponent (JuceVST3Editor& editor, AudioProcessor& plugin)
  713. : pluginEditor (plugin.createEditorIfNeeded()),
  714. owner (editor)
  715. {
  716. setOpaque (true);
  717. setBroughtToFrontOnMouseClick (true);
  718. // if hasEditor() returns true then createEditorIfNeeded has to return a valid editor
  719. jassert (pluginEditor != nullptr);
  720. if (pluginEditor != nullptr)
  721. {
  722. addAndMakeVisible (pluginEditor);
  723. pluginEditor->setTopLeftPosition (0, 0);
  724. lastBounds = getSizeToContainChild();
  725. isResizingParentToFitChild = true;
  726. setBounds (lastBounds);
  727. isResizingParentToFitChild = false;
  728. resizeHostWindow();
  729. }
  730. ignoreUnused (fakeMouseGenerator);
  731. }
  732. ~ContentWrapperComponent()
  733. {
  734. if (pluginEditor != nullptr)
  735. {
  736. PopupMenu::dismissAllActiveMenus();
  737. pluginEditor->processor.editorBeingDeleted (pluginEditor);
  738. }
  739. }
  740. void paint (Graphics& g) override
  741. {
  742. g.fillAll (Colours::black);
  743. }
  744. juce::Rectangle<int> getSizeToContainChild()
  745. {
  746. if (pluginEditor != nullptr)
  747. return getLocalArea (pluginEditor, pluginEditor->getLocalBounds());
  748. return {};
  749. }
  750. void childBoundsChanged (Component*) override
  751. {
  752. if (isResizingChildToFitParent)
  753. return;
  754. auto b = getSizeToContainChild();
  755. if (lastBounds != b)
  756. {
  757. lastBounds = b;
  758. isResizingParentToFitChild = true;
  759. resizeHostWindow();
  760. isResizingParentToFitChild = false;
  761. }
  762. }
  763. void resized() override
  764. {
  765. if (pluginEditor != nullptr)
  766. {
  767. if (! isResizingParentToFitChild)
  768. {
  769. lastBounds = getLocalBounds();
  770. isResizingChildToFitParent = true;
  771. pluginEditor->setTopLeftPosition (0, 0);
  772. pluginEditor->setBounds (pluginEditor->getLocalArea (this, getLocalBounds()));
  773. isResizingChildToFitParent = false;
  774. }
  775. }
  776. }
  777. void resizeHostWindow()
  778. {
  779. if (pluginEditor != nullptr)
  780. {
  781. auto b = getSizeToContainChild();
  782. auto w = b.getWidth();
  783. auto h = b.getHeight();
  784. auto host = getHostType();
  785. #if JUCE_WINDOWS
  786. setSize (w, h);
  787. #else
  788. if (owner.macHostWindow != nullptr && ! (host.isWavelab() || host.isReaper()))
  789. juce::setNativeHostWindowSizeVST (owner.macHostWindow, this, w, h, owner.isNSView);
  790. #endif
  791. if (owner.plugFrame != nullptr)
  792. {
  793. ViewRect newSize (0, 0, w, h);
  794. isResizingParentToFitChild = true;
  795. owner.plugFrame->resizeView (&owner, &newSize);
  796. isResizingParentToFitChild = false;
  797. #if JUCE_MAC
  798. if (host.isWavelab() || host.isReaper())
  799. #else
  800. if (host.isWavelab())
  801. #endif
  802. setBounds (0, 0, w, h);
  803. }
  804. }
  805. }
  806. ScopedPointer<AudioProcessorEditor> pluginEditor;
  807. private:
  808. JuceVST3Editor& owner;
  809. FakeMouseMoveGenerator fakeMouseGenerator;
  810. Rectangle<int> lastBounds;
  811. bool isResizingChildToFitParent = false;
  812. bool isResizingParentToFitChild = false;
  813. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ContentWrapperComponent)
  814. };
  815. //==============================================================================
  816. ComSmartPtr<JuceVST3EditController> owner;
  817. AudioProcessor& pluginInstance;
  818. ScopedPointer<ContentWrapperComponent> component;
  819. friend struct ContentWrapperComponent;
  820. #if JUCE_MAC
  821. void* macHostWindow = nullptr;
  822. bool isNSView = false;
  823. #endif
  824. #if JUCE_WINDOWS
  825. WindowsHooks hooks;
  826. #endif
  827. ScopedJuceInitialiser_GUI libraryInitialiser;
  828. //==============================================================================
  829. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (JuceVST3Editor)
  830. };
  831. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (JuceVST3EditController)
  832. };
  833. namespace
  834. {
  835. template <typename FloatType> struct AudioBusPointerHelper {};
  836. template <> struct AudioBusPointerHelper<float> { static inline float** impl (Vst::AudioBusBuffers& data) noexcept { return data.channelBuffers32; } };
  837. template <> struct AudioBusPointerHelper<double> { static inline double** impl (Vst::AudioBusBuffers& data) noexcept { return data.channelBuffers64; } };
  838. template <typename FloatType> struct ChooseBufferHelper {};
  839. template <> struct ChooseBufferHelper<float> { static inline AudioBuffer<float>& impl (AudioBuffer<float>& f, AudioBuffer<double>& ) noexcept { return f; } };
  840. template <> struct ChooseBufferHelper<double> { static inline AudioBuffer<double>& impl (AudioBuffer<float>& , AudioBuffer<double>& d) noexcept { return d; } };
  841. }
  842. //==============================================================================
  843. class JuceVST3Component : public Vst::IComponent,
  844. public Vst::IAudioProcessor,
  845. public Vst::IUnitInfo,
  846. public Vst::IConnectionPoint,
  847. public AudioPlayHead
  848. {
  849. public:
  850. JuceVST3Component (Vst::IHostApplication* h)
  851. : pluginInstance (createPluginFilterOfType (AudioProcessor::wrapperType_VST3)),
  852. host (h)
  853. {
  854. #ifdef JucePlugin_PreferredChannelConfigurations
  855. short configs[][2] = { JucePlugin_PreferredChannelConfigurations };
  856. const int numConfigs = sizeof (configs) / sizeof (short[2]);
  857. jassert (numConfigs > 0 && (configs[0][0] > 0 || configs[0][1] > 0));
  858. pluginInstance->setPlayConfigDetails (configs[0][0], configs[0][1], 44100.0, 1024);
  859. #endif
  860. // VST-3 requires your default layout to be non-discrete!
  861. // For example, your default layout must be mono, stereo, quadrophonic
  862. // and not AudioChannelSet::discreteChannels (2) etc.
  863. jassert (checkBusFormatsAreNotDiscrete());
  864. comPluginInstance = new JuceAudioProcessor (pluginInstance);
  865. zerostruct (processContext);
  866. processSetup.maxSamplesPerBlock = 1024;
  867. processSetup.processMode = Vst::kRealtime;
  868. processSetup.sampleRate = 44100.0;
  869. processSetup.symbolicSampleSize = Vst::kSample32;
  870. #if JUCE_FORCE_USE_LEGACY_PARAM_IDS
  871. vstBypassParameterId = static_cast<Vst::ParamID> (pluginInstance->getNumParameters());
  872. #else
  873. cacheParameterIDs();
  874. #endif
  875. pluginInstance->setPlayHead (this);
  876. }
  877. ~JuceVST3Component()
  878. {
  879. if (pluginInstance != nullptr)
  880. if (pluginInstance->getPlayHead() == this)
  881. pluginInstance->setPlayHead (nullptr);
  882. }
  883. //==============================================================================
  884. AudioProcessor& getPluginInstance() const noexcept { return *pluginInstance; }
  885. //==============================================================================
  886. static const FUID iid;
  887. JUCE_DECLARE_VST3_COM_REF_METHODS
  888. tresult PLUGIN_API queryInterface (const TUID targetIID, void** obj) override
  889. {
  890. TEST_FOR_AND_RETURN_IF_VALID (targetIID, IPluginBase)
  891. TEST_FOR_AND_RETURN_IF_VALID (targetIID, JuceVST3Component)
  892. TEST_FOR_AND_RETURN_IF_VALID (targetIID, Vst::IComponent)
  893. TEST_FOR_AND_RETURN_IF_VALID (targetIID, Vst::IAudioProcessor)
  894. TEST_FOR_AND_RETURN_IF_VALID (targetIID, Vst::IUnitInfo)
  895. TEST_FOR_AND_RETURN_IF_VALID (targetIID, Vst::IConnectionPoint)
  896. TEST_FOR_COMMON_BASE_AND_RETURN_IF_VALID (targetIID, FUnknown, Vst::IComponent)
  897. if (doUIDsMatch (targetIID, JuceAudioProcessor::iid))
  898. {
  899. comPluginInstance->addRef();
  900. *obj = comPluginInstance;
  901. return kResultOk;
  902. }
  903. *obj = nullptr;
  904. return kNoInterface;
  905. }
  906. //==============================================================================
  907. tresult PLUGIN_API initialize (FUnknown* hostContext) override
  908. {
  909. if (host != hostContext)
  910. host.loadFrom (hostContext);
  911. processContext.sampleRate = processSetup.sampleRate;
  912. preparePlugin (processSetup.sampleRate, (int) processSetup.maxSamplesPerBlock);
  913. return kResultTrue;
  914. }
  915. tresult PLUGIN_API terminate() override
  916. {
  917. getPluginInstance().releaseResources();
  918. return kResultTrue;
  919. }
  920. //==============================================================================
  921. tresult PLUGIN_API connect (IConnectionPoint* other) override
  922. {
  923. if (other != nullptr && juceVST3EditController == nullptr)
  924. juceVST3EditController.loadFrom (other);
  925. return kResultTrue;
  926. }
  927. tresult PLUGIN_API disconnect (IConnectionPoint*) override
  928. {
  929. juceVST3EditController = nullptr;
  930. return kResultTrue;
  931. }
  932. tresult PLUGIN_API notify (Vst::IMessage* message) override
  933. {
  934. if (message != nullptr && juceVST3EditController == nullptr)
  935. {
  936. Steinberg::int64 value = 0;
  937. if (message->getAttributes()->getInt ("JuceVST3EditController", value) == kResultTrue)
  938. {
  939. juceVST3EditController = (JuceVST3EditController*) (pointer_sized_int) value;
  940. if (juceVST3EditController != nullptr)
  941. juceVST3EditController->setAudioProcessor (comPluginInstance);
  942. else
  943. jassertfalse;
  944. }
  945. }
  946. return kResultTrue;
  947. }
  948. tresult PLUGIN_API getControllerClassId (TUID classID) override
  949. {
  950. memcpy (classID, JuceVST3EditController::iid, sizeof (TUID));
  951. return kResultTrue;
  952. }
  953. //==============================================================================
  954. tresult PLUGIN_API setActive (TBool state) override
  955. {
  956. if (! state)
  957. {
  958. getPluginInstance().releaseResources();
  959. deallocateChannelListAndBuffers (channelListFloat, emptyBufferFloat);
  960. deallocateChannelListAndBuffers (channelListDouble, emptyBufferDouble);
  961. }
  962. else
  963. {
  964. auto sampleRate = getPluginInstance().getSampleRate();
  965. auto bufferSize = getPluginInstance().getBlockSize();
  966. sampleRate = processSetup.sampleRate > 0.0
  967. ? processSetup.sampleRate
  968. : sampleRate;
  969. bufferSize = processSetup.maxSamplesPerBlock > 0
  970. ? (int) processSetup.maxSamplesPerBlock
  971. : bufferSize;
  972. allocateChannelListAndBuffers (channelListFloat, emptyBufferFloat);
  973. allocateChannelListAndBuffers (channelListDouble, emptyBufferDouble);
  974. preparePlugin (sampleRate, bufferSize);
  975. }
  976. return kResultOk;
  977. }
  978. tresult PLUGIN_API setIoMode (Vst::IoMode) override { return kNotImplemented; }
  979. tresult PLUGIN_API getRoutingInfo (Vst::RoutingInfo&, Vst::RoutingInfo&) override { return kNotImplemented; }
  980. bool isBypassed() { return comPluginInstance->isBypassed; }
  981. void setBypassed (bool bypassed) { comPluginInstance->isBypassed = bypassed; }
  982. //==============================================================================
  983. void writeJucePrivateStateInformation (MemoryOutputStream& out)
  984. {
  985. ValueTree privateData (kJucePrivateDataIdentifier);
  986. // for now we only store the bypass value
  987. privateData.setProperty ("Bypass", var (isBypassed()), nullptr);
  988. privateData.writeToStream (out);
  989. }
  990. void setJucePrivateStateInformation (const void* data, int sizeInBytes)
  991. {
  992. auto privateData = ValueTree::readFromData (data, static_cast<size_t> (sizeInBytes));
  993. setBypassed (static_cast<bool> (privateData.getProperty ("Bypass", var (false))));
  994. }
  995. void getStateInformation (MemoryBlock& destData)
  996. {
  997. pluginInstance->getStateInformation (destData);
  998. // With bypass support, JUCE now needs to store private state data.
  999. // Put this at the end of the plug-in state and add a few null characters
  1000. // so that plug-ins built with older versions of JUCE will hopefully ignore
  1001. // this data. Additionally, we need to add some sort of magic identifier
  1002. // at the very end of the private data so that JUCE has some sort of
  1003. // way to figure out if the data was stored with a newer JUCE version.
  1004. MemoryOutputStream extraData;
  1005. extraData.writeInt64 (0);
  1006. writeJucePrivateStateInformation (extraData);
  1007. auto privateDataSize = (int64) (extraData.getDataSize() - sizeof (int64));
  1008. extraData.writeInt64 (privateDataSize);
  1009. extraData << kJucePrivateDataIdentifier;
  1010. // write magic string
  1011. destData.append (extraData.getData(), extraData.getDataSize());
  1012. }
  1013. void setStateInformation (const void* data, int sizeAsInt)
  1014. {
  1015. int64 size = sizeAsInt;
  1016. // Check if this data was written with a newer JUCE version
  1017. // and if it has the JUCE private data magic code at the end
  1018. auto jucePrivDataIdentifierSize = std::strlen (kJucePrivateDataIdentifier);
  1019. if ((size_t) size >= jucePrivDataIdentifierSize + sizeof (int64))
  1020. {
  1021. auto buffer = static_cast<const char*> (data);
  1022. String magic (CharPointer_UTF8 (buffer + size - jucePrivDataIdentifierSize),
  1023. CharPointer_UTF8 (buffer + size));
  1024. if (magic == kJucePrivateDataIdentifier)
  1025. {
  1026. // found a JUCE private data section
  1027. uint64 privateDataSize;
  1028. std::memcpy (&privateDataSize,
  1029. buffer + ((size_t) size - jucePrivDataIdentifierSize - sizeof (uint64)),
  1030. sizeof (uint64));
  1031. privateDataSize = ByteOrder::swapIfBigEndian (privateDataSize);
  1032. size -= privateDataSize + jucePrivDataIdentifierSize + sizeof (uint64);
  1033. if (privateDataSize > 0)
  1034. setJucePrivateStateInformation (buffer + size, static_cast<int> (privateDataSize));
  1035. size -= sizeof (uint64);
  1036. }
  1037. }
  1038. if (size >= 0)
  1039. pluginInstance->setStateInformation (data, static_cast<int> (size));
  1040. }
  1041. //==============================================================================
  1042. #if JUCE_VST3_CAN_REPLACE_VST2
  1043. void loadVST2VstWBlock (const char* data, int size)
  1044. {
  1045. auto headerLen = static_cast<int> (htonl (*(juce::int32*) (data + 4)));
  1046. auto bank = (const vst2FxBank*) (data + (8 + headerLen));
  1047. auto version = static_cast<int> (htonl (bank->version1)); ignoreUnused (version);
  1048. jassert ('VstW' == htonl (*(juce::int32*) data));
  1049. jassert (1 == htonl (*(juce::int32*) (data + 8))); // version should be 1 according to Steinberg's docs
  1050. jassert ('CcnK' == htonl (bank->magic1));
  1051. jassert ('FBCh' == htonl (bank->magic2));
  1052. jassert (version == 1 || version == 2);
  1053. jassert (JucePlugin_VSTUniqueID == htonl (bank->fxID));
  1054. setStateInformation (bank->chunk,
  1055. jmin ((int) (size - (bank->chunk - data)),
  1056. (int) htonl (bank->chunkSize)));
  1057. }
  1058. bool loadVST3PresetFile (const char* data, int size)
  1059. {
  1060. if (size < 48)
  1061. return false;
  1062. // At offset 4 there's a little-endian version number which seems to typically be 1
  1063. // At offset 8 there's 32 bytes the SDK calls "ASCII-encoded class id"
  1064. auto chunkListOffset = (int) ByteOrder::littleEndianInt (data + 40);
  1065. jassert (memcmp (data + chunkListOffset, "List", 4) == 0);
  1066. auto entryCount = (int) ByteOrder::littleEndianInt (data + chunkListOffset + 4);
  1067. jassert (entryCount > 0);
  1068. for (int i = 0; i < entryCount; ++i)
  1069. {
  1070. auto entryOffset = chunkListOffset + 8 + 20 * i;
  1071. if (entryOffset + 20 > size)
  1072. return false;
  1073. if (memcmp (data + entryOffset, "Comp", 4) == 0)
  1074. {
  1075. // "Comp" entries seem to contain the data.
  1076. auto chunkOffset = ByteOrder::littleEndianInt64 (data + entryOffset + 4);
  1077. auto chunkSize = ByteOrder::littleEndianInt64 (data + entryOffset + 12);
  1078. if (chunkOffset + chunkSize > static_cast<juce::uint64> (size))
  1079. {
  1080. jassertfalse;
  1081. return false;
  1082. }
  1083. loadVST2VstWBlock (data + chunkOffset, (int) chunkSize);
  1084. }
  1085. }
  1086. return true;
  1087. }
  1088. bool loadVST2CompatibleState (const char* data, int size)
  1089. {
  1090. if (size < 4)
  1091. return false;
  1092. if (htonl (*(juce::int32*) data) == 'VstW')
  1093. {
  1094. loadVST2VstWBlock (data, size);
  1095. return true;
  1096. }
  1097. if (memcmp (data, "VST3", 4) == 0)
  1098. {
  1099. // In Cubase 5, when loading VST3 .vstpreset files,
  1100. // we get the whole content of the files to load.
  1101. // In Cubase 7 we get just the contents within and
  1102. // we go directly to the loadVST2VstW codepath instead.
  1103. return loadVST3PresetFile (data, size);
  1104. }
  1105. return false;
  1106. }
  1107. #endif
  1108. bool loadStateData (const void* data, int size)
  1109. {
  1110. #if JUCE_VST3_CAN_REPLACE_VST2
  1111. return loadVST2CompatibleState ((const char*) data, size);
  1112. #else
  1113. setStateInformation (data, size);
  1114. return true;
  1115. #endif
  1116. }
  1117. bool readFromMemoryStream (IBStream* state)
  1118. {
  1119. FUnknownPtr<ISizeableStream> s (state);
  1120. Steinberg::int64 size = 0;
  1121. if (s != nullptr
  1122. && s->getStreamSize (size) == kResultOk
  1123. && size > 0
  1124. && size < 1024 * 1024 * 100) // (some hosts seem to return junk for the size)
  1125. {
  1126. MemoryBlock block (static_cast<size_t> (size));
  1127. // turns out that Cubase 9 might give you the incorrect stream size :-(
  1128. Steinberg::int32 bytesRead = 1;
  1129. int len;
  1130. for (len = 0; bytesRead > 0 && len < static_cast<int> (block.getSize()); len += bytesRead)
  1131. if (state->read (block.getData(), static_cast<int32> (block.getSize()), &bytesRead) != kResultOk)
  1132. break;
  1133. if (len == 0)
  1134. return false;
  1135. block.setSize (static_cast<size_t> (len));
  1136. // Adobe Audition CS6 hack to avoid trying to use corrupted streams:
  1137. if (getHostType().isAdobeAudition())
  1138. if (block.getSize() >= 5 && memcmp (block.getData(), "VC2!E", 5) == 0)
  1139. return false;
  1140. return loadStateData (block.getData(), (int) block.getSize());
  1141. }
  1142. return false;
  1143. }
  1144. bool readFromUnknownStream (IBStream* state)
  1145. {
  1146. MemoryOutputStream allData;
  1147. {
  1148. const size_t bytesPerBlock = 4096;
  1149. HeapBlock<char> buffer (bytesPerBlock);
  1150. for (;;)
  1151. {
  1152. Steinberg::int32 bytesRead = 0;
  1153. auto status = state->read (buffer, (Steinberg::int32) bytesPerBlock, &bytesRead);
  1154. if (bytesRead <= 0 || (status != kResultTrue && ! getHostType().isWavelab()))
  1155. break;
  1156. allData.write (buffer, static_cast<size_t> (bytesRead));
  1157. }
  1158. }
  1159. const size_t dataSize = allData.getDataSize();
  1160. return dataSize > 0 && dataSize < 0x7fffffff
  1161. && loadStateData (allData.getData(), (int) dataSize);
  1162. }
  1163. tresult PLUGIN_API setState (IBStream* state) override
  1164. {
  1165. if (state == nullptr)
  1166. return kInvalidArgument;
  1167. FUnknownPtr<IBStream> stateRefHolder (state); // just in case the caller hasn't properly ref-counted the stream object
  1168. if (state->seek (0, IBStream::kIBSeekSet, nullptr) == kResultTrue)
  1169. {
  1170. if (! getHostType().isFruityLoops() && readFromMemoryStream (state))
  1171. return kResultTrue;
  1172. if (readFromUnknownStream (state))
  1173. return kResultTrue;
  1174. }
  1175. return kResultFalse;
  1176. }
  1177. #if JUCE_VST3_CAN_REPLACE_VST2
  1178. static tresult writeVST2Int (IBStream* state, int n)
  1179. {
  1180. juce::int32 t = (juce::int32) htonl (n);
  1181. return state->write (&t, 4);
  1182. }
  1183. static tresult writeVST2Header (IBStream* state, bool bypassed)
  1184. {
  1185. tresult status = writeVST2Int (state, 'VstW');
  1186. if (status == kResultOk) status = writeVST2Int (state, 8); // header size
  1187. if (status == kResultOk) status = writeVST2Int (state, 1); // version
  1188. if (status == kResultOk) status = writeVST2Int (state, bypassed ? 1 : 0); // bypass
  1189. return status;
  1190. }
  1191. #endif
  1192. tresult PLUGIN_API getState (IBStream* state) override
  1193. {
  1194. if (state == nullptr)
  1195. return kInvalidArgument;
  1196. juce::MemoryBlock mem;
  1197. getStateInformation (mem);
  1198. #if JUCE_VST3_CAN_REPLACE_VST2
  1199. tresult status = writeVST2Header (state, isBypassed());
  1200. if (status != kResultOk)
  1201. return status;
  1202. const int bankBlockSize = 160;
  1203. vst2FxBank bank;
  1204. zerostruct (bank);
  1205. bank.magic1 = (int32) htonl ('CcnK');
  1206. bank.size = (int32) htonl (bankBlockSize - 8 + (unsigned int) mem.getSize());
  1207. bank.magic2 = (int32) htonl ('FBCh');
  1208. bank.version1 = (int32) htonl (2);
  1209. bank.fxID = (int32) htonl (JucePlugin_VSTUniqueID);
  1210. bank.version2 = (int32) htonl (JucePlugin_VersionCode);
  1211. bank.chunkSize = (int32) htonl ((unsigned int) mem.getSize());
  1212. status = state->write (&bank, bankBlockSize);
  1213. if (status != kResultOk)
  1214. return status;
  1215. #endif
  1216. return state->write (mem.getData(), (Steinberg::int32) mem.getSize());
  1217. }
  1218. //==============================================================================
  1219. Steinberg::int32 PLUGIN_API getUnitCount() override
  1220. {
  1221. return 1;
  1222. }
  1223. tresult PLUGIN_API getUnitInfo (Steinberg::int32 unitIndex, Vst::UnitInfo& info) override
  1224. {
  1225. if (unitIndex == 0)
  1226. {
  1227. info.id = Vst::kRootUnitId;
  1228. info.parentUnitId = Vst::kNoParentUnitId;
  1229. info.programListId = Vst::kNoProgramListId;
  1230. toString128 (info.name, TRANS("Root Unit"));
  1231. return kResultTrue;
  1232. }
  1233. zerostruct (info);
  1234. return kResultFalse;
  1235. }
  1236. Steinberg::int32 PLUGIN_API getProgramListCount() override
  1237. {
  1238. if (getPluginInstance().getNumPrograms() > 0)
  1239. return 1;
  1240. return 0;
  1241. }
  1242. tresult PLUGIN_API getProgramListInfo (Steinberg::int32 listIndex, Vst::ProgramListInfo& info) override
  1243. {
  1244. if (listIndex == 0)
  1245. {
  1246. info.id = JuceVST3EditController::paramPreset;
  1247. info.programCount = (Steinberg::int32) getPluginInstance().getNumPrograms();
  1248. toString128 (info.name, TRANS("Factory Presets"));
  1249. return kResultTrue;
  1250. }
  1251. jassertfalse;
  1252. zerostruct (info);
  1253. return kResultFalse;
  1254. }
  1255. tresult PLUGIN_API getProgramName (Vst::ProgramListID listId, Steinberg::int32 programIndex, Vst::String128 name) override
  1256. {
  1257. if (listId == JuceVST3EditController::paramPreset
  1258. && isPositiveAndBelow ((int) programIndex, getPluginInstance().getNumPrograms()))
  1259. {
  1260. toString128 (name, getPluginInstance().getProgramName ((int) programIndex));
  1261. return kResultTrue;
  1262. }
  1263. jassertfalse;
  1264. toString128 (name, juce::String());
  1265. return kResultFalse;
  1266. }
  1267. tresult PLUGIN_API getProgramInfo (Vst::ProgramListID, Steinberg::int32, Vst::CString, Vst::String128) override { return kNotImplemented; }
  1268. tresult PLUGIN_API hasProgramPitchNames (Vst::ProgramListID, Steinberg::int32) override { return kNotImplemented; }
  1269. tresult PLUGIN_API getProgramPitchName (Vst::ProgramListID, Steinberg::int32, Steinberg::int16, Vst::String128) override { return kNotImplemented; }
  1270. tresult PLUGIN_API selectUnit (Vst::UnitID) override { return kNotImplemented; }
  1271. tresult PLUGIN_API setUnitProgramData (Steinberg::int32, Steinberg::int32, IBStream*) override { return kNotImplemented; }
  1272. Vst::UnitID PLUGIN_API getSelectedUnit() override { return Vst::kRootUnitId; }
  1273. tresult PLUGIN_API getUnitByBus (Vst::MediaType, Vst::BusDirection, Steinberg::int32, Steinberg::int32, Vst::UnitID& unitId) override
  1274. {
  1275. zerostruct (unitId);
  1276. return kNotImplemented;
  1277. }
  1278. //==============================================================================
  1279. bool getCurrentPosition (CurrentPositionInfo& info) override
  1280. {
  1281. info.timeInSamples = jmax ((juce::int64) 0, processContext.projectTimeSamples);
  1282. info.timeInSeconds = processContext.systemTime / 1000000000.0;
  1283. info.bpm = jmax (1.0, processContext.tempo);
  1284. info.timeSigNumerator = jmax (1, (int) processContext.timeSigNumerator);
  1285. info.timeSigDenominator = jmax (1, (int) processContext.timeSigDenominator);
  1286. info.ppqPositionOfLastBarStart = processContext.barPositionMusic;
  1287. info.ppqPosition = processContext.projectTimeMusic;
  1288. info.ppqLoopStart = processContext.cycleStartMusic;
  1289. info.ppqLoopEnd = processContext.cycleEndMusic;
  1290. info.isRecording = (processContext.state & Vst::ProcessContext::kRecording) != 0;
  1291. info.isPlaying = (processContext.state & Vst::ProcessContext::kPlaying) != 0;
  1292. info.isLooping = (processContext.state & Vst::ProcessContext::kCycleActive) != 0;
  1293. info.editOriginTime = 0.0;
  1294. info.frameRate = AudioPlayHead::fpsUnknown;
  1295. if ((processContext.state & Vst::ProcessContext::kSmpteValid) != 0)
  1296. {
  1297. switch (processContext.frameRate.framesPerSecond)
  1298. {
  1299. case 24: info.frameRate = AudioPlayHead::fps24; break;
  1300. case 25: info.frameRate = AudioPlayHead::fps25; break;
  1301. case 29: info.frameRate = AudioPlayHead::fps30drop; break;
  1302. case 30:
  1303. {
  1304. if ((processContext.frameRate.flags & Vst::FrameRate::kDropRate) != 0)
  1305. info.frameRate = AudioPlayHead::fps30drop;
  1306. else
  1307. info.frameRate = AudioPlayHead::fps30;
  1308. }
  1309. break;
  1310. default: break;
  1311. }
  1312. }
  1313. return true;
  1314. }
  1315. //==============================================================================
  1316. int getNumAudioBuses (bool isInput) const
  1317. {
  1318. int busCount = pluginInstance->getBusCount (isInput);
  1319. #ifdef JucePlugin_PreferredChannelConfigurations
  1320. short configs[][2] = {JucePlugin_PreferredChannelConfigurations};
  1321. const int numConfigs = sizeof (configs) / sizeof (short[2]);
  1322. bool hasOnlyZeroChannels = true;
  1323. for (int i = 0; i < numConfigs && hasOnlyZeroChannels == true; ++i)
  1324. if (configs[i][isInput ? 0 : 1] != 0)
  1325. hasOnlyZeroChannels = false;
  1326. busCount = jmin (busCount, hasOnlyZeroChannels ? 0 : 1);
  1327. #endif
  1328. return busCount;
  1329. }
  1330. //==============================================================================
  1331. Steinberg::int32 PLUGIN_API getBusCount (Vst::MediaType type, Vst::BusDirection dir) override
  1332. {
  1333. if (type == Vst::kAudio)
  1334. return getNumAudioBuses (dir == Vst::kInput);
  1335. if (type == Vst::kEvent)
  1336. {
  1337. if (dir == Vst::kInput)
  1338. return isMidiInputBusEnabled ? 1 : 0;
  1339. if (dir == Vst::kOutput)
  1340. return isMidiOutputBusEnabled ? 1 : 0;
  1341. }
  1342. return 0;
  1343. }
  1344. tresult PLUGIN_API getBusInfo (Vst::MediaType type, Vst::BusDirection dir,
  1345. Steinberg::int32 index, Vst::BusInfo& info) override
  1346. {
  1347. if (type == Vst::kAudio)
  1348. {
  1349. if (index < 0 || index >= getNumAudioBuses (dir == Vst::kInput))
  1350. return kResultFalse;
  1351. if (auto* bus = pluginInstance->getBus (dir == Vst::kInput, index))
  1352. {
  1353. info.mediaType = Vst::kAudio;
  1354. info.direction = dir;
  1355. info.channelCount = bus->getLastEnabledLayout().size();
  1356. toString128 (info.name, bus->getName());
  1357. #if JucePlugin_IsSynth
  1358. info.busType = (dir == Vst::kInput && index > 0 ? Vst::kAux : Vst::kMain);
  1359. #else
  1360. info.busType = (index == 0 ? Vst::kMain : Vst::kAux);
  1361. #endif
  1362. info.flags = (bus->isEnabledByDefault()) ? Vst::BusInfo::kDefaultActive : 0;
  1363. return kResultTrue;
  1364. }
  1365. }
  1366. if (type == Vst::kEvent)
  1367. {
  1368. info.flags = Vst::BusInfo::kDefaultActive;
  1369. #if JucePlugin_WantsMidiInput
  1370. if (dir == Vst::kInput && index == 0)
  1371. {
  1372. info.mediaType = Vst::kEvent;
  1373. info.direction = dir;
  1374. info.channelCount = 16;
  1375. toString128 (info.name, TRANS("MIDI Input"));
  1376. info.busType = Vst::kMain;
  1377. return kResultTrue;
  1378. }
  1379. #endif
  1380. #if JucePlugin_ProducesMidiOutput
  1381. if (dir == Vst::kOutput && index == 0)
  1382. {
  1383. info.mediaType = Vst::kEvent;
  1384. info.direction = dir;
  1385. info.channelCount = 16;
  1386. toString128 (info.name, TRANS("MIDI Output"));
  1387. info.busType = Vst::kMain;
  1388. return kResultTrue;
  1389. }
  1390. #endif
  1391. }
  1392. zerostruct (info);
  1393. return kResultFalse;
  1394. }
  1395. tresult PLUGIN_API activateBus (Vst::MediaType type, Vst::BusDirection dir, Steinberg::int32 index, TBool state) override
  1396. {
  1397. if (type == Vst::kEvent)
  1398. {
  1399. if (index != 0)
  1400. return kResultFalse;
  1401. if (dir == Vst::kInput)
  1402. isMidiInputBusEnabled = (state != 0);
  1403. else
  1404. isMidiOutputBusEnabled = (state != 0);
  1405. return kResultTrue;
  1406. }
  1407. if (type == Vst::kAudio)
  1408. {
  1409. if (index < 0 || index >= getNumAudioBuses (dir == Vst::kInput))
  1410. return kResultFalse;
  1411. if (auto* bus = pluginInstance->getBus (dir == Vst::kInput, index))
  1412. {
  1413. #ifdef JucePlugin_PreferredChannelConfigurations
  1414. auto newLayout = pluginInstance->getBusesLayout();
  1415. auto targetLayout = (state != 0 ? bus->getLastEnabledLayout() : AudioChannelSet::disabled());
  1416. (dir == Vst::kInput ? newLayout.inputBuses : newLayout.outputBuses).getReference (index) = targetLayout;
  1417. short configs[][2] = { JucePlugin_PreferredChannelConfigurations };
  1418. auto compLayout = pluginInstance->getNextBestLayoutInLayoutList (newLayout, configs);
  1419. if ((dir == Vst::kInput ? compLayout.inputBuses : compLayout.outputBuses).getReference (index) != targetLayout)
  1420. return kResultFalse;
  1421. #endif
  1422. return bus->enable (state != 0) ? kResultTrue : kResultFalse;
  1423. }
  1424. }
  1425. return kResultFalse;
  1426. }
  1427. bool checkBusFormatsAreNotDiscrete()
  1428. {
  1429. auto numInputBuses = pluginInstance->getBusCount (true);
  1430. auto numOutputBuses = pluginInstance->getBusCount (false);
  1431. for (int i = 0; i < numInputBuses; ++i)
  1432. if (pluginInstance->getChannelLayoutOfBus (true, i).isDiscreteLayout())
  1433. return false;
  1434. for (int i = 0; i < numOutputBuses; ++i)
  1435. if (pluginInstance->getChannelLayoutOfBus (false, i).isDiscreteLayout())
  1436. return false;
  1437. return true;
  1438. }
  1439. tresult PLUGIN_API setBusArrangements (Vst::SpeakerArrangement* inputs, Steinberg::int32 numIns,
  1440. Vst::SpeakerArrangement* outputs, Steinberg::int32 numOuts) override
  1441. {
  1442. auto numInputBuses = pluginInstance->getBusCount (true);
  1443. auto numOutputBuses = pluginInstance->getBusCount (false);
  1444. if (numIns > numInputBuses || numOuts > numOutputBuses)
  1445. return false;
  1446. auto requested = pluginInstance->getBusesLayout();
  1447. for (int i = 0; i < numIns; ++i)
  1448. requested.getChannelSet (true, i) = getChannelSetForSpeakerArrangement (inputs[i]);
  1449. for (int i = 0; i < numOuts; ++i)
  1450. requested.getChannelSet (false, i) = getChannelSetForSpeakerArrangement (outputs[i]);
  1451. #ifdef JucePlugin_PreferredChannelConfigurations
  1452. short configs[][2] = { JucePlugin_PreferredChannelConfigurations };
  1453. if (! AudioProcessor::containsLayout (requested, configs))
  1454. return kResultFalse;
  1455. #endif
  1456. return pluginInstance->setBusesLayoutWithoutEnabling (requested) ? kResultTrue : kResultFalse;
  1457. }
  1458. tresult PLUGIN_API getBusArrangement (Vst::BusDirection dir, Steinberg::int32 index, Vst::SpeakerArrangement& arr) override
  1459. {
  1460. if (auto* bus = pluginInstance->getBus (dir == Vst::kInput, index))
  1461. {
  1462. arr = getVst3SpeakerArrangement (bus->getLastEnabledLayout());
  1463. return kResultTrue;
  1464. }
  1465. return kResultFalse;
  1466. }
  1467. //==============================================================================
  1468. tresult PLUGIN_API canProcessSampleSize (Steinberg::int32 symbolicSampleSize) override
  1469. {
  1470. return (symbolicSampleSize == Vst::kSample32
  1471. || (getPluginInstance().supportsDoublePrecisionProcessing()
  1472. && symbolicSampleSize == Vst::kSample64)) ? kResultTrue : kResultFalse;
  1473. }
  1474. Steinberg::uint32 PLUGIN_API getLatencySamples() override
  1475. {
  1476. return (Steinberg::uint32) jmax (0, getPluginInstance().getLatencySamples());
  1477. }
  1478. tresult PLUGIN_API setupProcessing (Vst::ProcessSetup& newSetup) override
  1479. {
  1480. if (canProcessSampleSize (newSetup.symbolicSampleSize) != kResultTrue)
  1481. return kResultFalse;
  1482. processSetup = newSetup;
  1483. processContext.sampleRate = processSetup.sampleRate;
  1484. getPluginInstance().setProcessingPrecision (newSetup.symbolicSampleSize == Vst::kSample64
  1485. ? AudioProcessor::doublePrecision
  1486. : AudioProcessor::singlePrecision);
  1487. preparePlugin (processSetup.sampleRate, processSetup.maxSamplesPerBlock);
  1488. return kResultTrue;
  1489. }
  1490. tresult PLUGIN_API setProcessing (TBool state) override
  1491. {
  1492. if (! state)
  1493. getPluginInstance().reset();
  1494. return kResultTrue;
  1495. }
  1496. Steinberg::uint32 PLUGIN_API getTailSamples() override
  1497. {
  1498. auto tailLengthSeconds = getPluginInstance().getTailLengthSeconds();
  1499. if (tailLengthSeconds <= 0.0 || processSetup.sampleRate > 0.0)
  1500. return Vst::kNoTail;
  1501. return (Steinberg::uint32) roundToIntAccurate (tailLengthSeconds * processSetup.sampleRate);
  1502. }
  1503. //==============================================================================
  1504. void processParameterChanges (Vst::IParameterChanges& paramChanges)
  1505. {
  1506. jassert (pluginInstance != nullptr);
  1507. auto numParamsChanged = paramChanges.getParameterCount();
  1508. for (Steinberg::int32 i = 0; i < numParamsChanged; ++i)
  1509. {
  1510. if (auto* paramQueue = paramChanges.getParameterData (i))
  1511. {
  1512. auto numPoints = paramQueue->getPointCount();
  1513. Steinberg::int32 offsetSamples = 0;
  1514. double value = 0.0;
  1515. if (paramQueue->getPoint (numPoints - 1, offsetSamples, value) == kResultTrue)
  1516. {
  1517. auto vstParamID = paramQueue->getParameterId();
  1518. if (vstParamID == vstBypassParameterId)
  1519. setBypassed (static_cast<float> (value) != 0.0f);
  1520. #if JUCE_VST3_EMULATE_MIDI_CC_WITH_PARAMETERS
  1521. else if (juceVST3EditController->isMidiControllerParamID (vstParamID))
  1522. addParameterChangeToMidiBuffer (offsetSamples, vstParamID, value);
  1523. #endif
  1524. else if (vstParamID == JuceVST3EditController::paramPreset)
  1525. {
  1526. auto numPrograms = pluginInstance->getNumPrograms();
  1527. auto programValue = roundToInt (value * (jmax (0, numPrograms - 1)));
  1528. if (numPrograms > 1 && isPositiveAndBelow (programValue, numPrograms)
  1529. && programValue != pluginInstance->getCurrentProgram())
  1530. pluginInstance->setCurrentProgram (programValue);
  1531. }
  1532. else
  1533. {
  1534. auto index = getJuceIndexForVSTParamID (vstParamID);
  1535. if (isPositiveAndBelow (index, pluginInstance->getNumParameters()))
  1536. pluginInstance->setParameter (index, static_cast<float> (value));
  1537. }
  1538. }
  1539. }
  1540. }
  1541. }
  1542. void addParameterChangeToMidiBuffer (const Steinberg::int32 offsetSamples, const Vst::ParamID id, const double value)
  1543. {
  1544. // If the parameter is mapped to a MIDI CC message then insert it into the midiBuffer.
  1545. int channel, ctrlNumber;
  1546. if (juceVST3EditController->getMidiControllerForParameter (id, channel, ctrlNumber))
  1547. {
  1548. if (ctrlNumber == Vst::kAfterTouch)
  1549. midiBuffer.addEvent (MidiMessage::channelPressureChange (channel,
  1550. jlimit (0, 127, (int) (value * 128.0))), offsetSamples);
  1551. else if (ctrlNumber == Vst::kPitchBend)
  1552. midiBuffer.addEvent (MidiMessage::pitchWheel (channel,
  1553. jlimit (0, 0x3fff, (int) (value * 0x4000))), offsetSamples);
  1554. else
  1555. midiBuffer.addEvent (MidiMessage::controllerEvent (channel,
  1556. jlimit (0, 127, ctrlNumber),
  1557. jlimit (0, 127, (int) (value * 128.0))), offsetSamples);
  1558. }
  1559. }
  1560. tresult PLUGIN_API process (Vst::ProcessData& data) override
  1561. {
  1562. if (pluginInstance == nullptr)
  1563. return kResultFalse;
  1564. if ((processSetup.symbolicSampleSize == Vst::kSample64) != pluginInstance->isUsingDoublePrecision())
  1565. return kResultFalse;
  1566. if (data.processContext != nullptr)
  1567. processContext = *data.processContext;
  1568. else
  1569. zerostruct (processContext);
  1570. midiBuffer.clear();
  1571. #if JucePlugin_WantsMidiInput
  1572. if (data.inputEvents != nullptr)
  1573. MidiEventList::toMidiBuffer (midiBuffer, *data.inputEvents);
  1574. #endif
  1575. if (getHostType().isWavelab())
  1576. {
  1577. const int numInputChans = (data.inputs != nullptr && data.inputs[0].channelBuffers32 != nullptr) ? (int) data.inputs[0].numChannels : 0;
  1578. const int numOutputChans = (data.outputs != nullptr && data.outputs[0].channelBuffers32 != nullptr) ? (int) data.outputs[0].numChannels : 0;
  1579. if ((pluginInstance->getTotalNumInputChannels() + pluginInstance->getTotalNumOutputChannels()) > 0
  1580. && (numInputChans + numOutputChans) == 0)
  1581. return kResultFalse;
  1582. }
  1583. if (processSetup.symbolicSampleSize == Vst::kSample32) processAudio<float> (data, channelListFloat);
  1584. else if (processSetup.symbolicSampleSize == Vst::kSample64) processAudio<double> (data, channelListDouble);
  1585. else jassertfalse;
  1586. #if JucePlugin_ProducesMidiOutput
  1587. if (data.outputEvents != nullptr)
  1588. MidiEventList::toEventList (*data.outputEvents, midiBuffer);
  1589. #endif
  1590. return kResultTrue;
  1591. }
  1592. private:
  1593. //==============================================================================
  1594. Atomic<int> refCount { 1 };
  1595. AudioProcessor* pluginInstance;
  1596. ComSmartPtr<Vst::IHostApplication> host;
  1597. ComSmartPtr<JuceAudioProcessor> comPluginInstance;
  1598. ComSmartPtr<JuceVST3EditController> juceVST3EditController;
  1599. /**
  1600. Since VST3 does not provide a way of knowing the buffer size and sample rate at any point,
  1601. this object needs to be copied on every call to process() to be up-to-date...
  1602. */
  1603. Vst::ProcessContext processContext;
  1604. Vst::ProcessSetup processSetup;
  1605. MidiBuffer midiBuffer;
  1606. Array<float*> channelListFloat;
  1607. Array<double*> channelListDouble;
  1608. AudioBuffer<float> emptyBufferFloat;
  1609. AudioBuffer<double> emptyBufferDouble;
  1610. #if JucePlugin_WantsMidiInput
  1611. bool isMidiInputBusEnabled = true;
  1612. #else
  1613. bool isMidiInputBusEnabled = false;
  1614. #endif
  1615. #if JucePlugin_ProducesMidiOutput
  1616. bool isMidiOutputBusEnabled = true;
  1617. #else
  1618. bool isMidiOutputBusEnabled = false;
  1619. #endif
  1620. ScopedJuceInitialiser_GUI libraryInitialiser;
  1621. #if ! JUCE_FORCE_USE_LEGACY_PARAM_IDS
  1622. bool usingManagedParameter;
  1623. Array<Vst::ParamID> vstParamIDs;
  1624. HashMap<int32, int> paramMap;
  1625. #endif
  1626. Vst::ParamID vstBypassParameterId;
  1627. static const char* kJucePrivateDataIdentifier;
  1628. //==============================================================================
  1629. template <typename FloatType>
  1630. void processAudio (Vst::ProcessData& data, Array<FloatType*>& channelList)
  1631. {
  1632. int totalInputChans = 0, totalOutputChans = 0;
  1633. bool tmpBufferNeedsClearing = false;
  1634. auto plugInInputChannels = pluginInstance->getTotalNumInputChannels();
  1635. auto plugInOutputChannels = pluginInstance->getTotalNumOutputChannels();
  1636. // Wavelab workaround: wave-lab lies on the number of inputs/outputs so re-count here
  1637. int vstInputs;
  1638. for (vstInputs = 0; vstInputs < data.numInputs; ++vstInputs)
  1639. if (getPointerForAudioBus<FloatType> (data.inputs[vstInputs]) == nullptr
  1640. && data.inputs[vstInputs].numChannels > 0)
  1641. break;
  1642. int vstOutputs;
  1643. for (vstOutputs = 0; vstOutputs < data.numOutputs; ++vstOutputs)
  1644. if (getPointerForAudioBus<FloatType> (data.outputs[vstOutputs]) == nullptr
  1645. && data.outputs[vstOutputs].numChannels > 0)
  1646. break;
  1647. {
  1648. auto n = jmax (vstOutputs, getNumAudioBuses (false));
  1649. for (int bus = 0; bus < n && totalOutputChans < plugInOutputChannels; ++bus)
  1650. {
  1651. if (bus < vstOutputs)
  1652. {
  1653. if (auto** const busChannels = getPointerForAudioBus<FloatType> (data.outputs[bus]))
  1654. {
  1655. auto numChans = jmin ((int) data.outputs[bus].numChannels, plugInOutputChannels - totalOutputChans);
  1656. for (int i = 0; i < numChans; ++i)
  1657. {
  1658. if (auto dst = busChannels[i])
  1659. {
  1660. if (totalOutputChans >= plugInInputChannels)
  1661. FloatVectorOperations::clear (dst, (int) data.numSamples);
  1662. channelList.set (totalOutputChans++, busChannels[i]);
  1663. }
  1664. }
  1665. }
  1666. }
  1667. else
  1668. {
  1669. const int numChans = jmin (pluginInstance->getChannelCountOfBus (false, bus), plugInOutputChannels - totalOutputChans);
  1670. for (int i = 0; i < numChans; ++i)
  1671. {
  1672. if (auto* tmpBuffer = getTmpBufferForChannel<FloatType> (totalOutputChans, data.numSamples))\
  1673. {
  1674. tmpBufferNeedsClearing = true;
  1675. channelList.set (totalOutputChans++, tmpBuffer);
  1676. }
  1677. else
  1678. return;
  1679. }
  1680. }
  1681. }
  1682. }
  1683. {
  1684. auto n = jmax (vstInputs, getNumAudioBuses (true));
  1685. for (int bus = 0; bus < n && totalInputChans < plugInInputChannels; ++bus)
  1686. {
  1687. if (bus < vstInputs)
  1688. {
  1689. if (auto** const busChannels = getPointerForAudioBus<FloatType> (data.inputs[bus]))
  1690. {
  1691. const int numChans = jmin ((int) data.inputs[bus].numChannels, plugInInputChannels - totalInputChans);
  1692. for (int i = 0; i < numChans; ++i)
  1693. {
  1694. if (busChannels[i] != nullptr)
  1695. {
  1696. if (totalInputChans >= totalOutputChans)
  1697. channelList.set (totalInputChans, busChannels[i]);
  1698. else
  1699. {
  1700. auto* dst = channelList.getReference (totalInputChans);
  1701. auto* src = busChannels[i];
  1702. if (dst != src)
  1703. FloatVectorOperations::copy (dst, src, (int) data.numSamples);
  1704. }
  1705. }
  1706. ++totalInputChans;
  1707. }
  1708. }
  1709. }
  1710. else
  1711. {
  1712. auto numChans = jmin (pluginInstance->getChannelCountOfBus (true, bus), plugInInputChannels - totalInputChans);
  1713. for (int i = 0; i < numChans; ++i)
  1714. {
  1715. if (auto* tmpBuffer = getTmpBufferForChannel<FloatType> (totalInputChans, data.numSamples))
  1716. {
  1717. tmpBufferNeedsClearing = true;
  1718. channelList.set (totalInputChans++, tmpBuffer);
  1719. }
  1720. else
  1721. return;
  1722. }
  1723. }
  1724. }
  1725. }
  1726. if (tmpBufferNeedsClearing)
  1727. ChooseBufferHelper<FloatType>::impl (emptyBufferFloat, emptyBufferDouble).clear();
  1728. AudioBuffer<FloatType> buffer;
  1729. if (int totalChans = jmax (totalOutputChans, totalInputChans))
  1730. buffer.setDataToReferTo (channelList.getRawDataPointer(), totalChans, (int) data.numSamples);
  1731. {
  1732. const ScopedLock sl (pluginInstance->getCallbackLock());
  1733. pluginInstance->setNonRealtime (data.processMode == Vst::kOffline);
  1734. if (data.inputParameterChanges != nullptr)
  1735. processParameterChanges (*data.inputParameterChanges);
  1736. #if JUCE_DEBUG && ! JucePlugin_ProducesMidiOutput
  1737. const int numMidiEventsComingIn = midiBuffer.getNumEvents();
  1738. #endif
  1739. if (pluginInstance->isSuspended())
  1740. {
  1741. buffer.clear();
  1742. }
  1743. else
  1744. {
  1745. if (totalInputChans == pluginInstance->getTotalNumInputChannels()
  1746. && totalOutputChans == pluginInstance->getTotalNumOutputChannels())
  1747. {
  1748. if (isBypassed())
  1749. pluginInstance->processBlockBypassed (buffer, midiBuffer);
  1750. else
  1751. pluginInstance->processBlock (buffer, midiBuffer);
  1752. }
  1753. }
  1754. #if JUCE_DEBUG && (! JucePlugin_ProducesMidiOutput)
  1755. /* This assertion is caused when you've added some events to the
  1756. midiMessages array in your processBlock() method, which usually means
  1757. that you're trying to send them somewhere. But in this case they're
  1758. getting thrown away.
  1759. If your plugin does want to send MIDI messages, you'll need to set
  1760. the JucePlugin_ProducesMidiOutput macro to 1 in your
  1761. JucePluginCharacteristics.h file.
  1762. If you don't want to produce any MIDI output, then you should clear the
  1763. midiMessages array at the end of your processBlock() method, to
  1764. indicate that you don't want any of the events to be passed through
  1765. to the output.
  1766. */
  1767. jassert (midiBuffer.getNumEvents() <= numMidiEventsComingIn);
  1768. #endif
  1769. }
  1770. }
  1771. //==============================================================================
  1772. template <typename FloatType>
  1773. void allocateChannelListAndBuffers (Array<FloatType*>& channelList, AudioBuffer<FloatType>& buffer)
  1774. {
  1775. channelList.clearQuick();
  1776. channelList.insertMultiple (0, nullptr, 128);
  1777. auto& p = getPluginInstance();
  1778. buffer.setSize (jmax (p.getTotalNumInputChannels(), p.getTotalNumOutputChannels()), p.getBlockSize() * 4);
  1779. buffer.clear();
  1780. }
  1781. template <typename FloatType>
  1782. void deallocateChannelListAndBuffers (Array<FloatType*>& channelList, AudioBuffer<FloatType>& buffer)
  1783. {
  1784. channelList.clearQuick();
  1785. channelList.resize (0);
  1786. buffer.setSize (0, 0);
  1787. }
  1788. template <typename FloatType>
  1789. static FloatType** getPointerForAudioBus (Vst::AudioBusBuffers& data) noexcept
  1790. {
  1791. return AudioBusPointerHelper<FloatType>::impl (data);
  1792. }
  1793. template <typename FloatType>
  1794. FloatType* getTmpBufferForChannel (int channel, int numSamples) noexcept
  1795. {
  1796. auto& buffer = ChooseBufferHelper<FloatType>::impl (emptyBufferFloat, emptyBufferDouble);
  1797. // we can't do anything if the host requests to render many more samples than the
  1798. // block size, we need to bail out
  1799. if (numSamples > buffer.getNumSamples() || channel >= buffer.getNumChannels())
  1800. return nullptr;
  1801. return buffer.getWritePointer (channel);
  1802. }
  1803. void preparePlugin (double sampleRate, int bufferSize)
  1804. {
  1805. auto& p = getPluginInstance();
  1806. p.setRateAndBufferSizeDetails (sampleRate, bufferSize);
  1807. p.prepareToPlay (sampleRate, bufferSize);
  1808. }
  1809. //==============================================================================
  1810. #if JUCE_FORCE_USE_LEGACY_PARAM_IDS
  1811. inline Vst::ParamID getVSTParamIDForIndex (int paramIndex) const noexcept { return static_cast<Vst::ParamID> (paramIndex); }
  1812. inline int getJuceIndexForVSTParamID (Vst::ParamID paramID) const noexcept { return static_cast<int> (paramID); }
  1813. #else
  1814. void cacheParameterIDs()
  1815. {
  1816. const int numParameters = pluginInstance->getNumParameters();
  1817. usingManagedParameter = (pluginInstance->getParameters().size() == numParameters);
  1818. vstBypassParameterId = static_cast<Vst::ParamID> (usingManagedParameter ? JuceVST3EditController::paramBypass : numParameters);
  1819. for (int i = 0; i < numParameters; ++i)
  1820. {
  1821. auto paramID = JuceVST3EditController::generateVSTParamIDForIndex (pluginInstance, i);
  1822. // Consider yourself very unlucky if you hit this assertion. The hash code of your
  1823. // parameter ids are not unique.
  1824. jassert (! vstParamIDs.contains (paramID));
  1825. vstParamIDs.add (paramID);
  1826. paramMap.set (static_cast<int32> (paramID), i);
  1827. }
  1828. }
  1829. inline Vst::ParamID getVSTParamIDForIndex (int paramIndex) const noexcept
  1830. {
  1831. return usingManagedParameter ? vstParamIDs.getReference (paramIndex)
  1832. : static_cast<Vst::ParamID> (paramIndex);
  1833. }
  1834. inline int getJuceIndexForVSTParamID (Vst::ParamID paramID) const noexcept
  1835. {
  1836. return usingManagedParameter ? paramMap[static_cast<int32> (paramID)]
  1837. : static_cast<int> (paramID);
  1838. }
  1839. #endif
  1840. //==============================================================================
  1841. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (JuceVST3Component)
  1842. };
  1843. const char* JuceVST3Component::kJucePrivateDataIdentifier = "JUCEPrivateData";
  1844. //==============================================================================
  1845. #if JUCE_MSVC
  1846. #pragma warning (push, 0)
  1847. #pragma warning (disable: 4310)
  1848. #elif JUCE_CLANG
  1849. #pragma clang diagnostic push
  1850. #pragma clang diagnostic ignored "-Wall"
  1851. #endif
  1852. DECLARE_CLASS_IID (JuceAudioProcessor, 0x0101ABAB, 0xABCDEF01, JucePlugin_ManufacturerCode, JucePlugin_PluginCode)
  1853. DEF_CLASS_IID (JuceAudioProcessor)
  1854. #if JUCE_VST3_CAN_REPLACE_VST2
  1855. FUID getFUIDForVST2ID (bool forControllerUID)
  1856. {
  1857. TUID uuid;
  1858. extern JUCE_API void getUUIDForVST2ID (bool, uint8[16]);
  1859. getUUIDForVST2ID (forControllerUID, (uint8*) uuid);
  1860. return FUID (uuid);
  1861. }
  1862. const Steinberg::FUID JuceVST3Component ::iid (getFUIDForVST2ID (false));
  1863. const Steinberg::FUID JuceVST3EditController::iid (getFUIDForVST2ID (true));
  1864. #else
  1865. DECLARE_CLASS_IID (JuceVST3EditController, 0xABCDEF01, 0x1234ABCD, JucePlugin_ManufacturerCode, JucePlugin_PluginCode)
  1866. DEF_CLASS_IID (JuceVST3EditController)
  1867. DECLARE_CLASS_IID (JuceVST3Component, 0xABCDEF01, 0x9182FAEB, JucePlugin_ManufacturerCode, JucePlugin_PluginCode)
  1868. DEF_CLASS_IID (JuceVST3Component)
  1869. #endif
  1870. #if JUCE_MSVC
  1871. #pragma warning (pop)
  1872. #elif JUCE_CLANG
  1873. #pragma clang diagnostic pop
  1874. #endif
  1875. //==============================================================================
  1876. bool initModule()
  1877. {
  1878. #if JUCE_MAC
  1879. initialiseMacVST();
  1880. #endif
  1881. return true;
  1882. }
  1883. bool shutdownModule()
  1884. {
  1885. return true;
  1886. }
  1887. #undef JUCE_EXPORTED_FUNCTION
  1888. #if JUCE_WINDOWS
  1889. extern "C" __declspec (dllexport) bool InitDll() { return initModule(); }
  1890. extern "C" __declspec (dllexport) bool ExitDll() { return shutdownModule(); }
  1891. #define JUCE_EXPORTED_FUNCTION
  1892. #else
  1893. #define JUCE_EXPORTED_FUNCTION extern "C" __attribute__ ((visibility ("default")))
  1894. CFBundleRef globalBundleInstance = nullptr;
  1895. juce::uint32 numBundleRefs = 0;
  1896. juce::Array<CFBundleRef> bundleRefs;
  1897. enum { MaxPathLength = 2048 };
  1898. char modulePath[MaxPathLength] = { 0 };
  1899. void* moduleHandle = nullptr;
  1900. JUCE_EXPORTED_FUNCTION bool bundleEntry (CFBundleRef ref)
  1901. {
  1902. if (ref != nullptr)
  1903. {
  1904. ++numBundleRefs;
  1905. CFRetain (ref);
  1906. bundleRefs.add (ref);
  1907. if (moduleHandle == nullptr)
  1908. {
  1909. globalBundleInstance = ref;
  1910. moduleHandle = ref;
  1911. CFURLRef tempURL = CFBundleCopyBundleURL (ref);
  1912. CFURLGetFileSystemRepresentation (tempURL, true, (UInt8*) modulePath, MaxPathLength);
  1913. CFRelease (tempURL);
  1914. }
  1915. }
  1916. return initModule();
  1917. }
  1918. JUCE_EXPORTED_FUNCTION bool bundleExit()
  1919. {
  1920. if (shutdownModule())
  1921. {
  1922. if (--numBundleRefs == 0)
  1923. {
  1924. for (int i = 0; i < bundleRefs.size(); ++i)
  1925. CFRelease (bundleRefs.getUnchecked (i));
  1926. bundleRefs.clear();
  1927. }
  1928. return true;
  1929. }
  1930. return false;
  1931. }
  1932. #endif
  1933. //==============================================================================
  1934. /** This typedef represents VST3's createInstance() function signature */
  1935. typedef FUnknown* (*CreateFunction) (Vst::IHostApplication*);
  1936. static FUnknown* createComponentInstance (Vst::IHostApplication* host)
  1937. {
  1938. return static_cast<Vst::IAudioProcessor*> (new JuceVST3Component (host));
  1939. }
  1940. static FUnknown* createControllerInstance (Vst::IHostApplication* host)
  1941. {
  1942. return static_cast<Vst::IEditController*> (new JuceVST3EditController (host));
  1943. }
  1944. //==============================================================================
  1945. struct JucePluginFactory;
  1946. static JucePluginFactory* globalFactory = nullptr;
  1947. //==============================================================================
  1948. struct JucePluginFactory : public IPluginFactory3
  1949. {
  1950. JucePluginFactory()
  1951. : factoryInfo (JucePlugin_Manufacturer, JucePlugin_ManufacturerWebsite,
  1952. JucePlugin_ManufacturerEmail, Vst::kDefaultFactoryFlags)
  1953. {
  1954. }
  1955. virtual ~JucePluginFactory()
  1956. {
  1957. if (globalFactory == this)
  1958. globalFactory = nullptr;
  1959. }
  1960. //==============================================================================
  1961. bool registerClass (const PClassInfo2& info, CreateFunction createFunction)
  1962. {
  1963. if (createFunction == nullptr)
  1964. {
  1965. jassertfalse;
  1966. return false;
  1967. }
  1968. auto* entry = classes.add (new ClassEntry (info, createFunction));
  1969. entry->infoW.fromAscii (info);
  1970. return true;
  1971. }
  1972. bool isClassRegistered (const FUID& cid) const
  1973. {
  1974. for (int i = 0; i < classes.size(); ++i)
  1975. if (classes.getUnchecked (i)->infoW.cid == cid)
  1976. return true;
  1977. return false;
  1978. }
  1979. //==============================================================================
  1980. JUCE_DECLARE_VST3_COM_REF_METHODS
  1981. tresult PLUGIN_API queryInterface (const TUID targetIID, void** obj) override
  1982. {
  1983. TEST_FOR_AND_RETURN_IF_VALID (targetIID, IPluginFactory3)
  1984. TEST_FOR_AND_RETURN_IF_VALID (targetIID, IPluginFactory2)
  1985. TEST_FOR_AND_RETURN_IF_VALID (targetIID, IPluginFactory)
  1986. TEST_FOR_AND_RETURN_IF_VALID (targetIID, FUnknown)
  1987. jassertfalse; // Something new?
  1988. *obj = nullptr;
  1989. return kNotImplemented;
  1990. }
  1991. //==============================================================================
  1992. Steinberg::int32 PLUGIN_API countClasses() override
  1993. {
  1994. return (Steinberg::int32) classes.size();
  1995. }
  1996. tresult PLUGIN_API getFactoryInfo (PFactoryInfo* info) override
  1997. {
  1998. if (info == nullptr)
  1999. return kInvalidArgument;
  2000. memcpy (info, &factoryInfo, sizeof (PFactoryInfo));
  2001. return kResultOk;
  2002. }
  2003. tresult PLUGIN_API getClassInfo (Steinberg::int32 index, PClassInfo* info) override
  2004. {
  2005. return getPClassInfo<PClassInfo> (index, info);
  2006. }
  2007. tresult PLUGIN_API getClassInfo2 (Steinberg::int32 index, PClassInfo2* info) override
  2008. {
  2009. return getPClassInfo<PClassInfo2> (index, info);
  2010. }
  2011. tresult PLUGIN_API getClassInfoUnicode (Steinberg::int32 index, PClassInfoW* info) override
  2012. {
  2013. if (info != nullptr)
  2014. {
  2015. if (auto* entry = classes[(int) index])
  2016. {
  2017. memcpy (info, &entry->infoW, sizeof (PClassInfoW));
  2018. return kResultOk;
  2019. }
  2020. }
  2021. return kInvalidArgument;
  2022. }
  2023. tresult PLUGIN_API createInstance (FIDString cid, FIDString sourceIid, void** obj) override
  2024. {
  2025. *obj = nullptr;
  2026. FUID sourceFuid = sourceIid;
  2027. if (cid == nullptr || sourceIid == nullptr || ! sourceFuid.isValid())
  2028. {
  2029. jassertfalse; // The host you're running in has severe implementation issues!
  2030. return kInvalidArgument;
  2031. }
  2032. TUID iidToQuery;
  2033. sourceFuid.toTUID (iidToQuery);
  2034. for (auto* entry : classes)
  2035. {
  2036. if (doUIDsMatch (entry->infoW.cid, cid))
  2037. {
  2038. if (auto* instance = entry->createFunction (host))
  2039. {
  2040. const FReleaser releaser (instance);
  2041. if (instance->queryInterface (iidToQuery, obj) == kResultOk)
  2042. return kResultOk;
  2043. }
  2044. break;
  2045. }
  2046. }
  2047. return kNoInterface;
  2048. }
  2049. tresult PLUGIN_API setHostContext (FUnknown* context) override
  2050. {
  2051. host.loadFrom (context);
  2052. if (host != nullptr)
  2053. {
  2054. Vst::String128 name;
  2055. host->getName (name);
  2056. return kResultTrue;
  2057. }
  2058. return kNotImplemented;
  2059. }
  2060. private:
  2061. //==============================================================================
  2062. ScopedJuceInitialiser_GUI libraryInitialiser;
  2063. Atomic<int> refCount { 1 };
  2064. const PFactoryInfo factoryInfo;
  2065. ComSmartPtr<Vst::IHostApplication> host;
  2066. //==============================================================================
  2067. struct ClassEntry
  2068. {
  2069. ClassEntry() noexcept {}
  2070. ClassEntry (const PClassInfo2& info, CreateFunction fn) noexcept
  2071. : info2 (info), createFunction (fn) {}
  2072. PClassInfo2 info2;
  2073. PClassInfoW infoW;
  2074. CreateFunction createFunction = {};
  2075. bool isUnicode = false;
  2076. private:
  2077. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ClassEntry)
  2078. };
  2079. OwnedArray<ClassEntry> classes;
  2080. //==============================================================================
  2081. template<class PClassInfoType>
  2082. tresult PLUGIN_API getPClassInfo (Steinberg::int32 index, PClassInfoType* info)
  2083. {
  2084. if (info != nullptr)
  2085. {
  2086. zerostruct (*info);
  2087. if (auto* entry = classes[(int) index])
  2088. {
  2089. if (entry->isUnicode)
  2090. return kResultFalse;
  2091. memcpy (info, &entry->info2, sizeof (PClassInfoType));
  2092. return kResultOk;
  2093. }
  2094. }
  2095. jassertfalse;
  2096. return kInvalidArgument;
  2097. }
  2098. //==============================================================================
  2099. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (JucePluginFactory)
  2100. };
  2101. } // juce namespace
  2102. //==============================================================================
  2103. #ifndef JucePlugin_Vst3ComponentFlags
  2104. #if JucePlugin_IsSynth
  2105. #define JucePlugin_Vst3ComponentFlags Vst::kSimpleModeSupported
  2106. #else
  2107. #define JucePlugin_Vst3ComponentFlags 0
  2108. #endif
  2109. #endif
  2110. #ifndef JucePlugin_Vst3Category
  2111. #if JucePlugin_IsSynth
  2112. #define JucePlugin_Vst3Category Vst::PlugType::kInstrumentSynth
  2113. #else
  2114. #define JucePlugin_Vst3Category Vst::PlugType::kFx
  2115. #endif
  2116. #endif
  2117. //==============================================================================
  2118. // The VST3 plugin entry point.
  2119. JUCE_EXPORTED_FUNCTION IPluginFactory* PLUGIN_API GetPluginFactory()
  2120. {
  2121. PluginHostType::jucePlugInClientCurrentWrapperType = AudioProcessor::wrapperType_VST3;
  2122. #if JUCE_WINDOWS
  2123. // Cunning trick to force this function to be exported. Life's too short to
  2124. // faff around creating .def files for this kind of thing.
  2125. #pragma comment(linker, "/EXPORT:" __FUNCTION__ "=" __FUNCDNAME__)
  2126. #endif
  2127. if (globalFactory == nullptr)
  2128. {
  2129. globalFactory = new JucePluginFactory();
  2130. static const PClassInfo2 componentClass (JuceVST3Component::iid,
  2131. PClassInfo::kManyInstances,
  2132. kVstAudioEffectClass,
  2133. JucePlugin_Name,
  2134. JucePlugin_Vst3ComponentFlags,
  2135. JucePlugin_Vst3Category,
  2136. JucePlugin_Manufacturer,
  2137. JucePlugin_VersionString,
  2138. kVstVersionString);
  2139. globalFactory->registerClass (componentClass, createComponentInstance);
  2140. static const PClassInfo2 controllerClass (JuceVST3EditController::iid,
  2141. PClassInfo::kManyInstances,
  2142. kVstComponentControllerClass,
  2143. JucePlugin_Name,
  2144. JucePlugin_Vst3ComponentFlags,
  2145. JucePlugin_Vst3Category,
  2146. JucePlugin_Manufacturer,
  2147. JucePlugin_VersionString,
  2148. kVstVersionString);
  2149. globalFactory->registerClass (controllerClass, createControllerInstance);
  2150. }
  2151. else
  2152. {
  2153. globalFactory->addRef();
  2154. }
  2155. return dynamic_cast<IPluginFactory*> (globalFactory);
  2156. }
  2157. //==============================================================================
  2158. #if _MSC_VER || JUCE_MINGW
  2159. extern "C" BOOL WINAPI DllMain (HINSTANCE instance, DWORD reason, LPVOID) { if (reason == DLL_PROCESS_ATTACH) Process::setCurrentModuleInstanceHandle (instance); return true; }
  2160. #endif
  2161. #endif //JucePlugin_Build_VST3