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.

3029 lines
111KB

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