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.

2685 lines
98KB

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