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.

3172 lines
118KB

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