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.

2804 lines
102KB

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