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.

3017 lines
110KB

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