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.

2507 lines
91KB

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