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.

2677 lines
98KB

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